SCSI divide capacity by s->cluster_size (Rik van Riel)
[qemu] / hw / scsi-disk.c
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  *
9  * This code is licenced under the LGPL.
10  *
11  * Note that this file only handles the SCSI architecture model and device
12  * commands.  Emulation of interface/link layer protocols is handled by
13  * the host adapter emulator.
14  */
15
16 #include <qemu-common.h>
17 #include <sysemu.h>
18 //#define DEBUG_SCSI
19
20 #ifdef DEBUG_SCSI
21 #define DPRINTF(fmt, args...) \
22 do { printf("scsi-disk: " fmt , ##args); } while (0)
23 #else
24 #define DPRINTF(fmt, args...) do {} while(0)
25 #endif
26
27 #define BADF(fmt, args...) \
28 do { fprintf(stderr, "scsi-disk: " fmt , ##args); } while (0)
29
30 #include "qemu-common.h"
31 #include "block.h"
32 #include "scsi-disk.h"
33
34 #define SENSE_NO_SENSE        0
35 #define SENSE_NOT_READY       2
36 #define SENSE_HARDWARE_ERROR  4
37 #define SENSE_ILLEGAL_REQUEST 5
38
39 #define STATUS_GOOD            0
40 #define STATUS_CHECK_CONDITION 2
41
42 #define SCSI_DMA_BUF_SIZE    131072
43 #define SCSI_MAX_INQUIRY_LEN 256
44
45 #define SCSI_REQ_STATUS_RETRY 0x01
46
47 typedef struct SCSIRequest {
48     SCSIDeviceState *dev;
49     uint32_t tag;
50     /* ??? We should probably keep track of whether the data transfer is
51        a read or a write.  Currently we rely on the host getting it right.  */
52     /* Both sector and sector_count are in terms of qemu 512 byte blocks.  */
53     uint64_t sector;
54     uint32_t sector_count;
55     /* The amounnt of data in the buffer.  */
56     int buf_len;
57     uint8_t *dma_buf;
58     BlockDriverAIOCB *aiocb;
59     struct SCSIRequest *next;
60     uint32_t status;
61 } SCSIRequest;
62
63 struct SCSIDeviceState
64 {
65     BlockDriverState *bdrv;
66     SCSIRequest *requests;
67     /* The qemu block layer uses a fixed 512 byte sector size.
68        This is the number of 512 byte blocks in a single scsi sector.  */
69     int cluster_size;
70     int sense;
71     int tcq;
72     /* Completion functions may be called from either scsi_{read,write}_data
73        or from the AIO completion routines.  */
74     scsi_completionfn completion;
75     void *opaque;
76     char drive_serial_str[21];
77 };
78
79 /* Global pool of SCSIRequest structures.  */
80 static SCSIRequest *free_requests = NULL;
81
82 static SCSIRequest *scsi_new_request(SCSIDeviceState *s, uint32_t tag)
83 {
84     SCSIRequest *r;
85
86     if (free_requests) {
87         r = free_requests;
88         free_requests = r->next;
89     } else {
90         r = qemu_malloc(sizeof(SCSIRequest));
91         r->dma_buf = qemu_memalign(512, SCSI_DMA_BUF_SIZE);
92     }
93     r->dev = s;
94     r->tag = tag;
95     r->sector_count = 0;
96     r->buf_len = 0;
97     r->aiocb = NULL;
98     r->status = 0;
99
100     r->next = s->requests;
101     s->requests = r;
102     return r;
103 }
104
105 static void scsi_remove_request(SCSIRequest *r)
106 {
107     SCSIRequest *last;
108     SCSIDeviceState *s = r->dev;
109
110     if (s->requests == r) {
111         s->requests = r->next;
112     } else {
113         last = s->requests;
114         while (last && last->next != r)
115             last = last->next;
116         if (last) {
117             last->next = r->next;
118         } else {
119             BADF("Orphaned request\n");
120         }
121     }
122     r->next = free_requests;
123     free_requests = r;
124 }
125
126 static SCSIRequest *scsi_find_request(SCSIDeviceState *s, uint32_t tag)
127 {
128     SCSIRequest *r;
129
130     r = s->requests;
131     while (r && r->tag != tag)
132         r = r->next;
133
134     return r;
135 }
136
137 /* Helper function for command completion.  */
138 static void scsi_command_complete(SCSIRequest *r, int status, int sense)
139 {
140     SCSIDeviceState *s = r->dev;
141     uint32_t tag;
142     DPRINTF("Command complete tag=0x%x status=%d sense=%d\n", r->tag, status, sense);
143     s->sense = sense;
144     tag = r->tag;
145     scsi_remove_request(r);
146     s->completion(s->opaque, SCSI_REASON_DONE, tag, status);
147 }
148
149 /* Cancel a pending data transfer.  */
150 static void scsi_cancel_io(SCSIDevice *d, uint32_t tag)
151 {
152     SCSIDeviceState *s = d->state;
153     SCSIRequest *r;
154     DPRINTF("Cancel tag=0x%x\n", tag);
155     r = scsi_find_request(s, tag);
156     if (r) {
157         if (r->aiocb)
158             bdrv_aio_cancel(r->aiocb);
159         r->aiocb = NULL;
160         scsi_remove_request(r);
161     }
162 }
163
164 static void scsi_read_complete(void * opaque, int ret)
165 {
166     SCSIRequest *r = (SCSIRequest *)opaque;
167     SCSIDeviceState *s = r->dev;
168
169     if (ret) {
170         DPRINTF("IO error\n");
171         s->completion(s->opaque, SCSI_REASON_DATA, r->tag, 0);
172         scsi_command_complete(r, STATUS_CHECK_CONDITION, SENSE_NO_SENSE);
173         return;
174     }
175     DPRINTF("Data ready tag=0x%x len=%d\n", r->tag, r->buf_len);
176
177     s->completion(s->opaque, SCSI_REASON_DATA, r->tag, r->buf_len);
178 }
179
180 /* Read more data from scsi device into buffer.  */
181 static void scsi_read_data(SCSIDevice *d, uint32_t tag)
182 {
183     SCSIDeviceState *s = d->state;
184     SCSIRequest *r;
185     uint32_t n;
186
187     r = scsi_find_request(s, tag);
188     if (!r) {
189         BADF("Bad read tag 0x%x\n", tag);
190         /* ??? This is the wrong error.  */
191         scsi_command_complete(r, STATUS_CHECK_CONDITION, SENSE_HARDWARE_ERROR);
192         return;
193     }
194     if (r->sector_count == (uint32_t)-1) {
195         DPRINTF("Read buf_len=%d\n", r->buf_len);
196         r->sector_count = 0;
197         s->completion(s->opaque, SCSI_REASON_DATA, r->tag, r->buf_len);
198         return;
199     }
200     DPRINTF("Read sector_count=%d\n", r->sector_count);
201     if (r->sector_count == 0) {
202         scsi_command_complete(r, STATUS_GOOD, SENSE_NO_SENSE);
203         return;
204     }
205
206     n = r->sector_count;
207     if (n > SCSI_DMA_BUF_SIZE / 512)
208         n = SCSI_DMA_BUF_SIZE / 512;
209
210     r->buf_len = n * 512;
211     r->aiocb = bdrv_aio_read(s->bdrv, r->sector, r->dma_buf, n,
212                              scsi_read_complete, r);
213     if (r->aiocb == NULL)
214         scsi_command_complete(r, STATUS_CHECK_CONDITION, SENSE_HARDWARE_ERROR);
215     r->sector += n;
216     r->sector_count -= n;
217 }
218
219 static int scsi_handle_write_error(SCSIRequest *r, int error)
220 {
221     BlockInterfaceErrorAction action = drive_get_onerror(r->dev->bdrv);
222
223     if (action == BLOCK_ERR_IGNORE)
224         return 0;
225
226     if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)
227             || action == BLOCK_ERR_STOP_ANY) {
228         r->status |= SCSI_REQ_STATUS_RETRY;
229         vm_stop(0);
230     } else {
231         scsi_command_complete(r, STATUS_CHECK_CONDITION,
232                 SENSE_HARDWARE_ERROR);
233     }
234
235     return 1;
236 }
237
238 static void scsi_write_complete(void * opaque, int ret)
239 {
240     SCSIRequest *r = (SCSIRequest *)opaque;
241     SCSIDeviceState *s = r->dev;
242     uint32_t len;
243     uint32_t n;
244
245     r->aiocb = NULL;
246
247     if (ret) {
248         if (scsi_handle_write_error(r, -ret))
249             return;
250     }
251
252     n = r->buf_len / 512;
253     r->sector += n;
254     r->sector_count -= n;
255     if (r->sector_count == 0) {
256         scsi_command_complete(r, STATUS_GOOD, SENSE_NO_SENSE);
257     } else {
258         len = r->sector_count * 512;
259         if (len > SCSI_DMA_BUF_SIZE) {
260             len = SCSI_DMA_BUF_SIZE;
261         }
262         r->buf_len = len;
263         DPRINTF("Write complete tag=0x%x more=%d\n", r->tag, len);
264         s->completion(s->opaque, SCSI_REASON_DATA, r->tag, len);
265     }
266 }
267
268 static void scsi_write_request(SCSIRequest *r)
269 {
270     SCSIDeviceState *s = r->dev;
271     uint32_t n;
272
273     n = r->buf_len / 512;
274     if (n) {
275         r->aiocb = bdrv_aio_write(s->bdrv, r->sector, r->dma_buf, n,
276                                   scsi_write_complete, r);
277         if (r->aiocb == NULL)
278             scsi_command_complete(r, STATUS_CHECK_CONDITION,
279                                   SENSE_HARDWARE_ERROR);
280     } else {
281         /* Invoke completion routine to fetch data from host.  */
282         scsi_write_complete(r, 0);
283     }
284 }
285
286 /* Write data to a scsi device.  Returns nonzero on failure.
287    The transfer may complete asynchronously.  */
288 static int scsi_write_data(SCSIDevice *d, uint32_t tag)
289 {
290     SCSIDeviceState *s = d->state;
291     SCSIRequest *r;
292
293     DPRINTF("Write data tag=0x%x\n", tag);
294     r = scsi_find_request(s, tag);
295     if (!r) {
296         BADF("Bad write tag 0x%x\n", tag);
297         scsi_command_complete(r, STATUS_CHECK_CONDITION, SENSE_HARDWARE_ERROR);
298         return 1;
299     }
300
301     if (r->aiocb)
302         BADF("Data transfer already in progress\n");
303
304     scsi_write_request(r);
305
306     return 0;
307 }
308
309 static void scsi_dma_restart_cb(void *opaque, int running, int reason)
310 {
311     SCSIDeviceState *s = opaque;
312     SCSIRequest *r = s->requests;
313     if (!running)
314         return;
315
316     while (r) {
317         if (r->status & SCSI_REQ_STATUS_RETRY) {
318             r->status &= ~SCSI_REQ_STATUS_RETRY;
319             scsi_write_request(r); 
320         }
321         r = r->next;
322     }
323 }
324
325 /* Return a pointer to the data buffer.  */
326 static uint8_t *scsi_get_buf(SCSIDevice *d, uint32_t tag)
327 {
328     SCSIDeviceState *s = d->state;
329     SCSIRequest *r;
330
331     r = scsi_find_request(s, tag);
332     if (!r) {
333         BADF("Bad buffer tag 0x%x\n", tag);
334         return NULL;
335     }
336     return r->dma_buf;
337 }
338
339 /* Execute a scsi command.  Returns the length of the data expected by the
340    command.  This will be Positive for data transfers from the device
341    (eg. disk reads), negative for transfers to the device (eg. disk writes),
342    and zero if the command does not transfer any data.  */
343
344 static int32_t scsi_send_command(SCSIDevice *d, uint32_t tag,
345                                  uint8_t *buf, int lun)
346 {
347     SCSIDeviceState *s = d->state;
348     uint64_t nb_sectors;
349     uint64_t lba;
350     uint32_t len;
351     int cmdlen;
352     int is_write;
353     uint8_t command;
354     uint8_t *outbuf;
355     SCSIRequest *r;
356
357     command = buf[0];
358     r = scsi_find_request(s, tag);
359     if (r) {
360         BADF("Tag 0x%x already in use\n", tag);
361         scsi_cancel_io(d, tag);
362     }
363     /* ??? Tags are not unique for different luns.  We only implement a
364        single lun, so this should not matter.  */
365     r = scsi_new_request(s, tag);
366     outbuf = r->dma_buf;
367     is_write = 0;
368     DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", lun, tag, buf[0]);
369     switch (command >> 5) {
370     case 0:
371         lba = (uint64_t) buf[3] | ((uint64_t) buf[2] << 8) |
372               (((uint64_t) buf[1] & 0x1f) << 16);
373         len = buf[4];
374         cmdlen = 6;
375         break;
376     case 1:
377     case 2:
378         lba = (uint64_t) buf[5] | ((uint64_t) buf[4] << 8) |
379               ((uint64_t) buf[3] << 16) | ((uint64_t) buf[2] << 24);
380         len = buf[8] | (buf[7] << 8);
381         cmdlen = 10;
382         break;
383     case 4:
384         lba = (uint64_t) buf[9] | ((uint64_t) buf[8] << 8) |
385               ((uint64_t) buf[7] << 16) | ((uint64_t) buf[6] << 24) |
386               ((uint64_t) buf[5] << 32) | ((uint64_t) buf[4] << 40) |
387               ((uint64_t) buf[3] << 48) | ((uint64_t) buf[2] << 56);
388         len = buf[13] | (buf[12] << 8) | (buf[11] << 16) | (buf[10] << 24);
389         cmdlen = 16;
390         break;
391     case 5:
392         lba = (uint64_t) buf[5] | ((uint64_t) buf[4] << 8) |
393               ((uint64_t) buf[3] << 16) | ((uint64_t) buf[2] << 24);
394         len = buf[9] | (buf[8] << 8) | (buf[7] << 16) | (buf[6] << 24);
395         cmdlen = 12;
396         break;
397     default:
398         BADF("Unsupported command length, command %x\n", command);
399         goto fail;
400     }
401 #ifdef DEBUG_SCSI
402     {
403         int i;
404         for (i = 1; i < cmdlen; i++) {
405             printf(" 0x%02x", buf[i]);
406         }
407         printf("\n");
408     }
409 #endif
410     if (lun || buf[1] >> 5) {
411         /* Only LUN 0 supported.  */
412         DPRINTF("Unimplemented LUN %d\n", lun ? lun : buf[1] >> 5);
413         if (command != 0x03 && command != 0x12) /* REQUEST SENSE and INQUIRY */
414             goto fail;
415     }
416     switch (command) {
417     case 0x0:
418         DPRINTF("Test Unit Ready\n");
419         break;
420     case 0x03:
421         DPRINTF("Request Sense (len %d)\n", len);
422         if (len < 4)
423             goto fail;
424         memset(outbuf, 0, 4);
425         outbuf[0] = 0xf0;
426         outbuf[1] = 0;
427         outbuf[2] = s->sense;
428         r->buf_len = 4;
429         break;
430     case 0x12:
431         DPRINTF("Inquiry (len %d)\n", len);
432         if (buf[1] & 0x2) {
433             /* Command support data - optional, not implemented */
434             BADF("optional INQUIRY command support request not implemented\n");
435             goto fail;
436         }
437         else if (buf[1] & 0x1) {
438             /* Vital product data */
439             uint8_t page_code = buf[2];
440             if (len < 4) {
441                 BADF("Error: Inquiry (EVPD[%02X]) buffer size %d is "
442                      "less than 4\n", page_code, len);
443                 goto fail;
444             }
445
446             switch (page_code) {
447                 case 0x00:
448                     {
449                         /* Supported page codes, mandatory */
450                         DPRINTF("Inquiry EVPD[Supported pages] "
451                                 "buffer size %d\n", len);
452
453                         r->buf_len = 0;
454
455                         if (bdrv_get_type_hint(s->bdrv) == BDRV_TYPE_CDROM) {
456                             outbuf[r->buf_len++] = 5;
457                         } else {
458                             outbuf[r->buf_len++] = 0;
459                         }
460
461                         outbuf[r->buf_len++] = 0x00; // this page
462                         outbuf[r->buf_len++] = 0x00;
463                         outbuf[r->buf_len++] = 3;    // number of pages
464                         outbuf[r->buf_len++] = 0x00; // list of supported pages (this page)
465                         outbuf[r->buf_len++] = 0x80; // unit serial number
466                         outbuf[r->buf_len++] = 0x83; // device identification
467                     }
468                     break;
469                 case 0x80:
470                     {
471                         int l;
472
473                         /* Device serial number, optional */
474                         if (len < 4) {
475                             BADF("Error: EVPD[Serial number] Inquiry buffer "
476                                  "size %d too small, %d needed\n", len, 4);
477                             goto fail;
478                         }
479
480                         DPRINTF("Inquiry EVPD[Serial number] buffer size %d\n", len);
481                         l = MIN(len, strlen(s->drive_serial_str));
482
483                         r->buf_len = 0;
484
485                         /* Supported page codes */
486                         if (bdrv_get_type_hint(s->bdrv) == BDRV_TYPE_CDROM) {
487                             outbuf[r->buf_len++] = 5;
488                         } else {
489                             outbuf[r->buf_len++] = 0;
490                         }
491
492                         outbuf[r->buf_len++] = 0x80; // this page
493                         outbuf[r->buf_len++] = 0x00;
494                         outbuf[r->buf_len++] = l;
495                         memcpy(&outbuf[r->buf_len], s->drive_serial_str, l);
496                         r->buf_len += l;
497                     }
498
499                     break;
500                 case 0x83:
501                     {
502                         /* Device identification page, mandatory */
503                         int max_len = 255 - 8;
504                         int id_len = strlen(bdrv_get_device_name(s->bdrv));
505                         if (id_len > max_len)
506                             id_len = max_len;
507
508                         DPRINTF("Inquiry EVPD[Device identification] "
509                                 "buffer size %d\n", len);
510                         r->buf_len = 0;
511                         if (bdrv_get_type_hint(s->bdrv) == BDRV_TYPE_CDROM) {
512                             outbuf[r->buf_len++] = 5;
513                         } else {
514                             outbuf[r->buf_len++] = 0;
515                         }
516
517                         outbuf[r->buf_len++] = 0x83; // this page
518                         outbuf[r->buf_len++] = 0x00;
519                         outbuf[r->buf_len++] = 3 + id_len;
520
521                         outbuf[r->buf_len++] = 0x2; // ASCII
522                         outbuf[r->buf_len++] = 0;   // not officially assigned
523                         outbuf[r->buf_len++] = 0;   // reserved
524                         outbuf[r->buf_len++] = id_len; // length of data following
525
526                         memcpy(&outbuf[r->buf_len],
527                                bdrv_get_device_name(s->bdrv), id_len);
528                         r->buf_len += id_len;
529                     }
530                     break;
531                 default:
532                     BADF("Error: unsupported Inquiry (EVPD[%02X]) "
533                          "buffer size %d\n", page_code, len);
534                     goto fail;
535             }
536             /* done with EVPD */
537             break;
538         }
539         else {
540             /* Standard INQUIRY data */
541             if (buf[2] != 0) {
542                 BADF("Error: Inquiry (STANDARD) page or code "
543                      "is non-zero [%02X]\n", buf[2]);
544                 goto fail;
545             }
546
547             /* PAGE CODE == 0 */
548             if (len < 5) {
549                 BADF("Error: Inquiry (STANDARD) buffer size %d "
550                      "is less than 5\n", len);
551                 goto fail;
552             }
553
554             if (len < 36) {
555                 BADF("Error: Inquiry (STANDARD) buffer size %d "
556                      "is less than 36 (TODO: only 5 required)\n", len);
557             }
558         }
559
560         if(len > SCSI_MAX_INQUIRY_LEN)
561             len = SCSI_MAX_INQUIRY_LEN;
562
563         memset(outbuf, 0, len);
564
565         if (lun || buf[1] >> 5) {
566             outbuf[0] = 0x7f;   /* LUN not supported */
567         } else if (bdrv_get_type_hint(s->bdrv) == BDRV_TYPE_CDROM) {
568             outbuf[0] = 5;
569             outbuf[1] = 0x80;
570             memcpy(&outbuf[16], "QEMU CD-ROM    ", 16);
571         } else {
572             outbuf[0] = 0;
573             memcpy(&outbuf[16], "QEMU HARDDISK  ", 16);
574         }
575         memcpy(&outbuf[8], "QEMU   ", 8);
576         memcpy(&outbuf[32], QEMU_VERSION, 4);
577         /* Identify device as SCSI-3 rev 1.
578            Some later commands are also implemented. */
579         outbuf[2] = 3;
580         outbuf[3] = 2; /* Format 2 */
581         outbuf[4] = len - 5; /* Additional Length = (Len - 1) - 4 */
582         /* Sync data transfer and TCQ.  */
583         outbuf[7] = 0x10 | (s->tcq ? 0x02 : 0);
584         r->buf_len = len;
585         break;
586     case 0x16:
587         DPRINTF("Reserve(6)\n");
588         if (buf[1] & 1)
589             goto fail;
590         break;
591     case 0x17:
592         DPRINTF("Release(6)\n");
593         if (buf[1] & 1)
594             goto fail;
595         break;
596     case 0x1a:
597     case 0x5a:
598         {
599             uint8_t *p;
600             int page;
601
602             page = buf[2] & 0x3f;
603             DPRINTF("Mode Sense (page %d, len %d)\n", page, len);
604             p = outbuf;
605             memset(p, 0, 4);
606             outbuf[1] = 0; /* Default media type.  */
607             outbuf[3] = 0; /* Block descriptor length.  */
608             if (bdrv_get_type_hint(s->bdrv) == BDRV_TYPE_CDROM) {
609                 outbuf[2] = 0x80; /* Readonly.  */
610             }
611             p += 4;
612             if (page == 4) {
613                 int cylinders, heads, secs;
614
615                 /* Rigid disk device geometry page. */
616                 p[0] = 4;
617                 p[1] = 0x16;
618                 /* if a geometry hint is available, use it */
619                 bdrv_get_geometry_hint(s->bdrv, &cylinders, &heads, &secs);
620                 p[2] = (cylinders >> 16) & 0xff;
621                 p[3] = (cylinders >> 8) & 0xff;
622                 p[4] = cylinders & 0xff;
623                 p[5] = heads & 0xff;
624                 /* Write precomp start cylinder, disabled */
625                 p[6] = (cylinders >> 16) & 0xff;
626                 p[7] = (cylinders >> 8) & 0xff;
627                 p[8] = cylinders & 0xff;
628                 /* Reduced current start cylinder, disabled */
629                 p[9] = (cylinders >> 16) & 0xff;
630                 p[10] = (cylinders >> 8) & 0xff;
631                 p[11] = cylinders & 0xff;
632                 /* Device step rate [ns], 200ns */
633                 p[12] = 0;
634                 p[13] = 200;
635                 /* Landing zone cylinder */
636                 p[14] = 0xff;
637                 p[15] =  0xff;
638                 p[16] = 0xff;
639                 /* Medium rotation rate [rpm], 5400 rpm */
640                 p[20] = (5400 >> 8) & 0xff;
641                 p[21] = 5400 & 0xff;
642                 p += 0x16;
643             } else if (page == 5) {
644                 int cylinders, heads, secs;
645
646                 /* Flexible disk device geometry page. */
647                 p[0] = 5;
648                 p[1] = 0x1e;
649                 /* Transfer rate [kbit/s], 5Mbit/s */
650                 p[2] = 5000 >> 8;
651                 p[3] = 5000 & 0xff;
652                 /* if a geometry hint is available, use it */
653                 bdrv_get_geometry_hint(s->bdrv, &cylinders, &heads, &secs);
654                 p[4] = heads & 0xff;
655                 p[5] = secs & 0xff;
656                 p[6] = s->cluster_size * 2;
657                 p[8] = (cylinders >> 8) & 0xff;
658                 p[9] = cylinders & 0xff;
659                 /* Write precomp start cylinder, disabled */
660                 p[10] = (cylinders >> 8) & 0xff;
661                 p[11] = cylinders & 0xff;
662                 /* Reduced current start cylinder, disabled */
663                 p[12] = (cylinders >> 8) & 0xff;
664                 p[13] = cylinders & 0xff;
665                 /* Device step rate [100us], 100us */
666                 p[14] = 0;
667                 p[15] = 1;
668                 /* Device step pulse width [us], 1us */
669                 p[16] = 1;
670                 /* Device head settle delay [100us], 100us */
671                 p[17] = 0;
672                 p[18] = 1;
673                 /* Motor on delay [0.1s], 0.1s */
674                 p[19] = 1;
675                 /* Motor off delay [0.1s], 0.1s */
676                 p[20] = 1;
677                 /* Medium rotation rate [rpm], 5400 rpm */
678                 p[28] = (5400 >> 8) & 0xff;
679                 p[29] = 5400 & 0xff;
680                 p += 0x1e;
681             } else if ((page == 8 || page == 0x3f)) {
682                 /* Caching page.  */
683                 memset(p,0,20);
684                 p[0] = 8;
685                 p[1] = 0x12;
686                 p[2] = 4; /* WCE */
687                 p += 20;
688             }
689             if ((page == 0x3f || page == 0x2a)
690                     && (bdrv_get_type_hint(s->bdrv) == BDRV_TYPE_CDROM)) {
691                 /* CD Capabilities and Mechanical Status page. */
692                 p[0] = 0x2a;
693                 p[1] = 0x14;
694                 p[2] = 3; // CD-R & CD-RW read
695                 p[3] = 0; // Writing not supported
696                 p[4] = 0x7f; /* Audio, composite, digital out,
697                                          mode 2 form 1&2, multi session */
698                 p[5] = 0xff; /* CD DA, DA accurate, RW supported,
699                                          RW corrected, C2 errors, ISRC,
700                                          UPC, Bar code */
701                 p[6] = 0x2d | (bdrv_is_locked(s->bdrv)? 2 : 0);
702                 /* Locking supported, jumper present, eject, tray */
703                 p[7] = 0; /* no volume & mute control, no
704                                       changer */
705                 p[8] = (50 * 176) >> 8; // 50x read speed
706                 p[9] = (50 * 176) & 0xff;
707                 p[10] = 0 >> 8; // No volume
708                 p[11] = 0 & 0xff;
709                 p[12] = 2048 >> 8; // 2M buffer
710                 p[13] = 2048 & 0xff;
711                 p[14] = (16 * 176) >> 8; // 16x read speed current
712                 p[15] = (16 * 176) & 0xff;
713                 p[18] = (16 * 176) >> 8; // 16x write speed
714                 p[19] = (16 * 176) & 0xff;
715                 p[20] = (16 * 176) >> 8; // 16x write speed current
716                 p[21] = (16 * 176) & 0xff;
717                 p += 22;
718             }
719             r->buf_len = p - outbuf;
720             outbuf[0] = r->buf_len - 4;
721             if (r->buf_len > len)
722                 r->buf_len = len;
723         }
724         break;
725     case 0x1b:
726         DPRINTF("Start Stop Unit\n");
727         break;
728     case 0x1e:
729         DPRINTF("Prevent Allow Medium Removal (prevent = %d)\n", buf[4] & 3);
730         bdrv_set_locked(s->bdrv, buf[4] & 1);
731         break;
732     case 0x25:
733         DPRINTF("Read Capacity\n");
734         /* The normal LEN field for this command is zero.  */
735         memset(outbuf, 0, 8);
736         bdrv_get_geometry(s->bdrv, &nb_sectors);
737         nb_sectors /= s->cluster_size;
738         /* Returned value is the address of the last sector.  */
739         if (nb_sectors) {
740             nb_sectors--;
741             /* Clip to 2TB, instead of returning capacity modulo 2TB. */
742             if (nb_sectors > UINT32_MAX)
743                 nb_sectors = UINT32_MAX;
744             outbuf[0] = (nb_sectors >> 24) & 0xff;
745             outbuf[1] = (nb_sectors >> 16) & 0xff;
746             outbuf[2] = (nb_sectors >> 8) & 0xff;
747             outbuf[3] = nb_sectors & 0xff;
748             outbuf[4] = 0;
749             outbuf[5] = 0;
750             outbuf[6] = s->cluster_size * 2;
751             outbuf[7] = 0;
752             r->buf_len = 8;
753         } else {
754             scsi_command_complete(r, STATUS_CHECK_CONDITION, SENSE_NOT_READY);
755             return 0;
756         }
757         break;
758     case 0x08:
759     case 0x28:
760     case 0x88:
761         DPRINTF("Read (sector %lld, count %d)\n", lba, len);
762         r->sector = lba * s->cluster_size;
763         r->sector_count = len * s->cluster_size;
764         break;
765     case 0x0a:
766     case 0x2a:
767     case 0x8a:
768         DPRINTF("Write (sector %lld, count %d)\n", lba, len);
769         r->sector = lba * s->cluster_size;
770         r->sector_count = len * s->cluster_size;
771         is_write = 1;
772         break;
773     case 0x35:
774         DPRINTF("Synchronise cache (sector %d, count %d)\n", lba, len);
775         bdrv_flush(s->bdrv);
776         break;
777     case 0x43:
778         {
779             int start_track, format, msf, toclen;
780
781             msf = buf[1] & 2;
782             format = buf[2] & 0xf;
783             start_track = buf[6];
784             bdrv_get_geometry(s->bdrv, &nb_sectors);
785             DPRINTF("Read TOC (track %d format %d msf %d)\n", start_track, format, msf >> 1);
786             switch(format) {
787             case 0:
788                 toclen = cdrom_read_toc(nb_sectors, outbuf, msf, start_track);
789                 break;
790             case 1:
791                 /* multi session : only a single session defined */
792                 toclen = 12;
793                 memset(outbuf, 0, 12);
794                 outbuf[1] = 0x0a;
795                 outbuf[2] = 0x01;
796                 outbuf[3] = 0x01;
797                 break;
798             case 2:
799                 toclen = cdrom_read_toc_raw(nb_sectors, outbuf, msf, start_track);
800                 break;
801             default:
802                 goto error_cmd;
803             }
804             if (toclen > 0) {
805                 if (len > toclen)
806                   len = toclen;
807                 r->buf_len = len;
808                 break;
809             }
810         error_cmd:
811             DPRINTF("Read TOC error\n");
812             goto fail;
813         }
814     case 0x46:
815         DPRINTF("Get Configuration (rt %d, maxlen %d)\n", buf[1] & 3, len);
816         memset(outbuf, 0, 8);
817         /* ??? This should probably return much more information.  For now
818            just return the basic header indicating the CD-ROM profile.  */
819         outbuf[7] = 8; // CD-ROM
820         r->buf_len = 8;
821         break;
822     case 0x56:
823         DPRINTF("Reserve(10)\n");
824         if (buf[1] & 3)
825             goto fail;
826         break;
827     case 0x57:
828         DPRINTF("Release(10)\n");
829         if (buf[1] & 3)
830             goto fail;
831         break;
832     case 0x9e:
833         /* Service Action In subcommands. */
834         if ((buf[1] & 31) == 0x10) {
835             DPRINTF("SAI READ CAPACITY(16)\n");
836             memset(outbuf, 0, len);
837             bdrv_get_geometry(s->bdrv, &nb_sectors);
838             nb_sectors /= s->cluster_size;
839             /* Returned value is the address of the last sector.  */
840             if (nb_sectors) {
841                 nb_sectors--;
842                 outbuf[0] = (nb_sectors >> 56) & 0xff;
843                 outbuf[1] = (nb_sectors >> 48) & 0xff;
844                 outbuf[2] = (nb_sectors >> 40) & 0xff;
845                 outbuf[3] = (nb_sectors >> 32) & 0xff;
846                 outbuf[4] = (nb_sectors >> 24) & 0xff;
847                 outbuf[5] = (nb_sectors >> 16) & 0xff;
848                 outbuf[6] = (nb_sectors >> 8) & 0xff;
849                 outbuf[7] = nb_sectors & 0xff;
850                 outbuf[8] = 0;
851                 outbuf[9] = 0;
852                 outbuf[10] = s->cluster_size * 2;
853                 outbuf[11] = 0;
854                 /* Protection, exponent and lowest lba field left blank. */
855                 r->buf_len = len;
856             } else {
857                 scsi_command_complete(r, STATUS_CHECK_CONDITION, SENSE_NOT_READY);
858                 return 0;
859             }
860             break;
861         }
862         DPRINTF("Unsupported Service Action In\n");
863         goto fail;
864     case 0xa0:
865         DPRINTF("Report LUNs (len %d)\n", len);
866         if (len < 16)
867             goto fail;
868         memset(outbuf, 0, 16);
869         outbuf[3] = 8;
870         r->buf_len = 16;
871         break;
872     case 0x2f:
873         DPRINTF("Verify (sector %d, count %d)\n", lba, len);
874         break;
875     default:
876         DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
877     fail:
878         scsi_command_complete(r, STATUS_CHECK_CONDITION, SENSE_ILLEGAL_REQUEST);
879         return 0;
880     }
881     if (r->sector_count == 0 && r->buf_len == 0) {
882         scsi_command_complete(r, STATUS_GOOD, SENSE_NO_SENSE);
883     }
884     len = r->sector_count * 512 + r->buf_len;
885     if (is_write) {
886         return -len;
887     } else {
888         if (!r->sector_count)
889             r->sector_count = -1;
890         return len;
891     }
892 }
893
894 static void scsi_destroy(SCSIDevice *d)
895 {
896     qemu_free(d->state);
897     qemu_free(d);
898 }
899
900 SCSIDevice *scsi_disk_init(BlockDriverState *bdrv, int tcq,
901                            scsi_completionfn completion, void *opaque)
902 {
903     SCSIDevice *d;
904     SCSIDeviceState *s;
905
906     s = (SCSIDeviceState *)qemu_mallocz(sizeof(SCSIDeviceState));
907     s->bdrv = bdrv;
908     s->tcq = tcq;
909     s->completion = completion;
910     s->opaque = opaque;
911     if (bdrv_get_type_hint(s->bdrv) == BDRV_TYPE_CDROM) {
912         s->cluster_size = 4;
913     } else {
914         s->cluster_size = 1;
915     }
916     strncpy(s->drive_serial_str, drive_get_serial(s->bdrv),
917             sizeof(s->drive_serial_str));
918     if (strlen(s->drive_serial_str) == 0)
919         pstrcpy(s->drive_serial_str, sizeof(s->drive_serial_str), "0");
920     qemu_add_vm_change_state_handler(scsi_dma_restart_cb, s);
921     d = (SCSIDevice *)qemu_mallocz(sizeof(SCSIDevice));
922     d->state = s;
923     d->destroy = scsi_destroy;
924     d->send_command = scsi_send_command;
925     d->read_data = scsi_read_data;
926     d->write_data = scsi_write_data;
927     d->cancel_io = scsi_cancel_io;
928     d->get_buf = scsi_get_buf;
929
930     return d;
931 }