xref: /openbmc/qemu/hw/scsi/scsi-generic.c (revision fe7f9b8e)
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 (r->req.cmd.buf[0] == INQUIRY) {
198         /*
199          *  EVPD set to zero returns the standard INQUIRY data.
200          *
201          *  Check if scsi_version is unset (-1) to avoid re-defining it
202          *  each time an INQUIRY with standard data is received.
203          *  scsi_version is initialized with -1 in scsi_generic_reset
204          *  and scsi_disk_reset, making sure that we'll set the
205          *  scsi_version after a reset. If the version field of the
206          *  INQUIRY response somehow changes after a guest reboot,
207          *  we'll be able to keep track of it.
208          *
209          *  On SCSI-2 and older, first 3 bits of byte 2 is the
210          *  ANSI-approved version, while on later versions the
211          *  whole byte 2 contains the version. Check if we're dealing
212          *  with a newer version and, in that case, assign the
213          *  whole byte.
214          */
215         if (s->scsi_version == -1 && !(r->req.cmd.buf[1] & 0x01)) {
216             s->scsi_version = r->buf[2] & 0x07;
217             if (s->scsi_version > 2) {
218                 s->scsi_version = r->buf[2];
219             }
220         }
221         if (s->type == TYPE_DISK && r->req.cmd.buf[2] == 0xb0) {
222             uint32_t max_transfer =
223                 blk_get_max_transfer(s->conf.blk) / s->blocksize;
224 
225             assert(max_transfer);
226             stl_be_p(&r->buf[8], max_transfer);
227             /* Also take care of the opt xfer len. */
228             stl_be_p(&r->buf[12],
229                      MIN_NON_ZERO(max_transfer, ldl_be_p(&r->buf[12])));
230         }
231     }
232     scsi_req_data(&r->req, len);
233     scsi_req_unref(&r->req);
234 
235 done:
236     aio_context_release(blk_get_aio_context(s->conf.blk));
237 }
238 
239 /* Read more data from scsi device into buffer.  */
240 static void scsi_read_data(SCSIRequest *req)
241 {
242     SCSIGenericReq *r = DO_UPCAST(SCSIGenericReq, req, req);
243     SCSIDevice *s = r->req.dev;
244     int ret;
245 
246     DPRINTF("scsi_read_data tag=0x%x\n", req->tag);
247 
248     /* The request is used as the AIO opaque value, so add a ref.  */
249     scsi_req_ref(&r->req);
250     if (r->len == -1) {
251         scsi_command_complete_noio(r, 0);
252         return;
253     }
254 
255     ret = execute_command(s->conf.blk, r, SG_DXFER_FROM_DEV,
256                           scsi_read_complete);
257     if (ret < 0) {
258         scsi_command_complete_noio(r, ret);
259     }
260 }
261 
262 static void scsi_write_complete(void * opaque, int ret)
263 {
264     SCSIGenericReq *r = (SCSIGenericReq *)opaque;
265     SCSIDevice *s = r->req.dev;
266 
267     DPRINTF("scsi_write_complete() ret = %d\n", ret);
268 
269     assert(r->req.aiocb != NULL);
270     r->req.aiocb = NULL;
271 
272     aio_context_acquire(blk_get_aio_context(s->conf.blk));
273 
274     if (ret || r->req.io_canceled) {
275         scsi_command_complete_noio(r, ret);
276         goto done;
277     }
278 
279     if (r->req.cmd.buf[0] == MODE_SELECT && r->req.cmd.buf[4] == 12 &&
280         s->type == TYPE_TAPE) {
281         s->blocksize = (r->buf[9] << 16) | (r->buf[10] << 8) | r->buf[11];
282         DPRINTF("block size %d\n", s->blocksize);
283     }
284 
285     scsi_command_complete_noio(r, ret);
286 
287 done:
288     aio_context_release(blk_get_aio_context(s->conf.blk));
289 }
290 
291 /* Write data to a scsi device.  Returns nonzero on failure.
292    The transfer may complete asynchronously.  */
293 static void scsi_write_data(SCSIRequest *req)
294 {
295     SCSIGenericReq *r = DO_UPCAST(SCSIGenericReq, req, req);
296     SCSIDevice *s = r->req.dev;
297     int ret;
298 
299     DPRINTF("scsi_write_data tag=0x%x\n", req->tag);
300     if (r->len == 0) {
301         r->len = r->buflen;
302         scsi_req_data(&r->req, r->len);
303         return;
304     }
305 
306     /* The request is used as the AIO opaque value, so add a ref.  */
307     scsi_req_ref(&r->req);
308     ret = execute_command(s->conf.blk, r, SG_DXFER_TO_DEV, scsi_write_complete);
309     if (ret < 0) {
310         scsi_command_complete_noio(r, ret);
311     }
312 }
313 
314 /* Return a pointer to the data buffer.  */
315 static uint8_t *scsi_get_buf(SCSIRequest *req)
316 {
317     SCSIGenericReq *r = DO_UPCAST(SCSIGenericReq, req, req);
318 
319     return r->buf;
320 }
321 
322 /* Execute a scsi command.  Returns the length of the data expected by the
323    command.  This will be Positive for data transfers from the device
324    (eg. disk reads), negative for transfers to the device (eg. disk writes),
325    and zero if the command does not transfer any data.  */
326 
327 static int32_t scsi_send_command(SCSIRequest *req, uint8_t *cmd)
328 {
329     SCSIGenericReq *r = DO_UPCAST(SCSIGenericReq, req, req);
330     SCSIDevice *s = r->req.dev;
331     int ret;
332 
333 #ifdef DEBUG_SCSI
334     DPRINTF("Command: data=0x%02x", cmd[0]);
335     {
336         int i;
337         for (i = 1; i < r->req.cmd.len; i++) {
338             printf(" 0x%02x", cmd[i]);
339         }
340         printf("\n");
341     }
342 #endif
343 
344     if (r->req.cmd.xfer == 0) {
345         g_free(r->buf);
346         r->buflen = 0;
347         r->buf = NULL;
348         /* The request is used as the AIO opaque value, so add a ref.  */
349         scsi_req_ref(&r->req);
350         ret = execute_command(s->conf.blk, r, SG_DXFER_NONE,
351                               scsi_command_complete);
352         if (ret < 0) {
353             scsi_command_complete_noio(r, ret);
354             return 0;
355         }
356         return 0;
357     }
358 
359     if (r->buflen != r->req.cmd.xfer) {
360         g_free(r->buf);
361         r->buf = g_malloc(r->req.cmd.xfer);
362         r->buflen = r->req.cmd.xfer;
363     }
364 
365     memset(r->buf, 0, r->buflen);
366     r->len = r->req.cmd.xfer;
367     if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
368         r->len = 0;
369         return -r->req.cmd.xfer;
370     } else {
371         return r->req.cmd.xfer;
372     }
373 }
374 
375 static int read_naa_id(const uint8_t *p, uint64_t *p_wwn)
376 {
377     int i;
378 
379     if ((p[1] & 0xF) == 3) {
380         /* NAA designator type */
381         if (p[3] != 8) {
382             return -EINVAL;
383         }
384         *p_wwn = ldq_be_p(p + 4);
385         return 0;
386     }
387 
388     if ((p[1] & 0xF) == 8) {
389         /* SCSI name string designator type */
390         if (p[3] < 20 || memcmp(&p[4], "naa.", 4)) {
391             return -EINVAL;
392         }
393         if (p[3] > 20 && p[24] != ',') {
394             return -EINVAL;
395         }
396         *p_wwn = 0;
397         for (i = 8; i < 24; i++) {
398             char c = qemu_toupper(p[i]);
399             c -= (c >= '0' && c <= '9' ? '0' : 'A' - 10);
400             *p_wwn = (*p_wwn << 4) | c;
401         }
402         return 0;
403     }
404 
405     return -EINVAL;
406 }
407 
408 void scsi_generic_read_device_identification(SCSIDevice *s)
409 {
410     uint8_t cmd[6];
411     uint8_t buf[250];
412     uint8_t sensebuf[8];
413     sg_io_hdr_t io_header;
414     int ret;
415     int i, len;
416 
417     memset(cmd, 0, sizeof(cmd));
418     memset(buf, 0, sizeof(buf));
419     cmd[0] = INQUIRY;
420     cmd[1] = 1;
421     cmd[2] = 0x83;
422     cmd[4] = sizeof(buf);
423 
424     memset(&io_header, 0, sizeof(io_header));
425     io_header.interface_id = 'S';
426     io_header.dxfer_direction = SG_DXFER_FROM_DEV;
427     io_header.dxfer_len = sizeof(buf);
428     io_header.dxferp = buf;
429     io_header.cmdp = cmd;
430     io_header.cmd_len = sizeof(cmd);
431     io_header.mx_sb_len = sizeof(sensebuf);
432     io_header.sbp = sensebuf;
433     io_header.timeout = 6000; /* XXX */
434 
435     ret = blk_ioctl(s->conf.blk, SG_IO, &io_header);
436     if (ret < 0 || io_header.driver_status || io_header.host_status) {
437         return;
438     }
439 
440     len = MIN((buf[2] << 8) | buf[3], sizeof(buf) - 4);
441     for (i = 0; i + 3 <= len; ) {
442         const uint8_t *p = &buf[i + 4];
443         uint64_t wwn;
444 
445         if (i + (p[3] + 4) > len) {
446             break;
447         }
448 
449         if ((p[1] & 0x10) == 0) {
450             /* Associated with the logical unit */
451             if (read_naa_id(p, &wwn) == 0) {
452                 s->wwn = wwn;
453             }
454         } else if ((p[1] & 0x10) == 0x10) {
455             /* Associated with the target port */
456             if (read_naa_id(p, &wwn) == 0) {
457                 s->port_wwn = wwn;
458             }
459         }
460 
461         i += p[3] + 4;
462     }
463 }
464 
465 static int get_stream_blocksize(BlockBackend *blk)
466 {
467     uint8_t cmd[6];
468     uint8_t buf[12];
469     uint8_t sensebuf[8];
470     sg_io_hdr_t io_header;
471     int ret;
472 
473     memset(cmd, 0, sizeof(cmd));
474     memset(buf, 0, sizeof(buf));
475     cmd[0] = MODE_SENSE;
476     cmd[4] = sizeof(buf);
477 
478     memset(&io_header, 0, sizeof(io_header));
479     io_header.interface_id = 'S';
480     io_header.dxfer_direction = SG_DXFER_FROM_DEV;
481     io_header.dxfer_len = sizeof(buf);
482     io_header.dxferp = buf;
483     io_header.cmdp = cmd;
484     io_header.cmd_len = sizeof(cmd);
485     io_header.mx_sb_len = sizeof(sensebuf);
486     io_header.sbp = sensebuf;
487     io_header.timeout = 6000; /* XXX */
488 
489     ret = blk_ioctl(blk, SG_IO, &io_header);
490     if (ret < 0 || io_header.driver_status || io_header.host_status) {
491         return -1;
492     }
493     return (buf[9] << 16) | (buf[10] << 8) | buf[11];
494 }
495 
496 static void scsi_generic_reset(DeviceState *dev)
497 {
498     SCSIDevice *s = SCSI_DEVICE(dev);
499 
500     s->scsi_version = s->default_scsi_version;
501     scsi_device_purge_requests(s, SENSE_CODE(RESET));
502 }
503 
504 static void scsi_generic_realize(SCSIDevice *s, Error **errp)
505 {
506     int rc;
507     int sg_version;
508     struct sg_scsi_id scsiid;
509 
510     if (!s->conf.blk) {
511         error_setg(errp, "drive property not set");
512         return;
513     }
514 
515     if (blk_get_on_error(s->conf.blk, 0) != BLOCKDEV_ON_ERROR_ENOSPC) {
516         error_setg(errp, "Device doesn't support drive option werror");
517         return;
518     }
519     if (blk_get_on_error(s->conf.blk, 1) != BLOCKDEV_ON_ERROR_REPORT) {
520         error_setg(errp, "Device doesn't support drive option rerror");
521         return;
522     }
523 
524     /* check we are using a driver managing SG_IO (version 3 and after */
525     rc = blk_ioctl(s->conf.blk, SG_GET_VERSION_NUM, &sg_version);
526     if (rc < 0) {
527         error_setg_errno(errp, -rc, "cannot get SG_IO version number");
528         if (rc != -EPERM) {
529             error_append_hint(errp, "Is this a SCSI device?\n");
530         }
531         return;
532     }
533     if (sg_version < 30000) {
534         error_setg(errp, "scsi generic interface too old");
535         return;
536     }
537 
538     /* get LUN of the /dev/sg? */
539     if (blk_ioctl(s->conf.blk, SG_GET_SCSI_ID, &scsiid)) {
540         error_setg(errp, "SG_GET_SCSI_ID ioctl failed");
541         return;
542     }
543     if (!blkconf_apply_backend_options(&s->conf,
544                                        blk_is_read_only(s->conf.blk),
545                                        true, errp)) {
546         return;
547     }
548 
549     /* define device state */
550     s->type = scsiid.scsi_type;
551     DPRINTF("device type %d\n", s->type);
552 
553     switch (s->type) {
554     case TYPE_TAPE:
555         s->blocksize = get_stream_blocksize(s->conf.blk);
556         if (s->blocksize == -1) {
557             s->blocksize = 0;
558         }
559         break;
560 
561         /* Make a guess for block devices, we'll fix it when the guest sends.
562          * READ CAPACITY.  If they don't, they likely would assume these sizes
563          * anyway. (TODO: they could also send MODE SENSE).
564          */
565     case TYPE_ROM:
566     case TYPE_WORM:
567         s->blocksize = 2048;
568         break;
569     default:
570         s->blocksize = 512;
571         break;
572     }
573 
574     DPRINTF("block size %d\n", s->blocksize);
575 
576     /* Only used by scsi-block, but initialize it nevertheless to be clean.  */
577     s->default_scsi_version = -1;
578     scsi_generic_read_device_identification(s);
579 }
580 
581 const SCSIReqOps scsi_generic_req_ops = {
582     .size         = sizeof(SCSIGenericReq),
583     .free_req     = scsi_free_request,
584     .send_command = scsi_send_command,
585     .read_data    = scsi_read_data,
586     .write_data   = scsi_write_data,
587     .get_buf      = scsi_get_buf,
588     .load_request = scsi_generic_load_request,
589     .save_request = scsi_generic_save_request,
590 };
591 
592 static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun,
593                                      uint8_t *buf, void *hba_private)
594 {
595     return scsi_req_alloc(&scsi_generic_req_ops, d, tag, lun, hba_private);
596 }
597 
598 static Property scsi_generic_properties[] = {
599     DEFINE_PROP_DRIVE("drive", SCSIDevice, conf.blk),
600     DEFINE_PROP_BOOL("share-rw", SCSIDevice, conf.share_rw, false),
601     DEFINE_PROP_END_OF_LIST(),
602 };
603 
604 static int scsi_generic_parse_cdb(SCSIDevice *dev, SCSICommand *cmd,
605                                   uint8_t *buf, void *hba_private)
606 {
607     return scsi_bus_parse_cdb(dev, cmd, buf, hba_private);
608 }
609 
610 static void scsi_generic_class_initfn(ObjectClass *klass, void *data)
611 {
612     DeviceClass *dc = DEVICE_CLASS(klass);
613     SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);
614 
615     sc->realize      = scsi_generic_realize;
616     sc->alloc_req    = scsi_new_request;
617     sc->parse_cdb    = scsi_generic_parse_cdb;
618     dc->fw_name = "disk";
619     dc->desc = "pass through generic scsi device (/dev/sg*)";
620     dc->reset = scsi_generic_reset;
621     dc->props = scsi_generic_properties;
622     dc->vmsd  = &vmstate_scsi_device;
623 }
624 
625 static const TypeInfo scsi_generic_info = {
626     .name          = "scsi-generic",
627     .parent        = TYPE_SCSI_DEVICE,
628     .instance_size = sizeof(SCSIDevice),
629     .class_init    = scsi_generic_class_initfn,
630 };
631 
632 static void scsi_generic_register_types(void)
633 {
634     type_register_static(&scsi_generic_info);
635 }
636 
637 type_init(scsi_generic_register_types)
638 
639 #endif /* __linux__ */
640