xref: /qemu/hw/scsi/scsi-disk.c (revision e2ec3f97)
1 /*
2  * SCSI Device emulation
3  *
4  * Copyright (c) 2006 CodeSourcery.
5  * Based on code by Fabrice Bellard
6  *
7  * Written by Paul Brook
8  * Modifications:
9  *  2009-Dec-12 Artyom Tarasenko : implemented stamdard inquiry for the case
10  *                                 when the allocation length of CDB is smaller
11  *                                 than 36.
12  *  2009-Oct-13 Artyom Tarasenko : implemented the block descriptor in the
13  *                                 MODE SENSE response.
14  *
15  * This code is licensed under the LGPL.
16  *
17  * Note that this file only handles the SCSI architecture model and device
18  * commands.  Emulation of interface/link layer protocols is handled by
19  * the host adapter emulator.
20  */
21 
22 //#define DEBUG_SCSI
23 
24 #ifdef DEBUG_SCSI
25 #define DPRINTF(fmt, ...) \
26 do { printf("scsi-disk: " fmt , ## __VA_ARGS__); } while (0)
27 #else
28 #define DPRINTF(fmt, ...) do {} while(0)
29 #endif
30 
31 #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"
39 
40 #ifdef __linux
41 #include <scsi/sg.h>
42 #endif
43 
44 #define SCSI_DMA_BUF_SIZE           131072
45 #define SCSI_MAX_INQUIRY_LEN        256
46 #define SCSI_MAX_MODE_LEN           256
47 
48 #define DEFAULT_DISCARD_GRANULARITY 4096
49 
50 typedef struct SCSIDiskState SCSIDiskState;
51 
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;
63 
64 #define SCSI_DISK_F_REMOVABLE   0
65 #define SCSI_DISK_F_DPOFUA      1
66 
67 struct SCSIDiskState
68 {
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;
82 };
83 
84 static int scsi_handle_rw_error(SCSIDiskReq *r, int error);
85 
86 static void scsi_free_request(SCSIRequest *req)
87 {
88     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
89 
90     qemu_vfree(r->iov.iov_base);
91 }
92 
93 /* Helper function for command completion with sense.  */
94 static void scsi_check_condition(SCSIDiskReq *r, SCSISense sense)
95 {
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);
100 }
101 
102 /* Cancel a pending data transfer.  */
103 static void scsi_cancel_io(SCSIRequest *req)
104 {
105     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
106 
107     DPRINTF("Cancel tag=0x%x\n", req->tag);
108     if (r->req.aiocb) {
109         bdrv_aio_cancel(r->req.aiocb);
110 
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);
115     }
116     r->req.aiocb = NULL;
117 }
118 
119 static uint32_t scsi_init_iovec(SCSIDiskReq *r, size_t size)
120 {
121     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
122 
123     if (!r->iov.iov_base) {
124         r->buflen = size;
125         r->iov.iov_base = qemu_blockalign(s->qdev.conf.bs, r->buflen);
126     }
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;
130 }
131 
132 static void scsi_disk_save_request(QEMUFile *f, SCSIRequest *req)
133 {
134     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
135 
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);
146         }
147     }
148 }
149 
150 static void scsi_disk_load_request(QEMUFile *f, SCSIRequest *req)
151 {
152     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
153 
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);
167         }
168     }
169 
170     qemu_iovec_init_external(&r->qiov, &r->iov, 1);
171 }
172 
173 static void scsi_aio_complete(void *opaque, int ret)
174 {
175     SCSIDiskReq *r = (SCSIDiskReq *)opaque;
176     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
177 
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;
183     }
184 
185     if (ret < 0) {
186         if (scsi_handle_rw_error(r, -ret)) {
187             goto done;
188         }
189     }
190 
191     scsi_req_complete(&r->req, GOOD);
192 
193 done:
194     if (!r->req.io_canceled) {
195         scsi_req_unref(&r->req);
196     }
197 }
198 
199 static bool scsi_is_cmd_fua(SCSICommand *cmd)
200 {
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;
209 
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;
217 
218     case READ_6:
219     case WRITE_6:
220     default:
221         return false;
222     }
223 }
224 
225 static void scsi_write_do_fua(SCSIDiskReq *r)
226 {
227     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
228 
229     if (r->req.io_canceled) {
230         goto done;
231     }
232 
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;
237     }
238 
239     scsi_req_complete(&r->req, GOOD);
240 
241 done:
242     if (!r->req.io_canceled) {
243         scsi_req_unref(&r->req);
244     }
245 }
246 
247 static void scsi_dma_complete(void *opaque, int ret)
248 {
249     SCSIDiskReq *r = (SCSIDiskReq *)opaque;
250     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
251 
252     assert(r->req.aiocb != NULL);
253     r->req.aiocb = NULL;
254     bdrv_acct_done(s->qdev.conf.bs, &r->acct);
255     if (r->req.io_canceled) {
256         goto done;
257     }
258 
259     if (ret < 0) {
260         if (scsi_handle_rw_error(r, -ret)) {
261             goto done;
262         }
263     }
264 
265     r->sector += r->sector_count;
266     r->sector_count = 0;
267     if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
268         scsi_write_do_fua(r);
269         return;
270     } else {
271         scsi_req_complete(&r->req, GOOD);
272     }
273 
274 done:
275     if (!r->req.io_canceled) {
276         scsi_req_unref(&r->req);
277     }
278 }
279 
280 static void scsi_read_complete(void * opaque, int ret)
281 {
282     SCSIDiskReq *r = (SCSIDiskReq *)opaque;
283     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
284     int n;
285 
286     assert(r->req.aiocb != NULL);
287     r->req.aiocb = NULL;
288     bdrv_acct_done(s->qdev.conf.bs, &r->acct);
289     if (r->req.io_canceled) {
290         goto done;
291     }
292 
293     if (ret < 0) {
294         if (scsi_handle_rw_error(r, -ret)) {
295             goto done;
296         }
297     }
298 
299     DPRINTF("Data ready tag=0x%x len=%zd\n", r->req.tag, r->qiov.size);
300 
301     n = r->qiov.size / 512;
302     r->sector += n;
303     r->sector_count -= n;
304     scsi_req_data(&r->req, r->qiov.size);
305 
306 done:
307     if (!r->req.io_canceled) {
308         scsi_req_unref(&r->req);
309     }
310 }
311 
312 /* Actually issue a read to the block device.  */
313 static void scsi_do_read(void *opaque, int ret)
314 {
315     SCSIDiskReq *r = opaque;
316     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
317     uint32_t n;
318 
319     if (r->req.aiocb != NULL) {
320         r->req.aiocb = NULL;
321         bdrv_acct_done(s->qdev.conf.bs, &r->acct);
322     }
323     if (r->req.io_canceled) {
324         goto done;
325     }
326 
327     if (ret < 0) {
328         if (scsi_handle_rw_error(r, -ret)) {
329             goto done;
330         }
331     }
332 
333     /* The request is used as the AIO opaque value, so add a ref.  */
334     scsi_req_ref(&r->req);
335 
336     if (r->req.sg) {
337         dma_acct_start(s->qdev.conf.bs, &r->acct, r->req.sg, BDRV_ACCT_READ);
338         r->req.resid -= r->req.sg->size;
339         r->req.aiocb = dma_bdrv_read(s->qdev.conf.bs, r->req.sg, r->sector,
340                                      scsi_dma_complete, r);
341     } else {
342         n = scsi_init_iovec(r, SCSI_DMA_BUF_SIZE);
343         bdrv_acct_start(s->qdev.conf.bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
344         r->req.aiocb = bdrv_aio_readv(s->qdev.conf.bs, r->sector, &r->qiov, n,
345                                       scsi_read_complete, r);
346     }
347 
348 done:
349     if (!r->req.io_canceled) {
350         scsi_req_unref(&r->req);
351     }
352 }
353 
354 /* Read more data from scsi device into buffer.  */
355 static void scsi_read_data(SCSIRequest *req)
356 {
357     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
358     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
359     bool first;
360 
361     DPRINTF("Read sector_count=%d\n", r->sector_count);
362     if (r->sector_count == 0) {
363         /* This also clears the sense buffer for REQUEST SENSE.  */
364         scsi_req_complete(&r->req, GOOD);
365         return;
366     }
367 
368     /* No data transfer may already be in progress */
369     assert(r->req.aiocb == NULL);
370 
371     /* The request is used as the AIO opaque value, so add a ref.  */
372     scsi_req_ref(&r->req);
373     if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
374         DPRINTF("Data transfer direction invalid\n");
375         scsi_read_complete(r, -EINVAL);
376         return;
377     }
378 
379     if (s->tray_open) {
380         scsi_read_complete(r, -ENOMEDIUM);
381         return;
382     }
383 
384     first = !r->started;
385     r->started = true;
386     if (first && scsi_is_cmd_fua(&r->req.cmd)) {
387         bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
388         r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_do_read, r);
389     } else {
390         scsi_do_read(r, 0);
391     }
392 }
393 
394 /*
395  * scsi_handle_rw_error has two return values.  0 means that the error
396  * must be ignored, 1 means that the error has been processed and the
397  * caller should not do anything else for this request.  Note that
398  * scsi_handle_rw_error always manages its reference counts, independent
399  * of the return value.
400  */
401 static int scsi_handle_rw_error(SCSIDiskReq *r, int error)
402 {
403     bool is_read = (r->req.cmd.xfer == SCSI_XFER_FROM_DEV);
404     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
405     BlockErrorAction action = bdrv_get_error_action(s->qdev.conf.bs, is_read, error);
406 
407     if (action == BDRV_ACTION_REPORT) {
408         switch (error) {
409         case ENOMEDIUM:
410             scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
411             break;
412         case ENOMEM:
413             scsi_check_condition(r, SENSE_CODE(TARGET_FAILURE));
414             break;
415         case EINVAL:
416             scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
417             break;
418         default:
419             scsi_check_condition(r, SENSE_CODE(IO_ERROR));
420             break;
421         }
422     }
423     bdrv_error_action(s->qdev.conf.bs, action, is_read, error);
424     if (action == BDRV_ACTION_STOP) {
425         scsi_req_retry(&r->req);
426     }
427     return action != BDRV_ACTION_IGNORE;
428 }
429 
430 static void scsi_write_complete(void * opaque, int ret)
431 {
432     SCSIDiskReq *r = (SCSIDiskReq *)opaque;
433     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
434     uint32_t n;
435 
436     if (r->req.aiocb != NULL) {
437         r->req.aiocb = NULL;
438         bdrv_acct_done(s->qdev.conf.bs, &r->acct);
439     }
440     if (r->req.io_canceled) {
441         goto done;
442     }
443 
444     if (ret < 0) {
445         if (scsi_handle_rw_error(r, -ret)) {
446             goto done;
447         }
448     }
449 
450     n = r->qiov.size / 512;
451     r->sector += n;
452     r->sector_count -= n;
453     if (r->sector_count == 0) {
454         scsi_write_do_fua(r);
455         return;
456     } else {
457         scsi_init_iovec(r, SCSI_DMA_BUF_SIZE);
458         DPRINTF("Write complete tag=0x%x more=%zd\n", r->req.tag, r->qiov.size);
459         scsi_req_data(&r->req, r->qiov.size);
460     }
461 
462 done:
463     if (!r->req.io_canceled) {
464         scsi_req_unref(&r->req);
465     }
466 }
467 
468 static void scsi_write_data(SCSIRequest *req)
469 {
470     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
471     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
472     uint32_t n;
473 
474     /* No data transfer may already be in progress */
475     assert(r->req.aiocb == NULL);
476 
477     /* The request is used as the AIO opaque value, so add a ref.  */
478     scsi_req_ref(&r->req);
479     if (r->req.cmd.mode != SCSI_XFER_TO_DEV) {
480         DPRINTF("Data transfer direction invalid\n");
481         scsi_write_complete(r, -EINVAL);
482         return;
483     }
484 
485     if (!r->req.sg && !r->qiov.size) {
486         /* Called for the first time.  Ask the driver to send us more data.  */
487         r->started = true;
488         scsi_write_complete(r, 0);
489         return;
490     }
491     if (s->tray_open) {
492         scsi_write_complete(r, -ENOMEDIUM);
493         return;
494     }
495 
496     if (r->req.cmd.buf[0] == VERIFY_10 || r->req.cmd.buf[0] == VERIFY_12 ||
497         r->req.cmd.buf[0] == VERIFY_16) {
498         if (r->req.sg) {
499             scsi_dma_complete(r, 0);
500         } else {
501             scsi_write_complete(r, 0);
502         }
503         return;
504     }
505 
506     if (r->req.sg) {
507         dma_acct_start(s->qdev.conf.bs, &r->acct, r->req.sg, BDRV_ACCT_WRITE);
508         r->req.resid -= r->req.sg->size;
509         r->req.aiocb = dma_bdrv_write(s->qdev.conf.bs, r->req.sg, r->sector,
510                                       scsi_dma_complete, r);
511     } else {
512         n = r->qiov.size / 512;
513         bdrv_acct_start(s->qdev.conf.bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_WRITE);
514         r->req.aiocb = bdrv_aio_writev(s->qdev.conf.bs, r->sector, &r->qiov, n,
515                                        scsi_write_complete, r);
516     }
517 }
518 
519 /* Return a pointer to the data buffer.  */
520 static uint8_t *scsi_get_buf(SCSIRequest *req)
521 {
522     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
523 
524     return (uint8_t *)r->iov.iov_base;
525 }
526 
527 static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)
528 {
529     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
530     int buflen = 0;
531     int start;
532 
533     if (req->cmd.buf[1] & 0x1) {
534         /* Vital product data */
535         uint8_t page_code = req->cmd.buf[2];
536 
537         outbuf[buflen++] = s->qdev.type & 0x1f;
538         outbuf[buflen++] = page_code ; // this page
539         outbuf[buflen++] = 0x00;
540         outbuf[buflen++] = 0x00;
541         start = buflen;
542 
543         switch (page_code) {
544         case 0x00: /* Supported page codes, mandatory */
545         {
546             DPRINTF("Inquiry EVPD[Supported pages] "
547                     "buffer size %zd\n", req->cmd.xfer);
548             outbuf[buflen++] = 0x00; // list of supported pages (this page)
549             if (s->serial) {
550                 outbuf[buflen++] = 0x80; // unit serial number
551             }
552             outbuf[buflen++] = 0x83; // device identification
553             if (s->qdev.type == TYPE_DISK) {
554                 outbuf[buflen++] = 0xb0; // block limits
555                 outbuf[buflen++] = 0xb2; // thin provisioning
556             }
557             break;
558         }
559         case 0x80: /* Device serial number, optional */
560         {
561             int l;
562 
563             if (!s->serial) {
564                 DPRINTF("Inquiry (EVPD[Serial number] not supported\n");
565                 return -1;
566             }
567 
568             l = strlen(s->serial);
569             if (l > 20) {
570                 l = 20;
571             }
572 
573             DPRINTF("Inquiry EVPD[Serial number] "
574                     "buffer size %zd\n", req->cmd.xfer);
575             memcpy(outbuf+buflen, s->serial, l);
576             buflen += l;
577             break;
578         }
579 
580         case 0x83: /* Device identification page, mandatory */
581         {
582             const char *str = s->serial ?: bdrv_get_device_name(s->qdev.conf.bs);
583             int max_len = s->serial ? 20 : 255 - 8;
584             int id_len = strlen(str);
585 
586             if (id_len > max_len) {
587                 id_len = max_len;
588             }
589             DPRINTF("Inquiry EVPD[Device identification] "
590                     "buffer size %zd\n", req->cmd.xfer);
591 
592             outbuf[buflen++] = 0x2; // ASCII
593             outbuf[buflen++] = 0;   // not officially assigned
594             outbuf[buflen++] = 0;   // reserved
595             outbuf[buflen++] = id_len; // length of data following
596             memcpy(outbuf+buflen, str, id_len);
597             buflen += id_len;
598 
599             if (s->wwn) {
600                 outbuf[buflen++] = 0x1; // Binary
601                 outbuf[buflen++] = 0x3; // NAA
602                 outbuf[buflen++] = 0;   // reserved
603                 outbuf[buflen++] = 8;
604                 stq_be_p(&outbuf[buflen], s->wwn);
605                 buflen += 8;
606             }
607             break;
608         }
609         case 0xb0: /* block limits */
610         {
611             unsigned int unmap_sectors =
612                     s->qdev.conf.discard_granularity / s->qdev.blocksize;
613             unsigned int min_io_size =
614                     s->qdev.conf.min_io_size / s->qdev.blocksize;
615             unsigned int opt_io_size =
616                     s->qdev.conf.opt_io_size / s->qdev.blocksize;
617 
618             if (s->qdev.type == TYPE_ROM) {
619                 DPRINTF("Inquiry (EVPD[%02X] not supported for CDROM\n",
620                         page_code);
621                 return -1;
622             }
623             /* required VPD size with unmap support */
624             buflen = 0x40;
625             memset(outbuf + 4, 0, buflen - 4);
626 
627             /* optimal transfer length granularity */
628             outbuf[6] = (min_io_size >> 8) & 0xff;
629             outbuf[7] = min_io_size & 0xff;
630 
631             /* optimal transfer length */
632             outbuf[12] = (opt_io_size >> 24) & 0xff;
633             outbuf[13] = (opt_io_size >> 16) & 0xff;
634             outbuf[14] = (opt_io_size >> 8) & 0xff;
635             outbuf[15] = opt_io_size & 0xff;
636 
637             /* optimal unmap granularity */
638             outbuf[28] = (unmap_sectors >> 24) & 0xff;
639             outbuf[29] = (unmap_sectors >> 16) & 0xff;
640             outbuf[30] = (unmap_sectors >> 8) & 0xff;
641             outbuf[31] = unmap_sectors & 0xff;
642             break;
643         }
644         case 0xb2: /* thin provisioning */
645         {
646             buflen = 8;
647             outbuf[4] = 0;
648             outbuf[5] = 0xe0; /* unmap & write_same 10/16 all supported */
649             outbuf[6] = s->qdev.conf.discard_granularity ? 2 : 1;
650             outbuf[7] = 0;
651             break;
652         }
653         default:
654             return -1;
655         }
656         /* done with EVPD */
657         assert(buflen - start <= 255);
658         outbuf[start - 1] = buflen - start;
659         return buflen;
660     }
661 
662     /* Standard INQUIRY data */
663     if (req->cmd.buf[2] != 0) {
664         return -1;
665     }
666 
667     /* PAGE CODE == 0 */
668     buflen = req->cmd.xfer;
669     if (buflen > SCSI_MAX_INQUIRY_LEN) {
670         buflen = SCSI_MAX_INQUIRY_LEN;
671     }
672 
673     outbuf[0] = s->qdev.type & 0x1f;
674     outbuf[1] = (s->features & (1 << SCSI_DISK_F_REMOVABLE)) ? 0x80 : 0;
675 
676     strpadcpy((char *) &outbuf[16], 16, s->product, ' ');
677     strpadcpy((char *) &outbuf[8], 8, s->vendor, ' ');
678 
679     memset(&outbuf[32], 0, 4);
680     memcpy(&outbuf[32], s->version, MIN(4, strlen(s->version)));
681     /*
682      * We claim conformance to SPC-3, which is required for guests
683      * to ask for modern features like READ CAPACITY(16) or the
684      * block characteristics VPD page by default.  Not all of SPC-3
685      * is actually implemented, but we're good enough.
686      */
687     outbuf[2] = 5;
688     outbuf[3] = 2 | 0x10; /* Format 2, HiSup */
689 
690     if (buflen > 36) {
691         outbuf[4] = buflen - 5; /* Additional Length = (Len - 1) - 4 */
692     } else {
693         /* If the allocation length of CDB is too small,
694                the additional length is not adjusted */
695         outbuf[4] = 36 - 5;
696     }
697 
698     /* Sync data transfer and TCQ.  */
699     outbuf[7] = 0x10 | (req->bus->info->tcq ? 0x02 : 0);
700     return buflen;
701 }
702 
703 static inline bool media_is_dvd(SCSIDiskState *s)
704 {
705     uint64_t nb_sectors;
706     if (s->qdev.type != TYPE_ROM) {
707         return false;
708     }
709     if (!bdrv_is_inserted(s->qdev.conf.bs)) {
710         return false;
711     }
712     bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
713     return nb_sectors > CD_MAX_SECTORS;
714 }
715 
716 static inline bool media_is_cd(SCSIDiskState *s)
717 {
718     uint64_t nb_sectors;
719     if (s->qdev.type != TYPE_ROM) {
720         return false;
721     }
722     if (!bdrv_is_inserted(s->qdev.conf.bs)) {
723         return false;
724     }
725     bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
726     return nb_sectors <= CD_MAX_SECTORS;
727 }
728 
729 static int scsi_read_disc_information(SCSIDiskState *s, SCSIDiskReq *r,
730                                       uint8_t *outbuf)
731 {
732     uint8_t type = r->req.cmd.buf[1] & 7;
733 
734     if (s->qdev.type != TYPE_ROM) {
735         return -1;
736     }
737 
738     /* Types 1/2 are only defined for Blu-Ray.  */
739     if (type != 0) {
740         scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
741         return -1;
742     }
743 
744     memset(outbuf, 0, 34);
745     outbuf[1] = 32;
746     outbuf[2] = 0xe; /* last session complete, disc finalized */
747     outbuf[3] = 1;   /* first track on disc */
748     outbuf[4] = 1;   /* # of sessions */
749     outbuf[5] = 1;   /* first track of last session */
750     outbuf[6] = 1;   /* last track of last session */
751     outbuf[7] = 0x20; /* unrestricted use */
752     outbuf[8] = 0x00; /* CD-ROM or DVD-ROM */
753     /* 9-10-11: most significant byte corresponding bytes 4-5-6 */
754     /* 12-23: not meaningful for CD-ROM or DVD-ROM */
755     /* 24-31: disc bar code */
756     /* 32: disc application code */
757     /* 33: number of OPC tables */
758 
759     return 34;
760 }
761 
762 static int scsi_read_dvd_structure(SCSIDiskState *s, SCSIDiskReq *r,
763                                    uint8_t *outbuf)
764 {
765     static const int rds_caps_size[5] = {
766         [0] = 2048 + 4,
767         [1] = 4 + 4,
768         [3] = 188 + 4,
769         [4] = 2048 + 4,
770     };
771 
772     uint8_t media = r->req.cmd.buf[1];
773     uint8_t layer = r->req.cmd.buf[6];
774     uint8_t format = r->req.cmd.buf[7];
775     int size = -1;
776 
777     if (s->qdev.type != TYPE_ROM) {
778         return -1;
779     }
780     if (media != 0) {
781         scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
782         return -1;
783     }
784 
785     if (format != 0xff) {
786         if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {
787             scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
788             return -1;
789         }
790         if (media_is_cd(s)) {
791             scsi_check_condition(r, SENSE_CODE(INCOMPATIBLE_FORMAT));
792             return -1;
793         }
794         if (format >= ARRAY_SIZE(rds_caps_size)) {
795             return -1;
796         }
797         size = rds_caps_size[format];
798         memset(outbuf, 0, size);
799     }
800 
801     switch (format) {
802     case 0x00: {
803         /* Physical format information */
804         uint64_t nb_sectors;
805         if (layer != 0) {
806             goto fail;
807         }
808         bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
809 
810         outbuf[4] = 1;   /* DVD-ROM, part version 1 */
811         outbuf[5] = 0xf; /* 120mm disc, minimum rate unspecified */
812         outbuf[6] = 1;   /* one layer, read-only (per MMC-2 spec) */
813         outbuf[7] = 0;   /* default densities */
814 
815         stl_be_p(&outbuf[12], (nb_sectors >> 2) - 1); /* end sector */
816         stl_be_p(&outbuf[16], (nb_sectors >> 2) - 1); /* l0 end sector */
817         break;
818     }
819 
820     case 0x01: /* DVD copyright information, all zeros */
821         break;
822 
823     case 0x03: /* BCA information - invalid field for no BCA info */
824         return -1;
825 
826     case 0x04: /* DVD disc manufacturing information, all zeros */
827         break;
828 
829     case 0xff: { /* List capabilities */
830         int i;
831         size = 4;
832         for (i = 0; i < ARRAY_SIZE(rds_caps_size); i++) {
833             if (!rds_caps_size[i]) {
834                 continue;
835             }
836             outbuf[size] = i;
837             outbuf[size + 1] = 0x40; /* Not writable, readable */
838             stw_be_p(&outbuf[size + 2], rds_caps_size[i]);
839             size += 4;
840         }
841         break;
842      }
843 
844     default:
845         return -1;
846     }
847 
848     /* Size of buffer, not including 2 byte size field */
849     stw_be_p(outbuf, size - 2);
850     return size;
851 
852 fail:
853     return -1;
854 }
855 
856 static int scsi_event_status_media(SCSIDiskState *s, uint8_t *outbuf)
857 {
858     uint8_t event_code, media_status;
859 
860     media_status = 0;
861     if (s->tray_open) {
862         media_status = MS_TRAY_OPEN;
863     } else if (bdrv_is_inserted(s->qdev.conf.bs)) {
864         media_status = MS_MEDIA_PRESENT;
865     }
866 
867     /* Event notification descriptor */
868     event_code = MEC_NO_CHANGE;
869     if (media_status != MS_TRAY_OPEN) {
870         if (s->media_event) {
871             event_code = MEC_NEW_MEDIA;
872             s->media_event = false;
873         } else if (s->eject_request) {
874             event_code = MEC_EJECT_REQUESTED;
875             s->eject_request = false;
876         }
877     }
878 
879     outbuf[0] = event_code;
880     outbuf[1] = media_status;
881 
882     /* These fields are reserved, just clear them. */
883     outbuf[2] = 0;
884     outbuf[3] = 0;
885     return 4;
886 }
887 
888 static int scsi_get_event_status_notification(SCSIDiskState *s, SCSIDiskReq *r,
889                                               uint8_t *outbuf)
890 {
891     int size;
892     uint8_t *buf = r->req.cmd.buf;
893     uint8_t notification_class_request = buf[4];
894     if (s->qdev.type != TYPE_ROM) {
895         return -1;
896     }
897     if ((buf[1] & 1) == 0) {
898         /* asynchronous */
899         return -1;
900     }
901 
902     size = 4;
903     outbuf[0] = outbuf[1] = 0;
904     outbuf[3] = 1 << GESN_MEDIA; /* supported events */
905     if (notification_class_request & (1 << GESN_MEDIA)) {
906         outbuf[2] = GESN_MEDIA;
907         size += scsi_event_status_media(s, &outbuf[size]);
908     } else {
909         outbuf[2] = 0x80;
910     }
911     stw_be_p(outbuf, size - 4);
912     return size;
913 }
914 
915 static int scsi_get_configuration(SCSIDiskState *s, uint8_t *outbuf)
916 {
917     int current;
918 
919     if (s->qdev.type != TYPE_ROM) {
920         return -1;
921     }
922     current = media_is_dvd(s) ? MMC_PROFILE_DVD_ROM : MMC_PROFILE_CD_ROM;
923     memset(outbuf, 0, 40);
924     stl_be_p(&outbuf[0], 36); /* Bytes after the data length field */
925     stw_be_p(&outbuf[6], current);
926     /* outbuf[8] - outbuf[19]: Feature 0 - Profile list */
927     outbuf[10] = 0x03; /* persistent, current */
928     outbuf[11] = 8; /* two profiles */
929     stw_be_p(&outbuf[12], MMC_PROFILE_DVD_ROM);
930     outbuf[14] = (current == MMC_PROFILE_DVD_ROM);
931     stw_be_p(&outbuf[16], MMC_PROFILE_CD_ROM);
932     outbuf[18] = (current == MMC_PROFILE_CD_ROM);
933     /* outbuf[20] - outbuf[31]: Feature 1 - Core feature */
934     stw_be_p(&outbuf[20], 1);
935     outbuf[22] = 0x08 | 0x03; /* version 2, persistent, current */
936     outbuf[23] = 8;
937     stl_be_p(&outbuf[24], 1); /* SCSI */
938     outbuf[28] = 1; /* DBE = 1, mandatory */
939     /* outbuf[32] - outbuf[39]: Feature 3 - Removable media feature */
940     stw_be_p(&outbuf[32], 3);
941     outbuf[34] = 0x08 | 0x03; /* version 2, persistent, current */
942     outbuf[35] = 4;
943     outbuf[36] = 0x39; /* tray, load=1, eject=1, unlocked at powerup, lock=1 */
944     /* TODO: Random readable, CD read, DVD read, drive serial number,
945        power management */
946     return 40;
947 }
948 
949 static int scsi_emulate_mechanism_status(SCSIDiskState *s, uint8_t *outbuf)
950 {
951     if (s->qdev.type != TYPE_ROM) {
952         return -1;
953     }
954     memset(outbuf, 0, 8);
955     outbuf[5] = 1; /* CD-ROM */
956     return 8;
957 }
958 
959 static int mode_sense_page(SCSIDiskState *s, int page, uint8_t **p_outbuf,
960                            int page_control)
961 {
962     static const int mode_sense_valid[0x3f] = {
963         [MODE_PAGE_HD_GEOMETRY]            = (1 << TYPE_DISK),
964         [MODE_PAGE_FLEXIBLE_DISK_GEOMETRY] = (1 << TYPE_DISK),
965         [MODE_PAGE_CACHING]                = (1 << TYPE_DISK) | (1 << TYPE_ROM),
966         [MODE_PAGE_R_W_ERROR]              = (1 << TYPE_DISK) | (1 << TYPE_ROM),
967         [MODE_PAGE_AUDIO_CTL]              = (1 << TYPE_ROM),
968         [MODE_PAGE_CAPABILITIES]           = (1 << TYPE_ROM),
969     };
970 
971     uint8_t *p = *p_outbuf + 2;
972     int length;
973 
974     if ((mode_sense_valid[page] & (1 << s->qdev.type)) == 0) {
975         return -1;
976     }
977 
978     /*
979      * If Changeable Values are requested, a mask denoting those mode parameters
980      * that are changeable shall be returned. As we currently don't support
981      * parameter changes via MODE_SELECT all bits are returned set to zero.
982      * The buffer was already menset to zero by the caller of this function.
983      *
984      * The offsets here are off by two compared to the descriptions in the
985      * SCSI specs, because those include a 2-byte header.  This is unfortunate,
986      * but it is done so that offsets are consistent within our implementation
987      * of MODE SENSE and MODE SELECT.  MODE SELECT has to deal with both
988      * 2-byte and 4-byte headers.
989      */
990     switch (page) {
991     case MODE_PAGE_HD_GEOMETRY:
992         length = 0x16;
993         if (page_control == 1) { /* Changeable Values */
994             break;
995         }
996         /* if a geometry hint is available, use it */
997         p[0] = (s->qdev.conf.cyls >> 16) & 0xff;
998         p[1] = (s->qdev.conf.cyls >> 8) & 0xff;
999         p[2] = s->qdev.conf.cyls & 0xff;
1000         p[3] = s->qdev.conf.heads & 0xff;
1001         /* Write precomp start cylinder, disabled */
1002         p[4] = (s->qdev.conf.cyls >> 16) & 0xff;
1003         p[5] = (s->qdev.conf.cyls >> 8) & 0xff;
1004         p[6] = s->qdev.conf.cyls & 0xff;
1005         /* Reduced current start cylinder, disabled */
1006         p[7] = (s->qdev.conf.cyls >> 16) & 0xff;
1007         p[8] = (s->qdev.conf.cyls >> 8) & 0xff;
1008         p[9] = s->qdev.conf.cyls & 0xff;
1009         /* Device step rate [ns], 200ns */
1010         p[10] = 0;
1011         p[11] = 200;
1012         /* Landing zone cylinder */
1013         p[12] = 0xff;
1014         p[13] =  0xff;
1015         p[14] = 0xff;
1016         /* Medium rotation rate [rpm], 5400 rpm */
1017         p[18] = (5400 >> 8) & 0xff;
1018         p[19] = 5400 & 0xff;
1019         break;
1020 
1021     case MODE_PAGE_FLEXIBLE_DISK_GEOMETRY:
1022         length = 0x1e;
1023         if (page_control == 1) { /* Changeable Values */
1024             break;
1025         }
1026         /* Transfer rate [kbit/s], 5Mbit/s */
1027         p[0] = 5000 >> 8;
1028         p[1] = 5000 & 0xff;
1029         /* if a geometry hint is available, use it */
1030         p[2] = s->qdev.conf.heads & 0xff;
1031         p[3] = s->qdev.conf.secs & 0xff;
1032         p[4] = s->qdev.blocksize >> 8;
1033         p[6] = (s->qdev.conf.cyls >> 8) & 0xff;
1034         p[7] = s->qdev.conf.cyls & 0xff;
1035         /* Write precomp start cylinder, disabled */
1036         p[8] = (s->qdev.conf.cyls >> 8) & 0xff;
1037         p[9] = s->qdev.conf.cyls & 0xff;
1038         /* Reduced current start cylinder, disabled */
1039         p[10] = (s->qdev.conf.cyls >> 8) & 0xff;
1040         p[11] = s->qdev.conf.cyls & 0xff;
1041         /* Device step rate [100us], 100us */
1042         p[12] = 0;
1043         p[13] = 1;
1044         /* Device step pulse width [us], 1us */
1045         p[14] = 1;
1046         /* Device head settle delay [100us], 100us */
1047         p[15] = 0;
1048         p[16] = 1;
1049         /* Motor on delay [0.1s], 0.1s */
1050         p[17] = 1;
1051         /* Motor off delay [0.1s], 0.1s */
1052         p[18] = 1;
1053         /* Medium rotation rate [rpm], 5400 rpm */
1054         p[26] = (5400 >> 8) & 0xff;
1055         p[27] = 5400 & 0xff;
1056         break;
1057 
1058     case MODE_PAGE_CACHING:
1059         length = 0x12;
1060         if (page_control == 1 || /* Changeable Values */
1061             bdrv_enable_write_cache(s->qdev.conf.bs)) {
1062             p[0] = 4; /* WCE */
1063         }
1064         break;
1065 
1066     case MODE_PAGE_R_W_ERROR:
1067         length = 10;
1068         if (page_control == 1) { /* Changeable Values */
1069             break;
1070         }
1071         p[0] = 0x80; /* Automatic Write Reallocation Enabled */
1072         if (s->qdev.type == TYPE_ROM) {
1073             p[1] = 0x20; /* Read Retry Count */
1074         }
1075         break;
1076 
1077     case MODE_PAGE_AUDIO_CTL:
1078         length = 14;
1079         break;
1080 
1081     case MODE_PAGE_CAPABILITIES:
1082         length = 0x14;
1083         if (page_control == 1) { /* Changeable Values */
1084             break;
1085         }
1086 
1087         p[0] = 0x3b; /* CD-R & CD-RW read */
1088         p[1] = 0; /* Writing not supported */
1089         p[2] = 0x7f; /* Audio, composite, digital out,
1090                         mode 2 form 1&2, multi session */
1091         p[3] = 0xff; /* CD DA, DA accurate, RW supported,
1092                         RW corrected, C2 errors, ISRC,
1093                         UPC, Bar code */
1094         p[4] = 0x2d | (s->tray_locked ? 2 : 0);
1095         /* Locking supported, jumper present, eject, tray */
1096         p[5] = 0; /* no volume & mute control, no
1097                      changer */
1098         p[6] = (50 * 176) >> 8; /* 50x read speed */
1099         p[7] = (50 * 176) & 0xff;
1100         p[8] = 2 >> 8; /* Two volume levels */
1101         p[9] = 2 & 0xff;
1102         p[10] = 2048 >> 8; /* 2M buffer */
1103         p[11] = 2048 & 0xff;
1104         p[12] = (16 * 176) >> 8; /* 16x read speed current */
1105         p[13] = (16 * 176) & 0xff;
1106         p[16] = (16 * 176) >> 8; /* 16x write speed */
1107         p[17] = (16 * 176) & 0xff;
1108         p[18] = (16 * 176) >> 8; /* 16x write speed current */
1109         p[19] = (16 * 176) & 0xff;
1110         break;
1111 
1112     default:
1113         return -1;
1114     }
1115 
1116     assert(length < 256);
1117     (*p_outbuf)[0] = page;
1118     (*p_outbuf)[1] = length;
1119     *p_outbuf += length + 2;
1120     return length + 2;
1121 }
1122 
1123 static int scsi_disk_emulate_mode_sense(SCSIDiskReq *r, uint8_t *outbuf)
1124 {
1125     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
1126     uint64_t nb_sectors;
1127     bool dbd;
1128     int page, buflen, ret, page_control;
1129     uint8_t *p;
1130     uint8_t dev_specific_param;
1131 
1132     dbd = (r->req.cmd.buf[1] & 0x8) != 0;
1133     page = r->req.cmd.buf[2] & 0x3f;
1134     page_control = (r->req.cmd.buf[2] & 0xc0) >> 6;
1135     DPRINTF("Mode Sense(%d) (page %d, xfer %zd, page_control %d)\n",
1136         (r->req.cmd.buf[0] == MODE_SENSE) ? 6 : 10, page, r->req.cmd.xfer, page_control);
1137     memset(outbuf, 0, r->req.cmd.xfer);
1138     p = outbuf;
1139 
1140     if (s->qdev.type == TYPE_DISK) {
1141         dev_specific_param = s->features & (1 << SCSI_DISK_F_DPOFUA) ? 0x10 : 0;
1142         if (bdrv_is_read_only(s->qdev.conf.bs)) {
1143             dev_specific_param |= 0x80; /* Readonly.  */
1144         }
1145     } else {
1146         /* MMC prescribes that CD/DVD drives have no block descriptors,
1147          * and defines no device-specific parameter.  */
1148         dev_specific_param = 0x00;
1149         dbd = true;
1150     }
1151 
1152     if (r->req.cmd.buf[0] == MODE_SENSE) {
1153         p[1] = 0; /* Default media type.  */
1154         p[2] = dev_specific_param;
1155         p[3] = 0; /* Block descriptor length.  */
1156         p += 4;
1157     } else { /* MODE_SENSE_10 */
1158         p[2] = 0; /* Default media type.  */
1159         p[3] = dev_specific_param;
1160         p[6] = p[7] = 0; /* Block descriptor length.  */
1161         p += 8;
1162     }
1163 
1164     bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1165     if (!dbd && nb_sectors) {
1166         if (r->req.cmd.buf[0] == MODE_SENSE) {
1167             outbuf[3] = 8; /* Block descriptor length  */
1168         } else { /* MODE_SENSE_10 */
1169             outbuf[7] = 8; /* Block descriptor length  */
1170         }
1171         nb_sectors /= (s->qdev.blocksize / 512);
1172         if (nb_sectors > 0xffffff) {
1173             nb_sectors = 0;
1174         }
1175         p[0] = 0; /* media density code */
1176         p[1] = (nb_sectors >> 16) & 0xff;
1177         p[2] = (nb_sectors >> 8) & 0xff;
1178         p[3] = nb_sectors & 0xff;
1179         p[4] = 0; /* reserved */
1180         p[5] = 0; /* bytes 5-7 are the sector size in bytes */
1181         p[6] = s->qdev.blocksize >> 8;
1182         p[7] = 0;
1183         p += 8;
1184     }
1185 
1186     if (page_control == 3) {
1187         /* Saved Values */
1188         scsi_check_condition(r, SENSE_CODE(SAVING_PARAMS_NOT_SUPPORTED));
1189         return -1;
1190     }
1191 
1192     if (page == 0x3f) {
1193         for (page = 0; page <= 0x3e; page++) {
1194             mode_sense_page(s, page, &p, page_control);
1195         }
1196     } else {
1197         ret = mode_sense_page(s, page, &p, page_control);
1198         if (ret == -1) {
1199             return -1;
1200         }
1201     }
1202 
1203     buflen = p - outbuf;
1204     /*
1205      * The mode data length field specifies the length in bytes of the
1206      * following data that is available to be transferred. The mode data
1207      * length does not include itself.
1208      */
1209     if (r->req.cmd.buf[0] == MODE_SENSE) {
1210         outbuf[0] = buflen - 1;
1211     } else { /* MODE_SENSE_10 */
1212         outbuf[0] = ((buflen - 2) >> 8) & 0xff;
1213         outbuf[1] = (buflen - 2) & 0xff;
1214     }
1215     return buflen;
1216 }
1217 
1218 static int scsi_disk_emulate_read_toc(SCSIRequest *req, uint8_t *outbuf)
1219 {
1220     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1221     int start_track, format, msf, toclen;
1222     uint64_t nb_sectors;
1223 
1224     msf = req->cmd.buf[1] & 2;
1225     format = req->cmd.buf[2] & 0xf;
1226     start_track = req->cmd.buf[6];
1227     bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1228     DPRINTF("Read TOC (track %d format %d msf %d)\n", start_track, format, msf >> 1);
1229     nb_sectors /= s->qdev.blocksize / 512;
1230     switch (format) {
1231     case 0:
1232         toclen = cdrom_read_toc(nb_sectors, outbuf, msf, start_track);
1233         break;
1234     case 1:
1235         /* multi session : only a single session defined */
1236         toclen = 12;
1237         memset(outbuf, 0, 12);
1238         outbuf[1] = 0x0a;
1239         outbuf[2] = 0x01;
1240         outbuf[3] = 0x01;
1241         break;
1242     case 2:
1243         toclen = cdrom_read_toc_raw(nb_sectors, outbuf, msf, start_track);
1244         break;
1245     default:
1246         return -1;
1247     }
1248     return toclen;
1249 }
1250 
1251 static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)
1252 {
1253     SCSIRequest *req = &r->req;
1254     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1255     bool start = req->cmd.buf[4] & 1;
1256     bool loej = req->cmd.buf[4] & 2; /* load on start, eject on !start */
1257     int pwrcnd = req->cmd.buf[4] & 0xf0;
1258 
1259     if (pwrcnd) {
1260         /* eject/load only happens for power condition == 0 */
1261         return 0;
1262     }
1263 
1264     if ((s->features & (1 << SCSI_DISK_F_REMOVABLE)) && loej) {
1265         if (!start && !s->tray_open && s->tray_locked) {
1266             scsi_check_condition(r,
1267                                  bdrv_is_inserted(s->qdev.conf.bs)
1268                                  ? SENSE_CODE(ILLEGAL_REQ_REMOVAL_PREVENTED)
1269                                  : SENSE_CODE(NOT_READY_REMOVAL_PREVENTED));
1270             return -1;
1271         }
1272 
1273         if (s->tray_open != !start) {
1274             bdrv_eject(s->qdev.conf.bs, !start);
1275             s->tray_open = !start;
1276         }
1277     }
1278     return 0;
1279 }
1280 
1281 static void scsi_disk_emulate_read_data(SCSIRequest *req)
1282 {
1283     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1284     int buflen = r->iov.iov_len;
1285 
1286     if (buflen) {
1287         DPRINTF("Read buf_len=%d\n", buflen);
1288         r->iov.iov_len = 0;
1289         r->started = true;
1290         scsi_req_data(&r->req, buflen);
1291         return;
1292     }
1293 
1294     /* This also clears the sense buffer for REQUEST SENSE.  */
1295     scsi_req_complete(&r->req, GOOD);
1296 }
1297 
1298 static int scsi_disk_check_mode_select(SCSIDiskState *s, int page,
1299                                        uint8_t *inbuf, int inlen)
1300 {
1301     uint8_t mode_current[SCSI_MAX_MODE_LEN];
1302     uint8_t mode_changeable[SCSI_MAX_MODE_LEN];
1303     uint8_t *p;
1304     int len, expected_len, changeable_len, i;
1305 
1306     /* The input buffer does not include the page header, so it is
1307      * off by 2 bytes.
1308      */
1309     expected_len = inlen + 2;
1310     if (expected_len > SCSI_MAX_MODE_LEN) {
1311         return -1;
1312     }
1313 
1314     p = mode_current;
1315     memset(mode_current, 0, inlen + 2);
1316     len = mode_sense_page(s, page, &p, 0);
1317     if (len < 0 || len != expected_len) {
1318         return -1;
1319     }
1320 
1321     p = mode_changeable;
1322     memset(mode_changeable, 0, inlen + 2);
1323     changeable_len = mode_sense_page(s, page, &p, 1);
1324     assert(changeable_len == len);
1325 
1326     /* Check that unchangeable bits are the same as what MODE SENSE
1327      * would return.
1328      */
1329     for (i = 2; i < len; i++) {
1330         if (((mode_current[i] ^ inbuf[i - 2]) & ~mode_changeable[i]) != 0) {
1331             return -1;
1332         }
1333     }
1334     return 0;
1335 }
1336 
1337 static void scsi_disk_apply_mode_select(SCSIDiskState *s, int page, uint8_t *p)
1338 {
1339     switch (page) {
1340     case MODE_PAGE_CACHING:
1341         bdrv_set_enable_write_cache(s->qdev.conf.bs, (p[0] & 4) != 0);
1342         break;
1343 
1344     default:
1345         break;
1346     }
1347 }
1348 
1349 static int mode_select_pages(SCSIDiskReq *r, uint8_t *p, int len, bool change)
1350 {
1351     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
1352 
1353     while (len > 0) {
1354         int page, subpage, page_len;
1355 
1356         /* Parse both possible formats for the mode page headers.  */
1357         page = p[0] & 0x3f;
1358         if (p[0] & 0x40) {
1359             if (len < 4) {
1360                 goto invalid_param_len;
1361             }
1362             subpage = p[1];
1363             page_len = lduw_be_p(&p[2]);
1364             p += 4;
1365             len -= 4;
1366         } else {
1367             if (len < 2) {
1368                 goto invalid_param_len;
1369             }
1370             subpage = 0;
1371             page_len = p[1];
1372             p += 2;
1373             len -= 2;
1374         }
1375 
1376         if (subpage) {
1377             goto invalid_param;
1378         }
1379         if (page_len > len) {
1380             goto invalid_param_len;
1381         }
1382 
1383         if (!change) {
1384             if (scsi_disk_check_mode_select(s, page, p, page_len) < 0) {
1385                 goto invalid_param;
1386             }
1387         } else {
1388             scsi_disk_apply_mode_select(s, page, p);
1389         }
1390 
1391         p += page_len;
1392         len -= page_len;
1393     }
1394     return 0;
1395 
1396 invalid_param:
1397     scsi_check_condition(r, SENSE_CODE(INVALID_PARAM));
1398     return -1;
1399 
1400 invalid_param_len:
1401     scsi_check_condition(r, SENSE_CODE(INVALID_PARAM_LEN));
1402     return -1;
1403 }
1404 
1405 static void scsi_disk_emulate_mode_select(SCSIDiskReq *r, uint8_t *inbuf)
1406 {
1407     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
1408     uint8_t *p = inbuf;
1409     int cmd = r->req.cmd.buf[0];
1410     int len = r->req.cmd.xfer;
1411     int hdr_len = (cmd == MODE_SELECT ? 4 : 8);
1412     int bd_len;
1413     int pass;
1414 
1415     /* We only support PF=1, SP=0.  */
1416     if ((r->req.cmd.buf[1] & 0x11) != 0x10) {
1417         goto invalid_field;
1418     }
1419 
1420     if (len < hdr_len) {
1421         goto invalid_param_len;
1422     }
1423 
1424     bd_len = (cmd == MODE_SELECT ? p[3] : lduw_be_p(&p[6]));
1425     len -= hdr_len;
1426     p += hdr_len;
1427     if (len < bd_len) {
1428         goto invalid_param_len;
1429     }
1430     if (bd_len != 0 && bd_len != 8) {
1431         goto invalid_param;
1432     }
1433 
1434     len -= bd_len;
1435     p += bd_len;
1436 
1437     /* Ensure no change is made if there is an error!  */
1438     for (pass = 0; pass < 2; pass++) {
1439         if (mode_select_pages(r, p, len, pass == 1) < 0) {
1440             assert(pass == 0);
1441             return;
1442         }
1443     }
1444     if (!bdrv_enable_write_cache(s->qdev.conf.bs)) {
1445         /* The request is used as the AIO opaque value, so add a ref.  */
1446         scsi_req_ref(&r->req);
1447         bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
1448         r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);
1449         return;
1450     }
1451 
1452     scsi_req_complete(&r->req, GOOD);
1453     return;
1454 
1455 invalid_param:
1456     scsi_check_condition(r, SENSE_CODE(INVALID_PARAM));
1457     return;
1458 
1459 invalid_param_len:
1460     scsi_check_condition(r, SENSE_CODE(INVALID_PARAM_LEN));
1461     return;
1462 
1463 invalid_field:
1464     scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1465 }
1466 
1467 static inline bool check_lba_range(SCSIDiskState *s,
1468                                    uint64_t sector_num, uint32_t nb_sectors)
1469 {
1470     /*
1471      * The first line tests that no overflow happens when computing the last
1472      * sector.  The second line tests that the last accessed sector is in
1473      * range.
1474      *
1475      * Careful, the computations should not underflow for nb_sectors == 0,
1476      * and a 0-block read to the first LBA beyond the end of device is
1477      * valid.
1478      */
1479     return (sector_num <= sector_num + nb_sectors &&
1480             sector_num + nb_sectors <= s->qdev.max_lba + 1);
1481 }
1482 
1483 typedef struct UnmapCBData {
1484     SCSIDiskReq *r;
1485     uint8_t *inbuf;
1486     int count;
1487 } UnmapCBData;
1488 
1489 static void scsi_unmap_complete(void *opaque, int ret)
1490 {
1491     UnmapCBData *data = opaque;
1492     SCSIDiskReq *r = data->r;
1493     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
1494     uint64_t sector_num;
1495     uint32_t nb_sectors;
1496 
1497     r->req.aiocb = NULL;
1498     if (r->req.io_canceled) {
1499         goto done;
1500     }
1501 
1502     if (ret < 0) {
1503         if (scsi_handle_rw_error(r, -ret)) {
1504             goto done;
1505         }
1506     }
1507 
1508     if (data->count > 0) {
1509         sector_num = ldq_be_p(&data->inbuf[0]);
1510         nb_sectors = ldl_be_p(&data->inbuf[8]) & 0xffffffffULL;
1511         if (!check_lba_range(s, sector_num, nb_sectors)) {
1512             scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
1513             goto done;
1514         }
1515 
1516         r->req.aiocb = bdrv_aio_discard(s->qdev.conf.bs,
1517                                         sector_num * (s->qdev.blocksize / 512),
1518                                         nb_sectors * (s->qdev.blocksize / 512),
1519                                         scsi_unmap_complete, data);
1520         data->count--;
1521         data->inbuf += 16;
1522         return;
1523     }
1524 
1525     scsi_req_complete(&r->req, GOOD);
1526 
1527 done:
1528     if (!r->req.io_canceled) {
1529         scsi_req_unref(&r->req);
1530     }
1531     g_free(data);
1532 }
1533 
1534 static void scsi_disk_emulate_unmap(SCSIDiskReq *r, uint8_t *inbuf)
1535 {
1536     uint8_t *p = inbuf;
1537     int len = r->req.cmd.xfer;
1538     UnmapCBData *data;
1539 
1540     if (len < 8) {
1541         goto invalid_param_len;
1542     }
1543     if (len < lduw_be_p(&p[0]) + 2) {
1544         goto invalid_param_len;
1545     }
1546     if (len < lduw_be_p(&p[2]) + 8) {
1547         goto invalid_param_len;
1548     }
1549     if (lduw_be_p(&p[2]) & 15) {
1550         goto invalid_param_len;
1551     }
1552 
1553     data = g_new0(UnmapCBData, 1);
1554     data->r = r;
1555     data->inbuf = &p[8];
1556     data->count = lduw_be_p(&p[2]) >> 4;
1557 
1558     /* The matching unref is in scsi_unmap_complete, before data is freed.  */
1559     scsi_req_ref(&r->req);
1560     scsi_unmap_complete(data, 0);
1561     return;
1562 
1563 invalid_param_len:
1564     scsi_check_condition(r, SENSE_CODE(INVALID_PARAM_LEN));
1565 }
1566 
1567 static void scsi_disk_emulate_write_data(SCSIRequest *req)
1568 {
1569     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1570 
1571     if (r->iov.iov_len) {
1572         int buflen = r->iov.iov_len;
1573         DPRINTF("Write buf_len=%d\n", buflen);
1574         r->iov.iov_len = 0;
1575         scsi_req_data(&r->req, buflen);
1576         return;
1577     }
1578 
1579     switch (req->cmd.buf[0]) {
1580     case MODE_SELECT:
1581     case MODE_SELECT_10:
1582         /* This also clears the sense buffer for REQUEST SENSE.  */
1583         scsi_disk_emulate_mode_select(r, r->iov.iov_base);
1584         break;
1585 
1586     case UNMAP:
1587         scsi_disk_emulate_unmap(r, r->iov.iov_base);
1588         break;
1589 
1590     default:
1591         abort();
1592     }
1593 }
1594 
1595 static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
1596 {
1597     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1598     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1599     uint64_t nb_sectors;
1600     uint8_t *outbuf;
1601     int buflen;
1602 
1603     switch (req->cmd.buf[0]) {
1604     case INQUIRY:
1605     case MODE_SENSE:
1606     case MODE_SENSE_10:
1607     case RESERVE:
1608     case RESERVE_10:
1609     case RELEASE:
1610     case RELEASE_10:
1611     case START_STOP:
1612     case ALLOW_MEDIUM_REMOVAL:
1613     case GET_CONFIGURATION:
1614     case GET_EVENT_STATUS_NOTIFICATION:
1615     case MECHANISM_STATUS:
1616     case REQUEST_SENSE:
1617         break;
1618 
1619     default:
1620         if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {
1621             scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
1622             return 0;
1623         }
1624         break;
1625     }
1626 
1627     /*
1628      * FIXME: we shouldn't return anything bigger than 4k, but the code
1629      * requires the buffer to be as big as req->cmd.xfer in several
1630      * places.  So, do not allow CDBs with a very large ALLOCATION
1631      * LENGTH.  The real fix would be to modify scsi_read_data and
1632      * dma_buf_read, so that they return data beyond the buflen
1633      * as all zeros.
1634      */
1635     if (req->cmd.xfer > 65536) {
1636         goto illegal_request;
1637     }
1638     r->buflen = MAX(4096, req->cmd.xfer);
1639 
1640     if (!r->iov.iov_base) {
1641         r->iov.iov_base = qemu_blockalign(s->qdev.conf.bs, r->buflen);
1642     }
1643 
1644     buflen = req->cmd.xfer;
1645     outbuf = r->iov.iov_base;
1646     memset(outbuf, 0, r->buflen);
1647     switch (req->cmd.buf[0]) {
1648     case TEST_UNIT_READY:
1649         assert(!s->tray_open && bdrv_is_inserted(s->qdev.conf.bs));
1650         break;
1651     case INQUIRY:
1652         buflen = scsi_disk_emulate_inquiry(req, outbuf);
1653         if (buflen < 0) {
1654             goto illegal_request;
1655         }
1656         break;
1657     case MODE_SENSE:
1658     case MODE_SENSE_10:
1659         buflen = scsi_disk_emulate_mode_sense(r, outbuf);
1660         if (buflen < 0) {
1661             goto illegal_request;
1662         }
1663         break;
1664     case READ_TOC:
1665         buflen = scsi_disk_emulate_read_toc(req, outbuf);
1666         if (buflen < 0) {
1667             goto illegal_request;
1668         }
1669         break;
1670     case RESERVE:
1671         if (req->cmd.buf[1] & 1) {
1672             goto illegal_request;
1673         }
1674         break;
1675     case RESERVE_10:
1676         if (req->cmd.buf[1] & 3) {
1677             goto illegal_request;
1678         }
1679         break;
1680     case RELEASE:
1681         if (req->cmd.buf[1] & 1) {
1682             goto illegal_request;
1683         }
1684         break;
1685     case RELEASE_10:
1686         if (req->cmd.buf[1] & 3) {
1687             goto illegal_request;
1688         }
1689         break;
1690     case START_STOP:
1691         if (scsi_disk_emulate_start_stop(r) < 0) {
1692             return 0;
1693         }
1694         break;
1695     case ALLOW_MEDIUM_REMOVAL:
1696         s->tray_locked = req->cmd.buf[4] & 1;
1697         bdrv_lock_medium(s->qdev.conf.bs, req->cmd.buf[4] & 1);
1698         break;
1699     case READ_CAPACITY_10:
1700         /* The normal LEN field for this command is zero.  */
1701         memset(outbuf, 0, 8);
1702         bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1703         if (!nb_sectors) {
1704             scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));
1705             return 0;
1706         }
1707         if ((req->cmd.buf[8] & 1) == 0 && req->cmd.lba) {
1708             goto illegal_request;
1709         }
1710         nb_sectors /= s->qdev.blocksize / 512;
1711         /* Returned value is the address of the last sector.  */
1712         nb_sectors--;
1713         /* Remember the new size for read/write sanity checking. */
1714         s->qdev.max_lba = nb_sectors;
1715         /* Clip to 2TB, instead of returning capacity modulo 2TB. */
1716         if (nb_sectors > UINT32_MAX) {
1717             nb_sectors = UINT32_MAX;
1718         }
1719         outbuf[0] = (nb_sectors >> 24) & 0xff;
1720         outbuf[1] = (nb_sectors >> 16) & 0xff;
1721         outbuf[2] = (nb_sectors >> 8) & 0xff;
1722         outbuf[3] = nb_sectors & 0xff;
1723         outbuf[4] = 0;
1724         outbuf[5] = 0;
1725         outbuf[6] = s->qdev.blocksize >> 8;
1726         outbuf[7] = 0;
1727         break;
1728     case REQUEST_SENSE:
1729         /* Just return "NO SENSE".  */
1730         buflen = scsi_build_sense(NULL, 0, outbuf, r->buflen,
1731                                   (req->cmd.buf[1] & 1) == 0);
1732         if (buflen < 0) {
1733             goto illegal_request;
1734         }
1735         break;
1736     case MECHANISM_STATUS:
1737         buflen = scsi_emulate_mechanism_status(s, outbuf);
1738         if (buflen < 0) {
1739             goto illegal_request;
1740         }
1741         break;
1742     case GET_CONFIGURATION:
1743         buflen = scsi_get_configuration(s, outbuf);
1744         if (buflen < 0) {
1745             goto illegal_request;
1746         }
1747         break;
1748     case GET_EVENT_STATUS_NOTIFICATION:
1749         buflen = scsi_get_event_status_notification(s, r, outbuf);
1750         if (buflen < 0) {
1751             goto illegal_request;
1752         }
1753         break;
1754     case READ_DISC_INFORMATION:
1755         buflen = scsi_read_disc_information(s, r, outbuf);
1756         if (buflen < 0) {
1757             goto illegal_request;
1758         }
1759         break;
1760     case READ_DVD_STRUCTURE:
1761         buflen = scsi_read_dvd_structure(s, r, outbuf);
1762         if (buflen < 0) {
1763             goto illegal_request;
1764         }
1765         break;
1766     case SERVICE_ACTION_IN_16:
1767         /* Service Action In subcommands. */
1768         if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) {
1769             DPRINTF("SAI READ CAPACITY(16)\n");
1770             memset(outbuf, 0, req->cmd.xfer);
1771             bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1772             if (!nb_sectors) {
1773                 scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));
1774                 return 0;
1775             }
1776             if ((req->cmd.buf[14] & 1) == 0 && req->cmd.lba) {
1777                 goto illegal_request;
1778             }
1779             nb_sectors /= s->qdev.blocksize / 512;
1780             /* Returned value is the address of the last sector.  */
1781             nb_sectors--;
1782             /* Remember the new size for read/write sanity checking. */
1783             s->qdev.max_lba = nb_sectors;
1784             outbuf[0] = (nb_sectors >> 56) & 0xff;
1785             outbuf[1] = (nb_sectors >> 48) & 0xff;
1786             outbuf[2] = (nb_sectors >> 40) & 0xff;
1787             outbuf[3] = (nb_sectors >> 32) & 0xff;
1788             outbuf[4] = (nb_sectors >> 24) & 0xff;
1789             outbuf[5] = (nb_sectors >> 16) & 0xff;
1790             outbuf[6] = (nb_sectors >> 8) & 0xff;
1791             outbuf[7] = nb_sectors & 0xff;
1792             outbuf[8] = 0;
1793             outbuf[9] = 0;
1794             outbuf[10] = s->qdev.blocksize >> 8;
1795             outbuf[11] = 0;
1796             outbuf[12] = 0;
1797             outbuf[13] = get_physical_block_exp(&s->qdev.conf);
1798 
1799             /* set TPE bit if the format supports discard */
1800             if (s->qdev.conf.discard_granularity) {
1801                 outbuf[14] = 0x80;
1802             }
1803 
1804             /* Protection, exponent and lowest lba field left blank. */
1805             break;
1806         }
1807         DPRINTF("Unsupported Service Action In\n");
1808         goto illegal_request;
1809     case SYNCHRONIZE_CACHE:
1810         /* The request is used as the AIO opaque value, so add a ref.  */
1811         scsi_req_ref(&r->req);
1812         bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);
1813         r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);
1814         return 0;
1815     case SEEK_10:
1816         DPRINTF("Seek(10) (sector %" PRId64 ")\n", r->req.cmd.lba);
1817         if (r->req.cmd.lba > s->qdev.max_lba) {
1818             goto illegal_lba;
1819         }
1820         break;
1821     case MODE_SELECT:
1822         DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);
1823         break;
1824     case MODE_SELECT_10:
1825         DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);
1826         break;
1827     case UNMAP:
1828         DPRINTF("Unmap (len %lu)\n", (long)r->req.cmd.xfer);
1829         break;
1830     case WRITE_SAME_10:
1831     case WRITE_SAME_16:
1832         nb_sectors = scsi_data_cdb_length(r->req.cmd.buf);
1833         if (bdrv_is_read_only(s->qdev.conf.bs)) {
1834             scsi_check_condition(r, SENSE_CODE(WRITE_PROTECTED));
1835             return 0;
1836         }
1837         if (!check_lba_range(s, r->req.cmd.lba, nb_sectors)) {
1838             goto illegal_lba;
1839         }
1840 
1841         /*
1842          * We only support WRITE SAME with the unmap bit set for now.
1843          */
1844         if (!(req->cmd.buf[1] & 0x8)) {
1845             goto illegal_request;
1846         }
1847 
1848         /* The request is used as the AIO opaque value, so add a ref.  */
1849         scsi_req_ref(&r->req);
1850         r->req.aiocb = bdrv_aio_discard(s->qdev.conf.bs,
1851                                         r->req.cmd.lba * (s->qdev.blocksize / 512),
1852                                         nb_sectors * (s->qdev.blocksize / 512),
1853                                         scsi_aio_complete, r);
1854         return 0;
1855     default:
1856         DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
1857         scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
1858         return 0;
1859     }
1860     assert(!r->req.aiocb);
1861     r->iov.iov_len = MIN(r->buflen, req->cmd.xfer);
1862     if (r->iov.iov_len == 0) {
1863         scsi_req_complete(&r->req, GOOD);
1864     }
1865     if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
1866         assert(r->iov.iov_len == req->cmd.xfer);
1867         return -r->iov.iov_len;
1868     } else {
1869         return r->iov.iov_len;
1870     }
1871 
1872 illegal_request:
1873     if (r->req.status == -1) {
1874         scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1875     }
1876     return 0;
1877 
1878 illegal_lba:
1879     scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
1880     return 0;
1881 }
1882 
1883 /* Execute a scsi command.  Returns the length of the data expected by the
1884    command.  This will be Positive for data transfers from the device
1885    (eg. disk reads), negative for transfers to the device (eg. disk writes),
1886    and zero if the command does not transfer any data.  */
1887 
1888 static int32_t scsi_disk_dma_command(SCSIRequest *req, uint8_t *buf)
1889 {
1890     SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
1891     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
1892     uint32_t len;
1893     uint8_t command;
1894 
1895     command = buf[0];
1896 
1897     if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {
1898         scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));
1899         return 0;
1900     }
1901 
1902     len = scsi_data_cdb_length(r->req.cmd.buf);
1903     switch (command) {
1904     case READ_6:
1905     case READ_10:
1906     case READ_12:
1907     case READ_16:
1908         DPRINTF("Read (sector %" PRId64 ", count %u)\n", r->req.cmd.lba, len);
1909         if (r->req.cmd.buf[1] & 0xe0) {
1910             goto illegal_request;
1911         }
1912         if (!check_lba_range(s, r->req.cmd.lba, len)) {
1913             goto illegal_lba;
1914         }
1915         r->sector = r->req.cmd.lba * (s->qdev.blocksize / 512);
1916         r->sector_count = len * (s->qdev.blocksize / 512);
1917         break;
1918     case WRITE_6:
1919     case WRITE_10:
1920     case WRITE_12:
1921     case WRITE_16:
1922     case WRITE_VERIFY_10:
1923     case WRITE_VERIFY_12:
1924     case WRITE_VERIFY_16:
1925         if (bdrv_is_read_only(s->qdev.conf.bs)) {
1926             scsi_check_condition(r, SENSE_CODE(WRITE_PROTECTED));
1927             return 0;
1928         }
1929         /* fallthrough */
1930     case VERIFY_10:
1931     case VERIFY_12:
1932     case VERIFY_16:
1933         DPRINTF("Write %s(sector %" PRId64 ", count %u)\n",
1934                 (command & 0xe) == 0xe ? "And Verify " : "",
1935                 r->req.cmd.lba, len);
1936         if (r->req.cmd.buf[1] & 0xe0) {
1937             goto illegal_request;
1938         }
1939         if (!check_lba_range(s, r->req.cmd.lba, len)) {
1940             goto illegal_lba;
1941         }
1942         r->sector = r->req.cmd.lba * (s->qdev.blocksize / 512);
1943         r->sector_count = len * (s->qdev.blocksize / 512);
1944         break;
1945     default:
1946         abort();
1947     illegal_request:
1948         scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
1949         return 0;
1950     illegal_lba:
1951         scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
1952         return 0;
1953     }
1954     if (r->sector_count == 0) {
1955         scsi_req_complete(&r->req, GOOD);
1956     }
1957     assert(r->iov.iov_len == 0);
1958     if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
1959         return -r->sector_count * 512;
1960     } else {
1961         return r->sector_count * 512;
1962     }
1963 }
1964 
1965 static void scsi_disk_reset(DeviceState *dev)
1966 {
1967     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev.qdev, dev);
1968     uint64_t nb_sectors;
1969 
1970     scsi_device_purge_requests(&s->qdev, SENSE_CODE(RESET));
1971 
1972     bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);
1973     nb_sectors /= s->qdev.blocksize / 512;
1974     if (nb_sectors) {
1975         nb_sectors--;
1976     }
1977     s->qdev.max_lba = nb_sectors;
1978 }
1979 
1980 static void scsi_destroy(SCSIDevice *dev)
1981 {
1982     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
1983 
1984     scsi_device_purge_requests(&s->qdev, SENSE_CODE(NO_SENSE));
1985     blockdev_mark_auto_del(s->qdev.conf.bs);
1986 }
1987 
1988 static void scsi_disk_resize_cb(void *opaque)
1989 {
1990     SCSIDiskState *s = opaque;
1991 
1992     /* SPC lists this sense code as available only for
1993      * direct-access devices.
1994      */
1995     if (s->qdev.type == TYPE_DISK) {
1996         scsi_device_report_change(&s->qdev, SENSE_CODE(CAPACITY_CHANGED));
1997     }
1998 }
1999 
2000 static void scsi_cd_change_media_cb(void *opaque, bool load)
2001 {
2002     SCSIDiskState *s = opaque;
2003 
2004     /*
2005      * When a CD gets changed, we have to report an ejected state and
2006      * then a loaded state to guests so that they detect tray
2007      * open/close and media change events.  Guests that do not use
2008      * GET_EVENT_STATUS_NOTIFICATION to detect such tray open/close
2009      * states rely on this behavior.
2010      *
2011      * media_changed governs the state machine used for unit attention
2012      * report.  media_event is used by GET EVENT STATUS NOTIFICATION.
2013      */
2014     s->media_changed = load;
2015     s->tray_open = !load;
2016     scsi_device_set_ua(&s->qdev, SENSE_CODE(UNIT_ATTENTION_NO_MEDIUM));
2017     s->media_event = true;
2018     s->eject_request = false;
2019 }
2020 
2021 static void scsi_cd_eject_request_cb(void *opaque, bool force)
2022 {
2023     SCSIDiskState *s = opaque;
2024 
2025     s->eject_request = true;
2026     if (force) {
2027         s->tray_locked = false;
2028     }
2029 }
2030 
2031 static bool scsi_cd_is_tray_open(void *opaque)
2032 {
2033     return ((SCSIDiskState *)opaque)->tray_open;
2034 }
2035 
2036 static bool scsi_cd_is_medium_locked(void *opaque)
2037 {
2038     return ((SCSIDiskState *)opaque)->tray_locked;
2039 }
2040 
2041 static const BlockDevOps scsi_disk_removable_block_ops = {
2042     .change_media_cb = scsi_cd_change_media_cb,
2043     .eject_request_cb = scsi_cd_eject_request_cb,
2044     .is_tray_open = scsi_cd_is_tray_open,
2045     .is_medium_locked = scsi_cd_is_medium_locked,
2046 
2047     .resize_cb = scsi_disk_resize_cb,
2048 };
2049 
2050 static const BlockDevOps scsi_disk_block_ops = {
2051     .resize_cb = scsi_disk_resize_cb,
2052 };
2053 
2054 static void scsi_disk_unit_attention_reported(SCSIDevice *dev)
2055 {
2056     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2057     if (s->media_changed) {
2058         s->media_changed = false;
2059         scsi_device_set_ua(&s->qdev, SENSE_CODE(MEDIUM_CHANGED));
2060     }
2061 }
2062 
2063 static int scsi_initfn(SCSIDevice *dev)
2064 {
2065     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2066 
2067     if (!s->qdev.conf.bs) {
2068         error_report("drive property not set");
2069         return -1;
2070     }
2071 
2072     if (!(s->features & (1 << SCSI_DISK_F_REMOVABLE)) &&
2073         !bdrv_is_inserted(s->qdev.conf.bs)) {
2074         error_report("Device needs media, but drive is empty");
2075         return -1;
2076     }
2077 
2078     blkconf_serial(&s->qdev.conf, &s->serial);
2079     if (dev->type == TYPE_DISK
2080         && blkconf_geometry(&dev->conf, NULL, 65535, 255, 255) < 0) {
2081         return -1;
2082     }
2083 
2084     if (s->qdev.conf.discard_granularity == -1) {
2085         s->qdev.conf.discard_granularity =
2086             MAX(s->qdev.conf.logical_block_size, DEFAULT_DISCARD_GRANULARITY);
2087     }
2088 
2089     if (!s->version) {
2090         s->version = g_strdup(qemu_get_version());
2091     }
2092     if (!s->vendor) {
2093         s->vendor = g_strdup("QEMU");
2094     }
2095 
2096     if (bdrv_is_sg(s->qdev.conf.bs)) {
2097         error_report("unwanted /dev/sg*");
2098         return -1;
2099     }
2100 
2101     if (s->features & (1 << SCSI_DISK_F_REMOVABLE)) {
2102         bdrv_set_dev_ops(s->qdev.conf.bs, &scsi_disk_removable_block_ops, s);
2103     } else {
2104         bdrv_set_dev_ops(s->qdev.conf.bs, &scsi_disk_block_ops, s);
2105     }
2106     bdrv_set_buffer_alignment(s->qdev.conf.bs, s->qdev.blocksize);
2107 
2108     bdrv_iostatus_enable(s->qdev.conf.bs);
2109     add_boot_device_path(s->qdev.conf.bootindex, &dev->qdev, NULL);
2110     return 0;
2111 }
2112 
2113 static int scsi_hd_initfn(SCSIDevice *dev)
2114 {
2115     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2116     s->qdev.blocksize = s->qdev.conf.logical_block_size;
2117     s->qdev.type = TYPE_DISK;
2118     if (!s->product) {
2119         s->product = g_strdup("QEMU HARDDISK");
2120     }
2121     return scsi_initfn(&s->qdev);
2122 }
2123 
2124 static int scsi_cd_initfn(SCSIDevice *dev)
2125 {
2126     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2127     s->qdev.blocksize = 2048;
2128     s->qdev.type = TYPE_ROM;
2129     s->features |= 1 << SCSI_DISK_F_REMOVABLE;
2130     if (!s->product) {
2131         s->product = g_strdup("QEMU CD-ROM");
2132     }
2133     return scsi_initfn(&s->qdev);
2134 }
2135 
2136 static int scsi_disk_initfn(SCSIDevice *dev)
2137 {
2138     DriveInfo *dinfo;
2139 
2140     if (!dev->conf.bs) {
2141         return scsi_initfn(dev);  /* ... and die there */
2142     }
2143 
2144     dinfo = drive_get_by_blockdev(dev->conf.bs);
2145     if (dinfo->media_cd) {
2146         return scsi_cd_initfn(dev);
2147     } else {
2148         return scsi_hd_initfn(dev);
2149     }
2150 }
2151 
2152 static const SCSIReqOps scsi_disk_emulate_reqops = {
2153     .size         = sizeof(SCSIDiskReq),
2154     .free_req     = scsi_free_request,
2155     .send_command = scsi_disk_emulate_command,
2156     .read_data    = scsi_disk_emulate_read_data,
2157     .write_data   = scsi_disk_emulate_write_data,
2158     .get_buf      = scsi_get_buf,
2159 };
2160 
2161 static const SCSIReqOps scsi_disk_dma_reqops = {
2162     .size         = sizeof(SCSIDiskReq),
2163     .free_req     = scsi_free_request,
2164     .send_command = scsi_disk_dma_command,
2165     .read_data    = scsi_read_data,
2166     .write_data   = scsi_write_data,
2167     .cancel_io    = scsi_cancel_io,
2168     .get_buf      = scsi_get_buf,
2169     .load_request = scsi_disk_load_request,
2170     .save_request = scsi_disk_save_request,
2171 };
2172 
2173 static const SCSIReqOps *const scsi_disk_reqops_dispatch[256] = {
2174     [TEST_UNIT_READY]                 = &scsi_disk_emulate_reqops,
2175     [INQUIRY]                         = &scsi_disk_emulate_reqops,
2176     [MODE_SENSE]                      = &scsi_disk_emulate_reqops,
2177     [MODE_SENSE_10]                   = &scsi_disk_emulate_reqops,
2178     [START_STOP]                      = &scsi_disk_emulate_reqops,
2179     [ALLOW_MEDIUM_REMOVAL]            = &scsi_disk_emulate_reqops,
2180     [READ_CAPACITY_10]                = &scsi_disk_emulate_reqops,
2181     [READ_TOC]                        = &scsi_disk_emulate_reqops,
2182     [READ_DVD_STRUCTURE]              = &scsi_disk_emulate_reqops,
2183     [READ_DISC_INFORMATION]           = &scsi_disk_emulate_reqops,
2184     [GET_CONFIGURATION]               = &scsi_disk_emulate_reqops,
2185     [GET_EVENT_STATUS_NOTIFICATION]   = &scsi_disk_emulate_reqops,
2186     [MECHANISM_STATUS]                = &scsi_disk_emulate_reqops,
2187     [SERVICE_ACTION_IN_16]            = &scsi_disk_emulate_reqops,
2188     [REQUEST_SENSE]                   = &scsi_disk_emulate_reqops,
2189     [SYNCHRONIZE_CACHE]               = &scsi_disk_emulate_reqops,
2190     [SEEK_10]                         = &scsi_disk_emulate_reqops,
2191     [MODE_SELECT]                     = &scsi_disk_emulate_reqops,
2192     [MODE_SELECT_10]                  = &scsi_disk_emulate_reqops,
2193     [UNMAP]                           = &scsi_disk_emulate_reqops,
2194     [WRITE_SAME_10]                   = &scsi_disk_emulate_reqops,
2195     [WRITE_SAME_16]                   = &scsi_disk_emulate_reqops,
2196 
2197     [READ_6]                          = &scsi_disk_dma_reqops,
2198     [READ_10]                         = &scsi_disk_dma_reqops,
2199     [READ_12]                         = &scsi_disk_dma_reqops,
2200     [READ_16]                         = &scsi_disk_dma_reqops,
2201     [VERIFY_10]                       = &scsi_disk_dma_reqops,
2202     [VERIFY_12]                       = &scsi_disk_dma_reqops,
2203     [VERIFY_16]                       = &scsi_disk_dma_reqops,
2204     [WRITE_6]                         = &scsi_disk_dma_reqops,
2205     [WRITE_10]                        = &scsi_disk_dma_reqops,
2206     [WRITE_12]                        = &scsi_disk_dma_reqops,
2207     [WRITE_16]                        = &scsi_disk_dma_reqops,
2208     [WRITE_VERIFY_10]                 = &scsi_disk_dma_reqops,
2209     [WRITE_VERIFY_12]                 = &scsi_disk_dma_reqops,
2210     [WRITE_VERIFY_16]                 = &scsi_disk_dma_reqops,
2211 };
2212 
2213 static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun,
2214                                      uint8_t *buf, void *hba_private)
2215 {
2216     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
2217     SCSIRequest *req;
2218     const SCSIReqOps *ops;
2219     uint8_t command;
2220 
2221     command = buf[0];
2222     ops = scsi_disk_reqops_dispatch[command];
2223     if (!ops) {
2224         ops = &scsi_disk_emulate_reqops;
2225     }
2226     req = scsi_req_alloc(ops, &s->qdev, tag, lun, hba_private);
2227 
2228 #ifdef DEBUG_SCSI
2229     DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", lun, tag, buf[0]);
2230     {
2231         int i;
2232         for (i = 1; i < req->cmd.len; i++) {
2233             printf(" 0x%02x", buf[i]);
2234         }
2235         printf("\n");
2236     }
2237 #endif
2238 
2239     return req;
2240 }
2241 
2242 #ifdef __linux__
2243 static int get_device_type(SCSIDiskState *s)
2244 {
2245     BlockDriverState *bdrv = s->qdev.conf.bs;
2246     uint8_t cmd[16];
2247     uint8_t buf[36];
2248     uint8_t sensebuf[8];
2249     sg_io_hdr_t io_header;
2250     int ret;
2251 
2252     memset(cmd, 0, sizeof(cmd));
2253     memset(buf, 0, sizeof(buf));
2254     cmd[0] = INQUIRY;
2255     cmd[4] = sizeof(buf);
2256 
2257     memset(&io_header, 0, sizeof(io_header));
2258     io_header.interface_id = 'S';
2259     io_header.dxfer_direction = SG_DXFER_FROM_DEV;
2260     io_header.dxfer_len = sizeof(buf);
2261     io_header.dxferp = buf;
2262     io_header.cmdp = cmd;
2263     io_header.cmd_len = sizeof(cmd);
2264     io_header.mx_sb_len = sizeof(sensebuf);
2265     io_header.sbp = sensebuf;
2266     io_header.timeout = 6000; /* XXX */
2267 
2268     ret = bdrv_ioctl(bdrv, SG_IO, &io_header);
2269     if (ret < 0 || io_header.driver_status || io_header.host_status) {
2270         return -1;
2271     }
2272     s->qdev.type = buf[0];
2273     if (buf[1] & 0x80) {
2274         s->features |= 1 << SCSI_DISK_F_REMOVABLE;
2275     }
2276     return 0;
2277 }
2278 
2279 static int scsi_block_initfn(SCSIDevice *dev)
2280 {
2281     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);
2282     int sg_version;
2283     int rc;
2284 
2285     if (!s->qdev.conf.bs) {
2286         error_report("scsi-block: drive property not set");
2287         return -1;
2288     }
2289 
2290     /* check we are using a driver managing SG_IO (version 3 and after) */
2291     if (bdrv_ioctl(s->qdev.conf.bs, SG_GET_VERSION_NUM, &sg_version) < 0 ||
2292         sg_version < 30000) {
2293         error_report("scsi-block: scsi generic interface too old");
2294         return -1;
2295     }
2296 
2297     /* get device type from INQUIRY data */
2298     rc = get_device_type(s);
2299     if (rc < 0) {
2300         error_report("scsi-block: INQUIRY failed");
2301         return -1;
2302     }
2303 
2304     /* Make a guess for the block size, we'll fix it when the guest sends.
2305      * READ CAPACITY.  If they don't, they likely would assume these sizes
2306      * anyway. (TODO: check in /sys).
2307      */
2308     if (s->qdev.type == TYPE_ROM || s->qdev.type == TYPE_WORM) {
2309         s->qdev.blocksize = 2048;
2310     } else {
2311         s->qdev.blocksize = 512;
2312     }
2313     return scsi_initfn(&s->qdev);
2314 }
2315 
2316 static SCSIRequest *scsi_block_new_request(SCSIDevice *d, uint32_t tag,
2317                                            uint32_t lun, uint8_t *buf,
2318                                            void *hba_private)
2319 {
2320     SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
2321 
2322     switch (buf[0]) {
2323     case READ_6:
2324     case READ_10:
2325     case READ_12:
2326     case READ_16:
2327     case VERIFY_10:
2328     case VERIFY_12:
2329     case VERIFY_16:
2330     case WRITE_6:
2331     case WRITE_10:
2332     case WRITE_12:
2333     case WRITE_16:
2334     case WRITE_VERIFY_10:
2335     case WRITE_VERIFY_12:
2336     case WRITE_VERIFY_16:
2337         /* If we are not using O_DIRECT, we might read stale data from the
2338 	 * host cache if writes were made using other commands than these
2339 	 * ones (such as WRITE SAME or EXTENDED COPY, etc.).  So, without
2340 	 * O_DIRECT everything must go through SG_IO.
2341          */
2342         if (bdrv_get_flags(s->qdev.conf.bs) & BDRV_O_NOCACHE) {
2343             break;
2344         }
2345 
2346         /* MMC writing cannot be done via pread/pwrite, because it sometimes
2347          * involves writing beyond the maximum LBA or to negative LBA (lead-in).
2348          * And once you do these writes, reading from the block device is
2349          * unreliable, too.  It is even possible that reads deliver random data
2350          * from the host page cache (this is probably a Linux bug).
2351          *
2352          * We might use scsi_disk_dma_reqops as long as no writing commands are
2353          * seen, but performance usually isn't paramount on optical media.  So,
2354          * just make scsi-block operate the same as scsi-generic for them.
2355          */
2356         if (s->qdev.type != TYPE_ROM) {
2357             return scsi_req_alloc(&scsi_disk_dma_reqops, &s->qdev, tag, lun,
2358                                   hba_private);
2359         }
2360     }
2361 
2362     return scsi_req_alloc(&scsi_generic_req_ops, &s->qdev, tag, lun,
2363                           hba_private);
2364 }
2365 #endif
2366 
2367 #define DEFINE_SCSI_DISK_PROPERTIES()                                \
2368     DEFINE_BLOCK_PROPERTIES(SCSIDiskState, qdev.conf),               \
2369     DEFINE_PROP_STRING("ver", SCSIDiskState, version),               \
2370     DEFINE_PROP_STRING("serial", SCSIDiskState, serial),             \
2371     DEFINE_PROP_STRING("vendor", SCSIDiskState, vendor),             \
2372     DEFINE_PROP_STRING("product", SCSIDiskState, product)
2373 
2374 static Property scsi_hd_properties[] = {
2375     DEFINE_SCSI_DISK_PROPERTIES(),
2376     DEFINE_PROP_BIT("removable", SCSIDiskState, features,
2377                     SCSI_DISK_F_REMOVABLE, false),
2378     DEFINE_PROP_BIT("dpofua", SCSIDiskState, features,
2379                     SCSI_DISK_F_DPOFUA, false),
2380     DEFINE_PROP_HEX64("wwn", SCSIDiskState, wwn, 0),
2381     DEFINE_BLOCK_CHS_PROPERTIES(SCSIDiskState, qdev.conf),
2382     DEFINE_PROP_END_OF_LIST(),
2383 };
2384 
2385 static const VMStateDescription vmstate_scsi_disk_state = {
2386     .name = "scsi-disk",
2387     .version_id = 1,
2388     .minimum_version_id = 1,
2389     .minimum_version_id_old = 1,
2390     .fields = (VMStateField[]) {
2391         VMSTATE_SCSI_DEVICE(qdev, SCSIDiskState),
2392         VMSTATE_BOOL(media_changed, SCSIDiskState),
2393         VMSTATE_BOOL(media_event, SCSIDiskState),
2394         VMSTATE_BOOL(eject_request, SCSIDiskState),
2395         VMSTATE_BOOL(tray_open, SCSIDiskState),
2396         VMSTATE_BOOL(tray_locked, SCSIDiskState),
2397         VMSTATE_END_OF_LIST()
2398     }
2399 };
2400 
2401 static void scsi_hd_class_initfn(ObjectClass *klass, void *data)
2402 {
2403     DeviceClass *dc = DEVICE_CLASS(klass);
2404     SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
2405 
2406     sc->init         = scsi_hd_initfn;
2407     sc->destroy      = scsi_destroy;
2408     sc->alloc_req    = scsi_new_request;
2409     sc->unit_attention_reported = scsi_disk_unit_attention_reported;
2410     dc->fw_name = "disk";
2411     dc->desc = "virtual SCSI disk";
2412     dc->reset = scsi_disk_reset;
2413     dc->props = scsi_hd_properties;
2414     dc->vmsd  = &vmstate_scsi_disk_state;
2415 }
2416 
2417 static const TypeInfo scsi_hd_info = {
2418     .name          = "scsi-hd",
2419     .parent        = TYPE_SCSI_DEVICE,
2420     .instance_size = sizeof(SCSIDiskState),
2421     .class_init    = scsi_hd_class_initfn,
2422 };
2423 
2424 static Property scsi_cd_properties[] = {
2425     DEFINE_SCSI_DISK_PROPERTIES(),
2426     DEFINE_PROP_HEX64("wwn", SCSIDiskState, wwn, 0),
2427     DEFINE_PROP_END_OF_LIST(),
2428 };
2429 
2430 static void scsi_cd_class_initfn(ObjectClass *klass, void *data)
2431 {
2432     DeviceClass *dc = DEVICE_CLASS(klass);
2433     SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
2434 
2435     sc->init         = scsi_cd_initfn;
2436     sc->destroy      = scsi_destroy;
2437     sc->alloc_req    = scsi_new_request;
2438     sc->unit_attention_reported = scsi_disk_unit_attention_reported;
2439     dc->fw_name = "disk";
2440     dc->desc = "virtual SCSI CD-ROM";
2441     dc->reset = scsi_disk_reset;
2442     dc->props = scsi_cd_properties;
2443     dc->vmsd  = &vmstate_scsi_disk_state;
2444 }
2445 
2446 static const TypeInfo scsi_cd_info = {
2447     .name          = "scsi-cd",
2448     .parent        = TYPE_SCSI_DEVICE,
2449     .instance_size = sizeof(SCSIDiskState),
2450     .class_init    = scsi_cd_class_initfn,
2451 };
2452 
2453 #ifdef __linux__
2454 static Property scsi_block_properties[] = {
2455     DEFINE_PROP_DRIVE("drive", SCSIDiskState, qdev.conf.bs),
2456     DEFINE_PROP_INT32("bootindex", SCSIDiskState, qdev.conf.bootindex, -1),
2457     DEFINE_PROP_END_OF_LIST(),
2458 };
2459 
2460 static void scsi_block_class_initfn(ObjectClass *klass, void *data)
2461 {
2462     DeviceClass *dc = DEVICE_CLASS(klass);
2463     SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
2464 
2465     sc->init         = scsi_block_initfn;
2466     sc->destroy      = scsi_destroy;
2467     sc->alloc_req    = scsi_block_new_request;
2468     dc->fw_name = "disk";
2469     dc->desc = "SCSI block device passthrough";
2470     dc->reset = scsi_disk_reset;
2471     dc->props = scsi_block_properties;
2472     dc->vmsd  = &vmstate_scsi_disk_state;
2473 }
2474 
2475 static const TypeInfo scsi_block_info = {
2476     .name          = "scsi-block",
2477     .parent        = TYPE_SCSI_DEVICE,
2478     .instance_size = sizeof(SCSIDiskState),
2479     .class_init    = scsi_block_class_initfn,
2480 };
2481 #endif
2482 
2483 static Property scsi_disk_properties[] = {
2484     DEFINE_SCSI_DISK_PROPERTIES(),
2485     DEFINE_PROP_BIT("removable", SCSIDiskState, features,
2486                     SCSI_DISK_F_REMOVABLE, false),
2487     DEFINE_PROP_BIT("dpofua", SCSIDiskState, features,
2488                     SCSI_DISK_F_DPOFUA, false),
2489     DEFINE_PROP_HEX64("wwn", SCSIDiskState, wwn, 0),
2490     DEFINE_PROP_END_OF_LIST(),
2491 };
2492 
2493 static void scsi_disk_class_initfn(ObjectClass *klass, void *data)
2494 {
2495     DeviceClass *dc = DEVICE_CLASS(klass);
2496     SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
2497 
2498     sc->init         = scsi_disk_initfn;
2499     sc->destroy      = scsi_destroy;
2500     sc->alloc_req    = scsi_new_request;
2501     sc->unit_attention_reported = scsi_disk_unit_attention_reported;
2502     dc->fw_name = "disk";
2503     dc->desc = "virtual SCSI disk or CD-ROM (legacy)";
2504     dc->reset = scsi_disk_reset;
2505     dc->props = scsi_disk_properties;
2506     dc->vmsd  = &vmstate_scsi_disk_state;
2507 }
2508 
2509 static const TypeInfo scsi_disk_info = {
2510     .name          = "scsi-disk",
2511     .parent        = TYPE_SCSI_DEVICE,
2512     .instance_size = sizeof(SCSIDiskState),
2513     .class_init    = scsi_disk_class_initfn,
2514 };
2515 
2516 static void scsi_disk_register_types(void)
2517 {
2518     type_register_static(&scsi_hd_info);
2519     type_register_static(&scsi_cd_info);
2520 #ifdef __linux__
2521     type_register_static(&scsi_block_info);
2522 #endif
2523     type_register_static(&scsi_disk_info);
2524 }
2525 
2526 type_init(scsi_disk_register_types)
2527