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