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