scsi-bus.c 59.6 KB
Newer Older
P
Peter Maydell 已提交
1
#include "qemu/osdep.h"
2
#include "hw/hw.h"
3
#include "qapi/error.h"
4
#include "qemu/error-report.h"
P
Paolo Bonzini 已提交
5 6
#include "hw/scsi/scsi.h"
#include "block/scsi.h"
7
#include "hw/qdev.h"
8
#include "sysemu/block-backend.h"
9
#include "sysemu/blockdev.h"
10
#include "trace.h"
11
#include "sysemu/dma.h"
12
#include "qemu/cutils.h"
13

P
Paolo Bonzini 已提交
14
static char *scsibus_get_dev_path(DeviceState *dev);
15
static char *scsibus_get_fw_dev_path(DeviceState *dev);
16
static void scsi_req_dequeue(SCSIRequest *req);
17 18
static uint8_t *scsi_target_alloc_buf(SCSIRequest *req, size_t len);
static void scsi_target_free_buf(SCSIRequest *req);
19

20 21 22 23 24 25 26
static Property scsi_props[] = {
    DEFINE_PROP_UINT32("channel", SCSIDevice, channel, 0),
    DEFINE_PROP_UINT32("scsi-id", SCSIDevice, id, -1),
    DEFINE_PROP_UINT32("lun", SCSIDevice, lun, -1),
    DEFINE_PROP_END_OF_LIST(),
};

27 28 29
static void scsi_bus_class_init(ObjectClass *klass, void *data)
{
    BusClass *k = BUS_CLASS(klass);
30
    HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass);
31 32 33

    k->get_dev_path = scsibus_get_dev_path;
    k->get_fw_dev_path = scsibus_get_fw_dev_path;
34
    hc->unplug = qdev_simple_device_unplug_cb;
35 36 37 38 39 40 41
}

static const TypeInfo scsi_bus_info = {
    .name = TYPE_SCSI_BUS,
    .parent = TYPE_BUS,
    .instance_size = sizeof(SCSIBus),
    .class_init = scsi_bus_class_init,
42 43 44 45
    .interfaces = (InterfaceInfo[]) {
        { TYPE_HOTPLUG_HANDLER },
        { }
    }
46 47 48
};
static int next_scsi_bus;

49
static void scsi_device_realize(SCSIDevice *s, Error **errp)
50 51
{
    SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s);
52 53
    if (sc->realize) {
        sc->realize(s, errp);
54 55 56
    }
}

57 58 59 60 61 62 63 64 65 66 67 68 69 70
int scsi_bus_parse_cdb(SCSIDevice *dev, SCSICommand *cmd, uint8_t *buf,
                       void *hba_private)
{
    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);
    int rc;

    assert(cmd->len == 0);
    rc = scsi_req_parse_cdb(dev, cmd, buf);
    if (bus->info->parse_cdb) {
        rc = bus->info->parse_cdb(dev, cmd, buf, hba_private);
    }
    return rc;
}

71 72 73 74 75 76 77 78 79 80 81
static SCSIRequest *scsi_device_alloc_req(SCSIDevice *s, uint32_t tag, uint32_t lun,
                                          uint8_t *buf, void *hba_private)
{
    SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s);
    if (sc->alloc_req) {
        return sc->alloc_req(s, tag, lun, buf, hba_private);
    }

    return NULL;
}

82
void scsi_device_unit_attention_reported(SCSIDevice *s)
83 84 85 86 87 88 89
{
    SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s);
    if (sc->unit_attention_reported) {
        sc->unit_attention_reported(s);
    }
}

90
/* Create a scsi bus, and attach devices to it.  */
91 92
void scsi_bus_new(SCSIBus *bus, size_t bus_size, DeviceState *host,
                  const SCSIBusInfo *info, const char *bus_name)
93
{
94
    qbus_create_inplace(bus, bus_size, TYPE_SCSI_BUS, host, bus_name);
95
    bus->busnr = next_scsi_bus++;
96
    bus->info = info;
97
    qbus_set_bus_hotplug_handler(BUS(bus), &error_abort);
98 99
}

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
static void scsi_dma_restart_bh(void *opaque)
{
    SCSIDevice *s = opaque;
    SCSIRequest *req, *next;

    qemu_bh_delete(s->bh);
    s->bh = NULL;

    QTAILQ_FOREACH_SAFE(req, &s->requests, next, next) {
        scsi_req_ref(req);
        if (req->retry) {
            req->retry = false;
            switch (req->cmd.mode) {
            case SCSI_XFER_FROM_DEV:
            case SCSI_XFER_TO_DEV:
                scsi_req_continue(req);
                break;
            case SCSI_XFER_NONE:
                scsi_req_dequeue(req);
                scsi_req_enqueue(req);
                break;
            }
        }
        scsi_req_unref(req);
    }
}

void scsi_req_retry(SCSIRequest *req)
{
    /* No need to save a reference, because scsi_dma_restart_bh just
     * looks at the request list.  */
    req->retry = true;
}

static void scsi_dma_restart_cb(void *opaque, int running, RunState state)
{
    SCSIDevice *s = opaque;

    if (!running) {
        return;
    }
    if (!s->bh) {
142 143
        AioContext *ctx = blk_get_aio_context(s->conf.blk);
        s->bh = aio_bh_new(ctx, scsi_dma_restart_bh, s);
144 145 146 147
        qemu_bh_schedule(s->bh);
    }
}

148
static void scsi_qdev_realize(DeviceState *qdev, Error **errp)
149
{
150
    SCSIDevice *dev = SCSI_DEVICE(qdev);
151
    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);
P
Paolo Bonzini 已提交
152
    SCSIDevice *d;
153
    Error *local_err = NULL;
154

P
Paolo Bonzini 已提交
155
    if (dev->channel > bus->info->max_channel) {
156 157
        error_setg(errp, "bad scsi channel id: %d", dev->channel);
        return;
P
Paolo Bonzini 已提交
158
    }
P
Paolo Bonzini 已提交
159
    if (dev->id != -1 && dev->id > bus->info->max_target) {
160 161
        error_setg(errp, "bad scsi device id: %d", dev->id);
        return;
162
    }
163
    if (dev->lun != -1 && dev->lun > bus->info->max_lun) {
164 165
        error_setg(errp, "bad scsi device lun: %d", dev->lun);
        return;
166
    }
167

P
Paolo Bonzini 已提交
168 169 170 171 172 173
    if (dev->id == -1) {
        int id = -1;
        if (dev->lun == -1) {
            dev->lun = 0;
        }
        do {
P
Paolo Bonzini 已提交
174
            d = scsi_device_find(bus, dev->channel, ++id, dev->lun);
175 176
        } while (d && d->lun == dev->lun && id < bus->info->max_target);
        if (d && d->lun == dev->lun) {
177 178
            error_setg(errp, "no free target");
            return;
P
Paolo Bonzini 已提交
179 180 181 182 183
        }
        dev->id = id;
    } else if (dev->lun == -1) {
        int lun = -1;
        do {
P
Paolo Bonzini 已提交
184
            d = scsi_device_find(bus, dev->channel, dev->id, ++lun);
P
Paolo Bonzini 已提交
185
        } while (d && d->lun == lun && lun < bus->info->max_lun);
186
        if (d && d->lun == lun) {
187 188
            error_setg(errp, "no free lun");
            return;
P
Paolo Bonzini 已提交
189 190 191
        }
        dev->lun = lun;
    } else {
P
Paolo Bonzini 已提交
192
        d = scsi_device_find(bus, dev->channel, dev->id, dev->lun);
193 194
        assert(d);
        if (d->lun == dev->lun && dev != d) {
195 196
            error_setg(errp, "lun already used by '%s'", d->qdev.id);
            return;
P
Paolo Bonzini 已提交
197
        }
198 199
    }

200
    QTAILQ_INIT(&dev->requests);
201 202 203 204
    scsi_device_realize(dev, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        return;
205
    }
206 207
    dev->vmsentry = qemu_add_vm_change_state_handler(scsi_dma_restart_cb,
                                                     dev);
G
Gerd Hoffmann 已提交
208 209
}

210
static void scsi_qdev_unrealize(DeviceState *qdev, Error **errp)
G
Gerd Hoffmann 已提交
211
{
212
    SCSIDevice *dev = SCSI_DEVICE(qdev);
G
Gerd Hoffmann 已提交
213

214 215 216
    if (dev->vmsentry) {
        qemu_del_vm_change_state_handler(dev->vmsentry);
    }
217 218 219

    scsi_device_purge_requests(dev, SENSE_CODE(NO_SENSE));
    blockdev_mark_auto_del(dev->conf.blk);
220 221 222
}

/* handle legacy '-drive if=scsi,...' cmd line args */
223
SCSIDevice *scsi_bus_legacy_add_drive(SCSIBus *bus, BlockBackend *blk,
224
                                      int unit, bool removable, int bootindex,
225
                                      const char *serial, Error **errp)
226 227
{
    const char *driver;
228
    char *name;
229
    DeviceState *dev;
230
    Error *err = NULL;
231

232
    driver = blk_is_sg(blk) ? "scsi-generic" : "scsi-disk";
233
    dev = qdev_create(&bus->qbus, driver);
234 235 236 237
    name = g_strdup_printf("legacy[%d]", unit);
    object_property_add_child(OBJECT(bus), name, OBJECT(dev), NULL);
    g_free(name);

238
    qdev_prop_set_uint32(dev, "scsi-id", unit);
239
    if (bootindex >= 0) {
240 241
        object_property_set_int(OBJECT(dev), bootindex, "bootindex",
                                &error_abort);
242
    }
243
    if (object_property_find(OBJECT(dev), "removable", NULL)) {
244 245
        qdev_prop_set_bit(dev, "removable", removable);
    }
246
    if (serial && object_property_find(OBJECT(dev), "serial", NULL)) {
247 248
        qdev_prop_set_string(dev, "serial", serial);
    }
249 250
    qdev_prop_set_drive(dev, "drive", blk, &err);
    if (err) {
251
        error_propagate(errp, err);
252
        object_unparent(OBJECT(dev));
253 254
        return NULL;
    }
255 256 257
    object_property_set_bool(OBJECT(dev), true, "realized", &err);
    if (err != NULL) {
        error_propagate(errp, err);
258
        object_unparent(OBJECT(dev));
259
        return NULL;
260
    }
261
    return SCSI_DEVICE(dev);
262 263
}

264
void scsi_bus_legacy_handle_cmdline(SCSIBus *bus, Error **errp)
265
{
266
    Location loc;
267
    DriveInfo *dinfo;
268 269
    int unit;
    Error *err = NULL;
270

271
    loc_push_none(&loc);
272
    for (unit = 0; unit <= bus->info->max_target; unit++) {
273 274 275 276
        dinfo = drive_get(IF_SCSI, bus->busnr, unit);
        if (dinfo == NULL) {
            continue;
        }
277
        qemu_opts_loc_restore(dinfo->opts);
278
        scsi_bus_legacy_add_drive(bus, blk_by_legacy_dinfo(dinfo),
279
                                  unit, false, -1, NULL, &err);
280 281
        if (err != NULL) {
            error_propagate(errp, err);
282 283
            break;
        }
284
    }
285
    loc_pop(&loc);
286
}
287

288 289 290 291 292 293 294 295 296 297 298 299
static int32_t scsi_invalid_field(SCSIRequest *req, uint8_t *buf)
{
    scsi_req_build_sense(req, SENSE_CODE(INVALID_FIELD));
    scsi_req_complete(req, CHECK_CONDITION);
    return 0;
}

static const struct SCSIReqOps reqops_invalid_field = {
    .size         = sizeof(SCSIRequest),
    .send_command = scsi_invalid_field
};

300 301 302 303 304 305 306 307 308
/* SCSIReqOps implementation for invalid commands.  */

static int32_t scsi_invalid_command(SCSIRequest *req, uint8_t *buf)
{
    scsi_req_build_sense(req, SENSE_CODE(INVALID_OPCODE));
    scsi_req_complete(req, CHECK_CONDITION);
    return 0;
}

P
Paolo Bonzini 已提交
309
static const struct SCSIReqOps reqops_invalid_opcode = {
310 311 312 313
    .size         = sizeof(SCSIRequest),
    .send_command = scsi_invalid_command
};

314 315 316 317
/* SCSIReqOps implementation for unit attention conditions.  */

static int32_t scsi_unit_attention(SCSIRequest *req, uint8_t *buf)
{
318
    if (req->dev->unit_attention.key == UNIT_ATTENTION) {
319 320 321 322 323 324 325 326
        scsi_req_build_sense(req, req->dev->unit_attention);
    } else if (req->bus->unit_attention.key == UNIT_ATTENTION) {
        scsi_req_build_sense(req, req->bus->unit_attention);
    }
    scsi_req_complete(req, CHECK_CONDITION);
    return 0;
}

P
Paolo Bonzini 已提交
327
static const struct SCSIReqOps reqops_unit_attention = {
328 329 330 331
    .size         = sizeof(SCSIRequest),
    .send_command = scsi_unit_attention
};

332 333 334 335 336 337 338 339
/* SCSIReqOps implementation for REPORT LUNS and for commands sent to
   an invalid LUN.  */

typedef struct SCSITargetReq SCSITargetReq;

struct SCSITargetReq {
    SCSIRequest req;
    int len;
340 341
    uint8_t *buf;
    int buf_len;
342 343 344 345 346 347 348 349 350 351 352 353 354 355
};

static void store_lun(uint8_t *outbuf, int lun)
{
    if (lun < 256) {
        outbuf[1] = lun;
        return;
    }
    outbuf[1] = (lun & 255);
    outbuf[0] = (lun >> 8) | 0x40;
}

static bool scsi_target_emulate_report_luns(SCSITargetReq *r)
{
A
Anthony Liguori 已提交
356
    BusChild *kid;
357
    int i, len, n;
P
Paolo Bonzini 已提交
358
    int channel, id;
359 360
    bool found_lun0;

361 362 363 364 365 366
    if (r->req.cmd.xfer < 16) {
        return false;
    }
    if (r->req.cmd.buf[2] > 2) {
        return false;
    }
P
Paolo Bonzini 已提交
367
    channel = r->req.dev->channel;
368 369 370
    id = r->req.dev->id;
    found_lun0 = false;
    n = 0;
A
Anthony Liguori 已提交
371 372
    QTAILQ_FOREACH(kid, &r->req.bus->qbus.children, sibling) {
        DeviceState *qdev = kid->child;
373
        SCSIDevice *dev = SCSI_DEVICE(qdev);
374

P
Paolo Bonzini 已提交
375
        if (dev->channel == channel && dev->id == id) {
376 377 378 379 380 381 382 383 384 385
            if (dev->lun == 0) {
                found_lun0 = true;
            }
            n += 8;
        }
    }
    if (!found_lun0) {
        n += 8;
    }

386 387 388
    scsi_target_alloc_buf(&r->req, n + 8);

    len = MIN(n + 8, r->req.cmd.xfer & ~7);
389
    memset(r->buf, 0, len);
390
    stl_be_p(&r->buf[0], n);
391
    i = found_lun0 ? 8 : 16;
A
Anthony Liguori 已提交
392 393
    QTAILQ_FOREACH(kid, &r->req.bus->qbus.children, sibling) {
        DeviceState *qdev = kid->child;
394
        SCSIDevice *dev = SCSI_DEVICE(qdev);
395

P
Paolo Bonzini 已提交
396
        if (dev->channel == channel && dev->id == id) {
397 398 399
            store_lun(&r->buf[i], dev->lun);
            i += 8;
        }
400
    }
401 402
    assert(i == n + 8);
    r->len = len;
403 404 405 406 407 408
    return true;
}

static bool scsi_target_emulate_inquiry(SCSITargetReq *r)
{
    assert(r->req.dev->lun != r->req.lun);
409 410 411

    scsi_target_alloc_buf(&r->req, SCSI_INQUIRY_LEN);

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    if (r->req.cmd.buf[1] & 0x2) {
        /* Command support data - optional, not implemented */
        return false;
    }

    if (r->req.cmd.buf[1] & 0x1) {
        /* Vital product data */
        uint8_t page_code = r->req.cmd.buf[2];
        r->buf[r->len++] = page_code ; /* this page */
        r->buf[r->len++] = 0x00;

        switch (page_code) {
        case 0x00: /* Supported page codes, mandatory */
        {
            int pages;
            pages = r->len++;
            r->buf[r->len++] = 0x00; /* list of supported pages (this page) */
            r->buf[pages] = r->len - pages - 1; /* number of pages */
            break;
        }
        default:
            return false;
        }
        /* done with EVPD */
436
        assert(r->len < r->buf_len);
437 438 439 440 441 442 443 444 445 446
        r->len = MIN(r->req.cmd.xfer, r->len);
        return true;
    }

    /* Standard INQUIRY data */
    if (r->req.cmd.buf[2] != 0) {
        return false;
    }

    /* PAGE CODE == 0 */
447
    r->len = MIN(r->req.cmd.xfer, SCSI_INQUIRY_LEN);
448 449 450 451 452 453 454 455
    memset(r->buf, 0, r->len);
    if (r->req.lun != 0) {
        r->buf[0] = TYPE_NO_LUN;
    } else {
        r->buf[0] = TYPE_NOT_PRESENT | TYPE_INACTIVE;
        r->buf[2] = 5; /* Version */
        r->buf[3] = 2 | 0x10; /* HiSup, response data format */
        r->buf[4] = r->len - 5; /* Additional Length = (Len - 1) - 4 */
456
        r->buf[7] = 0x10 | (r->req.bus->info->tcq ? 0x02 : 0); /* Sync, TCQ.  */
457 458
        memcpy(&r->buf[8], "QEMU    ", 8);
        memcpy(&r->buf[16], "QEMU TARGET     ", 16);
459
        pstrcpy((char *) &r->buf[32], 4, qemu_hw_version());
460 461 462 463
    }
    return true;
}

464 465 466 467 468 469 470 471
static size_t scsi_sense_len(SCSIRequest *req)
{
    if (req->dev->type == TYPE_SCANNER)
        return SCSI_SENSE_LEN_SCANNER;
    else
        return SCSI_SENSE_LEN;
}

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
static int32_t scsi_target_send_command(SCSIRequest *req, uint8_t *buf)
{
    SCSITargetReq *r = DO_UPCAST(SCSITargetReq, req, req);

    switch (buf[0]) {
    case REPORT_LUNS:
        if (!scsi_target_emulate_report_luns(r)) {
            goto illegal_request;
        }
        break;
    case INQUIRY:
        if (!scsi_target_emulate_inquiry(r)) {
            goto illegal_request;
        }
        break;
487
    case REQUEST_SENSE:
488
        scsi_target_alloc_buf(&r->req, scsi_sense_len(req));
489
        r->len = scsi_device_get_sense(r->req.dev, r->buf,
490
                                       MIN(req->cmd.xfer, r->buf_len),
491
                                       (req->cmd.buf[1] & 1) == 0);
492
        if (r->req.dev->sense_is_ua) {
493
            scsi_device_unit_attention_reported(req->dev);
494 495 496
            r->req.dev->sense_len = 0;
            r->req.dev->sense_is_ua = false;
        }
497
        break;
498 499
    case TEST_UNIT_READY:
        break;
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
    default:
        scsi_req_build_sense(req, SENSE_CODE(LUN_NOT_SUPPORTED));
        scsi_req_complete(req, CHECK_CONDITION);
        return 0;
    illegal_request:
        scsi_req_build_sense(req, SENSE_CODE(INVALID_FIELD));
        scsi_req_complete(req, CHECK_CONDITION);
        return 0;
    }

    if (!r->len) {
        scsi_req_complete(req, GOOD);
    }
    return r->len;
}

static void scsi_target_read_data(SCSIRequest *req)
{
    SCSITargetReq *r = DO_UPCAST(SCSITargetReq, req, req);
    uint32_t n;

    n = r->len;
    if (n > 0) {
        r->len = 0;
        scsi_req_data(&r->req, n);
    } else {
        scsi_req_complete(&r->req, GOOD);
    }
}

static uint8_t *scsi_target_get_buf(SCSIRequest *req)
{
    SCSITargetReq *r = DO_UPCAST(SCSITargetReq, req, req);

    return r->buf;
}

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
static uint8_t *scsi_target_alloc_buf(SCSIRequest *req, size_t len)
{
    SCSITargetReq *r = DO_UPCAST(SCSITargetReq, req, req);

    r->buf = g_malloc(len);
    r->buf_len = len;

    return r->buf;
}

static void scsi_target_free_buf(SCSIRequest *req)
{
    SCSITargetReq *r = DO_UPCAST(SCSITargetReq, req, req);

    g_free(r->buf);
}

P
Paolo Bonzini 已提交
554
static const struct SCSIReqOps reqops_target_command = {
555 556 557 558
    .size         = sizeof(SCSITargetReq),
    .send_command = scsi_target_send_command,
    .read_data    = scsi_target_read_data,
    .get_buf      = scsi_target_get_buf,
559
    .free_req     = scsi_target_free_buf,
560 561 562
};


P
Paolo Bonzini 已提交
563 564
SCSIRequest *scsi_req_alloc(const SCSIReqOps *reqops, SCSIDevice *d,
                            uint32_t tag, uint32_t lun, void *hba_private)
565 566
{
    SCSIRequest *req;
567 568
    SCSIBus *bus = scsi_bus_from_device(d);
    BusState *qbus = BUS(bus);
F
Fam Zheng 已提交
569 570
    const int memset_off = offsetof(SCSIRequest, sense)
                           + sizeof(req->sense);
571

572
    req = g_malloc(reqops->size);
F
Fam Zheng 已提交
573
    memset((uint8_t *)req + memset_off, 0, reqops->size - memset_off);
574
    req->refcount = 1;
575
    req->bus = bus;
576 577 578
    req->dev = d;
    req->tag = tag;
    req->lun = lun;
579
    req->hba_private = hba_private;
G
Gerd Hoffmann 已提交
580
    req->status = -1;
P
Paolo Bonzini 已提交
581
    req->ops = reqops;
582 583
    object_ref(OBJECT(d));
    object_ref(OBJECT(qbus->parent));
584
    notifier_list_init(&req->cancel_notifiers);
585
    trace_scsi_req_alloc(req->dev->id, req->lun, req->tag);
586 587 588
    return req;
}

589
SCSIRequest *scsi_req_new(SCSIDevice *d, uint32_t tag, uint32_t lun,
590
                          uint8_t *buf, void *hba_private)
P
Paolo Bonzini 已提交
591
{
592
    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, d->qdev.parent_bus);
593
    const SCSIReqOps *ops;
594
    SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(d);
595
    SCSIRequest *req;
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
    SCSICommand cmd = { .len = 0 };
    int ret;

    if ((d->unit_attention.key == UNIT_ATTENTION ||
         bus->unit_attention.key == UNIT_ATTENTION) &&
        (buf[0] != INQUIRY &&
         buf[0] != REPORT_LUNS &&
         buf[0] != GET_CONFIGURATION &&
         buf[0] != GET_EVENT_STATUS_NOTIFICATION &&

         /*
          * If we already have a pending unit attention condition,
          * report this one before triggering another one.
          */
         !(buf[0] == REQUEST_SENSE && d->sense_is_ua))) {
        ops = &reqops_unit_attention;
    } else if (lun != d->lun ||
               buf[0] == REPORT_LUNS ||
               (buf[0] == REQUEST_SENSE && d->sense_len)) {
        ops = &reqops_target_command;
    } else {
        ops = NULL;
    }
619

620 621 622 623 624 625
    if (ops != NULL || !sc->parse_cdb) {
        ret = scsi_req_parse_cdb(d, &cmd, buf);
    } else {
        ret = sc->parse_cdb(d, &cmd, buf, hba_private);
    }

626
    if (ret != 0) {
627 628 629
        trace_scsi_req_parse_bad(d->id, lun, tag, buf[0]);
        req = scsi_req_alloc(&reqops_invalid_opcode, d, tag, lun, hba_private);
    } else {
630
        assert(cmd.len != 0);
631 632
        trace_scsi_req_parsed(d->id, lun, tag, buf[0],
                              cmd.mode, cmd.xfer);
633
        if (cmd.lba != -1) {
634 635 636
            trace_scsi_req_parsed_lba(d->id, lun, tag, buf[0],
                                      cmd.lba);
        }
637

638 639
        if (cmd.xfer > INT32_MAX) {
            req = scsi_req_alloc(&reqops_invalid_field, d, tag, lun, hba_private);
640 641
        } else if (ops) {
            req = scsi_req_alloc(ops, d, tag, lun, hba_private);
642
        } else {
643
            req = scsi_device_alloc_req(d, tag, lun, buf, hba_private);
644
        }
645 646 647
    }

    req->cmd = cmd;
648 649
    req->resid = req->cmd.xfer;

650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    switch (buf[0]) {
    case INQUIRY:
        trace_scsi_inquiry(d->id, lun, tag, cmd.buf[1], cmd.buf[2]);
        break;
    case TEST_UNIT_READY:
        trace_scsi_test_unit_ready(d->id, lun, tag);
        break;
    case REPORT_LUNS:
        trace_scsi_report_luns(d->id, lun, tag);
        break;
    case REQUEST_SENSE:
        trace_scsi_request_sense(d->id, lun, tag);
        break;
    default:
        break;
    }

667
    return req;
P
Paolo Bonzini 已提交
668 669
}

P
Paolo Bonzini 已提交
670 671
uint8_t *scsi_req_get_buf(SCSIRequest *req)
{
672
    return req->ops->get_buf(req);
P
Paolo Bonzini 已提交
673 674
}

675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
static void scsi_clear_unit_attention(SCSIRequest *req)
{
    SCSISense *ua;
    if (req->dev->unit_attention.key != UNIT_ATTENTION &&
        req->bus->unit_attention.key != UNIT_ATTENTION) {
        return;
    }

    /*
     * If an INQUIRY command enters the enabled command state,
     * the device server shall [not] clear any unit attention condition;
     * See also MMC-6, paragraphs 6.5 and 6.6.2.
     */
    if (req->cmd.buf[0] == INQUIRY ||
        req->cmd.buf[0] == GET_CONFIGURATION ||
        req->cmd.buf[0] == GET_EVENT_STATUS_NOTIFICATION) {
        return;
    }

    if (req->dev->unit_attention.key == UNIT_ATTENTION) {
        ua = &req->dev->unit_attention;
    } else {
        ua = &req->bus->unit_attention;
    }

    /*
     * If a REPORT LUNS command enters the enabled command state, [...]
     * the device server shall clear any pending unit attention condition
     * with an additional sense code of REPORTED LUNS DATA HAS CHANGED.
     */
    if (req->cmd.buf[0] == REPORT_LUNS &&
        !(ua->asc == SENSE_CODE(REPORTED_LUNS_CHANGED).asc &&
          ua->ascq == SENSE_CODE(REPORTED_LUNS_CHANGED).ascq)) {
        return;
    }

    *ua = SENSE_CODE(NO_SENSE);
}

714 715
int scsi_req_get_sense(SCSIRequest *req, uint8_t *buf, int len)
{
716 717
    int ret;

718 719
    assert(len >= 14);
    if (!req->sense_len) {
720 721
        return 0;
    }
722 723 724 725 726 727 728 729 730 731

    ret = scsi_build_sense(req->sense, req->sense_len, buf, len, true);

    /*
     * FIXME: clearing unit attention conditions upon autosense should be done
     * only if the UA_INTLCK_CTRL field in the Control mode page is set to 00b
     * (SAM-5, 5.14).
     *
     * We assume UA_INTLCK_CTRL to be 00b for HBAs that support autosense, and
     * 10b for HBAs that do not support it (do not call scsi_req_get_sense).
732
     * Here we handle unit attention clearing for UA_INTLCK_CTRL == 00b.
733
     */
734
    if (req->dev->sense_is_ua) {
735
        scsi_device_unit_attention_reported(req->dev);
736 737 738
        req->dev->sense_len = 0;
        req->dev->sense_is_ua = false;
    }
739
    return ret;
740 741 742 743 744 745 746 747 748 749 750 751
}

int scsi_device_get_sense(SCSIDevice *dev, uint8_t *buf, int len, bool fixed)
{
    return scsi_build_sense(dev->sense, dev->sense_len, buf, len, fixed);
}

void scsi_req_build_sense(SCSIRequest *req, SCSISense sense)
{
    trace_scsi_req_build_sense(req->dev->id, req->lun, req->tag,
                               sense.key, sense.asc, sense.ascq);
    memset(req->sense, 0, 18);
752
    req->sense[0] = 0x70;
753
    req->sense[2] = sense.key;
754
    req->sense[7] = 10;
755 756 757
    req->sense[12] = sense.asc;
    req->sense[13] = sense.ascq;
    req->sense_len = 18;
758 759
}

760
static void scsi_req_enqueue_internal(SCSIRequest *req)
761
{
762 763
    assert(!req->enqueued);
    scsi_req_ref(req);
764 765 766 767 768
    if (req->bus->info->get_sg_list) {
        req->sg = req->bus->info->get_sg_list(req);
    } else {
        req->sg = NULL;
    }
769 770
    req->enqueued = true;
    QTAILQ_INSERT_TAIL(&req->dev->requests, req, next);
771
}
772

773 774 775 776 777 778
int32_t scsi_req_enqueue(SCSIRequest *req)
{
    int32_t rc;

    assert(!req->retry);
    scsi_req_enqueue_internal(req);
779
    scsi_req_ref(req);
780
    rc = req->ops->send_command(req, req->cmd.buf);
781 782
    scsi_req_unref(req);
    return rc;
783 784
}

785
static void scsi_req_dequeue(SCSIRequest *req)
786
{
787
    trace_scsi_req_dequeue(req->dev->id, req->lun, req->tag);
788
    req->retry = false;
789 790 791
    if (req->enqueued) {
        QTAILQ_REMOVE(&req->dev->requests, req, next);
        req->enqueued = false;
P
Paolo Bonzini 已提交
792
        scsi_req_unref(req);
793 794 795
    }
}

796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
static int scsi_get_performance_length(int num_desc, int type, int data_type)
{
    /* MMC-6, paragraph 6.7.  */
    switch (type) {
    case 0:
        if ((data_type & 3) == 0) {
            /* Each descriptor is as in Table 295 - Nominal performance.  */
            return 16 * num_desc + 8;
        } else {
            /* Each descriptor is as in Table 296 - Exceptions.  */
            return 6 * num_desc + 8;
        }
    case 1:
    case 4:
    case 5:
        return 8 * num_desc + 8;
    case 2:
        return 2048 * num_desc + 8;
    case 3:
        return 16 * num_desc + 8;
    default:
        return 8;
    }
}

821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
static int ata_passthrough_xfer_unit(SCSIDevice *dev, uint8_t *buf)
{
    int byte_block = (buf[2] >> 2) & 0x1;
    int type = (buf[2] >> 4) & 0x1;
    int xfer_unit;

    if (byte_block) {
        if (type) {
            xfer_unit = dev->blocksize;
        } else {
            xfer_unit = 512;
        }
    } else {
        xfer_unit = 1;
    }

    return xfer_unit;
}

840
static int ata_passthrough_12_xfer(SCSIDevice *dev, uint8_t *buf)
841 842 843 844 845 846 847 848
{
    int length = buf[2] & 0x3;
    int xfer;
    int unit = ata_passthrough_xfer_unit(dev, buf);

    switch (length) {
    case 0:
    case 3: /* USB-specific.  */
G
Gerd Hoffmann 已提交
849
    default:
850 851 852 853 854 855 856 857 858 859 860 861 862
        xfer = 0;
        break;
    case 1:
        xfer = buf[3];
        break;
    case 2:
        xfer = buf[4];
        break;
    }

    return xfer * unit;
}

863
static int ata_passthrough_16_xfer(SCSIDevice *dev, uint8_t *buf)
864 865 866 867 868 869 870 871 872
{
    int extend = buf[1] & 0x1;
    int length = buf[2] & 0x3;
    int xfer;
    int unit = ata_passthrough_xfer_unit(dev, buf);

    switch (length) {
    case 0:
    case 3: /* USB-specific.  */
G
Gerd Hoffmann 已提交
873
    default:
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
        xfer = 0;
        break;
    case 1:
        xfer = buf[4];
        xfer |= (extend ? buf[3] << 8 : 0);
        break;
    case 2:
        xfer = buf[6];
        xfer |= (extend ? buf[5] << 8 : 0);
        break;
    }

    return xfer * unit;
}

889
uint32_t scsi_data_cdb_xfer(uint8_t *buf)
890 891 892 893
{
    if ((buf[0] >> 5) == 0 && buf[4] == 0) {
        return 256;
    } else {
894
        return scsi_cdb_xfer(buf);
895 896 897
    }
}

898
uint32_t scsi_cdb_xfer(uint8_t *buf)
899
{
P
Paolo Bonzini 已提交
900
    switch (buf[0] >> 5) {
901
    case 0:
902
        return buf[4];
903 904 905
        break;
    case 1:
    case 2:
906
        return lduw_be_p(&buf[7]);
907 908
        break;
    case 4:
909
        return ldl_be_p(&buf[10]) & 0xffffffffULL;
910 911
        break;
    case 5:
912
        return ldl_be_p(&buf[6]) & 0xffffffffULL;
913 914 915 916
        break;
    default:
        return -1;
    }
917
}
918

919
static int scsi_req_xfer(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
920
{
921
    cmd->xfer = scsi_cdb_xfer(buf);
P
Paolo Bonzini 已提交
922
    switch (buf[0]) {
923
    case TEST_UNIT_READY:
924
    case REWIND:
925
    case START_STOP:
P
Paolo Bonzini 已提交
926
    case SET_CAPACITY:
927
    case WRITE_FILEMARKS:
928
    case WRITE_FILEMARKS_16:
929
    case SPACE:
930 931
    case RESERVE:
    case RELEASE:
932 933 934 935
    case ERASE:
    case ALLOW_MEDIUM_REMOVAL:
    case SEEK_10:
    case SYNCHRONIZE_CACHE:
936 937
    case SYNCHRONIZE_CACHE_16:
    case LOCATE_16:
938 939 940
    case LOCK_UNLOCK_CACHE:
    case SET_CD_SPEED:
    case SET_LIMITS:
941
    case WRITE_LONG_10:
942
    case UPDATE_BLOCK:
943 944 945 946 947
    case RESERVE_TRACK:
    case SET_READ_AHEAD:
    case PRE_FETCH:
    case PRE_FETCH_16:
    case ALLOW_OVERWRITE:
P
Paolo Bonzini 已提交
948
        cmd->xfer = 0;
949
        break;
950 951 952 953 954
    case VERIFY_10:
    case VERIFY_12:
    case VERIFY_16:
        if ((buf[1] & 2) == 0) {
            cmd->xfer = 0;
955
        } else if ((buf[1] & 4) != 0) {
956 957 958 959
            cmd->xfer = 1;
        }
        cmd->xfer *= dev->blocksize;
        break;
960 961
    case MODE_SENSE:
        break;
962
    case WRITE_SAME_10:
963 964
    case WRITE_SAME_16:
        cmd->xfer = dev->blocksize;
965
        break;
966
    case READ_CAPACITY_10:
P
Paolo Bonzini 已提交
967
        cmd->xfer = 8;
968 969
        break;
    case READ_BLOCK_LIMITS:
P
Paolo Bonzini 已提交
970
        cmd->xfer = 6;
971 972
        break;
    case SEND_VOLUME_TAG:
973 974 975 976 977 978
        /* GPCMD_SET_STREAMING from multimedia commands.  */
        if (dev->type == TYPE_ROM) {
            cmd->xfer = buf[10] | (buf[9] << 8);
        } else {
            cmd->xfer = buf[9] | (buf[8] << 8);
        }
979
        break;
980 981 982 983 984
    case WRITE_6:
        /* length 0 means 256 blocks */
        if (cmd->xfer == 0) {
            cmd->xfer = 256;
        }
985
        /* fall through */
986
    case WRITE_10:
987
    case WRITE_VERIFY_10:
988 989
    case WRITE_12:
    case WRITE_VERIFY_12:
G
Gerd Hoffmann 已提交
990 991
    case WRITE_16:
    case WRITE_VERIFY_16:
P
Paolo Bonzini 已提交
992
        cmd->xfer *= dev->blocksize;
993 994 995
        break;
    case READ_6:
    case READ_REVERSE:
996 997 998 999
        /* length 0 means 256 blocks */
        if (cmd->xfer == 0) {
            cmd->xfer = 256;
        }
1000
        /* fall through */
1001
    case READ_10:
1002
    case READ_12:
G
Gerd Hoffmann 已提交
1003
    case READ_16:
P
Paolo Bonzini 已提交
1004
        cmd->xfer *= dev->blocksize;
1005
        break;
1006 1007 1008 1009 1010 1011 1012 1013 1014
    case FORMAT_UNIT:
        /* MMC mandates the parameter list to be 12-bytes long.  Parameters
         * for block devices are restricted to the header right now.  */
        if (dev->type == TYPE_ROM && (buf[1] & 16)) {
            cmd->xfer = 12;
        } else {
            cmd->xfer = (buf[1] & 16) == 0 ? 0 : (buf[1] & 32 ? 8 : 4);
        }
        break;
1015
    case INQUIRY:
1016 1017
    case RECEIVE_DIAGNOSTIC:
    case SEND_DIAGNOSTIC:
P
Paolo Bonzini 已提交
1018
        cmd->xfer = buf[4] | (buf[3] << 8);
1019
        break;
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
    case READ_CD:
    case READ_BUFFER:
    case WRITE_BUFFER:
    case SEND_CUE_SHEET:
        cmd->xfer = buf[8] | (buf[7] << 8) | (buf[6] << 16);
        break;
    case PERSISTENT_RESERVE_OUT:
        cmd->xfer = ldl_be_p(&buf[5]) & 0xffffffffULL;
        break;
    case ERASE_12:
        if (dev->type == TYPE_ROM) {
            /* MMC command GET PERFORMANCE.  */
            cmd->xfer = scsi_get_performance_length(buf[9] | (buf[8] << 8),
                                                    buf[10], buf[1] & 0x1f);
        }
        break;
    case MECHANISM_STATUS:
    case READ_DVD_STRUCTURE:
    case SEND_DVD_STRUCTURE:
1039 1040
    case MAINTENANCE_OUT:
    case MAINTENANCE_IN:
P
Paolo Bonzini 已提交
1041
        if (dev->type == TYPE_ROM) {
1042
            /* GPCMD_REPORT_KEY and GPCMD_SEND_KEY from multi media commands */
P
Paolo Bonzini 已提交
1043
            cmd->xfer = buf[9] | (buf[8] << 8);
1044 1045
        }
        break;
1046 1047 1048 1049 1050
    case ATA_PASSTHROUGH_12:
        if (dev->type == TYPE_ROM) {
            /* BLANK command of MMC */
            cmd->xfer = 0;
        } else {
1051
            cmd->xfer = ata_passthrough_12_xfer(dev, buf);
1052 1053 1054
        }
        break;
    case ATA_PASSTHROUGH_16:
1055
        cmd->xfer = ata_passthrough_16_xfer(dev, buf);
1056
        break;
1057 1058 1059 1060
    }
    return 0;
}

1061
static int scsi_req_stream_xfer(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
1062
{
P
Paolo Bonzini 已提交
1063
    switch (buf[0]) {
1064
    /* stream commands */
1065 1066 1067 1068
    case ERASE_12:
    case ERASE_16:
        cmd->xfer = 0;
        break;
1069 1070 1071 1072
    case READ_6:
    case READ_REVERSE:
    case RECOVER_BUFFERED_DATA:
    case WRITE_6:
P
Paolo Bonzini 已提交
1073 1074 1075 1076
        cmd->xfer = buf[4] | (buf[3] << 8) | (buf[2] << 16);
        if (buf[1] & 0x01) { /* fixed */
            cmd->xfer *= dev->blocksize;
        }
1077
        break;
P
Paolo Bonzini 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086
    case READ_16:
    case READ_REVERSE_16:
    case VERIFY_16:
    case WRITE_16:
        cmd->xfer = buf[14] | (buf[13] << 8) | (buf[12] << 16);
        if (buf[1] & 0x01) { /* fixed */
            cmd->xfer *= dev->blocksize;
        }
        break;
1087
    case REWIND:
C
Christian Hoff 已提交
1088
    case LOAD_UNLOAD:
P
Paolo Bonzini 已提交
1089
        cmd->xfer = 0;
1090
        break;
1091 1092 1093 1094
    case SPACE_16:
        cmd->xfer = buf[13] | (buf[12] << 8);
        break;
    case READ_POSITION:
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
        switch (buf[1] & 0x1f) /* operation code */ {
        case SHORT_FORM_BLOCK_ID:
        case SHORT_FORM_VENDOR_SPECIFIC:
            cmd->xfer = 20;
            break;
        case LONG_FORM:
            cmd->xfer = 32;
            break;
        case EXTENDED_FORM:
            cmd->xfer = buf[8] | (buf[7] << 8);
            break;
        default:
            return -1;
        }

1110 1111 1112 1113
        break;
    case FORMAT_UNIT:
        cmd->xfer = buf[4] | (buf[3] << 8);
        break;
1114 1115
    /* generic commands */
    default:
1116
        return scsi_req_xfer(cmd, dev, buf);
1117 1118 1119 1120
    }
    return 0;
}

1121
static int scsi_req_medium_changer_xfer(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
{
    switch (buf[0]) {
    /* medium changer commands */
    case EXCHANGE_MEDIUM:
    case INITIALIZE_ELEMENT_STATUS:
    case INITIALIZE_ELEMENT_STATUS_WITH_RANGE:
    case MOVE_MEDIUM:
    case POSITION_TO_ELEMENT:
        cmd->xfer = 0;
        break;
    case READ_ELEMENT_STATUS:
        cmd->xfer = buf[9] | (buf[8] << 8) | (buf[7] << 16);
        break;

    /* generic commands */
    default:
1138
        return scsi_req_xfer(cmd, dev, buf);
1139 1140 1141 1142
    }
    return 0;
}

1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
static int scsi_req_scanner_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
{
    switch (buf[0]) {
    /* Scanner commands */
    case OBJECT_POSITION:
        cmd->xfer = 0;
        break;
    case SCAN:
        cmd->xfer = buf[4];
        break;
    case READ_10:
    case SEND:
    case GET_WINDOW:
    case SET_WINDOW:
        cmd->xfer = buf[8] | (buf[7] << 8) | (buf[6] << 16);
        break;
    default:
        /* GET_DATA_BUFFER_STATUS xfer handled by scsi_req_xfer */
        return scsi_req_xfer(cmd, dev, buf);
    }

    return 0;
}
1166

P
Paolo Bonzini 已提交
1167
static void scsi_cmd_xfer_mode(SCSICommand *cmd)
G
Gerd Hoffmann 已提交
1168
{
1169 1170 1171 1172
    if (!cmd->xfer) {
        cmd->mode = SCSI_XFER_NONE;
        return;
    }
P
Paolo Bonzini 已提交
1173
    switch (cmd->buf[0]) {
G
Gerd Hoffmann 已提交
1174 1175
    case WRITE_6:
    case WRITE_10:
1176
    case WRITE_VERIFY_10:
G
Gerd Hoffmann 已提交
1177 1178
    case WRITE_12:
    case WRITE_VERIFY_12:
G
Gerd Hoffmann 已提交
1179 1180
    case WRITE_16:
    case WRITE_VERIFY_16:
1181 1182 1183
    case VERIFY_10:
    case VERIFY_12:
    case VERIFY_16:
G
Gerd Hoffmann 已提交
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    case COPY:
    case COPY_VERIFY:
    case COMPARE:
    case CHANGE_DEFINITION:
    case LOG_SELECT:
    case MODE_SELECT:
    case MODE_SELECT_10:
    case SEND_DIAGNOSTIC:
    case WRITE_BUFFER:
    case FORMAT_UNIT:
    case REASSIGN_BLOCKS:
    case SEARCH_EQUAL:
    case SEARCH_HIGH:
    case SEARCH_LOW:
    case UPDATE_BLOCK:
1199 1200
    case WRITE_LONG_10:
    case WRITE_SAME_10:
1201
    case WRITE_SAME_16:
1202
    case UNMAP:
G
Gerd Hoffmann 已提交
1203 1204 1205 1206 1207
    case SEARCH_HIGH_12:
    case SEARCH_EQUAL_12:
    case SEARCH_LOW_12:
    case MEDIUM_SCAN:
    case SEND_VOLUME_TAG:
1208 1209
    case SEND_CUE_SHEET:
    case SEND_DVD_STRUCTURE:
1210
    case PERSISTENT_RESERVE_OUT:
1211
    case MAINTENANCE_OUT:
1212 1213 1214 1215 1216
    case SET_WINDOW:
    case SCAN:
        /* SCAN conflicts with START_STOP.  START_STOP has cmd->xfer set to 0 for
         * non-scanner devices, so we only get here for SCAN and not for START_STOP.
         */
P
Paolo Bonzini 已提交
1217
        cmd->mode = SCSI_XFER_TO_DEV;
G
Gerd Hoffmann 已提交
1218
        break;
1219 1220 1221 1222 1223 1224
    case ATA_PASSTHROUGH_12:
    case ATA_PASSTHROUGH_16:
        /* T_DIR */
        cmd->mode = (cmd->buf[2] & 0x8) ?
                   SCSI_XFER_FROM_DEV : SCSI_XFER_TO_DEV;
        break;
G
Gerd Hoffmann 已提交
1225
    default:
1226
        cmd->mode = SCSI_XFER_FROM_DEV;
G
Gerd Hoffmann 已提交
1227 1228 1229 1230
        break;
    }
}

P
Paolo Bonzini 已提交
1231
static uint64_t scsi_cmd_lba(SCSICommand *cmd)
1232
{
P
Paolo Bonzini 已提交
1233
    uint8_t *buf = cmd->buf;
1234 1235 1236 1237
    uint64_t lba;

    switch (buf[0] >> 5) {
    case 0:
1238
        lba = ldl_be_p(&buf[0]) & 0x1fffff;
1239 1240 1241
        break;
    case 1:
    case 2:
1242
    case 5:
1243
        lba = ldl_be_p(&buf[2]) & 0xffffffffULL;
1244 1245
        break;
    case 4:
1246
        lba = ldq_be_p(&buf[2]);
1247 1248 1249 1250 1251 1252 1253 1254
        break;
    default:
        lba = -1;

    }
    return lba;
}

1255 1256
int scsi_cdb_length(uint8_t *buf) {
    int cdb_len;
1257

1258 1259
    switch (buf[0] >> 5) {
    case 0:
1260
        cdb_len = 6;
1261 1262 1263
        break;
    case 1:
    case 2:
1264
        cdb_len = 10;
1265 1266
        break;
    case 4:
1267
        cdb_len = 16;
1268 1269
        break;
    case 5:
1270
        cdb_len = 12;
1271 1272
        break;
    default:
1273
        cdb_len = -1;
1274
    }
1275 1276 1277 1278 1279 1280
    return cdb_len;
}

int scsi_req_parse_cdb(SCSIDevice *dev, SCSICommand *cmd, uint8_t *buf)
{
    int rc;
1281
    int len;
1282 1283

    cmd->lba = -1;
1284 1285 1286 1287
    len = scsi_cdb_length(buf);
    if (len < 0) {
        return -1;
    }
1288

1289
    cmd->len = len;
1290 1291
    switch (dev->type) {
    case TYPE_TAPE:
1292
        rc = scsi_req_stream_xfer(cmd, dev, buf);
1293 1294
        break;
    case TYPE_MEDIUM_CHANGER:
1295
        rc = scsi_req_medium_changer_xfer(cmd, dev, buf);
1296
        break;
1297 1298 1299
    case TYPE_SCANNER:
        rc = scsi_req_scanner_length(cmd, dev, buf);
        break;
1300
    default:
1301
        rc = scsi_req_xfer(cmd, dev, buf);
1302
        break;
1303
    }
1304

1305 1306 1307
    if (rc != 0)
        return rc;

1308 1309 1310
    memcpy(cmd->buf, buf, cmd->len);
    scsi_cmd_xfer_mode(cmd);
    cmd->lba = scsi_cmd_lba(cmd);
1311 1312
    return 0;
}
G
Gerd Hoffmann 已提交
1313

1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
void scsi_device_report_change(SCSIDevice *dev, SCSISense sense)
{
    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);

    scsi_device_set_ua(dev, sense);
    if (bus->info->change) {
        bus->info->change(bus, dev, sense);
    }
}

1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
/*
 * Predefined sense codes
 */

/* No sense data available */
const struct SCSISense sense_code_NO_SENSE = {
    .key = NO_SENSE , .asc = 0x00 , .ascq = 0x00
};

/* LUN not ready, Manual intervention required */
const struct SCSISense sense_code_LUN_NOT_READY = {
    .key = NOT_READY, .asc = 0x04, .ascq = 0x03
};

/* LUN not ready, Medium not present */
const struct SCSISense sense_code_NO_MEDIUM = {
    .key = NOT_READY, .asc = 0x3a, .ascq = 0x00
};

1343 1344
/* LUN not ready, medium removal prevented */
const struct SCSISense sense_code_NOT_READY_REMOVAL_PREVENTED = {
1345
    .key = NOT_READY, .asc = 0x53, .ascq = 0x02
1346 1347
};

1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
/* Hardware error, internal target failure */
const struct SCSISense sense_code_TARGET_FAILURE = {
    .key = HARDWARE_ERROR, .asc = 0x44, .ascq = 0x00
};

/* Illegal request, invalid command operation code */
const struct SCSISense sense_code_INVALID_OPCODE = {
    .key = ILLEGAL_REQUEST, .asc = 0x20, .ascq = 0x00
};

/* Illegal request, LBA out of range */
const struct SCSISense sense_code_LBA_OUT_OF_RANGE = {
    .key = ILLEGAL_REQUEST, .asc = 0x21, .ascq = 0x00
};

/* Illegal request, Invalid field in CDB */
const struct SCSISense sense_code_INVALID_FIELD = {
    .key = ILLEGAL_REQUEST, .asc = 0x24, .ascq = 0x00
};

1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
/* Illegal request, Invalid field in parameter list */
const struct SCSISense sense_code_INVALID_PARAM = {
    .key = ILLEGAL_REQUEST, .asc = 0x26, .ascq = 0x00
};

/* Illegal request, Parameter list length error */
const struct SCSISense sense_code_INVALID_PARAM_LEN = {
    .key = ILLEGAL_REQUEST, .asc = 0x1a, .ascq = 0x00
};

1378 1379 1380 1381 1382
/* Illegal request, LUN not supported */
const struct SCSISense sense_code_LUN_NOT_SUPPORTED = {
    .key = ILLEGAL_REQUEST, .asc = 0x25, .ascq = 0x00
};

1383 1384 1385 1386 1387 1388
/* Illegal request, Saving parameters not supported */
const struct SCSISense sense_code_SAVING_PARAMS_NOT_SUPPORTED = {
    .key = ILLEGAL_REQUEST, .asc = 0x39, .ascq = 0x00
};

/* Illegal request, Incompatible medium installed */
1389
const struct SCSISense sense_code_INCOMPATIBLE_FORMAT = {
1390 1391 1392
    .key = ILLEGAL_REQUEST, .asc = 0x30, .ascq = 0x00
};

1393 1394
/* Illegal request, medium removal prevented */
const struct SCSISense sense_code_ILLEGAL_REQ_REMOVAL_PREVENTED = {
1395
    .key = ILLEGAL_REQUEST, .asc = 0x53, .ascq = 0x02
1396 1397
};

1398 1399 1400 1401 1402
/* Illegal request, Invalid Transfer Tag */
const struct SCSISense sense_code_INVALID_TAG = {
    .key = ILLEGAL_REQUEST, .asc = 0x4b, .ascq = 0x01
};

1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
/* Command aborted, I/O process terminated */
const struct SCSISense sense_code_IO_ERROR = {
    .key = ABORTED_COMMAND, .asc = 0x00, .ascq = 0x06
};

/* Command aborted, I_T Nexus loss occurred */
const struct SCSISense sense_code_I_T_NEXUS_LOSS = {
    .key = ABORTED_COMMAND, .asc = 0x29, .ascq = 0x07
};

/* Command aborted, Logical Unit failure */
const struct SCSISense sense_code_LUN_FAILURE = {
    .key = ABORTED_COMMAND, .asc = 0x3e, .ascq = 0x01
};

1418 1419 1420 1421 1422
/* Command aborted, Overlapped Commands Attempted */
const struct SCSISense sense_code_OVERLAPPED_COMMANDS = {
    .key = ABORTED_COMMAND, .asc = 0x4e, .ascq = 0x00
};

1423 1424 1425 1426 1427
/* Unit attention, Capacity data has changed */
const struct SCSISense sense_code_CAPACITY_CHANGED = {
    .key = UNIT_ATTENTION, .asc = 0x2a, .ascq = 0x09
};

1428 1429 1430 1431 1432
/* Unit attention, Power on, reset or bus device reset occurred */
const struct SCSISense sense_code_RESET = {
    .key = UNIT_ATTENTION, .asc = 0x29, .ascq = 0x00
};

1433 1434 1435 1436 1437
/* Unit attention, No medium */
const struct SCSISense sense_code_UNIT_ATTENTION_NO_MEDIUM = {
    .key = UNIT_ATTENTION, .asc = 0x3a, .ascq = 0x00
};

1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
/* Unit attention, Medium may have changed */
const struct SCSISense sense_code_MEDIUM_CHANGED = {
    .key = UNIT_ATTENTION, .asc = 0x28, .ascq = 0x00
};

/* Unit attention, Reported LUNs data has changed */
const struct SCSISense sense_code_REPORTED_LUNS_CHANGED = {
    .key = UNIT_ATTENTION, .asc = 0x3f, .ascq = 0x0e
};

/* Unit attention, Device internal reset */
const struct SCSISense sense_code_DEVICE_INTERNAL_RESET = {
    .key = UNIT_ATTENTION, .asc = 0x29, .ascq = 0x04
};

1453 1454 1455 1456 1457
/* Data Protection, Write Protected */
const struct SCSISense sense_code_WRITE_PROTECTED = {
    .key = DATA_PROTECT, .asc = 0x27, .ascq = 0x00
};

1458 1459 1460 1461 1462
/* Data Protection, Space Allocation Failed Write Protect */
const struct SCSISense sense_code_SPACE_ALLOC_FAILED = {
    .key = DATA_PROTECT, .asc = 0x27, .ascq = 0x07
};

1463 1464 1465
/*
 * scsi_build_sense
 *
1466
 * Convert between fixed and descriptor sense buffers
1467
 */
1468 1469
int scsi_build_sense(uint8_t *in_buf, int in_len,
                     uint8_t *buf, int len, bool fixed)
1470
{
1471 1472
    bool fixed_in;
    SCSISense sense;
1473 1474 1475 1476
    if (!fixed && len < 8) {
        return 0;
    }

1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
    if (in_len == 0) {
        sense.key = NO_SENSE;
        sense.asc = 0;
        sense.ascq = 0;
    } else {
        fixed_in = (in_buf[0] & 2) == 0;

        if (fixed == fixed_in) {
            memcpy(buf, in_buf, MIN(len, in_len));
            return MIN(len, in_len);
        }

        if (fixed_in) {
            sense.key = in_buf[2];
            sense.asc = in_buf[12];
            sense.ascq = in_buf[13];
        } else {
            sense.key = in_buf[1];
            sense.asc = in_buf[2];
            sense.ascq = in_buf[3];
        }
    }

1500 1501 1502
    memset(buf, 0, len);
    if (fixed) {
        /* Return fixed format sense buffer */
1503
        buf[0] = 0x70;
1504
        buf[2] = sense.key;
1505
        buf[7] = 10;
1506 1507
        buf[12] = sense.asc;
        buf[13] = sense.ascq;
1508
        return MIN(len, SCSI_SENSE_LEN);
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
    } else {
        /* Return descriptor format sense buffer */
        buf[0] = 0x72;
        buf[1] = sense.key;
        buf[2] = sense.asc;
        buf[3] = sense.ascq;
        return 8;
    }
}

1519
const char *scsi_command_name(uint8_t cmd)
G
Gerd Hoffmann 已提交
1520 1521 1522
{
    static const char *names[] = {
        [ TEST_UNIT_READY          ] = "TEST_UNIT_READY",
1523
        [ REWIND                   ] = "REWIND",
G
Gerd Hoffmann 已提交
1524 1525 1526
        [ REQUEST_SENSE            ] = "REQUEST_SENSE",
        [ FORMAT_UNIT              ] = "FORMAT_UNIT",
        [ READ_BLOCK_LIMITS        ] = "READ_BLOCK_LIMITS",
1527 1528
        [ REASSIGN_BLOCKS          ] = "REASSIGN_BLOCKS/INITIALIZE ELEMENT STATUS",
        /* LOAD_UNLOAD and INITIALIZE_ELEMENT_STATUS use the same operation code */
G
Gerd Hoffmann 已提交
1529 1530
        [ READ_6                   ] = "READ_6",
        [ WRITE_6                  ] = "WRITE_6",
P
Paolo Bonzini 已提交
1531
        [ SET_CAPACITY             ] = "SET_CAPACITY",
G
Gerd Hoffmann 已提交
1532 1533 1534 1535 1536
        [ READ_REVERSE             ] = "READ_REVERSE",
        [ WRITE_FILEMARKS          ] = "WRITE_FILEMARKS",
        [ SPACE                    ] = "SPACE",
        [ INQUIRY                  ] = "INQUIRY",
        [ RECOVER_BUFFERED_DATA    ] = "RECOVER_BUFFERED_DATA",
1537 1538
        [ MAINTENANCE_IN           ] = "MAINTENANCE_IN",
        [ MAINTENANCE_OUT          ] = "MAINTENANCE_OUT",
G
Gerd Hoffmann 已提交
1539 1540 1541 1542 1543 1544
        [ MODE_SELECT              ] = "MODE_SELECT",
        [ RESERVE                  ] = "RESERVE",
        [ RELEASE                  ] = "RELEASE",
        [ COPY                     ] = "COPY",
        [ ERASE                    ] = "ERASE",
        [ MODE_SENSE               ] = "MODE_SENSE",
C
Christian Hoff 已提交
1545 1546
        [ START_STOP               ] = "START_STOP/LOAD_UNLOAD",
        /* LOAD_UNLOAD and START_STOP use the same operation code */
G
Gerd Hoffmann 已提交
1547 1548 1549
        [ RECEIVE_DIAGNOSTIC       ] = "RECEIVE_DIAGNOSTIC",
        [ SEND_DIAGNOSTIC          ] = "SEND_DIAGNOSTIC",
        [ ALLOW_MEDIUM_REMOVAL     ] = "ALLOW_MEDIUM_REMOVAL",
1550
        [ READ_CAPACITY_10         ] = "READ_CAPACITY_10",
G
Gerd Hoffmann 已提交
1551 1552
        [ READ_10                  ] = "READ_10",
        [ WRITE_10                 ] = "WRITE_10",
1553 1554
        [ SEEK_10                  ] = "SEEK_10/POSITION_TO_ELEMENT",
        /* SEEK_10 and POSITION_TO_ELEMENT use the same operation code */
1555 1556
        [ WRITE_VERIFY_10          ] = "WRITE_VERIFY_10",
        [ VERIFY_10                ] = "VERIFY_10",
G
Gerd Hoffmann 已提交
1557 1558 1559 1560
        [ SEARCH_HIGH              ] = "SEARCH_HIGH",
        [ SEARCH_EQUAL             ] = "SEARCH_EQUAL",
        [ SEARCH_LOW               ] = "SEARCH_LOW",
        [ SET_LIMITS               ] = "SET_LIMITS",
P
Paolo Bonzini 已提交
1561
        [ PRE_FETCH                ] = "PRE_FETCH/READ_POSITION",
1562
        /* READ_POSITION and PRE_FETCH use the same operation code */
G
Gerd Hoffmann 已提交
1563 1564
        [ SYNCHRONIZE_CACHE        ] = "SYNCHRONIZE_CACHE",
        [ LOCK_UNLOCK_CACHE        ] = "LOCK_UNLOCK_CACHE",
1565 1566
        [ READ_DEFECT_DATA         ] = "READ_DEFECT_DATA/INITIALIZE_ELEMENT_STATUS_WITH_RANGE",
        /* READ_DEFECT_DATA and INITIALIZE_ELEMENT_STATUS_WITH_RANGE use the same operation code */
G
Gerd Hoffmann 已提交
1567 1568 1569 1570 1571 1572
        [ MEDIUM_SCAN              ] = "MEDIUM_SCAN",
        [ COMPARE                  ] = "COMPARE",
        [ COPY_VERIFY              ] = "COPY_VERIFY",
        [ WRITE_BUFFER             ] = "WRITE_BUFFER",
        [ READ_BUFFER              ] = "READ_BUFFER",
        [ UPDATE_BLOCK             ] = "UPDATE_BLOCK",
1573 1574
        [ READ_LONG_10             ] = "READ_LONG_10",
        [ WRITE_LONG_10            ] = "WRITE_LONG_10",
G
Gerd Hoffmann 已提交
1575
        [ CHANGE_DEFINITION        ] = "CHANGE_DEFINITION",
1576 1577
        [ WRITE_SAME_10            ] = "WRITE_SAME_10",
        [ UNMAP                    ] = "UNMAP",
G
Gerd Hoffmann 已提交
1578
        [ READ_TOC                 ] = "READ_TOC",
1579
        [ REPORT_DENSITY_SUPPORT   ] = "REPORT_DENSITY_SUPPORT",
P
Paolo Bonzini 已提交
1580
        [ SANITIZE                 ] = "SANITIZE",
1581
        [ GET_CONFIGURATION        ] = "GET_CONFIGURATION",
G
Gerd Hoffmann 已提交
1582 1583 1584 1585 1586 1587 1588 1589
        [ LOG_SELECT               ] = "LOG_SELECT",
        [ LOG_SENSE                ] = "LOG_SENSE",
        [ MODE_SELECT_10           ] = "MODE_SELECT_10",
        [ RESERVE_10               ] = "RESERVE_10",
        [ RELEASE_10               ] = "RELEASE_10",
        [ MODE_SENSE_10            ] = "MODE_SENSE_10",
        [ PERSISTENT_RESERVE_IN    ] = "PERSISTENT_RESERVE_IN",
        [ PERSISTENT_RESERVE_OUT   ] = "PERSISTENT_RESERVE_OUT",
1590 1591
        [ WRITE_FILEMARKS_16       ] = "WRITE_FILEMARKS_16",
        [ EXTENDED_COPY            ] = "EXTENDED_COPY",
1592
        [ ATA_PASSTHROUGH_16       ] = "ATA_PASSTHROUGH_16",
1593 1594 1595 1596 1597 1598 1599
        [ ACCESS_CONTROL_IN        ] = "ACCESS_CONTROL_IN",
        [ ACCESS_CONTROL_OUT       ] = "ACCESS_CONTROL_OUT",
        [ READ_16                  ] = "READ_16",
        [ COMPARE_AND_WRITE        ] = "COMPARE_AND_WRITE",
        [ WRITE_16                 ] = "WRITE_16",
        [ WRITE_VERIFY_16          ] = "WRITE_VERIFY_16",
        [ VERIFY_16                ] = "VERIFY_16",
P
Paolo Bonzini 已提交
1600 1601 1602
        [ PRE_FETCH_16             ] = "PRE_FETCH_16",
        [ SYNCHRONIZE_CACHE_16     ] = "SPACE_16/SYNCHRONIZE_CACHE_16",
        /* SPACE_16 and SYNCHRONIZE_CACHE_16 use the same operation code */
1603
        [ LOCATE_16                ] = "LOCATE_16",
P
Paolo Bonzini 已提交
1604
        [ WRITE_SAME_16            ] = "ERASE_16/WRITE_SAME_16",
1605
        /* ERASE_16 and WRITE_SAME_16 use the same operation code */
1606
        [ SERVICE_ACTION_IN_16     ] = "SERVICE_ACTION_IN_16",
1607 1608
        [ WRITE_LONG_16            ] = "WRITE_LONG_16",
        [ REPORT_LUNS              ] = "REPORT_LUNS",
1609
        [ ATA_PASSTHROUGH_12       ] = "BLANK/ATA_PASSTHROUGH_12",
G
Gerd Hoffmann 已提交
1610
        [ MOVE_MEDIUM              ] = "MOVE_MEDIUM",
1611
        [ EXCHANGE_MEDIUM          ] = "EXCHANGE MEDIUM",
G
Gerd Hoffmann 已提交
1612 1613
        [ READ_12                  ] = "READ_12",
        [ WRITE_12                 ] = "WRITE_12",
P
Paolo Bonzini 已提交
1614 1615
        [ ERASE_12                 ] = "ERASE_12/GET_PERFORMANCE",
        /* ERASE_12 and GET_PERFORMANCE use the same operation code */
1616
        [ SERVICE_ACTION_IN_12     ] = "SERVICE_ACTION_IN_12",
G
Gerd Hoffmann 已提交
1617
        [ WRITE_VERIFY_12          ] = "WRITE_VERIFY_12",
1618
        [ VERIFY_12                ] = "VERIFY_12",
G
Gerd Hoffmann 已提交
1619 1620 1621 1622
        [ SEARCH_HIGH_12           ] = "SEARCH_HIGH_12",
        [ SEARCH_EQUAL_12          ] = "SEARCH_EQUAL_12",
        [ SEARCH_LOW_12            ] = "SEARCH_LOW_12",
        [ READ_ELEMENT_STATUS      ] = "READ_ELEMENT_STATUS",
P
Paolo Bonzini 已提交
1623 1624 1625
        [ SEND_VOLUME_TAG          ] = "SEND_VOLUME_TAG/SET_STREAMING",
        /* SEND_VOLUME_TAG and SET_STREAMING use the same operation code */
        [ READ_CD                  ] = "READ_CD",
1626
        [ READ_DEFECT_DATA_12      ] = "READ_DEFECT_DATA_12",
P
Paolo Bonzini 已提交
1627 1628 1629 1630
        [ READ_DVD_STRUCTURE       ] = "READ_DVD_STRUCTURE",
        [ RESERVE_TRACK            ] = "RESERVE_TRACK",
        [ SEND_CUE_SHEET           ] = "SEND_CUE_SHEET",
        [ SEND_DVD_STRUCTURE       ] = "SEND_DVD_STRUCTURE",
G
Gerd Hoffmann 已提交
1631
        [ SET_CD_SPEED             ] = "SET_CD_SPEED",
P
Paolo Bonzini 已提交
1632 1633 1634
        [ SET_READ_AHEAD           ] = "SET_READ_AHEAD",
        [ ALLOW_OVERWRITE          ] = "ALLOW_OVERWRITE",
        [ MECHANISM_STATUS         ] = "MECHANISM_STATUS",
1635 1636
        [ GET_EVENT_STATUS_NOTIFICATION ] = "GET_EVENT_STATUS_NOTIFICATION",
        [ READ_DISC_INFORMATION    ] = "READ_DISC_INFORMATION",
G
Gerd Hoffmann 已提交
1637 1638 1639 1640 1641 1642 1643
    };

    if (cmd >= ARRAY_SIZE(names) || names[cmd] == NULL)
        return "*UNKNOWN*";
    return names[cmd];
}

P
Paolo Bonzini 已提交
1644 1645
SCSIRequest *scsi_req_ref(SCSIRequest *req)
{
P
Paolo Bonzini 已提交
1646
    assert(req->refcount > 0);
P
Paolo Bonzini 已提交
1647 1648 1649 1650 1651 1652
    req->refcount++;
    return req;
}

void scsi_req_unref(SCSIRequest *req)
{
1653
    assert(req->refcount > 0);
P
Paolo Bonzini 已提交
1654
    if (--req->refcount == 0) {
1655 1656 1657
        BusState *qbus = req->dev->qdev.parent_bus;
        SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, qbus);

P
Paolo Bonzini 已提交
1658 1659 1660
        if (bus->info->free_request && req->hba_private) {
            bus->info->free_request(bus, req->hba_private);
        }
1661 1662
        if (req->ops->free_req) {
            req->ops->free_req(req);
P
Paolo Bonzini 已提交
1663
        }
1664 1665
        object_unref(OBJECT(req->dev));
        object_unref(OBJECT(qbus->parent));
1666
        g_free(req);
P
Paolo Bonzini 已提交
1667 1668 1669
    }
}

1670 1671 1672 1673
/* Tell the device that we finished processing this chunk of I/O.  It
   will start the next chunk or complete the command.  */
void scsi_req_continue(SCSIRequest *req)
{
1674 1675 1676 1677
    if (req->io_canceled) {
        trace_scsi_req_continue_canceled(req->dev->id, req->lun, req->tag);
        return;
    }
1678 1679
    trace_scsi_req_continue(req->dev->id, req->lun, req->tag);
    if (req->cmd.mode == SCSI_XFER_TO_DEV) {
1680
        req->ops->write_data(req);
1681
    } else {
1682
        req->ops->read_data(req);
1683 1684 1685
    }
}

P
Paolo Bonzini 已提交
1686 1687
/* Called by the devices when data is ready for the HBA.  The HBA should
   start a DMA operation to read or fill the device's data buffer.
1688
   Once it completes, calling scsi_req_continue will restart I/O.  */
P
Paolo Bonzini 已提交
1689 1690
void scsi_req_data(SCSIRequest *req, int len)
{
1691
    uint8_t *buf;
1692 1693
    if (req->io_canceled) {
        trace_scsi_req_data_canceled(req->dev->id, req->lun, req->tag, len);
1694
        return;
1695
    }
1696 1697
    trace_scsi_req_data(req->dev->id, req->lun, req->tag, len);
    assert(req->cmd.mode != SCSI_XFER_NONE);
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
    if (!req->sg) {
        req->resid -= len;
        req->bus->info->transfer_data(req, len);
        return;
    }

    /* If the device calls scsi_req_data and the HBA specified a
     * scatter/gather list, the transfer has to happen in a single
     * step.  */
    assert(!req->dma_started);
    req->dma_started = true;

    buf = scsi_req_get_buf(req);
    if (req->cmd.mode == SCSI_XFER_FROM_DEV) {
        req->resid = dma_buf_read(buf, len, req->sg);
    } else {
        req->resid = dma_buf_write(buf, len, req->sg);
    }
    scsi_req_continue(req);
P
Paolo Bonzini 已提交
1717 1718
}

G
Gerd Hoffmann 已提交
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
void scsi_req_print(SCSIRequest *req)
{
    FILE *fp = stderr;
    int i;

    fprintf(fp, "[%s id=%d] %s",
            req->dev->qdev.parent_bus->name,
            req->dev->id,
            scsi_command_name(req->cmd.buf[0]));
    for (i = 1; i < req->cmd.len; i++) {
        fprintf(fp, " 0x%02x", req->cmd.buf[i]);
    }
    switch (req->cmd.mode) {
    case SCSI_XFER_NONE:
        fprintf(fp, " - none\n");
        break;
    case SCSI_XFER_FROM_DEV:
        fprintf(fp, " - from-dev len=%zd\n", req->cmd.xfer);
        break;
    case SCSI_XFER_TO_DEV:
        fprintf(fp, " - to-dev len=%zd\n", req->cmd.xfer);
        break;
    default:
        fprintf(fp, " - Oops\n");
        break;
    }
}

1747
void scsi_req_complete(SCSIRequest *req, int status)
G
Gerd Hoffmann 已提交
1748
{
1749 1750
    assert(req->status == -1);
    req->status = status;
1751

1752
    assert(req->sense_len <= sizeof(req->sense));
1753 1754 1755 1756 1757 1758
    if (status == GOOD) {
        req->sense_len = 0;
    }

    if (req->sense_len) {
        memcpy(req->dev->sense, req->sense, req->sense_len);
1759 1760 1761 1762 1763
        req->dev->sense_len = req->sense_len;
        req->dev->sense_is_ua = (req->ops == &reqops_unit_attention);
    } else {
        req->dev->sense_len = 0;
        req->dev->sense_is_ua = false;
1764 1765
    }

1766 1767 1768 1769 1770 1771 1772
    /*
     * Unit attention state is now stored in the device's sense buffer
     * if the HBA didn't do autosense.  Clear the pending unit attention
     * flags.
     */
    scsi_clear_unit_attention(req);

P
Paolo Bonzini 已提交
1773
    scsi_req_ref(req);
1774
    scsi_req_dequeue(req);
1775
    req->bus->info->complete(req, req->status, req->resid);
1776 1777 1778

    /* Cancelled requests might end up being completed instead of cancelled */
    notifier_list_notify(&req->cancel_notifiers, req);
P
Paolo Bonzini 已提交
1779
    scsi_req_unref(req);
G
Gerd Hoffmann 已提交
1780
}
1781

1782 1783 1784 1785 1786 1787 1788
/* Called by the devices when the request is canceled. */
void scsi_req_cancel_complete(SCSIRequest *req)
{
    assert(req->io_canceled);
    if (req->bus->info->cancel) {
        req->bus->info->cancel(req);
    }
1789
    notifier_list_notify(&req->cancel_notifiers, req);
1790 1791 1792
    scsi_req_unref(req);
}

1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
/* Cancel @req asynchronously. @notifier is added to @req's cancellation
 * notifier list, the bus will be notified the requests cancellation is
 * completed.
 * */
void scsi_req_cancel_async(SCSIRequest *req, Notifier *notifier)
{
    trace_scsi_req_cancel(req->dev->id, req->lun, req->tag);
    if (notifier) {
        notifier_list_add(&req->cancel_notifiers, notifier);
    }
1803 1804 1805 1806 1807 1808 1809 1810 1811
    if (req->io_canceled) {
        /* A blk_aio_cancel_async is pending; when it finishes,
         * scsi_req_cancel_complete will be called and will
         * call the notifier we just added.  Just wait for that.
         */
        assert(req->aiocb);
        return;
    }
    /* Dropped in scsi_req_cancel_complete.  */
1812 1813 1814 1815
    scsi_req_ref(req);
    scsi_req_dequeue(req);
    req->io_canceled = true;
    if (req->aiocb) {
1816
        blk_aio_cancel_async(req->aiocb);
1817 1818
    } else {
        scsi_req_cancel_complete(req);
1819 1820 1821
    }
}

P
Paolo Bonzini 已提交
1822 1823
void scsi_req_cancel(SCSIRequest *req)
{
1824
    trace_scsi_req_cancel(req->dev->id, req->lun, req->tag);
1825 1826
    if (!req->enqueued) {
        return;
P
Paolo Bonzini 已提交
1827
    }
1828 1829
    assert(!req->io_canceled);
    /* Dropped in scsi_req_cancel_complete.  */
P
Paolo Bonzini 已提交
1830 1831
    scsi_req_ref(req);
    scsi_req_dequeue(req);
1832
    req->io_canceled = true;
F
Fam Zheng 已提交
1833
    if (req->aiocb) {
1834
        blk_aio_cancel(req->aiocb);
1835 1836
    } else {
        scsi_req_cancel_complete(req);
1837
    }
P
Paolo Bonzini 已提交
1838 1839
}

1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
static int scsi_ua_precedence(SCSISense sense)
{
    if (sense.key != UNIT_ATTENTION) {
        return INT_MAX;
    }
    if (sense.asc == 0x29 && sense.ascq == 0x04) {
        /* DEVICE INTERNAL RESET goes with POWER ON OCCURRED */
        return 1;
    } else if (sense.asc == 0x3F && sense.ascq == 0x01) {
        /* MICROCODE HAS BEEN CHANGED goes with SCSI BUS RESET OCCURRED */
        return 2;
    } else if (sense.asc == 0x29 && (sense.ascq == 0x05 || sense.ascq == 0x06)) {
        /* These two go with "all others". */
        ;
    } else if (sense.asc == 0x29 && sense.ascq <= 0x07) {
        /* POWER ON, RESET OR BUS DEVICE RESET OCCURRED = 0
         * POWER ON OCCURRED = 1
         * SCSI BUS RESET OCCURRED = 2
         * BUS DEVICE RESET FUNCTION OCCURRED = 3
         * I_T NEXUS LOSS OCCURRED = 7
         */
        return sense.ascq;
    } else if (sense.asc == 0x2F && sense.ascq == 0x01) {
        /* COMMANDS CLEARED BY POWER LOSS NOTIFICATION  */
        return 8;
    }
    return (sense.asc << 8) | sense.ascq;
}

void scsi_device_set_ua(SCSIDevice *sdev, SCSISense sense)
{
    int prec1, prec2;
    if (sense.key != UNIT_ATTENTION) {
        return;
    }
    trace_scsi_device_set_ua(sdev->id, sdev->lun, sense.key,
                             sense.asc, sense.ascq);

    /*
     * Override a pre-existing unit attention condition, except for a more
     * important reset condition.
    */
    prec1 = scsi_ua_precedence(sdev->unit_attention);
    prec2 = scsi_ua_precedence(sense);
    if (prec2 < prec1) {
        sdev->unit_attention = sense;
    }
}

1889
void scsi_device_purge_requests(SCSIDevice *sdev, SCSISense sense)
P
Paolo Bonzini 已提交
1890 1891 1892
{
    SCSIRequest *req;

1893
    aio_context_acquire(blk_get_aio_context(sdev->conf.blk));
P
Paolo Bonzini 已提交
1894 1895
    while (!QTAILQ_EMPTY(&sdev->requests)) {
        req = QTAILQ_FIRST(&sdev->requests);
1896
        scsi_req_cancel_async(req, NULL);
P
Paolo Bonzini 已提交
1897
    }
1898 1899
    blk_drain(sdev->conf.blk);
    aio_context_release(blk_get_aio_context(sdev->conf.blk));
1900
    scsi_device_set_ua(sdev, sense);
P
Paolo Bonzini 已提交
1901 1902
}

P
Paolo Bonzini 已提交
1903 1904
static char *scsibus_get_dev_path(DeviceState *dev)
{
C
Cao jin 已提交
1905
    SCSIDevice *d = SCSI_DEVICE(dev);
P
Paolo Bonzini 已提交
1906
    DeviceState *hba = dev->parent_bus->parent;
1907
    char *id;
P
Paolo Bonzini 已提交
1908
    char *path;
P
Paolo Bonzini 已提交
1909

1910
    id = qdev_get_dev_path(hba);
P
Paolo Bonzini 已提交
1911
    if (id) {
P
Paolo Bonzini 已提交
1912
        path = g_strdup_printf("%s/%d:%d:%d", id, d->channel, d->id, d->lun);
P
Paolo Bonzini 已提交
1913
    } else {
P
Paolo Bonzini 已提交
1914
        path = g_strdup_printf("%d:%d:%d", d->channel, d->id, d->lun);
P
Paolo Bonzini 已提交
1915
    }
P
Paolo Bonzini 已提交
1916 1917
    g_free(id);
    return path;
P
Paolo Bonzini 已提交
1918 1919
}

1920 1921
static char *scsibus_get_fw_dev_path(DeviceState *dev)
{
1922
    SCSIDevice *d = SCSI_DEVICE(dev);
1923 1924
    return g_strdup_printf("channel@%x/%s@%x,%x", d->channel,
                           qdev_fw_name(dev), d->id, d->lun);
1925 1926
}

P
Paolo Bonzini 已提交
1927
SCSIDevice *scsi_device_find(SCSIBus *bus, int channel, int id, int lun)
1928
{
A
Anthony Liguori 已提交
1929
    BusChild *kid;
1930
    SCSIDevice *target_dev = NULL;
1931

A
Anthony Liguori 已提交
1932 1933
    QTAILQ_FOREACH_REVERSE(kid, &bus->qbus.children, ChildrenHead, sibling) {
        DeviceState *qdev = kid->child;
1934
        SCSIDevice *dev = SCSI_DEVICE(qdev);
1935

P
Paolo Bonzini 已提交
1936
        if (dev->channel == channel && dev->id == id) {
1937 1938 1939 1940 1941 1942 1943
            if (dev->lun == lun) {
                return dev;
            }
            target_dev = dev;
        }
    }
    return target_dev;
1944
}
1945

1946 1947
/* SCSI request list.  For simplicity, pv points to the whole device */

J
Jianjun Duan 已提交
1948 1949
static int put_scsi_requests(QEMUFile *f, void *pv, size_t size,
                             VMStateField *field, QJSON *vmdesc)
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
{
    SCSIDevice *s = pv;
    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, s->qdev.parent_bus);
    SCSIRequest *req;

    QTAILQ_FOREACH(req, &s->requests, next) {
        assert(!req->io_canceled);
        assert(req->status == -1);
        assert(req->enqueued);

1960
        qemu_put_sbyte(f, req->retry ? 1 : 2);
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
        qemu_put_buffer(f, req->cmd.buf, sizeof(req->cmd.buf));
        qemu_put_be32s(f, &req->tag);
        qemu_put_be32s(f, &req->lun);
        if (bus->info->save_request) {
            bus->info->save_request(f, req);
        }
        if (req->ops->save_request) {
            req->ops->save_request(f, req);
        }
    }
    qemu_put_sbyte(f, 0);
J
Jianjun Duan 已提交
1972 1973

    return 0;
1974 1975
}

J
Jianjun Duan 已提交
1976 1977
static int get_scsi_requests(QEMUFile *f, void *pv, size_t size,
                             VMStateField *field)
1978 1979 1980
{
    SCSIDevice *s = pv;
    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, s->qdev.parent_bus);
1981
    int8_t sbyte;
1982

1983
    while ((sbyte = qemu_get_sbyte(f)) > 0) {
1984 1985 1986 1987 1988 1989 1990 1991 1992
        uint8_t buf[SCSI_CMD_BUF_SIZE];
        uint32_t tag;
        uint32_t lun;
        SCSIRequest *req;

        qemu_get_buffer(f, buf, sizeof(buf));
        qemu_get_be32s(f, &tag);
        qemu_get_be32s(f, &lun);
        req = scsi_req_new(s, tag, lun, buf, NULL);
1993
        req->retry = (sbyte == 1);
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
        if (bus->info->load_request) {
            req->hba_private = bus->info->load_request(f, req);
        }
        if (req->ops->load_request) {
            req->ops->load_request(f, req);
        }

        /* Just restart it later.  */
        scsi_req_enqueue_internal(req);

        /* At this point, the request will be kept alive by the reference
         * added by scsi_req_enqueue_internal, so we can release our reference.
         * The HBA of course will add its own reference in the load_request
         * callback if it needs to hold on the SCSIRequest.
         */
        scsi_req_unref(req);
    }

    return 0;
}

2015
static const VMStateInfo vmstate_info_scsi_requests = {
2016 2017 2018 2019 2020
    .name = "scsi-requests",
    .get  = get_scsi_requests,
    .put  = put_scsi_requests,
};

2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031
static bool scsi_sense_state_needed(void *opaque)
{
    SCSIDevice *s = opaque;

    return s->sense_len > SCSI_SENSE_BUF_SIZE_OLD;
}

static const VMStateDescription vmstate_scsi_sense_state = {
    .name = "SCSIDevice/sense",
    .version_id = 1,
    .minimum_version_id = 1,
2032
    .needed = scsi_sense_state_needed,
2033
    .fields = (VMStateField[]) {
2034 2035 2036 2037 2038 2039 2040
        VMSTATE_UINT8_SUB_ARRAY(sense, SCSIDevice,
                                SCSI_SENSE_BUF_SIZE_OLD,
                                SCSI_SENSE_BUF_SIZE - SCSI_SENSE_BUF_SIZE_OLD),
        VMSTATE_END_OF_LIST()
    }
};

2041 2042 2043 2044 2045 2046 2047 2048 2049
const VMStateDescription vmstate_scsi_device = {
    .name = "SCSIDevice",
    .version_id = 1,
    .minimum_version_id = 1,
    .fields = (VMStateField[]) {
        VMSTATE_UINT8(unit_attention.key, SCSIDevice),
        VMSTATE_UINT8(unit_attention.asc, SCSIDevice),
        VMSTATE_UINT8(unit_attention.ascq, SCSIDevice),
        VMSTATE_BOOL(sense_is_ua, SCSIDevice),
2050
        VMSTATE_UINT8_SUB_ARRAY(sense, SCSIDevice, 0, SCSI_SENSE_BUF_SIZE_OLD),
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
        VMSTATE_UINT32(sense_len, SCSIDevice),
        {
            .name         = "requests",
            .version_id   = 0,
            .field_exists = NULL,
            .size         = 0,   /* ouch */
            .info         = &vmstate_info_scsi_requests,
            .flags        = VMS_SINGLE,
            .offset       = 0,
        },
        VMSTATE_END_OF_LIST()
2062
    },
2063 2064 2065
    .subsections = (const VMStateDescription*[]) {
        &vmstate_scsi_sense_state,
        NULL
2066 2067 2068
    }
};

2069 2070 2071
static void scsi_device_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *k = DEVICE_CLASS(klass);
2072
    set_bit(DEVICE_CATEGORY_STORAGE, k->categories);
2073 2074 2075 2076
    k->bus_type  = TYPE_SCSI_BUS;
    k->realize   = scsi_qdev_realize;
    k->unrealize = scsi_qdev_unrealize;
    k->props     = scsi_props;
2077 2078
}

G
Gonglei 已提交
2079 2080 2081
static void scsi_dev_instance_init(Object *obj)
{
    DeviceState *dev = DEVICE(obj);
C
Cao jin 已提交
2082
    SCSIDevice *s = SCSI_DEVICE(dev);
G
Gonglei 已提交
2083 2084 2085 2086 2087 2088

    device_add_bootindex_property(obj, &s->conf.bootindex,
                                  "bootindex", NULL,
                                  &s->qdev, NULL);
}

2089
static const TypeInfo scsi_device_type_info = {
2090 2091 2092 2093 2094
    .name = TYPE_SCSI_DEVICE,
    .parent = TYPE_DEVICE,
    .instance_size = sizeof(SCSIDevice),
    .abstract = true,
    .class_size = sizeof(SCSIDeviceClass),
2095
    .class_init = scsi_device_class_init,
G
Gonglei 已提交
2096
    .instance_init = scsi_dev_instance_init,
2097 2098
};

A
Andreas Färber 已提交
2099
static void scsi_register_types(void)
2100
{
2101
    type_register_static(&scsi_bus_info);
2102 2103 2104
    type_register_static(&scsi_device_type_info);
}

A
Andreas Färber 已提交
2105
type_init(scsi_register_types)