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