xref: /openbmc/qemu/hw/scsi/scsi-generic.c (revision c964b660)
1 /*
2  * Generic SCSI Device support
3  *
4  * Copyright (c) 2007 Bull S.A.S.
5  * Based on code by Paul Brook
6  * Based on code by Fabrice Bellard
7  *
8  * Written by Laurent Vivier <Laurent.Vivier@bull.net>
9  *
10  * This code is licensed under the LGPL.
11  *
12  */
13 
14 #include "qemu/osdep.h"
15 #include "qemu-common.h"
16 #include "qemu/error-report.h"
17 #include "hw/scsi/scsi.h"
18 #include "sysemu/block-backend.h"
19 #include "sysemu/blockdev.h"
20 
21 #ifdef __linux__
22 
23 //#define DEBUG_SCSI
24 
25 #ifdef DEBUG_SCSI
26 #define DPRINTF(fmt, ...) \
27 do { printf("scsi-generic: " fmt , ## __VA_ARGS__); } while (0)
28 #else
29 #define DPRINTF(fmt, ...) do {} while(0)
30 #endif
31 
32 #define BADF(fmt, ...) \
33 do { fprintf(stderr, "scsi-generic: " fmt , ## __VA_ARGS__); } while (0)
34 
35 #include <scsi/sg.h>
36 #include "block/scsi.h"
37 
38 #define SG_ERR_DRIVER_TIMEOUT  0x06
39 #define SG_ERR_DRIVER_SENSE    0x08
40 
41 #define SG_ERR_DID_OK          0x00
42 #define SG_ERR_DID_NO_CONNECT  0x01
43 #define SG_ERR_DID_BUS_BUSY    0x02
44 #define SG_ERR_DID_TIME_OUT    0x03
45 
46 #ifndef MAX_UINT
47 #define MAX_UINT ((unsigned int)-1)
48 #endif
49 
50 typedef struct SCSIGenericReq {
51     SCSIRequest req;
52     uint8_t *buf;
53     int buflen;
54     int len;
55     sg_io_hdr_t io_header;
56 } SCSIGenericReq;
57 
58 static void scsi_generic_save_request(QEMUFile *f, SCSIRequest *req)
59 {
60     SCSIGenericReq *r = DO_UPCAST(SCSIGenericReq, req, req);
61 
62     qemu_put_sbe32s(f, &r->buflen);
63     if (r->buflen && r->req.cmd.mode == SCSI_XFER_TO_DEV) {
64         assert(!r->req.sg);
65         qemu_put_buffer(f, r->buf, r->req.cmd.xfer);
66     }
67 }
68 
69 static void scsi_generic_load_request(QEMUFile *f, SCSIRequest *req)
70 {
71     SCSIGenericReq *r = DO_UPCAST(SCSIGenericReq, req, req);
72 
73     qemu_get_sbe32s(f, &r->buflen);
74     if (r->buflen && r->req.cmd.mode == SCSI_XFER_TO_DEV) {
75         assert(!r->req.sg);
76         qemu_get_buffer(f, r->buf, r->req.cmd.xfer);
77     }
78 }
79 
80 static void scsi_free_request(SCSIRequest *req)
81 {
82     SCSIGenericReq *r = DO_UPCAST(SCSIGenericReq, req, req);
83 
84     g_free(r->buf);
85 }
86 
87 /* Helper function for command completion.  */
88 static void scsi_command_complete_noio(SCSIGenericReq *r, int ret)
89 {
90     int status;
91 
92     assert(r->req.aiocb == NULL);
93 
94     if (r->req.io_canceled) {
95         scsi_req_cancel_complete(&r->req);
96         goto done;
97     }
98     if (r->io_header.driver_status & SG_ERR_DRIVER_SENSE) {
99         r->req.sense_len = r->io_header.sb_len_wr;
100     }
101 
102     if (ret != 0) {
103         switch (ret) {
104         case -EDOM:
105             status = TASK_SET_FULL;
106             break;
107         case -ENOMEM:
108             status = CHECK_CONDITION;
109             scsi_req_build_sense(&r->req, SENSE_CODE(TARGET_FAILURE));
110             break;
111         default:
112             status = CHECK_CONDITION;
113             scsi_req_build_sense(&r->req, SENSE_CODE(IO_ERROR));
114             break;
115         }
116     } else {
117         if (r->io_header.host_status == SG_ERR_DID_NO_CONNECT ||
118             r->io_header.host_status == SG_ERR_DID_BUS_BUSY ||
119             r->io_header.host_status == SG_ERR_DID_TIME_OUT ||
120             (r->io_header.driver_status & SG_ERR_DRIVER_TIMEOUT)) {
121             status = BUSY;
122             BADF("Driver Timeout\n");
123         } else if (r->io_header.host_status) {
124             status = CHECK_CONDITION;
125             scsi_req_build_sense(&r->req, SENSE_CODE(I_T_NEXUS_LOSS));
126         } else if (r->io_header.status) {
127             status = r->io_header.status;
128         } else if (r->io_header.driver_status & SG_ERR_DRIVER_SENSE) {
129             status = CHECK_CONDITION;
130         } else {
131             status = GOOD;
132         }
133     }
134     DPRINTF("Command complete 0x%p tag=0x%x status=%d\n",
135             r, r->req.tag, status);
136 
137     scsi_req_complete(&r->req, status);
138 done:
139     scsi_req_unref(&r->req);
140 }
141 
142 static void scsi_command_complete(void *opaque, int ret)
143 {
144     SCSIGenericReq *r = (SCSIGenericReq *)opaque;
145 
146     assert(r->req.aiocb != NULL);
147     r->req.aiocb = NULL;
148     scsi_command_complete_noio(r, ret);
149 }
150 
151 static int execute_command(BlockBackend *blk,
152                            SCSIGenericReq *r, int direction,
153                            BlockCompletionFunc *complete)
154 {
155     r->io_header.interface_id = 'S';
156     r->io_header.dxfer_direction = direction;
157     r->io_header.dxferp = r->buf;
158     r->io_header.dxfer_len = r->buflen;
159     r->io_header.cmdp = r->req.cmd.buf;
160     r->io_header.cmd_len = r->req.cmd.len;
161     r->io_header.mx_sb_len = sizeof(r->req.sense);
162     r->io_header.sbp = r->req.sense;
163     r->io_header.timeout = MAX_UINT;
164     r->io_header.usr_ptr = r;
165     r->io_header.flags |= SG_FLAG_DIRECT_IO;
166 
167     r->req.aiocb = blk_aio_ioctl(blk, SG_IO, &r->io_header, complete, r);
168     if (r->req.aiocb == NULL) {
169         return -EIO;
170     }
171 
172     return 0;
173 }
174 
175 static void scsi_read_complete(void * opaque, int ret)
176 {
177     SCSIGenericReq *r = (SCSIGenericReq *)opaque;
178     SCSIDevice *s = r->req.dev;
179     int len;
180 
181     assert(r->req.aiocb != NULL);
182     r->req.aiocb = NULL;
183 
184     if (ret || r->req.io_canceled) {
185         scsi_command_complete_noio(r, ret);
186         return;
187     }
188 
189     len = r->io_header.dxfer_len - r->io_header.resid;
190     DPRINTF("Data ready tag=0x%x len=%d\n", r->req.tag, len);
191 
192     r->len = -1;
193     if (len == 0) {
194         scsi_command_complete_noio(r, 0);
195         return;
196     }
197 
198     /* Snoop READ CAPACITY output to set the blocksize.  */
199     if (r->req.cmd.buf[0] == READ_CAPACITY_10 &&
200         (ldl_be_p(&r->buf[0]) != 0xffffffffU || s->max_lba == 0)) {
201         s->blocksize = ldl_be_p(&r->buf[4]);
202         s->max_lba = ldl_be_p(&r->buf[0]) & 0xffffffffULL;
203     } else if (r->req.cmd.buf[0] == SERVICE_ACTION_IN_16 &&
204                (r->req.cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) {
205         s->blocksize = ldl_be_p(&r->buf[8]);
206         s->max_lba = ldq_be_p(&r->buf[0]);
207     }
208     blk_set_guest_block_size(s->conf.blk, s->blocksize);
209 
210     /* Patch MODE SENSE device specific parameters if the BDS is opened
211      * readonly.
212      */
213     if ((s->type == TYPE_DISK || s->type == TYPE_TAPE) &&
214         blk_is_read_only(s->conf.blk) &&
215         (r->req.cmd.buf[0] == MODE_SENSE ||
216          r->req.cmd.buf[0] == MODE_SENSE_10) &&
217         (r->req.cmd.buf[1] & 0x8) == 0) {
218         if (r->req.cmd.buf[0] == MODE_SENSE) {
219             r->buf[2] |= 0x80;
220         } else  {
221             r->buf[3] |= 0x80;
222         }
223     }
224     scsi_req_data(&r->req, len);
225     scsi_req_unref(&r->req);
226 }
227 
228 /* Read more data from scsi device into buffer.  */
229 static void scsi_read_data(SCSIRequest *req)
230 {
231     SCSIGenericReq *r = DO_UPCAST(SCSIGenericReq, req, req);
232     SCSIDevice *s = r->req.dev;
233     int ret;
234 
235     DPRINTF("scsi_read_data 0x%x\n", req->tag);
236 
237     /* The request is used as the AIO opaque value, so add a ref.  */
238     scsi_req_ref(&r->req);
239     if (r->len == -1) {
240         scsi_command_complete_noio(r, 0);
241         return;
242     }
243 
244     ret = execute_command(s->conf.blk, r, SG_DXFER_FROM_DEV,
245                           scsi_read_complete);
246     if (ret < 0) {
247         scsi_command_complete_noio(r, ret);
248     }
249 }
250 
251 static void scsi_write_complete(void * opaque, int ret)
252 {
253     SCSIGenericReq *r = (SCSIGenericReq *)opaque;
254     SCSIDevice *s = r->req.dev;
255 
256     DPRINTF("scsi_write_complete() ret = %d\n", ret);
257 
258     assert(r->req.aiocb != NULL);
259     r->req.aiocb = NULL;
260 
261     if (ret || r->req.io_canceled) {
262         scsi_command_complete_noio(r, ret);
263         return;
264     }
265 
266     if (r->req.cmd.buf[0] == MODE_SELECT && r->req.cmd.buf[4] == 12 &&
267         s->type == TYPE_TAPE) {
268         s->blocksize = (r->buf[9] << 16) | (r->buf[10] << 8) | r->buf[11];
269         DPRINTF("block size %d\n", s->blocksize);
270     }
271 
272     scsi_command_complete_noio(r, ret);
273 }
274 
275 /* Write data to a scsi device.  Returns nonzero on failure.
276    The transfer may complete asynchronously.  */
277 static void scsi_write_data(SCSIRequest *req)
278 {
279     SCSIGenericReq *r = DO_UPCAST(SCSIGenericReq, req, req);
280     SCSIDevice *s = r->req.dev;
281     int ret;
282 
283     DPRINTF("scsi_write_data 0x%x\n", req->tag);
284     if (r->len == 0) {
285         r->len = r->buflen;
286         scsi_req_data(&r->req, r->len);
287         return;
288     }
289 
290     /* The request is used as the AIO opaque value, so add a ref.  */
291     scsi_req_ref(&r->req);
292     ret = execute_command(s->conf.blk, r, SG_DXFER_TO_DEV, scsi_write_complete);
293     if (ret < 0) {
294         scsi_command_complete_noio(r, ret);
295     }
296 }
297 
298 /* Return a pointer to the data buffer.  */
299 static uint8_t *scsi_get_buf(SCSIRequest *req)
300 {
301     SCSIGenericReq *r = DO_UPCAST(SCSIGenericReq, req, req);
302 
303     return r->buf;
304 }
305 
306 /* Execute a scsi command.  Returns the length of the data expected by the
307    command.  This will be Positive for data transfers from the device
308    (eg. disk reads), negative for transfers to the device (eg. disk writes),
309    and zero if the command does not transfer any data.  */
310 
311 static int32_t scsi_send_command(SCSIRequest *req, uint8_t *cmd)
312 {
313     SCSIGenericReq *r = DO_UPCAST(SCSIGenericReq, req, req);
314     SCSIDevice *s = r->req.dev;
315     int ret;
316 
317 #ifdef DEBUG_SCSI
318     {
319         int i;
320         for (i = 1; i < r->req.cmd.len; i++) {
321             printf(" 0x%02x", cmd[i]);
322         }
323         printf("\n");
324     }
325 #endif
326 
327     if (r->req.cmd.xfer == 0) {
328         g_free(r->buf);
329         r->buflen = 0;
330         r->buf = NULL;
331         /* The request is used as the AIO opaque value, so add a ref.  */
332         scsi_req_ref(&r->req);
333         ret = execute_command(s->conf.blk, r, SG_DXFER_NONE,
334                               scsi_command_complete);
335         if (ret < 0) {
336             scsi_command_complete_noio(r, ret);
337             return 0;
338         }
339         return 0;
340     }
341 
342     if (r->buflen != r->req.cmd.xfer) {
343         g_free(r->buf);
344         r->buf = g_malloc(r->req.cmd.xfer);
345         r->buflen = r->req.cmd.xfer;
346     }
347 
348     memset(r->buf, 0, r->buflen);
349     r->len = r->req.cmd.xfer;
350     if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
351         r->len = 0;
352         return -r->req.cmd.xfer;
353     } else {
354         return r->req.cmd.xfer;
355     }
356 }
357 
358 static int read_naa_id(const uint8_t *p, uint64_t *p_wwn)
359 {
360     int i;
361 
362     if ((p[1] & 0xF) == 3) {
363         /* NAA designator type */
364         if (p[3] != 8) {
365             return -EINVAL;
366         }
367         *p_wwn = ldq_be_p(p + 4);
368         return 0;
369     }
370 
371     if ((p[1] & 0xF) == 8) {
372         /* SCSI name string designator type */
373         if (p[3] < 20 || memcmp(&p[4], "naa.", 4)) {
374             return -EINVAL;
375         }
376         if (p[3] > 20 && p[24] != ',') {
377             return -EINVAL;
378         }
379         *p_wwn = 0;
380         for (i = 8; i < 24; i++) {
381             char c = toupper(p[i]);
382             c -= (c >= '0' && c <= '9' ? '0' : 'A' - 10);
383             *p_wwn = (*p_wwn << 4) | c;
384         }
385         return 0;
386     }
387 
388     return -EINVAL;
389 }
390 
391 void scsi_generic_read_device_identification(SCSIDevice *s)
392 {
393     uint8_t cmd[6];
394     uint8_t buf[250];
395     uint8_t sensebuf[8];
396     sg_io_hdr_t io_header;
397     int ret;
398     int i, len;
399 
400     memset(cmd, 0, sizeof(cmd));
401     memset(buf, 0, sizeof(buf));
402     cmd[0] = INQUIRY;
403     cmd[1] = 1;
404     cmd[2] = 0x83;
405     cmd[4] = sizeof(buf);
406 
407     memset(&io_header, 0, sizeof(io_header));
408     io_header.interface_id = 'S';
409     io_header.dxfer_direction = SG_DXFER_FROM_DEV;
410     io_header.dxfer_len = sizeof(buf);
411     io_header.dxferp = buf;
412     io_header.cmdp = cmd;
413     io_header.cmd_len = sizeof(cmd);
414     io_header.mx_sb_len = sizeof(sensebuf);
415     io_header.sbp = sensebuf;
416     io_header.timeout = 6000; /* XXX */
417 
418     ret = blk_ioctl(s->conf.blk, SG_IO, &io_header);
419     if (ret < 0 || io_header.driver_status || io_header.host_status) {
420         return;
421     }
422 
423     len = MIN((buf[2] << 8) | buf[3], sizeof(buf) - 4);
424     for (i = 0; i + 3 <= len; ) {
425         const uint8_t *p = &buf[i + 4];
426         uint64_t wwn;
427 
428         if (i + (p[3] + 4) > len) {
429             break;
430         }
431 
432         if ((p[1] & 0x10) == 0) {
433             /* Associated with the logical unit */
434             if (read_naa_id(p, &wwn) == 0) {
435                 s->wwn = wwn;
436             }
437         } else if ((p[1] & 0x10) == 0x10) {
438             /* Associated with the target port */
439             if (read_naa_id(p, &wwn) == 0) {
440                 s->port_wwn = wwn;
441             }
442         }
443 
444         i += p[3] + 4;
445     }
446 }
447 
448 static int get_stream_blocksize(BlockBackend *blk)
449 {
450     uint8_t cmd[6];
451     uint8_t buf[12];
452     uint8_t sensebuf[8];
453     sg_io_hdr_t io_header;
454     int ret;
455 
456     memset(cmd, 0, sizeof(cmd));
457     memset(buf, 0, sizeof(buf));
458     cmd[0] = MODE_SENSE;
459     cmd[4] = sizeof(buf);
460 
461     memset(&io_header, 0, sizeof(io_header));
462     io_header.interface_id = 'S';
463     io_header.dxfer_direction = SG_DXFER_FROM_DEV;
464     io_header.dxfer_len = sizeof(buf);
465     io_header.dxferp = buf;
466     io_header.cmdp = cmd;
467     io_header.cmd_len = sizeof(cmd);
468     io_header.mx_sb_len = sizeof(sensebuf);
469     io_header.sbp = sensebuf;
470     io_header.timeout = 6000; /* XXX */
471 
472     ret = blk_ioctl(blk, SG_IO, &io_header);
473     if (ret < 0 || io_header.driver_status || io_header.host_status) {
474         return -1;
475     }
476     return (buf[9] << 16) | (buf[10] << 8) | buf[11];
477 }
478 
479 static void scsi_generic_reset(DeviceState *dev)
480 {
481     SCSIDevice *s = SCSI_DEVICE(dev);
482 
483     scsi_device_purge_requests(s, SENSE_CODE(RESET));
484 }
485 
486 static void scsi_generic_realize(SCSIDevice *s, Error **errp)
487 {
488     int rc;
489     int sg_version;
490     struct sg_scsi_id scsiid;
491 
492     if (!s->conf.blk) {
493         error_setg(errp, "drive property not set");
494         return;
495     }
496 
497     if (blk_get_on_error(s->conf.blk, 0) != BLOCKDEV_ON_ERROR_ENOSPC) {
498         error_setg(errp, "Device doesn't support drive option werror");
499         return;
500     }
501     if (blk_get_on_error(s->conf.blk, 1) != BLOCKDEV_ON_ERROR_REPORT) {
502         error_setg(errp, "Device doesn't support drive option rerror");
503         return;
504     }
505 
506     /* check we are using a driver managing SG_IO (version 3 and after */
507     rc = blk_ioctl(s->conf.blk, SG_GET_VERSION_NUM, &sg_version);
508     if (rc < 0) {
509         error_setg(errp, "cannot get SG_IO version number: %s.  "
510                          "Is this a SCSI device?",
511                          strerror(-rc));
512         return;
513     }
514     if (sg_version < 30000) {
515         error_setg(errp, "scsi generic interface too old");
516         return;
517     }
518 
519     /* get LUN of the /dev/sg? */
520     if (blk_ioctl(s->conf.blk, SG_GET_SCSI_ID, &scsiid)) {
521         error_setg(errp, "SG_GET_SCSI_ID ioctl failed");
522         return;
523     }
524 
525     /* define device state */
526     s->type = scsiid.scsi_type;
527     DPRINTF("device type %d\n", s->type);
528 
529     switch (s->type) {
530     case TYPE_TAPE:
531         s->blocksize = get_stream_blocksize(s->conf.blk);
532         if (s->blocksize == -1) {
533             s->blocksize = 0;
534         }
535         break;
536 
537         /* Make a guess for block devices, we'll fix it when the guest sends.
538          * READ CAPACITY.  If they don't, they likely would assume these sizes
539          * anyway. (TODO: they could also send MODE SENSE).
540          */
541     case TYPE_ROM:
542     case TYPE_WORM:
543         s->blocksize = 2048;
544         break;
545     default:
546         s->blocksize = 512;
547         break;
548     }
549 
550     DPRINTF("block size %d\n", s->blocksize);
551 
552     scsi_generic_read_device_identification(s);
553 }
554 
555 const SCSIReqOps scsi_generic_req_ops = {
556     .size         = sizeof(SCSIGenericReq),
557     .free_req     = scsi_free_request,
558     .send_command = scsi_send_command,
559     .read_data    = scsi_read_data,
560     .write_data   = scsi_write_data,
561     .get_buf      = scsi_get_buf,
562     .load_request = scsi_generic_load_request,
563     .save_request = scsi_generic_save_request,
564 };
565 
566 static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun,
567                                      uint8_t *buf, void *hba_private)
568 {
569     SCSIRequest *req;
570 
571     req = scsi_req_alloc(&scsi_generic_req_ops, d, tag, lun, hba_private);
572     return req;
573 }
574 
575 static Property scsi_generic_properties[] = {
576     DEFINE_PROP_DRIVE("drive", SCSIDevice, conf.blk),
577     DEFINE_PROP_END_OF_LIST(),
578 };
579 
580 static int scsi_generic_parse_cdb(SCSIDevice *dev, SCSICommand *cmd,
581                                   uint8_t *buf, void *hba_private)
582 {
583     return scsi_bus_parse_cdb(dev, cmd, buf, hba_private);
584 }
585 
586 static void scsi_generic_class_initfn(ObjectClass *klass, void *data)
587 {
588     DeviceClass *dc = DEVICE_CLASS(klass);
589     SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
590 
591     sc->realize      = scsi_generic_realize;
592     sc->alloc_req    = scsi_new_request;
593     sc->parse_cdb    = scsi_generic_parse_cdb;
594     dc->fw_name = "disk";
595     dc->desc = "pass through generic scsi device (/dev/sg*)";
596     dc->reset = scsi_generic_reset;
597     dc->props = scsi_generic_properties;
598     dc->vmsd  = &vmstate_scsi_device;
599 }
600 
601 static const TypeInfo scsi_generic_info = {
602     .name          = "scsi-generic",
603     .parent        = TYPE_SCSI_DEVICE,
604     .instance_size = sizeof(SCSIDevice),
605     .class_init    = scsi_generic_class_initfn,
606 };
607 
608 static void scsi_generic_register_types(void)
609 {
610     type_register_static(&scsi_generic_info);
611 }
612 
613 type_init(scsi_generic_register_types)
614 
615 #endif /* __linux__ */
616