scsi-bus.c 39.5 KB
Newer Older
1
#include "hw.h"
2
#include "qemu-error.h"
G
Gerd Hoffmann 已提交
3
#include "scsi.h"
4
#include "scsi-defs.h"
5
#include "qdev.h"
B
Blue Swirl 已提交
6
#include "blockdev.h"
7
#include "trace.h"
8

9
static char *scsibus_get_fw_dev_path(DeviceState *dev);
10
static int scsi_req_parse(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf);
11
static void scsi_req_dequeue(SCSIRequest *req);
12

13 14 15
static struct BusInfo scsi_bus_info = {
    .name  = "SCSI",
    .size  = sizeof(SCSIBus),
16
    .get_fw_dev_path = scsibus_get_fw_dev_path,
17
    .props = (Property[]) {
P
Paolo Bonzini 已提交
18
        DEFINE_PROP_UINT32("channel", SCSIDevice, channel, 0),
19
        DEFINE_PROP_UINT32("scsi-id", SCSIDevice, id, -1),
P
Paolo Bonzini 已提交
20
        DEFINE_PROP_UINT32("lun", SCSIDevice, lun, -1),
21 22 23 24 25 26
        DEFINE_PROP_END_OF_LIST(),
    },
};
static int next_scsi_bus;

/* Create a scsi bus, and attach devices to it.  */
27
void scsi_bus_new(SCSIBus *bus, DeviceState *host, const SCSIBusInfo *info)
28
{
29
    qbus_create_inplace(&bus->qbus, &scsi_bus_info, host, NULL);
30
    bus->busnr = next_scsi_bus++;
31
    bus->info = info;
G
Gerd Hoffmann 已提交
32
    bus->qbus.allow_hotplug = 1;
33 34
}

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
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) {
        s->bh = qemu_bh_new(scsi_dma_restart_bh, s);
        qemu_bh_schedule(s->bh);
    }
}

82 83 84 85 86
static int scsi_qdev_init(DeviceState *qdev, DeviceInfo *base)
{
    SCSIDevice *dev = DO_UPCAST(SCSIDevice, qdev, qdev);
    SCSIDeviceInfo *info = DO_UPCAST(SCSIDeviceInfo, qdev, base);
    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);
P
Paolo Bonzini 已提交
87
    SCSIDevice *d;
G
Gerd Hoffmann 已提交
88
    int rc = -1;
89

P
Paolo Bonzini 已提交
90 91 92 93
    if (dev->channel > bus->info->max_channel) {
        error_report("bad scsi channel id: %d", dev->channel);
        goto err;
    }
P
Paolo Bonzini 已提交
94
    if (dev->id != -1 && dev->id > bus->info->max_target) {
95
        error_report("bad scsi device id: %d", dev->id);
96 97 98
        goto err;
    }

P
Paolo Bonzini 已提交
99 100 101 102 103 104
    if (dev->id == -1) {
        int id = -1;
        if (dev->lun == -1) {
            dev->lun = 0;
        }
        do {
P
Paolo Bonzini 已提交
105
            d = scsi_device_find(bus, dev->channel, ++id, dev->lun);
P
Paolo Bonzini 已提交
106 107 108 109 110 111 112 113 114
        } while (d && d->lun == dev->lun && id <= bus->info->max_target);
        if (id > bus->info->max_target) {
            error_report("no free target");
            goto err;
        }
        dev->id = id;
    } else if (dev->lun == -1) {
        int lun = -1;
        do {
P
Paolo Bonzini 已提交
115
            d = scsi_device_find(bus, dev->channel, dev->id, ++lun);
P
Paolo Bonzini 已提交
116 117 118 119 120 121 122
        } while (d && d->lun == lun && lun < bus->info->max_lun);
        if (lun > bus->info->max_lun) {
            error_report("no free lun");
            goto err;
        }
        dev->lun = lun;
    } else {
P
Paolo Bonzini 已提交
123
        d = scsi_device_find(bus, dev->channel, dev->id, dev->lun);
P
Paolo Bonzini 已提交
124 125 126
        if (dev->lun == d->lun && dev != d) {
            qdev_free(&d->qdev);
        }
127 128 129
    }

    dev->info = info;
130
    QTAILQ_INIT(&dev->requests);
G
Gerd Hoffmann 已提交
131
    rc = dev->info->init(dev);
132 133 134 135
    if (rc == 0) {
        dev->vmsentry = qemu_add_vm_change_state_handler(scsi_dma_restart_cb,
                                                         dev);
    }
136 137

err:
G
Gerd Hoffmann 已提交
138 139 140 141 142 143 144
    return rc;
}

static int scsi_qdev_exit(DeviceState *qdev)
{
    SCSIDevice *dev = DO_UPCAST(SCSIDevice, qdev, qdev);

145 146 147
    if (dev->vmsentry) {
        qemu_del_vm_change_state_handler(dev->vmsentry);
    }
148 149
    if (dev->info->destroy) {
        dev->info->destroy(dev);
G
Gerd Hoffmann 已提交
150 151
    }
    return 0;
152 153 154 155 156 157
}

void scsi_qdev_register(SCSIDeviceInfo *info)
{
    info->qdev.bus_info = &scsi_bus_info;
    info->qdev.init     = scsi_qdev_init;
G
Gerd Hoffmann 已提交
158
    info->qdev.unplug   = qdev_simple_unplug_cb;
G
Gerd Hoffmann 已提交
159
    info->qdev.exit     = scsi_qdev_exit;
160 161 162 163
    qdev_register(&info->qdev);
}

/* handle legacy '-drive if=scsi,...' cmd line args */
164 165
SCSIDevice *scsi_bus_legacy_add_drive(SCSIBus *bus, BlockDriverState *bdrv,
                                      int unit, bool removable)
166 167 168 169
{
    const char *driver;
    DeviceState *dev;

170
    driver = bdrv_is_sg(bdrv) ? "scsi-generic" : "scsi-disk";
171 172
    dev = qdev_create(&bus->qbus, driver);
    qdev_prop_set_uint32(dev, "scsi-id", unit);
173 174 175
    if (qdev_prop_exists(dev, "removable")) {
        qdev_prop_set_bit(dev, "removable", removable);
    }
176 177 178 179
    if (qdev_prop_set_drive(dev, "drive", bdrv) < 0) {
        qdev_free(dev);
        return NULL;
    }
180 181
    if (qdev_init(dev) < 0)
        return NULL;
182 183 184
    return DO_UPCAST(SCSIDevice, qdev, dev);
}

185
int scsi_bus_legacy_handle_cmdline(SCSIBus *bus)
186
{
187
    Location loc;
188
    DriveInfo *dinfo;
189
    int res = 0, unit;
190

191
    loc_push_none(&loc);
P
Paolo Bonzini 已提交
192
    for (unit = 0; unit < bus->info->max_target; unit++) {
193 194 195 196
        dinfo = drive_get(IF_SCSI, bus->busnr, unit);
        if (dinfo == NULL) {
            continue;
        }
197
        qemu_opts_loc_restore(dinfo->opts);
198
        if (!scsi_bus_legacy_add_drive(bus, dinfo->bdrv, unit, false)) {
199 200 201
            res = -1;
            break;
        }
202
    }
203
    loc_pop(&loc);
204
    return res;
205
}
206

207 208 209 210 211 212 213 214 215
/* 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 已提交
216
static const struct SCSIReqOps reqops_invalid_opcode = {
217 218 219 220
    .size         = sizeof(SCSIRequest),
    .send_command = scsi_invalid_command
};

221 222 223 224 225 226 227 228 229 230 231 232 233
/* SCSIReqOps implementation for unit attention conditions.  */

static int32_t scsi_unit_attention(SCSIRequest *req, uint8_t *buf)
{
    if (req->dev && req->dev->unit_attention.key == UNIT_ATTENTION) {
        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 已提交
234
static const struct SCSIReqOps reqops_unit_attention = {
235 236 237 238
    .size         = sizeof(SCSIRequest),
    .send_command = scsi_unit_attention
};

239 240 241 242 243 244 245 246
/* SCSIReqOps implementation for REPORT LUNS and for commands sent to
   an invalid LUN.  */

typedef struct SCSITargetReq SCSITargetReq;

struct SCSITargetReq {
    SCSIRequest req;
    int len;
247
    uint8_t buf[2056];
248 249 250 251 252 253 254 255 256 257 258 259 260 261
};

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)
{
262 263
    DeviceState *qdev;
    int i, len, n;
P
Paolo Bonzini 已提交
264
    int channel, id;
265 266
    bool found_lun0;

267 268 269 270 271 272
    if (r->req.cmd.xfer < 16) {
        return false;
    }
    if (r->req.cmd.buf[2] > 2) {
        return false;
    }
P
Paolo Bonzini 已提交
273
    channel = r->req.dev->channel;
274 275 276 277 278 279
    id = r->req.dev->id;
    found_lun0 = false;
    n = 0;
    QTAILQ_FOREACH(qdev, &r->req.bus->qbus.children, sibling) {
        SCSIDevice *dev = DO_UPCAST(SCSIDevice, qdev, qdev);

P
Paolo Bonzini 已提交
280
        if (dev->channel == channel && dev->id == id) {
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
            if (dev->lun == 0) {
                found_lun0 = true;
            }
            n += 8;
        }
    }
    if (!found_lun0) {
        n += 8;
    }
    len = MIN(n + 8, r->req.cmd.xfer & ~7);
    if (len > sizeof(r->buf)) {
        /* TODO: > 256 LUNs? */
        return false;
    }

296
    memset(r->buf, 0, len);
297 298 299 300 301
    stl_be_p(&r->buf, n);
    i = found_lun0 ? 8 : 16;
    QTAILQ_FOREACH(qdev, &r->req.bus->qbus.children, sibling) {
        SCSIDevice *dev = DO_UPCAST(SCSIDevice, qdev, qdev);

P
Paolo Bonzini 已提交
302
        if (dev->channel == channel && dev->id == id) {
303 304 305
            store_lun(&r->buf[i], dev->lun);
            i += 8;
        }
306
    }
307 308
    assert(i == n + 8);
    r->len = len;
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    return true;
}

static bool scsi_target_emulate_inquiry(SCSITargetReq *r)
{
    assert(r->req.dev->lun != r->req.lun);
    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];
        if (r->req.cmd.xfer < 4) {
            return false;
        }

        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 */
        assert(r->len < sizeof(r->buf));
        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 */
    if (r->req.cmd.xfer < 5) {
        return -1;
    }

    r->len = MIN(r->req.cmd.xfer, 36);
    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 */
367
        r->buf[7] = 0x10 | (r->req.bus->info->tcq ? 0x02 : 0); /* Sync, TCQ.  */
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
        memcpy(&r->buf[8], "QEMU    ", 8);
        memcpy(&r->buf[16], "QEMU TARGET     ", 16);
        strncpy((char *) &r->buf[32], QEMU_VERSION, 4);
    }
    return true;
}

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;
390 391 392 393
    case REQUEST_SENSE:
        if (req->cmd.xfer < 4) {
            goto illegal_request;
        }
394 395
        r->len = scsi_device_get_sense(r->req.dev, r->buf,
                                       MIN(req->cmd.xfer, sizeof r->buf),
396
                                       (req->cmd.buf[1] & 1) == 0);
397 398 399 400 401 402 403
        if (r->req.dev->sense_is_ua) {
            if (r->req.dev->info->unit_attention_reported) {
                r->req.dev->info->unit_attention_reported(req->dev);
            }
            r->req.dev->sense_len = 0;
            r->req.dev->sense_is_ua = false;
        }
404
        break;
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    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;
}

P
Paolo Bonzini 已提交
442
static const struct SCSIReqOps reqops_target_command = {
443 444 445 446 447 448 449
    .size         = sizeof(SCSITargetReq),
    .send_command = scsi_target_send_command,
    .read_data    = scsi_target_read_data,
    .get_buf      = scsi_target_get_buf,
};


P
Paolo Bonzini 已提交
450 451
SCSIRequest *scsi_req_alloc(const SCSIReqOps *reqops, SCSIDevice *d,
                            uint32_t tag, uint32_t lun, void *hba_private)
452 453 454
{
    SCSIRequest *req;

455
    req = g_malloc0(reqops->size);
456
    req->refcount = 1;
457 458 459 460
    req->bus = scsi_bus_from_device(d);
    req->dev = d;
    req->tag = tag;
    req->lun = lun;
461
    req->hba_private = hba_private;
G
Gerd Hoffmann 已提交
462
    req->status = -1;
463
    req->sense_len = 0;
P
Paolo Bonzini 已提交
464
    req->ops = reqops;
465
    trace_scsi_req_alloc(req->dev->id, req->lun, req->tag);
466 467 468
    return req;
}

469
SCSIRequest *scsi_req_new(SCSIDevice *d, uint32_t tag, uint32_t lun,
470
                          uint8_t *buf, void *hba_private)
P
Paolo Bonzini 已提交
471
{
472
    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, d->qdev.parent_bus);
473
    SCSIRequest *req;
474 475 476 477 478 479 480 481
    SCSICommand cmd;

    if (scsi_req_parse(&cmd, d, buf) != 0) {
        trace_scsi_req_parse_bad(d->id, lun, tag, buf[0]);
        req = scsi_req_alloc(&reqops_invalid_opcode, d, tag, lun, hba_private);
    } else {
        trace_scsi_req_parsed(d->id, lun, tag, buf[0],
                              cmd.mode, cmd.xfer);
482
        if (cmd.lba != -1) {
483 484 485
            trace_scsi_req_parsed_lba(d->id, lun, tag, buf[0],
                                      cmd.lba);
        }
486

487 488 489 490 491
        if ((d->unit_attention.key == UNIT_ATTENTION ||
             bus->unit_attention.key == UNIT_ATTENTION) &&
            (buf[0] != INQUIRY &&
             buf[0] != REPORT_LUNS &&
             buf[0] != GET_CONFIGURATION &&
492 493 494 495 496 497 498
             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))) {
499 500 501
            req = scsi_req_alloc(&reqops_unit_attention, d, tag, lun,
                                 hba_private);
        } else if (lun != d->lun ||
502
            buf[0] == REPORT_LUNS ||
503
            (buf[0] == REQUEST_SENSE && (d->sense_len || cmd.xfer < 4))) {
504 505 506
            req = scsi_req_alloc(&reqops_target_command, d, tag, lun,
                                 hba_private);
        } else {
P
Paolo Bonzini 已提交
507
            req = d->info->alloc_req(d, tag, lun, buf, hba_private);
508
        }
509 510 511
    }

    req->cmd = cmd;
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
    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;
    }

529
    return req;
P
Paolo Bonzini 已提交
530 531
}

P
Paolo Bonzini 已提交
532 533
uint8_t *scsi_req_get_buf(SCSIRequest *req)
{
534
    return req->ops->get_buf(req);
P
Paolo Bonzini 已提交
535 536
}

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
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);
}

576 577
int scsi_req_get_sense(SCSIRequest *req, uint8_t *buf, int len)
{
578 579
    int ret;

580 581
    assert(len >= 14);
    if (!req->sense_len) {
582 583
        return 0;
    }
584 585 586 587 588 589 590 591 592 593

    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).
594
     * Here we handle unit attention clearing for UA_INTLCK_CTRL == 00b.
595
     */
596 597 598 599 600 601 602
    if (req->dev->sense_is_ua) {
        if (req->dev->info->unit_attention_reported) {
            req->dev->info->unit_attention_reported(req->dev);
        }
        req->dev->sense_len = 0;
        req->dev->sense_is_ua = false;
    }
603
    return ret;
604 605 606 607 608 609 610 611 612 613 614 615 616 617
}

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);
    req->sense[0] = 0xf0;
    req->sense[2] = sense.key;
618
    req->sense[7] = 10;
619 620 621
    req->sense[12] = sense.asc;
    req->sense[13] = sense.ascq;
    req->sense_len = 18;
622 623
}

624
int32_t scsi_req_enqueue(SCSIRequest *req)
625
{
626 627
    int32_t rc;

628 629 630 631
    assert(!req->enqueued);
    scsi_req_ref(req);
    req->enqueued = true;
    QTAILQ_INSERT_TAIL(&req->dev->requests, req, next);
632 633

    scsi_req_ref(req);
634
    rc = req->ops->send_command(req, req->cmd.buf);
635 636
    scsi_req_unref(req);
    return rc;
637 638
}

639
static void scsi_req_dequeue(SCSIRequest *req)
640
{
641
    trace_scsi_req_dequeue(req->dev->id, req->lun, req->tag);
642
    req->retry = false;
643 644 645
    if (req->enqueued) {
        QTAILQ_REMOVE(&req->dev->requests, req, next);
        req->enqueued = false;
P
Paolo Bonzini 已提交
646
        scsi_req_unref(req);
647 648 649
    }
}

650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
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;
    }
}

P
Paolo Bonzini 已提交
675
static int scsi_req_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
676
{
P
Paolo Bonzini 已提交
677
    switch (buf[0] >> 5) {
678
    case 0:
P
Paolo Bonzini 已提交
679 680
        cmd->xfer = buf[4];
        cmd->len = 6;
681
        /* length 0 means 256 blocks */
P
Paolo Bonzini 已提交
682 683 684
        if (cmd->xfer == 0) {
            cmd->xfer = 256;
        }
685 686 687
        break;
    case 1:
    case 2:
688
        cmd->xfer = lduw_be_p(&buf[7]);
P
Paolo Bonzini 已提交
689
        cmd->len = 10;
690 691
        break;
    case 4:
692
        cmd->xfer = ldl_be_p(&buf[10]) & 0xffffffffULL;
P
Paolo Bonzini 已提交
693
        cmd->len = 16;
694 695
        break;
    case 5:
696
        cmd->xfer = ldl_be_p(&buf[6]) & 0xffffffffULL;
P
Paolo Bonzini 已提交
697
        cmd->len = 12;
698 699 700 701 702
        break;
    default:
        return -1;
    }

P
Paolo Bonzini 已提交
703
    switch (buf[0]) {
704
    case TEST_UNIT_READY:
705
    case REWIND:
706
    case START_STOP:
P
Paolo Bonzini 已提交
707
    case SET_CAPACITY:
708
    case WRITE_FILEMARKS:
709
    case WRITE_FILEMARKS_16:
710
    case SPACE:
711 712
    case RESERVE:
    case RELEASE:
713 714
    case ERASE:
    case ALLOW_MEDIUM_REMOVAL:
715
    case VERIFY_10:
716 717
    case SEEK_10:
    case SYNCHRONIZE_CACHE:
718 719
    case SYNCHRONIZE_CACHE_16:
    case LOCATE_16:
720 721 722 723
    case LOCK_UNLOCK_CACHE:
    case LOAD_UNLOAD:
    case SET_CD_SPEED:
    case SET_LIMITS:
724
    case WRITE_LONG_10:
725 726
    case MOVE_MEDIUM:
    case UPDATE_BLOCK:
727 728 729 730 731
    case RESERVE_TRACK:
    case SET_READ_AHEAD:
    case PRE_FETCH:
    case PRE_FETCH_16:
    case ALLOW_OVERWRITE:
P
Paolo Bonzini 已提交
732
        cmd->xfer = 0;
733 734 735
        break;
    case MODE_SENSE:
        break;
736
    case WRITE_SAME_10:
P
Paolo Bonzini 已提交
737
        cmd->xfer = 1;
738
        break;
739
    case READ_CAPACITY_10:
P
Paolo Bonzini 已提交
740
        cmd->xfer = 8;
741 742
        break;
    case READ_BLOCK_LIMITS:
P
Paolo Bonzini 已提交
743
        cmd->xfer = 6;
744 745
        break;
    case SEND_VOLUME_TAG:
746 747 748 749 750 751
        /* 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);
        }
752 753
        break;
    case WRITE_10:
754
    case WRITE_VERIFY_10:
755 756 757
    case WRITE_6:
    case WRITE_12:
    case WRITE_VERIFY_12:
G
Gerd Hoffmann 已提交
758 759
    case WRITE_16:
    case WRITE_VERIFY_16:
P
Paolo Bonzini 已提交
760
        cmd->xfer *= dev->blocksize;
761 762 763 764 765 766
        break;
    case READ_10:
    case READ_6:
    case READ_REVERSE:
    case RECOVER_BUFFERED_DATA:
    case READ_12:
G
Gerd Hoffmann 已提交
767
    case READ_16:
P
Paolo Bonzini 已提交
768
        cmd->xfer *= dev->blocksize;
769
        break;
770 771 772 773 774 775 776 777 778
    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;
779
    case INQUIRY:
780 781
    case RECEIVE_DIAGNOSTIC:
    case SEND_DIAGNOSTIC:
P
Paolo Bonzini 已提交
782
        cmd->xfer = buf[4] | (buf[3] << 8);
783
        break;
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
    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:
803 804
    case MAINTENANCE_OUT:
    case MAINTENANCE_IN:
P
Paolo Bonzini 已提交
805
        if (dev->type == TYPE_ROM) {
806
            /* GPCMD_REPORT_KEY and GPCMD_SEND_KEY from multi media commands */
P
Paolo Bonzini 已提交
807
            cmd->xfer = buf[9] | (buf[8] << 8);
808 809
        }
        break;
810 811 812 813
    }
    return 0;
}

P
Paolo Bonzini 已提交
814
static int scsi_req_stream_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
815
{
P
Paolo Bonzini 已提交
816
    switch (buf[0]) {
817
    /* stream commands */
818 819 820 821
    case ERASE_12:
    case ERASE_16:
        cmd->xfer = 0;
        break;
822 823 824 825
    case READ_6:
    case READ_REVERSE:
    case RECOVER_BUFFERED_DATA:
    case WRITE_6:
P
Paolo Bonzini 已提交
826 827 828 829 830
        cmd->len = 6;
        cmd->xfer = buf[4] | (buf[3] << 8) | (buf[2] << 16);
        if (buf[1] & 0x01) { /* fixed */
            cmd->xfer *= dev->blocksize;
        }
831 832 833
        break;
    case REWIND:
    case START_STOP:
P
Paolo Bonzini 已提交
834 835
        cmd->len = 6;
        cmd->xfer = 0;
836
        break;
837 838 839 840 841 842 843 844 845
    case SPACE_16:
        cmd->xfer = buf[13] | (buf[12] << 8);
        break;
    case READ_POSITION:
        cmd->xfer = buf[8] | (buf[7] << 8);
        break;
    case FORMAT_UNIT:
        cmd->xfer = buf[4] | (buf[3] << 8);
        break;
846 847
    /* generic commands */
    default:
P
Paolo Bonzini 已提交
848
        return scsi_req_length(cmd, dev, buf);
849 850 851 852
    }
    return 0;
}

P
Paolo Bonzini 已提交
853
static void scsi_cmd_xfer_mode(SCSICommand *cmd)
G
Gerd Hoffmann 已提交
854
{
P
Paolo Bonzini 已提交
855
    switch (cmd->buf[0]) {
G
Gerd Hoffmann 已提交
856 857
    case WRITE_6:
    case WRITE_10:
858
    case WRITE_VERIFY_10:
G
Gerd Hoffmann 已提交
859 860
    case WRITE_12:
    case WRITE_VERIFY_12:
G
Gerd Hoffmann 已提交
861 862
    case WRITE_16:
    case WRITE_VERIFY_16:
G
Gerd Hoffmann 已提交
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
    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:
878 879
    case WRITE_LONG_10:
    case WRITE_SAME_10:
G
Gerd Hoffmann 已提交
880 881 882 883 884
    case SEARCH_HIGH_12:
    case SEARCH_EQUAL_12:
    case SEARCH_LOW_12:
    case MEDIUM_SCAN:
    case SEND_VOLUME_TAG:
885 886
    case SEND_CUE_SHEET:
    case SEND_DVD_STRUCTURE:
887
    case PERSISTENT_RESERVE_OUT:
888
    case MAINTENANCE_OUT:
P
Paolo Bonzini 已提交
889
        cmd->mode = SCSI_XFER_TO_DEV;
G
Gerd Hoffmann 已提交
890 891
        break;
    default:
P
Paolo Bonzini 已提交
892 893
        if (cmd->xfer)
            cmd->mode = SCSI_XFER_FROM_DEV;
G
Gerd Hoffmann 已提交
894
        else {
P
Paolo Bonzini 已提交
895
            cmd->mode = SCSI_XFER_NONE;
G
Gerd Hoffmann 已提交
896 897 898 899 900
        }
        break;
    }
}

P
Paolo Bonzini 已提交
901
static uint64_t scsi_cmd_lba(SCSICommand *cmd)
902
{
P
Paolo Bonzini 已提交
903
    uint8_t *buf = cmd->buf;
904 905 906 907
    uint64_t lba;

    switch (buf[0] >> 5) {
    case 0:
908
        lba = ldl_be_p(&buf[0]) & 0x1fffff;
909 910 911
        break;
    case 1:
    case 2:
912
    case 5:
913
        lba = ldl_be_p(&buf[2]) & 0xffffffffULL;
914 915
        break;
    case 4:
916
        lba = ldq_be_p(&buf[2]);
917 918 919 920 921 922 923 924
        break;
    default:
        lba = -1;

    }
    return lba;
}

925
int scsi_req_parse(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)
926 927 928
{
    int rc;

929 930
    if (dev->type == TYPE_TAPE) {
        rc = scsi_req_stream_length(cmd, dev, buf);
931
    } else {
932
        rc = scsi_req_length(cmd, dev, buf);
933 934 935 936
    }
    if (rc != 0)
        return rc;

937 938 939
    memcpy(cmd->buf, buf, cmd->len);
    scsi_cmd_xfer_mode(cmd);
    cmd->lba = scsi_cmd_lba(cmd);
940 941
    return 0;
}
G
Gerd Hoffmann 已提交
942

943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
/*
 * 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
};

962 963 964 965 966
/* LUN not ready, medium removal prevented */
const struct SCSISense sense_code_NOT_READY_REMOVAL_PREVENTED = {
    .key = NOT_READY, .asc = 0x53, .ascq = 0x00
};

967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
/* 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
};

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

992 993 994 995 996 997
/* 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 */
998
const struct SCSISense sense_code_INCOMPATIBLE_FORMAT = {
999 1000 1001
    .key = ILLEGAL_REQUEST, .asc = 0x30, .ascq = 0x00
};

1002 1003 1004 1005 1006
/* Illegal request, medium removal prevented */
const struct SCSISense sense_code_ILLEGAL_REQ_REMOVAL_PREVENTED = {
    .key = ILLEGAL_REQUEST, .asc = 0x53, .ascq = 0x00
};

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
/* 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
};

1022 1023 1024 1025 1026
/* Unit attention, Power on, reset or bus device reset occurred */
const struct SCSISense sense_code_RESET = {
    .key = UNIT_ATTENTION, .asc = 0x29, .ascq = 0x00
};

1027 1028 1029 1030 1031
/* Unit attention, No medium */
const struct SCSISense sense_code_UNIT_ATTENTION_NO_MEDIUM = {
    .key = UNIT_ATTENTION, .asc = 0x3a, .ascq = 0x00
};

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
/* 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
};

1047 1048 1049
/*
 * scsi_build_sense
 *
1050
 * Convert between fixed and descriptor sense buffers
1051
 */
1052 1053
int scsi_build_sense(uint8_t *in_buf, int in_len,
                     uint8_t *buf, int len, bool fixed)
1054
{
1055 1056
    bool fixed_in;
    SCSISense sense;
1057 1058 1059 1060
    if (!fixed && len < 8) {
        return 0;
    }

1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
    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];
        }
    }

1084 1085 1086 1087 1088
    memset(buf, 0, len);
    if (fixed) {
        /* Return fixed format sense buffer */
        buf[0] = 0xf0;
        buf[2] = sense.key;
1089
        buf[7] = 10;
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
        buf[12] = sense.asc;
        buf[13] = sense.ascq;
        return MIN(len, 18);
    } else {
        /* Return descriptor format sense buffer */
        buf[0] = 0x72;
        buf[1] = sense.key;
        buf[2] = sense.asc;
        buf[3] = sense.ascq;
        return 8;
    }
}

G
Gerd Hoffmann 已提交
1103 1104 1105 1106
static const char *scsi_command_name(uint8_t cmd)
{
    static const char *names[] = {
        [ TEST_UNIT_READY          ] = "TEST_UNIT_READY",
1107
        [ REWIND                   ] = "REWIND",
G
Gerd Hoffmann 已提交
1108 1109 1110 1111 1112 1113
        [ REQUEST_SENSE            ] = "REQUEST_SENSE",
        [ FORMAT_UNIT              ] = "FORMAT_UNIT",
        [ READ_BLOCK_LIMITS        ] = "READ_BLOCK_LIMITS",
        [ REASSIGN_BLOCKS          ] = "REASSIGN_BLOCKS",
        [ READ_6                   ] = "READ_6",
        [ WRITE_6                  ] = "WRITE_6",
P
Paolo Bonzini 已提交
1114
        [ SET_CAPACITY             ] = "SET_CAPACITY",
G
Gerd Hoffmann 已提交
1115 1116 1117 1118 1119
        [ READ_REVERSE             ] = "READ_REVERSE",
        [ WRITE_FILEMARKS          ] = "WRITE_FILEMARKS",
        [ SPACE                    ] = "SPACE",
        [ INQUIRY                  ] = "INQUIRY",
        [ RECOVER_BUFFERED_DATA    ] = "RECOVER_BUFFERED_DATA",
1120 1121
        [ MAINTENANCE_IN           ] = "MAINTENANCE_IN",
        [ MAINTENANCE_OUT          ] = "MAINTENANCE_OUT",
G
Gerd Hoffmann 已提交
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
        [ MODE_SELECT              ] = "MODE_SELECT",
        [ RESERVE                  ] = "RESERVE",
        [ RELEASE                  ] = "RELEASE",
        [ COPY                     ] = "COPY",
        [ ERASE                    ] = "ERASE",
        [ MODE_SENSE               ] = "MODE_SENSE",
        [ START_STOP               ] = "START_STOP",
        [ RECEIVE_DIAGNOSTIC       ] = "RECEIVE_DIAGNOSTIC",
        [ SEND_DIAGNOSTIC          ] = "SEND_DIAGNOSTIC",
        [ ALLOW_MEDIUM_REMOVAL     ] = "ALLOW_MEDIUM_REMOVAL",
1132
        [ READ_CAPACITY_10         ] = "READ_CAPACITY_10",
G
Gerd Hoffmann 已提交
1133 1134 1135
        [ READ_10                  ] = "READ_10",
        [ WRITE_10                 ] = "WRITE_10",
        [ SEEK_10                  ] = "SEEK_10",
1136 1137
        [ WRITE_VERIFY_10          ] = "WRITE_VERIFY_10",
        [ VERIFY_10                ] = "VERIFY_10",
G
Gerd Hoffmann 已提交
1138 1139 1140 1141
        [ SEARCH_HIGH              ] = "SEARCH_HIGH",
        [ SEARCH_EQUAL             ] = "SEARCH_EQUAL",
        [ SEARCH_LOW               ] = "SEARCH_LOW",
        [ SET_LIMITS               ] = "SET_LIMITS",
P
Paolo Bonzini 已提交
1142
        [ PRE_FETCH                ] = "PRE_FETCH/READ_POSITION",
1143
        /* READ_POSITION and PRE_FETCH use the same operation code */
G
Gerd Hoffmann 已提交
1144 1145 1146 1147 1148 1149 1150 1151 1152
        [ SYNCHRONIZE_CACHE        ] = "SYNCHRONIZE_CACHE",
        [ LOCK_UNLOCK_CACHE        ] = "LOCK_UNLOCK_CACHE",
        [ READ_DEFECT_DATA         ] = "READ_DEFECT_DATA",
        [ MEDIUM_SCAN              ] = "MEDIUM_SCAN",
        [ COMPARE                  ] = "COMPARE",
        [ COPY_VERIFY              ] = "COPY_VERIFY",
        [ WRITE_BUFFER             ] = "WRITE_BUFFER",
        [ READ_BUFFER              ] = "READ_BUFFER",
        [ UPDATE_BLOCK             ] = "UPDATE_BLOCK",
1153 1154
        [ READ_LONG_10             ] = "READ_LONG_10",
        [ WRITE_LONG_10            ] = "WRITE_LONG_10",
G
Gerd Hoffmann 已提交
1155
        [ CHANGE_DEFINITION        ] = "CHANGE_DEFINITION",
1156 1157
        [ WRITE_SAME_10            ] = "WRITE_SAME_10",
        [ UNMAP                    ] = "UNMAP",
G
Gerd Hoffmann 已提交
1158
        [ READ_TOC                 ] = "READ_TOC",
1159 1160
        [ REPORT_DENSITY_SUPPORT   ] = "REPORT_DENSITY_SUPPORT",
        [ GET_CONFIGURATION        ] = "GET_CONFIGURATION",
G
Gerd Hoffmann 已提交
1161 1162 1163 1164 1165 1166 1167 1168
        [ 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",
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
        [ WRITE_FILEMARKS_16       ] = "WRITE_FILEMARKS_16",
        [ EXTENDED_COPY            ] = "EXTENDED_COPY",
        [ ATA_PASSTHROUGH          ] = "ATA_PASSTHROUGH",
        [ 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 已提交
1179 1180 1181
        [ 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 */
1182
        [ LOCATE_16                ] = "LOCATE_16",
P
Paolo Bonzini 已提交
1183
        [ WRITE_SAME_16            ] = "ERASE_16/WRITE_SAME_16",
1184
        /* ERASE_16 and WRITE_SAME_16 use the same operation code */
1185
        [ SERVICE_ACTION_IN_16     ] = "SERVICE_ACTION_IN_16",
1186 1187 1188
        [ WRITE_LONG_16            ] = "WRITE_LONG_16",
        [ REPORT_LUNS              ] = "REPORT_LUNS",
        [ BLANK                    ] = "BLANK",
G
Gerd Hoffmann 已提交
1189
        [ MOVE_MEDIUM              ] = "MOVE_MEDIUM",
1190
        [ LOAD_UNLOAD              ] = "LOAD_UNLOAD",
G
Gerd Hoffmann 已提交
1191 1192
        [ READ_12                  ] = "READ_12",
        [ WRITE_12                 ] = "WRITE_12",
P
Paolo Bonzini 已提交
1193 1194
        [ ERASE_12                 ] = "ERASE_12/GET_PERFORMANCE",
        /* ERASE_12 and GET_PERFORMANCE use the same operation code */
1195
        [ SERVICE_ACTION_IN_12     ] = "SERVICE_ACTION_IN_12",
G
Gerd Hoffmann 已提交
1196
        [ WRITE_VERIFY_12          ] = "WRITE_VERIFY_12",
1197
        [ VERIFY_12                ] = "VERIFY_12",
G
Gerd Hoffmann 已提交
1198 1199 1200 1201
        [ 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 已提交
1202 1203 1204
        [ SEND_VOLUME_TAG          ] = "SEND_VOLUME_TAG/SET_STREAMING",
        /* SEND_VOLUME_TAG and SET_STREAMING use the same operation code */
        [ READ_CD                  ] = "READ_CD",
1205
        [ READ_DEFECT_DATA_12      ] = "READ_DEFECT_DATA_12",
P
Paolo Bonzini 已提交
1206 1207 1208 1209
        [ 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 已提交
1210
        [ SET_CD_SPEED             ] = "SET_CD_SPEED",
P
Paolo Bonzini 已提交
1211 1212 1213
        [ SET_READ_AHEAD           ] = "SET_READ_AHEAD",
        [ ALLOW_OVERWRITE          ] = "ALLOW_OVERWRITE",
        [ MECHANISM_STATUS         ] = "MECHANISM_STATUS",
G
Gerd Hoffmann 已提交
1214 1215 1216 1217 1218 1219 1220
    };

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

P
Paolo Bonzini 已提交
1221 1222 1223 1224 1225 1226 1227 1228 1229
SCSIRequest *scsi_req_ref(SCSIRequest *req)
{
    req->refcount++;
    return req;
}

void scsi_req_unref(SCSIRequest *req)
{
    if (--req->refcount == 0) {
1230 1231
        if (req->ops->free_req) {
            req->ops->free_req(req);
P
Paolo Bonzini 已提交
1232
        }
1233
        g_free(req);
P
Paolo Bonzini 已提交
1234 1235 1236
    }
}

1237 1238 1239 1240 1241 1242
/* 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)
{
    trace_scsi_req_continue(req->dev->id, req->lun, req->tag);
    if (req->cmd.mode == SCSI_XFER_TO_DEV) {
1243
        req->ops->write_data(req);
1244
    } else {
1245
        req->ops->read_data(req);
1246 1247 1248
    }
}

P
Paolo Bonzini 已提交
1249 1250
/* 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.
1251
   Once it completes, calling scsi_req_continue will restart I/O.  */
P
Paolo Bonzini 已提交
1252 1253
void scsi_req_data(SCSIRequest *req, int len)
{
1254 1255 1256 1257 1258 1259
    if (req->io_canceled) {
        trace_scsi_req_data_canceled(req->dev->id, req->lun, req->tag, len);
    } else {
        trace_scsi_req_data(req->dev->id, req->lun, req->tag, len);
        req->bus->info->transfer_data(req, len);
    }
P
Paolo Bonzini 已提交
1260 1261
}

G
Gerd Hoffmann 已提交
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
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;
    }
}

1290
void scsi_req_complete(SCSIRequest *req, int status)
G
Gerd Hoffmann 已提交
1291
{
1292 1293
    assert(req->status == -1);
    req->status = status;
1294 1295 1296 1297 1298 1299 1300 1301

    assert(req->sense_len < sizeof(req->sense));
    if (status == GOOD) {
        req->sense_len = 0;
    }

    if (req->sense_len) {
        memcpy(req->dev->sense, req->sense, req->sense_len);
1302 1303 1304 1305 1306
        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;
1307 1308
    }

1309 1310 1311 1312 1313 1314 1315
    /*
     * 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 已提交
1316
    scsi_req_ref(req);
1317
    scsi_req_dequeue(req);
1318
    req->bus->info->complete(req, req->status);
P
Paolo Bonzini 已提交
1319
    scsi_req_unref(req);
G
Gerd Hoffmann 已提交
1320
}
1321

P
Paolo Bonzini 已提交
1322 1323
void scsi_req_cancel(SCSIRequest *req)
{
1324 1325
    if (!req->enqueued) {
        return;
P
Paolo Bonzini 已提交
1326 1327 1328
    }
    scsi_req_ref(req);
    scsi_req_dequeue(req);
1329 1330 1331 1332
    req->io_canceled = true;
    if (req->ops->cancel_io) {
        req->ops->cancel_io(req);
    }
1333 1334
    if (req->bus->info->cancel) {
        req->bus->info->cancel(req);
P
Paolo Bonzini 已提交
1335 1336 1337 1338
    }
    scsi_req_unref(req);
}

P
Paolo Bonzini 已提交
1339 1340
void scsi_req_abort(SCSIRequest *req, int status)
{
1341 1342 1343 1344 1345 1346
    if (!req->enqueued) {
        return;
    }
    scsi_req_ref(req);
    scsi_req_dequeue(req);
    req->io_canceled = true;
1347 1348
    if (req->ops->cancel_io) {
        req->ops->cancel_io(req);
P
Paolo Bonzini 已提交
1349
    }
1350
    scsi_req_complete(req, status);
1351
    scsi_req_unref(req);
P
Paolo Bonzini 已提交
1352 1353
}

1354
void scsi_device_purge_requests(SCSIDevice *sdev, SCSISense sense)
P
Paolo Bonzini 已提交
1355 1356 1357 1358 1359
{
    SCSIRequest *req;

    while (!QTAILQ_EMPTY(&sdev->requests)) {
        req = QTAILQ_FIRST(&sdev->requests);
P
Paolo Bonzini 已提交
1360
        scsi_req_cancel(req);
P
Paolo Bonzini 已提交
1361
    }
1362
    sdev->unit_attention = sense;
P
Paolo Bonzini 已提交
1363 1364
}

1365 1366
static char *scsibus_get_fw_dev_path(DeviceState *dev)
{
Z
Zhi Yong Wu 已提交
1367
    SCSIDevice *d = DO_UPCAST(SCSIDevice, qdev, dev);
1368 1369
    char path[100];

P
Paolo Bonzini 已提交
1370
    snprintf(path, sizeof(path), "%s@%d,%d,%d", qdev_fw_name(dev),
P
Paolo Bonzini 已提交
1371
             d->channel, d->id, d->lun);
1372

1373 1374 1375
    return strdup(path);
}

P
Paolo Bonzini 已提交
1376
SCSIDevice *scsi_device_find(SCSIBus *bus, int channel, int id, int lun)
1377 1378 1379
{
    DeviceState *qdev;
    SCSIDevice *target_dev = NULL;
1380

1381 1382
    QTAILQ_FOREACH_REVERSE(qdev, &bus->qbus.children, ChildrenHead, sibling) {
        SCSIDevice *dev = DO_UPCAST(SCSIDevice, qdev, qdev);
1383

P
Paolo Bonzini 已提交
1384
        if (dev->channel == channel && dev->id == id) {
1385 1386 1387 1388 1389 1390 1391
            if (dev->lun == lun) {
                return dev;
            }
            target_dev = dev;
        }
    }
    return target_dev;
1392
}