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