virtio-scsi.c 26.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Virtio SCSI HBA
 *
 * Copyright IBM, Corp. 2010
 * Copyright Red Hat, Inc. 2011
 *
 * Authors:
 *   Stefan Hajnoczi    <stefanha@linux.vnet.ibm.com>
 *   Paolo Bonzini      <pbonzini@redhat.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2 or later.
 * See the COPYING file in the top-level directory.
 *
 */

P
Paolo Bonzini 已提交
16
#include "hw/virtio/virtio-scsi.h"
17
#include "qemu/error-report.h"
18
#include "qemu/iov.h"
P
Paolo Bonzini 已提交
19 20 21
#include <hw/scsi/scsi.h>
#include <block/scsi.h>
#include <hw/virtio/virtio-bus.h>
22
#include "hw/virtio/virtio-access.h"
23
#include "migration/migration.h"
24

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
static inline int virtio_scsi_get_lun(uint8_t *lun)
{
    return ((lun[2] << 8) | lun[3]) & 0x3FFF;
}

static inline SCSIDevice *virtio_scsi_device_find(VirtIOSCSI *s, uint8_t *lun)
{
    if (lun[0] != 1) {
        return NULL;
    }
    if (lun[2] != 0 && !(lun[2] >= 0x40 && lun[2] < 0x80)) {
        return NULL;
    }
    return scsi_device_find(&s->bus, 0, lun[1], virtio_scsi_get_lun(lun));
}

41
VirtIOSCSIReq *virtio_scsi_init_req(VirtIOSCSI *s, VirtQueue *vq)
42 43
{
    VirtIOSCSIReq *req;
44 45 46
    VirtIOSCSICommon *vs = (VirtIOSCSICommon *)s;
    const size_t zero_skip = offsetof(VirtIOSCSIReq, elem)
                             + sizeof(VirtQueueElement);
47

48
    req = g_slice_alloc(sizeof(*req) + vs->cdb_size);
49 50 51
    req->vq = vq;
    req->dev = s;
    qemu_sglist_init(&req->qsgl, DEVICE(s), 8, &address_space_memory);
52
    qemu_iovec_init(&req->resp_iov, 1);
53
    memset((uint8_t *)req + zero_skip, 0, sizeof(*req) - zero_skip);
54 55 56
    return req;
}

57
void virtio_scsi_free_req(VirtIOSCSIReq *req)
58
{
59 60
    VirtIOSCSICommon *vs = (VirtIOSCSICommon *)req->dev;

61
    qemu_iovec_destroy(&req->resp_iov);
62
    qemu_sglist_destroy(&req->qsgl);
63
    g_slice_free1(sizeof(*req) + vs->cdb_size, req);
64 65
}

66 67 68 69
static void virtio_scsi_complete_req(VirtIOSCSIReq *req)
{
    VirtIOSCSI *s = req->dev;
    VirtQueue *vq = req->vq;
70
    VirtIODevice *vdev = VIRTIO_DEVICE(s);
71 72

    qemu_iovec_from_buf(&req->resp_iov, 0, &req->resp, req->resp_size);
F
Fam Zheng 已提交
73 74 75 76 77 78 79 80
    if (req->vring) {
        assert(req->vq == NULL);
        virtio_scsi_vring_push_notify(req);
    } else {
        virtqueue_push(vq, &req->elem, req->qsgl.size + req->resp_iov.size);
        virtio_notify(vdev, vq);
    }

81 82 83 84
    if (req->sreq) {
        req->sreq->hba_private = NULL;
        scsi_req_unref(req->sreq);
    }
85
    virtio_scsi_free_req(req);
86 87 88 89 90 91 92 93
}

static void virtio_scsi_bad_req(void)
{
    error_report("wrong size for virtio-scsi headers");
    exit(1);
}

94 95
static size_t qemu_sgl_concat(VirtIOSCSIReq *req, struct iovec *iov,
                              hwaddr *addr, int num, size_t skip)
96
{
97
    QEMUSGList *qsgl = &req->qsgl;
98 99 100 101 102 103 104 105 106 107 108 109 110
    size_t copied = 0;

    while (num) {
        if (skip >= iov->iov_len) {
            skip -= iov->iov_len;
        } else {
            qemu_sglist_add(qsgl, *addr + skip, iov->iov_len - skip);
            copied += iov->iov_len - skip;
            skip = 0;
        }
        iov++;
        addr++;
        num--;
111
    }
112 113 114

    assert(skip == 0);
    return copied;
115 116
}

117 118
static int virtio_scsi_parse_req(VirtIOSCSIReq *req,
                                 unsigned req_size, unsigned resp_size)
119
{
120
    size_t in_size, out_size;
121

122 123
    if (iov_to_buf(req->elem.out_sg, req->elem.out_num, 0,
                   &req->req, req_size) < req_size) {
124 125 126
        return -EINVAL;
    }

127 128 129
    if (qemu_iovec_concat_iov(&req->resp_iov,
                              req->elem.in_sg, req->elem.in_num, 0,
                              resp_size) < resp_size) {
130 131
        return -EINVAL;
    }
132
    req->resp_size = resp_size;
133

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    out_size = qemu_sgl_concat(req, req->elem.out_sg,
                               &req->elem.out_addr[0], req->elem.out_num,
                               req_size);
    in_size = qemu_sgl_concat(req, req->elem.in_sg,
                              &req->elem.in_addr[0], req->elem.in_num,
                              resp_size);

    if (out_size && in_size) {
        return -ENOTSUP;
    }

    if (out_size) {
        req->mode = SCSI_XFER_TO_DEV;
    } else if (in_size) {
        req->mode = SCSI_XFER_FROM_DEV;
149
    }
150 151

    return 0;
152 153 154 155
}

static VirtIOSCSIReq *virtio_scsi_pop_req(VirtIOSCSI *s, VirtQueue *vq)
{
156
    VirtIOSCSIReq *req = virtio_scsi_init_req(s, vq);
157
    if (!virtqueue_pop(vq, &req->elem)) {
158
        virtio_scsi_free_req(req);
159 160 161 162 163
        return NULL;
    }
    return req;
}

164 165 166
static void virtio_scsi_save_request(QEMUFile *f, SCSIRequest *sreq)
{
    VirtIOSCSIReq *req = sreq->hba_private;
167
    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(req->dev);
168
    uint32_t n = virtio_queue_get_id(req->vq) - 2;
169

170
    assert(n < vs->conf.num_queues);
171
    qemu_put_be32s(f, &n);
172 173 174 175 176 177 178
    qemu_put_buffer(f, (unsigned char *)&req->elem, sizeof(req->elem));
}

static void *virtio_scsi_load_request(QEMUFile *f, SCSIRequest *sreq)
{
    SCSIBus *bus = sreq->bus;
    VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus);
179
    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);
180
    VirtIOSCSIReq *req;
181
    uint32_t n;
182

183
    qemu_get_be32s(f, &n);
184
    assert(n < vs->conf.num_queues);
185
    req = virtio_scsi_init_req(s, vs->cmd_vqs[n]);
186
    qemu_get_buffer(f, (unsigned char *)&req->elem, sizeof(req->elem));
187 188 189 190 191 192 193 194 195
    /* TODO: add a way for SCSIBusInfo's load_request to fail,
     * and fail migration instead of asserting here.
     * When we do, we might be able to re-enable NDEBUG below.
     */
#ifdef NDEBUG
#error building with NDEBUG is not supported
#endif
    assert(req->elem.in_num <= ARRAY_SIZE(req->elem.in_sg));
    assert(req->elem.out_num <= ARRAY_SIZE(req->elem.out_sg));
196 197 198 199 200 201

    if (virtio_scsi_parse_req(req, sizeof(VirtIOSCSICmdReq) + vs->cdb_size,
                              sizeof(VirtIOSCSICmdResp) + vs->sense_size) < 0) {
        error_report("invalid SCSI request migration data");
        exit(1);
    }
202 203 204 205

    scsi_req_ref(sreq);
    req->sreq = sreq;
    if (req->sreq->cmd.mode != SCSI_XFER_NONE) {
206
        assert(req->sreq->cmd.mode == req->mode);
207 208 209 210
    }
    return req;
}

211
static void virtio_scsi_do_tmf(VirtIOSCSI *s, VirtIOSCSIReq *req)
212
{
213
    SCSIDevice *d = virtio_scsi_device_find(s, req->req.tmf.lun);
214
    SCSIRequest *r, *next;
A
Anthony Liguori 已提交
215
    BusChild *kid;
216 217
    int target;

F
Fam Zheng 已提交
218 219 220 221 222
    if (s->dataplane_started && bdrv_get_aio_context(d->conf.bs) != s->ctx) {
        aio_context_acquire(s->ctx);
        bdrv_set_aio_context(d->conf.bs, s->ctx);
        aio_context_release(s->ctx);
    }
223
    /* Here VIRTIO_SCSI_S_OK means "FUNCTION COMPLETE".  */
224
    req->resp.tmf.response = VIRTIO_SCSI_S_OK;
225

226
    virtio_tswap32s(VIRTIO_DEVICE(s), &req->req.tmf.subtype);
227
    switch (req->req.tmf.subtype) {
228 229 230 231 232
    case VIRTIO_SCSI_T_TMF_ABORT_TASK:
    case VIRTIO_SCSI_T_TMF_QUERY_TASK:
        if (!d) {
            goto fail;
        }
233
        if (d->lun != virtio_scsi_get_lun(req->req.tmf.lun)) {
234 235 236
            goto incorrect_lun;
        }
        QTAILQ_FOREACH_SAFE(r, &d->requests, next, next) {
237
            VirtIOSCSIReq *cmd_req = r->hba_private;
238
            if (cmd_req && cmd_req->req.cmd.tag == req->req.tmf.tag) {
239 240 241
                break;
            }
        }
242 243 244 245 246 247
        if (r) {
            /*
             * Assert that the request has not been completed yet, we
             * check for it in the loop above.
             */
            assert(r->hba_private);
248
            if (req->req.tmf.subtype == VIRTIO_SCSI_T_TMF_QUERY_TASK) {
249 250 251
                /* "If the specified command is present in the task set, then
                 * return a service response set to FUNCTION SUCCEEDED".
                 */
252
                req->resp.tmf.response = VIRTIO_SCSI_S_FUNCTION_SUCCEEDED;
253 254 255 256 257 258 259 260 261 262
            } else {
                scsi_req_cancel(r);
            }
        }
        break;

    case VIRTIO_SCSI_T_TMF_LOGICAL_UNIT_RESET:
        if (!d) {
            goto fail;
        }
263
        if (d->lun != virtio_scsi_get_lun(req->req.tmf.lun)) {
264 265 266 267 268 269 270 271 272 273 274 275 276
            goto incorrect_lun;
        }
        s->resetting++;
        qdev_reset_all(&d->qdev);
        s->resetting--;
        break;

    case VIRTIO_SCSI_T_TMF_ABORT_TASK_SET:
    case VIRTIO_SCSI_T_TMF_CLEAR_TASK_SET:
    case VIRTIO_SCSI_T_TMF_QUERY_TASK_SET:
        if (!d) {
            goto fail;
        }
277
        if (d->lun != virtio_scsi_get_lun(req->req.tmf.lun)) {
278 279 280 281
            goto incorrect_lun;
        }
        QTAILQ_FOREACH_SAFE(r, &d->requests, next, next) {
            if (r->hba_private) {
282
                if (req->req.tmf.subtype == VIRTIO_SCSI_T_TMF_QUERY_TASK_SET) {
283 284 285
                    /* "If there is any command present in the task set, then
                     * return a service response set to FUNCTION SUCCEEDED".
                     */
286
                    req->resp.tmf.response = VIRTIO_SCSI_S_FUNCTION_SUCCEEDED;
287 288 289 290 291 292 293 294 295
                    break;
                } else {
                    scsi_req_cancel(r);
                }
            }
        }
        break;

    case VIRTIO_SCSI_T_TMF_I_T_NEXUS_RESET:
296
        target = req->req.tmf.lun[1];
297
        s->resetting++;
A
Anthony Liguori 已提交
298 299
        QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
             d = DO_UPCAST(SCSIDevice, qdev, kid->child);
300 301 302 303 304 305 306 307 308
             if (d->channel == 0 && d->id == target) {
                qdev_reset_all(&d->qdev);
             }
        }
        s->resetting--;
        break;

    case VIRTIO_SCSI_T_TMF_CLEAR_ACA:
    default:
309
        req->resp.tmf.response = VIRTIO_SCSI_S_FUNCTION_REJECTED;
310
        break;
311 312
    }

313 314 315
    return;

incorrect_lun:
316
    req->resp.tmf.response = VIRTIO_SCSI_S_INCORRECT_LUN;
317 318 319
    return;

fail:
320
    req->resp.tmf.response = VIRTIO_SCSI_S_BAD_TARGET;
321 322
}

323
void virtio_scsi_handle_ctrl_req(VirtIOSCSI *s, VirtIOSCSIReq *req)
324
{
325 326
    VirtIODevice *vdev = (VirtIODevice *)s;
    int type;
327

328 329 330 331 332
    if (iov_to_buf(req->elem.out_sg, req->elem.out_num, 0,
                &type, sizeof(type)) < sizeof(type)) {
        virtio_scsi_bad_req();
        return;
    }
333

334 335 336 337
    virtio_tswap32s(vdev, &req->req.tmf.type);
    if (req->req.tmf.type == VIRTIO_SCSI_T_TMF) {
        if (virtio_scsi_parse_req(req, sizeof(VirtIOSCSICtrlTMFReq),
                    sizeof(VirtIOSCSICtrlTMFResp)) < 0) {
338
            virtio_scsi_bad_req();
339 340
        } else {
            virtio_scsi_do_tmf(s, req);
341
        }
342

343 344 345 346 347 348 349 350
    } else if (req->req.tmf.type == VIRTIO_SCSI_T_AN_QUERY ||
            req->req.tmf.type == VIRTIO_SCSI_T_AN_SUBSCRIBE) {
        if (virtio_scsi_parse_req(req, sizeof(VirtIOSCSICtrlANReq),
                    sizeof(VirtIOSCSICtrlANResp)) < 0) {
            virtio_scsi_bad_req();
        } else {
            req->resp.an.event_actual = 0;
            req->resp.an.response = VIRTIO_SCSI_S_OK;
351
        }
352 353 354 355 356 357 358 359 360
    }
    virtio_scsi_complete_req(req);
}

static void virtio_scsi_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)
{
    VirtIOSCSI *s = (VirtIOSCSI *)vdev;
    VirtIOSCSIReq *req;

361
    if (s->ctx && !s->dataplane_disabled) {
F
Fam Zheng 已提交
362 363 364
        virtio_scsi_dataplane_start(s);
        return;
    }
365 366
    while ((req = virtio_scsi_pop_req(s, vq))) {
        virtio_scsi_handle_ctrl_req(s, req);
367 368 369
    }
}

370 371
static void virtio_scsi_complete_cmd_req(VirtIOSCSIReq *req)
{
372 373 374 375
    /* Sense data is not in req->resp and is copied separately
     * in virtio_scsi_command_complete.
     */
    req->resp_size = sizeof(VirtIOSCSICmdResp);
376 377 378
    virtio_scsi_complete_req(req);
}

379 380 381 382
static void virtio_scsi_command_complete(SCSIRequest *r, uint32_t status,
                                         size_t resid)
{
    VirtIOSCSIReq *req = r->hba_private;
383
    uint8_t sense[SCSI_SENSE_BUF_SIZE];
384
    uint32_t sense_len;
385
    VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
386

387 388 389 390
    if (r->io_canceled) {
        return;
    }

391 392 393
    req->resp.cmd.response = VIRTIO_SCSI_S_OK;
    req->resp.cmd.status = status;
    if (req->resp.cmd.status == GOOD) {
394
        req->resp.cmd.resid = virtio_tswap32(vdev, resid);
395
    } else {
396
        req->resp.cmd.resid = 0;
397
        sense_len = scsi_req_get_sense(r, sense, sizeof(sense));
398 399 400
        sense_len = MIN(sense_len, req->resp_iov.size - sizeof(req->resp.cmd));
        qemu_iovec_from_buf(&req->resp_iov, sizeof(req->resp.cmd),
                            &req->resp, sense_len);
401
        req->resp.cmd.sense_len = virtio_tswap32(vdev, sense_len);
402
    }
403
    virtio_scsi_complete_cmd_req(req);
404 405
}

P
Paolo Bonzini 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418 419
static int virtio_scsi_parse_cdb(SCSIDevice *dev, SCSICommand *cmd,
                                 uint8_t *buf, void *hba_private)
{
    VirtIOSCSIReq *req = hba_private;

    if (cmd->len == 0) {
        cmd->len = MIN(VIRTIO_SCSI_CDB_SIZE, SCSI_CMD_BUF_SIZE);
        memcpy(cmd->buf, buf, cmd->len);
    }

    /* Extract the direction and mode directly from the request, for
     * host device passthrough.
     */
    cmd->xfer = req->qsgl.size;
420
    cmd->mode = req->mode;
P
Paolo Bonzini 已提交
421 422 423
    return 0;
}

424 425 426 427 428 429 430 431 432 433 434 435 436 437
static QEMUSGList *virtio_scsi_get_sg_list(SCSIRequest *r)
{
    VirtIOSCSIReq *req = r->hba_private;

    return &req->qsgl;
}

static void virtio_scsi_request_cancelled(SCSIRequest *r)
{
    VirtIOSCSIReq *req = r->hba_private;

    if (!req) {
        return;
    }
438
    if (req->dev->resetting) {
439
        req->resp.cmd.response = VIRTIO_SCSI_S_RESET;
440
    } else {
441
        req->resp.cmd.response = VIRTIO_SCSI_S_ABORTED;
442
    }
443
    virtio_scsi_complete_cmd_req(req);
444 445 446
}

static void virtio_scsi_fail_cmd_req(VirtIOSCSIReq *req)
447
{
448
    req->resp.cmd.response = VIRTIO_SCSI_S_FAILURE;
449
    virtio_scsi_complete_cmd_req(req);
450 451
}

452
bool virtio_scsi_handle_cmd_req_prepare(VirtIOSCSI *s, VirtIOSCSIReq *req)
453 454 455 456 457 458 459 460 461 462 463 464 465
{
    VirtIOSCSICommon *vs = &s->parent_obj;
    SCSIDevice *d;
    int rc;

    rc = virtio_scsi_parse_req(req, sizeof(VirtIOSCSICmdReq) + vs->cdb_size,
                               sizeof(VirtIOSCSICmdResp) + vs->sense_size);
    if (rc < 0) {
        if (rc == -ENOTSUP) {
            virtio_scsi_fail_cmd_req(req);
        } else {
            virtio_scsi_bad_req();
        }
466
        return false;
467 468 469 470 471 472
    }

    d = virtio_scsi_device_find(s, req->req.cmd.lun);
    if (!d) {
        req->resp.cmd.response = VIRTIO_SCSI_S_BAD_TARGET;
        virtio_scsi_complete_cmd_req(req);
473
        return false;
474
    }
F
Fam Zheng 已提交
475 476 477 478 479
    if (s->dataplane_started && bdrv_get_aio_context(d->conf.bs) != s->ctx) {
        aio_context_acquire(s->ctx);
        bdrv_set_aio_context(d->conf.bs, s->ctx);
        aio_context_release(s->ctx);
    }
480 481 482 483 484 485 486 487 488
    req->sreq = scsi_req_new(d, req->req.cmd.tag,
                             virtio_scsi_get_lun(req->req.cmd.lun),
                             req->req.cdb, req);

    if (req->sreq->cmd.mode != SCSI_XFER_NONE
        && (req->sreq->cmd.mode != req->mode ||
            req->sreq->cmd.xfer > req->qsgl.size)) {
        req->resp.cmd.response = VIRTIO_SCSI_S_OVERRUN;
        virtio_scsi_complete_cmd_req(req);
489
        return false;
490
    }
491 492
    scsi_req_ref(req->sreq);
    bdrv_io_plug(d->conf.bs);
493 494
    return true;
}
495

496 497 498
void virtio_scsi_handle_cmd_req_submit(VirtIOSCSI *s, VirtIOSCSIReq *req)
{
    if (scsi_req_enqueue(req->sreq)) {
499 500
        scsi_req_continue(req->sreq);
    }
501 502
    bdrv_io_unplug(req->sreq->dev->conf.bs);
    scsi_req_unref(req->sreq);
503 504
}

505 506
static void virtio_scsi_handle_cmd(VirtIODevice *vdev, VirtQueue *vq)
{
507
    /* use non-QOM casts in the data path */
508
    VirtIOSCSI *s = (VirtIOSCSI *)vdev;
509 510
    VirtIOSCSIReq *req, *next;
    QTAILQ_HEAD(, VirtIOSCSIReq) reqs = QTAILQ_HEAD_INITIALIZER(reqs);
511

512
    if (s->ctx && !s->dataplane_disabled) {
F
Fam Zheng 已提交
513 514 515
        virtio_scsi_dataplane_start(s);
        return;
    }
516
    while ((req = virtio_scsi_pop_req(s, vq))) {
517
        if (virtio_scsi_handle_cmd_req_prepare(s, req)) {
518
            QTAILQ_INSERT_TAIL(&reqs, req, next);
519
        }
520
    }
521 522 523 524

    QTAILQ_FOREACH_SAFE(req, &reqs, next, next) {
        virtio_scsi_handle_cmd_req_submit(s, req);
    }
525 526 527 528 529 530
}

static void virtio_scsi_get_config(VirtIODevice *vdev,
                                   uint8_t *config)
{
    VirtIOSCSIConfig *scsiconf = (VirtIOSCSIConfig *)config;
531
    VirtIOSCSICommon *s = VIRTIO_SCSI_COMMON(vdev);
532

533 534 535 536 537 538 539 540 541 542
    virtio_stl_p(vdev, &scsiconf->num_queues, s->conf.num_queues);
    virtio_stl_p(vdev, &scsiconf->seg_max, 128 - 2);
    virtio_stl_p(vdev, &scsiconf->max_sectors, s->conf.max_sectors);
    virtio_stl_p(vdev, &scsiconf->cmd_per_lun, s->conf.cmd_per_lun);
    virtio_stl_p(vdev, &scsiconf->event_info_size, sizeof(VirtIOSCSIEvent));
    virtio_stl_p(vdev, &scsiconf->sense_size, s->sense_size);
    virtio_stl_p(vdev, &scsiconf->cdb_size, s->cdb_size);
    virtio_stw_p(vdev, &scsiconf->max_channel, VIRTIO_SCSI_MAX_CHANNEL);
    virtio_stw_p(vdev, &scsiconf->max_target, VIRTIO_SCSI_MAX_TARGET);
    virtio_stl_p(vdev, &scsiconf->max_lun, VIRTIO_SCSI_MAX_LUN);
543 544 545 546 547 548
}

static void virtio_scsi_set_config(VirtIODevice *vdev,
                                   const uint8_t *config)
{
    VirtIOSCSIConfig *scsiconf = (VirtIOSCSIConfig *)config;
549
    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(vdev);
550

551 552
    if ((uint32_t) virtio_ldl_p(vdev, &scsiconf->sense_size) >= 65536 ||
        (uint32_t) virtio_ldl_p(vdev, &scsiconf->cdb_size) >= 256) {
553 554 555 556
        error_report("bad data written to virtio-scsi configuration space");
        exit(1);
    }

557 558
    vs->sense_size = virtio_ldl_p(vdev, &scsiconf->sense_size);
    vs->cdb_size = virtio_ldl_p(vdev, &scsiconf->cdb_size);
559 560 561 562 563 564 565 566 567 568
}

static uint32_t virtio_scsi_get_features(VirtIODevice *vdev,
                                         uint32_t requested_features)
{
    return requested_features;
}

static void virtio_scsi_reset(VirtIODevice *vdev)
{
569 570
    VirtIOSCSI *s = VIRTIO_SCSI(vdev);
    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(vdev);
571

F
Fam Zheng 已提交
572 573 574
    if (s->ctx) {
        virtio_scsi_dataplane_stop(s);
    }
575 576 577 578
    s->resetting++;
    qbus_reset_all(&s->bus.qbus);
    s->resetting--;

579 580
    vs->sense_size = VIRTIO_SCSI_SENSE_SIZE;
    vs->cdb_size = VIRTIO_SCSI_CDB_SIZE;
581
    s->events_dropped = false;
582 583
}

584 585 586 587 588
/* The device does not have anything to save beyond the virtio data.
 * Request data is saved with callbacks from SCSI devices.
 */
static void virtio_scsi_save(QEMUFile *f, void *opaque)
{
589 590
    VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
    virtio_save(vdev, f);
591 592 593 594
}

static int virtio_scsi_load(QEMUFile *f, void *opaque, int version_id)
{
595
    VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
596 597
    int ret;

598
    ret = virtio_load(vdev, f, version_id);
599 600 601
    if (ret) {
        return ret;
    }
602 603 604
    return 0;
}

605 606
void virtio_scsi_push_event(VirtIOSCSI *s, SCSIDevice *dev,
                            uint32_t event, uint32_t reason)
607
{
608
    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);
609
    VirtIOSCSIReq *req;
610
    VirtIOSCSIEvent *evt;
611
    VirtIODevice *vdev = VIRTIO_DEVICE(s);
612

613
    if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {
614 615 616
        return;
    }

F
Fam Zheng 已提交
617 618 619 620 621 622 623 624 625 626
    if (s->dataplane_started) {
        assert(s->ctx);
        aio_context_acquire(s->ctx);
    }

    if (s->dataplane_started) {
        req = virtio_scsi_pop_req_vring(s, s->event_vring);
    } else {
        req = virtio_scsi_pop_req(s, vs->event_vq);
    }
627 628
    if (!req) {
        s->events_dropped = true;
F
Fam Zheng 已提交
629
        goto out;
630
    }
631

632 633 634 635 636
    if (s->events_dropped) {
        event |= VIRTIO_SCSI_T_EVENTS_MISSED;
        s->events_dropped = false;
    }

637
    if (virtio_scsi_parse_req(req, 0, sizeof(VirtIOSCSIEvent))) {
638 639 640
        virtio_scsi_bad_req();
    }

641
    evt = &req->resp.event;
642
    memset(evt, 0, sizeof(VirtIOSCSIEvent));
643 644
    evt->event = virtio_tswap32(vdev, event);
    evt->reason = virtio_tswap32(vdev, reason);
645
    if (!dev) {
646
        assert(event == VIRTIO_SCSI_T_EVENTS_MISSED);
647
    } else {
648 649 650 651 652 653 654 655
        evt->lun[0] = 1;
        evt->lun[1] = dev->id;

        /* Linux wants us to keep the same encoding we use for REPORT LUNS.  */
        if (dev->lun >= 256) {
            evt->lun[2] = (dev->lun >> 8) | 0x40;
        }
        evt->lun[3] = dev->lun & 0xFF;
656 657
    }
    virtio_scsi_complete_req(req);
F
Fam Zheng 已提交
658 659 660 661
out:
    if (s->dataplane_started) {
        aio_context_release(s->ctx);
    }
662 663 664 665
}

static void virtio_scsi_handle_event(VirtIODevice *vdev, VirtQueue *vq)
{
666
    VirtIOSCSI *s = VIRTIO_SCSI(vdev);
667

668
    if (s->ctx && !s->dataplane_disabled) {
F
Fam Zheng 已提交
669 670 671
        virtio_scsi_dataplane_start(s);
        return;
    }
672 673
    if (s->events_dropped) {
        virtio_scsi_push_event(s, NULL, VIRTIO_SCSI_T_NO_EVENT, 0);
674 675 676
    }
}

677 678 679
static void virtio_scsi_change(SCSIBus *bus, SCSIDevice *dev, SCSISense sense)
{
    VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus);
680
    VirtIODevice *vdev = VIRTIO_DEVICE(s);
681

682
    if (((vdev->guest_features >> VIRTIO_SCSI_F_CHANGE) & 1) &&
683 684 685 686 687 688
        dev->type != TYPE_ROM) {
        virtio_scsi_push_event(s, dev, VIRTIO_SCSI_T_PARAM_CHANGE,
                               sense.asc | (sense.ascq << 8));
    }
}

689 690 691
static void virtio_scsi_hotplug(SCSIBus *bus, SCSIDevice *dev)
{
    VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus);
692
    VirtIODevice *vdev = VIRTIO_DEVICE(s);
693

694
    if ((vdev->guest_features >> VIRTIO_SCSI_F_HOTPLUG) & 1) {
695 696 697 698 699 700 701 702
        virtio_scsi_push_event(s, dev, VIRTIO_SCSI_T_TRANSPORT_RESET,
                               VIRTIO_SCSI_EVT_RESET_RESCAN);
    }
}

static void virtio_scsi_hot_unplug(SCSIBus *bus, SCSIDevice *dev)
{
    VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus);
703
    VirtIODevice *vdev = VIRTIO_DEVICE(s);
704

705
    if ((vdev->guest_features >> VIRTIO_SCSI_F_HOTPLUG) & 1) {
706 707 708 709 710
        virtio_scsi_push_event(s, dev, VIRTIO_SCSI_T_TRANSPORT_RESET,
                               VIRTIO_SCSI_EVT_RESET_REMOVED);
    }
}

711 712 713 714 715 716 717 718
static struct SCSIBusInfo virtio_scsi_scsi_info = {
    .tcq = true,
    .max_channel = VIRTIO_SCSI_MAX_CHANNEL,
    .max_target = VIRTIO_SCSI_MAX_TARGET,
    .max_lun = VIRTIO_SCSI_MAX_LUN,

    .complete = virtio_scsi_command_complete,
    .cancel = virtio_scsi_request_cancelled,
719
    .change = virtio_scsi_change,
720 721
    .hotplug = virtio_scsi_hotplug,
    .hot_unplug = virtio_scsi_hot_unplug,
P
Paolo Bonzini 已提交
722
    .parse_cdb = virtio_scsi_parse_cdb,
723
    .get_sg_list = virtio_scsi_get_sg_list,
724 725
    .save_request = virtio_scsi_save_request,
    .load_request = virtio_scsi_load_request,
726 727
};

728 729 730
void virtio_scsi_common_realize(DeviceState *dev, Error **errp,
                                HandleOutput ctrl, HandleOutput evt,
                                HandleOutput cmd)
731
{
732 733
    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
    VirtIOSCSICommon *s = VIRTIO_SCSI_COMMON(dev);
734
    int i;
735

736
    virtio_init(vdev, "virtio-scsi", VIRTIO_ID_SCSI,
737
                sizeof(VirtIOSCSIConfig));
738

739 740 741 742 743 744
    if (s->conf.num_queues <= 0 || s->conf.num_queues > VIRTIO_PCI_QUEUE_MAX) {
        error_setg(errp, "Invalid number of queues (= %" PRId32 "), "
                         "must be a positive integer less than %d.",
                   s->conf.num_queues, VIRTIO_PCI_QUEUE_MAX);
        return;
    }
745
    s->cmd_vqs = g_malloc0(s->conf.num_queues * sizeof(VirtQueue *));
746 747
    s->sense_size = VIRTIO_SCSI_SENSE_SIZE;
    s->cdb_size = VIRTIO_SCSI_CDB_SIZE;
748

749
    s->ctrl_vq = virtio_add_queue(vdev, VIRTIO_SCSI_VQ_SIZE,
750
                                  ctrl);
751
    s->event_vq = virtio_add_queue(vdev, VIRTIO_SCSI_VQ_SIZE,
752
                                   evt);
753
    for (i = 0; i < s->conf.num_queues; i++) {
754
        s->cmd_vqs[i] = virtio_add_queue(vdev, VIRTIO_SCSI_VQ_SIZE,
755
                                         cmd);
756
    }
757 758 759 760

    if (s->conf.iothread) {
        virtio_scsi_set_iothread(VIRTIO_SCSI(s), s->conf.iothread);
    }
761 762
}

763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
/* Disable dataplane thread during live migration since it does not
 * update the dirty memory bitmap yet.
 */
static void virtio_scsi_migration_state_changed(Notifier *notifier, void *data)
{
    VirtIOSCSI *s = container_of(notifier, VirtIOSCSI,
                                 migration_state_notifier);
    MigrationState *mig = data;

    if (migration_in_setup(mig)) {
        if (!s->dataplane_started) {
            return;
        }
        virtio_scsi_dataplane_stop(s);
        s->dataplane_disabled = true;
    } else if (migration_has_finished(mig) ||
               migration_has_failed(mig)) {
        if (s->dataplane_started) {
            return;
        }
        bdrv_drain_all(); /* complete in-flight non-dataplane requests */
        s->dataplane_disabled = false;
    }
}

788
static void virtio_scsi_device_realize(DeviceState *dev, Error **errp)
789
{
790
    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
791
    VirtIOSCSI *s = VIRTIO_SCSI(dev);
792
    static int virtio_scsi_id;
793
    Error *err = NULL;
794

795 796 797
    virtio_scsi_common_realize(dev, &err, virtio_scsi_handle_ctrl,
                               virtio_scsi_handle_event,
                               virtio_scsi_handle_cmd);
798 799 800
    if (err != NULL) {
        error_propagate(errp, err);
        return;
801 802
    }

803
    scsi_bus_new(&s->bus, sizeof(s->bus), dev,
804
                 &virtio_scsi_scsi_info, vdev->bus_name);
805

806
    if (!dev->hotplugged) {
807 808
        scsi_bus_legacy_handle_cmdline(&s->bus, &err);
        if (err != NULL) {
809 810
            error_propagate(errp, err);
            return;
811
        }
812 813
    }

814
    register_savevm(dev, "virtio-scsi", virtio_scsi_id++, 1,
815
                    virtio_scsi_save, virtio_scsi_load, s);
816 817
    s->migration_state_notifier.notify = virtio_scsi_migration_state_changed;
    add_migration_state_change_notifier(&s->migration_state_notifier);
818 819
}

820 821 822 823 824 825 826 827 828 829
static void virtio_scsi_instance_init(Object *obj)
{
    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(obj);

    object_property_add_link(obj, "iothread", TYPE_IOTHREAD,
                             (Object **)&vs->conf.iothread,
                             qdev_prop_allow_set_link_before_realize,
                             OBJ_PROP_LINK_UNREF_ON_RELEASE, &error_abort);
}

830
void virtio_scsi_common_unrealize(DeviceState *dev, Error **errp)
831
{
832 833
    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(dev);
834 835

    g_free(vs->cmd_vqs);
836
    virtio_cleanup(vdev);
837 838
}

839
static void virtio_scsi_device_unrealize(DeviceState *dev, Error **errp)
840
{
841 842 843
    VirtIOSCSI *s = VIRTIO_SCSI(dev);

    unregister_savevm(dev, "virtio-scsi", s);
844
    remove_migration_state_change_notifier(&s->migration_state_notifier);
845

846
    virtio_scsi_common_unrealize(dev, errp);
847 848 849
}

static Property virtio_scsi_properties[] = {
850
    DEFINE_VIRTIO_SCSI_PROPERTIES(VirtIOSCSI, parent_obj.conf),
851 852 853
    DEFINE_PROP_END_OF_LIST(),
};

854 855 856
static void virtio_scsi_common_class_init(ObjectClass *klass, void *data)
{
    VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
857
    DeviceClass *dc = DEVICE_CLASS(klass);
858 859

    vdc->get_config = virtio_scsi_get_config;
860
    set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
861 862
}

863 864 865 866
static void virtio_scsi_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);
    VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
867

868
    dc->props = virtio_scsi_properties;
869
    set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
870
    vdc->realize = virtio_scsi_device_realize;
871
    vdc->unrealize = virtio_scsi_device_unrealize;
872 873 874 875 876
    vdc->set_config = virtio_scsi_set_config;
    vdc->get_features = virtio_scsi_get_features;
    vdc->reset = virtio_scsi_reset;
}

877 878 879 880
static const TypeInfo virtio_scsi_common_info = {
    .name = TYPE_VIRTIO_SCSI_COMMON,
    .parent = TYPE_VIRTIO_DEVICE,
    .instance_size = sizeof(VirtIOSCSICommon),
881
    .abstract = true,
882 883 884
    .class_init = virtio_scsi_common_class_init,
};

885 886
static const TypeInfo virtio_scsi_info = {
    .name = TYPE_VIRTIO_SCSI,
887
    .parent = TYPE_VIRTIO_SCSI_COMMON,
888
    .instance_size = sizeof(VirtIOSCSI),
889
    .instance_init = virtio_scsi_instance_init,
890 891 892 893 894
    .class_init = virtio_scsi_class_init,
};

static void virtio_register_types(void)
{
895
    type_register_static(&virtio_scsi_common_info);
896 897 898 899
    type_register_static(&virtio_scsi_info);
}

type_init(virtio_register_types)