virtio-serial-bus: Unset hotplug handler when unrealize
[qemu/ar7.git] / hw / block / virtio-blk.c
blob604d37dfc844307e4fa45d6aa9f94bdad455bb99
1 /*
2 * Virtio Block Device
4 * Copyright IBM, Corp. 2007
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
14 #include "qemu/osdep.h"
15 #include "qapi/error.h"
16 #include "qemu-common.h"
17 #include "qemu/iov.h"
18 #include "qemu/error-report.h"
19 #include "trace.h"
20 #include "hw/block/block.h"
21 #include "sysemu/block-backend.h"
22 #include "sysemu/blockdev.h"
23 #include "hw/virtio/virtio-blk.h"
24 #include "dataplane/virtio-blk.h"
25 #include "block/scsi.h"
26 #ifdef __linux__
27 # include <scsi/sg.h>
28 #endif
29 #include "hw/virtio/virtio-bus.h"
30 #include "hw/virtio/virtio-access.h"
32 static void virtio_blk_init_request(VirtIOBlock *s, VirtQueue *vq,
33 VirtIOBlockReq *req)
35 req->dev = s;
36 req->vq = vq;
37 req->qiov.size = 0;
38 req->in_len = 0;
39 req->next = NULL;
40 req->mr_next = NULL;
43 static void virtio_blk_free_request(VirtIOBlockReq *req)
45 g_free(req);
48 static void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
50 VirtIOBlock *s = req->dev;
51 VirtIODevice *vdev = VIRTIO_DEVICE(s);
53 trace_virtio_blk_req_complete(req, status);
55 stb_p(&req->in->status, status);
56 virtqueue_push(req->vq, &req->elem, req->in_len);
57 if (s->dataplane_started && !s->dataplane_disabled) {
58 virtio_blk_data_plane_notify(s->dataplane, req->vq);
59 } else {
60 virtio_notify(vdev, req->vq);
64 static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
65 bool is_read)
67 BlockErrorAction action = blk_get_error_action(req->dev->blk,
68 is_read, error);
69 VirtIOBlock *s = req->dev;
71 if (action == BLOCK_ERROR_ACTION_STOP) {
72 /* Break the link as the next request is going to be parsed from the
73 * ring again. Otherwise we may end up doing a double completion! */
74 req->mr_next = NULL;
75 req->next = s->rq;
76 s->rq = req;
77 } else if (action == BLOCK_ERROR_ACTION_REPORT) {
78 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
79 block_acct_failed(blk_get_stats(s->blk), &req->acct);
80 virtio_blk_free_request(req);
83 blk_error_action(s->blk, action, is_read, error);
84 return action != BLOCK_ERROR_ACTION_IGNORE;
87 static void virtio_blk_rw_complete(void *opaque, int ret)
89 VirtIOBlockReq *next = opaque;
90 VirtIOBlock *s = next->dev;
92 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
93 while (next) {
94 VirtIOBlockReq *req = next;
95 next = req->mr_next;
96 trace_virtio_blk_rw_complete(req, ret);
98 if (req->qiov.nalloc != -1) {
99 /* If nalloc is != 1 req->qiov is a local copy of the original
100 * external iovec. It was allocated in submit_merged_requests
101 * to be able to merge requests. */
102 qemu_iovec_destroy(&req->qiov);
105 if (ret) {
106 int p = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);
107 bool is_read = !(p & VIRTIO_BLK_T_OUT);
108 /* Note that memory may be dirtied on read failure. If the
109 * virtio request is not completed here, as is the case for
110 * BLOCK_ERROR_ACTION_STOP, the memory may not be copied
111 * correctly during live migration. While this is ugly,
112 * it is acceptable because the device is free to write to
113 * the memory until the request is completed (which will
114 * happen on the other side of the migration).
116 if (virtio_blk_handle_rw_error(req, -ret, is_read)) {
117 continue;
121 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
122 block_acct_done(blk_get_stats(req->dev->blk), &req->acct);
123 virtio_blk_free_request(req);
125 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
128 static void virtio_blk_flush_complete(void *opaque, int ret)
130 VirtIOBlockReq *req = opaque;
131 VirtIOBlock *s = req->dev;
133 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
134 if (ret) {
135 if (virtio_blk_handle_rw_error(req, -ret, 0)) {
136 goto out;
140 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
141 block_acct_done(blk_get_stats(req->dev->blk), &req->acct);
142 virtio_blk_free_request(req);
144 out:
145 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
148 #ifdef __linux__
150 typedef struct {
151 VirtIOBlockReq *req;
152 struct sg_io_hdr hdr;
153 } VirtIOBlockIoctlReq;
155 static void virtio_blk_ioctl_complete(void *opaque, int status)
157 VirtIOBlockIoctlReq *ioctl_req = opaque;
158 VirtIOBlockReq *req = ioctl_req->req;
159 VirtIOBlock *s = req->dev;
160 VirtIODevice *vdev = VIRTIO_DEVICE(s);
161 struct virtio_scsi_inhdr *scsi;
162 struct sg_io_hdr *hdr;
164 scsi = (void *)req->elem.in_sg[req->elem.in_num - 2].iov_base;
166 if (status) {
167 status = VIRTIO_BLK_S_UNSUPP;
168 virtio_stl_p(vdev, &scsi->errors, 255);
169 goto out;
172 hdr = &ioctl_req->hdr;
174 * From SCSI-Generic-HOWTO: "Some lower level drivers (e.g. ide-scsi)
175 * clear the masked_status field [hence status gets cleared too, see
176 * block/scsi_ioctl.c] even when a CHECK_CONDITION or COMMAND_TERMINATED
177 * status has occurred. However they do set DRIVER_SENSE in driver_status
178 * field. Also a (sb_len_wr > 0) indicates there is a sense buffer.
180 if (hdr->status == 0 && hdr->sb_len_wr > 0) {
181 hdr->status = CHECK_CONDITION;
184 virtio_stl_p(vdev, &scsi->errors,
185 hdr->status | (hdr->msg_status << 8) |
186 (hdr->host_status << 16) | (hdr->driver_status << 24));
187 virtio_stl_p(vdev, &scsi->residual, hdr->resid);
188 virtio_stl_p(vdev, &scsi->sense_len, hdr->sb_len_wr);
189 virtio_stl_p(vdev, &scsi->data_len, hdr->dxfer_len);
191 out:
192 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
193 virtio_blk_req_complete(req, status);
194 virtio_blk_free_request(req);
195 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
196 g_free(ioctl_req);
199 #endif
201 static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s, VirtQueue *vq)
203 VirtIOBlockReq *req = virtqueue_pop(vq, sizeof(VirtIOBlockReq));
205 if (req) {
206 virtio_blk_init_request(s, vq, req);
208 return req;
211 static int virtio_blk_handle_scsi_req(VirtIOBlockReq *req)
213 int status = VIRTIO_BLK_S_OK;
214 struct virtio_scsi_inhdr *scsi = NULL;
215 VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
216 VirtQueueElement *elem = &req->elem;
217 VirtIOBlock *blk = req->dev;
219 #ifdef __linux__
220 int i;
221 VirtIOBlockIoctlReq *ioctl_req;
222 BlockAIOCB *acb;
223 #endif
226 * We require at least one output segment each for the virtio_blk_outhdr
227 * and the SCSI command block.
229 * We also at least require the virtio_blk_inhdr, the virtio_scsi_inhdr
230 * and the sense buffer pointer in the input segments.
232 if (elem->out_num < 2 || elem->in_num < 3) {
233 status = VIRTIO_BLK_S_IOERR;
234 goto fail;
238 * The scsi inhdr is placed in the second-to-last input segment, just
239 * before the regular inhdr.
241 scsi = (void *)elem->in_sg[elem->in_num - 2].iov_base;
243 if (!blk->conf.scsi) {
244 status = VIRTIO_BLK_S_UNSUPP;
245 goto fail;
249 * No support for bidirection commands yet.
251 if (elem->out_num > 2 && elem->in_num > 3) {
252 status = VIRTIO_BLK_S_UNSUPP;
253 goto fail;
256 #ifdef __linux__
257 ioctl_req = g_new0(VirtIOBlockIoctlReq, 1);
258 ioctl_req->req = req;
259 ioctl_req->hdr.interface_id = 'S';
260 ioctl_req->hdr.cmd_len = elem->out_sg[1].iov_len;
261 ioctl_req->hdr.cmdp = elem->out_sg[1].iov_base;
262 ioctl_req->hdr.dxfer_len = 0;
264 if (elem->out_num > 2) {
266 * If there are more than the minimally required 2 output segments
267 * there is write payload starting from the third iovec.
269 ioctl_req->hdr.dxfer_direction = SG_DXFER_TO_DEV;
270 ioctl_req->hdr.iovec_count = elem->out_num - 2;
272 for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
273 ioctl_req->hdr.dxfer_len += elem->out_sg[i + 2].iov_len;
276 ioctl_req->hdr.dxferp = elem->out_sg + 2;
278 } else if (elem->in_num > 3) {
280 * If we have more than 3 input segments the guest wants to actually
281 * read data.
283 ioctl_req->hdr.dxfer_direction = SG_DXFER_FROM_DEV;
284 ioctl_req->hdr.iovec_count = elem->in_num - 3;
285 for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
286 ioctl_req->hdr.dxfer_len += elem->in_sg[i].iov_len;
289 ioctl_req->hdr.dxferp = elem->in_sg;
290 } else {
292 * Some SCSI commands don't actually transfer any data.
294 ioctl_req->hdr.dxfer_direction = SG_DXFER_NONE;
297 ioctl_req->hdr.sbp = elem->in_sg[elem->in_num - 3].iov_base;
298 ioctl_req->hdr.mx_sb_len = elem->in_sg[elem->in_num - 3].iov_len;
300 acb = blk_aio_ioctl(blk->blk, SG_IO, &ioctl_req->hdr,
301 virtio_blk_ioctl_complete, ioctl_req);
302 if (!acb) {
303 g_free(ioctl_req);
304 status = VIRTIO_BLK_S_UNSUPP;
305 goto fail;
307 return -EINPROGRESS;
308 #else
309 abort();
310 #endif
312 fail:
313 /* Just put anything nonzero so that the ioctl fails in the guest. */
314 if (scsi) {
315 virtio_stl_p(vdev, &scsi->errors, 255);
317 return status;
320 static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
322 int status;
324 status = virtio_blk_handle_scsi_req(req);
325 if (status != -EINPROGRESS) {
326 virtio_blk_req_complete(req, status);
327 virtio_blk_free_request(req);
331 static inline void submit_requests(BlockBackend *blk, MultiReqBuffer *mrb,
332 int start, int num_reqs, int niov)
334 QEMUIOVector *qiov = &mrb->reqs[start]->qiov;
335 int64_t sector_num = mrb->reqs[start]->sector_num;
336 bool is_write = mrb->is_write;
338 if (num_reqs > 1) {
339 int i;
340 struct iovec *tmp_iov = qiov->iov;
341 int tmp_niov = qiov->niov;
343 /* mrb->reqs[start]->qiov was initialized from external so we can't
344 * modify it here. We need to initialize it locally and then add the
345 * external iovecs. */
346 qemu_iovec_init(qiov, niov);
348 for (i = 0; i < tmp_niov; i++) {
349 qemu_iovec_add(qiov, tmp_iov[i].iov_base, tmp_iov[i].iov_len);
352 for (i = start + 1; i < start + num_reqs; i++) {
353 qemu_iovec_concat(qiov, &mrb->reqs[i]->qiov, 0,
354 mrb->reqs[i]->qiov.size);
355 mrb->reqs[i - 1]->mr_next = mrb->reqs[i];
358 trace_virtio_blk_submit_multireq(mrb, start, num_reqs,
359 sector_num << BDRV_SECTOR_BITS,
360 qiov->size, is_write);
361 block_acct_merge_done(blk_get_stats(blk),
362 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ,
363 num_reqs - 1);
366 if (is_write) {
367 blk_aio_pwritev(blk, sector_num << BDRV_SECTOR_BITS, qiov, 0,
368 virtio_blk_rw_complete, mrb->reqs[start]);
369 } else {
370 blk_aio_preadv(blk, sector_num << BDRV_SECTOR_BITS, qiov, 0,
371 virtio_blk_rw_complete, mrb->reqs[start]);
375 static int multireq_compare(const void *a, const void *b)
377 const VirtIOBlockReq *req1 = *(VirtIOBlockReq **)a,
378 *req2 = *(VirtIOBlockReq **)b;
381 * Note that we can't simply subtract sector_num1 from sector_num2
382 * here as that could overflow the return value.
384 if (req1->sector_num > req2->sector_num) {
385 return 1;
386 } else if (req1->sector_num < req2->sector_num) {
387 return -1;
388 } else {
389 return 0;
393 static void virtio_blk_submit_multireq(BlockBackend *blk, MultiReqBuffer *mrb)
395 int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
396 uint32_t max_transfer;
397 int64_t sector_num = 0;
399 if (mrb->num_reqs == 1) {
400 submit_requests(blk, mrb, 0, 1, -1);
401 mrb->num_reqs = 0;
402 return;
405 max_transfer = blk_get_max_transfer(mrb->reqs[0]->dev->blk);
407 qsort(mrb->reqs, mrb->num_reqs, sizeof(*mrb->reqs),
408 &multireq_compare);
410 for (i = 0; i < mrb->num_reqs; i++) {
411 VirtIOBlockReq *req = mrb->reqs[i];
412 if (num_reqs > 0) {
414 * NOTE: We cannot merge the requests in below situations:
415 * 1. requests are not sequential
416 * 2. merge would exceed maximum number of IOVs
417 * 3. merge would exceed maximum transfer length of backend device
419 if (sector_num + nb_sectors != req->sector_num ||
420 niov > blk_get_max_iov(blk) - req->qiov.niov ||
421 req->qiov.size > max_transfer ||
422 nb_sectors > (max_transfer -
423 req->qiov.size) / BDRV_SECTOR_SIZE) {
424 submit_requests(blk, mrb, start, num_reqs, niov);
425 num_reqs = 0;
429 if (num_reqs == 0) {
430 sector_num = req->sector_num;
431 nb_sectors = niov = 0;
432 start = i;
435 nb_sectors += req->qiov.size / BDRV_SECTOR_SIZE;
436 niov += req->qiov.niov;
437 num_reqs++;
440 submit_requests(blk, mrb, start, num_reqs, niov);
441 mrb->num_reqs = 0;
444 static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
446 block_acct_start(blk_get_stats(req->dev->blk), &req->acct, 0,
447 BLOCK_ACCT_FLUSH);
450 * Make sure all outstanding writes are posted to the backing device.
452 if (mrb->is_write && mrb->num_reqs > 0) {
453 virtio_blk_submit_multireq(req->dev->blk, mrb);
455 blk_aio_flush(req->dev->blk, virtio_blk_flush_complete, req);
458 static bool virtio_blk_sect_range_ok(VirtIOBlock *dev,
459 uint64_t sector, size_t size)
461 uint64_t nb_sectors = size >> BDRV_SECTOR_BITS;
462 uint64_t total_sectors;
464 if (nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
465 return false;
467 if (sector & dev->sector_mask) {
468 return false;
470 if (size % dev->conf.conf.logical_block_size) {
471 return false;
473 blk_get_geometry(dev->blk, &total_sectors);
474 if (sector > total_sectors || nb_sectors > total_sectors - sector) {
475 return false;
477 return true;
480 static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
482 uint32_t type;
483 struct iovec *in_iov = req->elem.in_sg;
484 struct iovec *iov = req->elem.out_sg;
485 unsigned in_num = req->elem.in_num;
486 unsigned out_num = req->elem.out_num;
487 VirtIOBlock *s = req->dev;
488 VirtIODevice *vdev = VIRTIO_DEVICE(s);
490 if (req->elem.out_num < 1 || req->elem.in_num < 1) {
491 virtio_error(vdev, "virtio-blk missing headers");
492 return -1;
495 if (unlikely(iov_to_buf(iov, out_num, 0, &req->out,
496 sizeof(req->out)) != sizeof(req->out))) {
497 virtio_error(vdev, "virtio-blk request outhdr too short");
498 return -1;
501 iov_discard_front(&iov, &out_num, sizeof(req->out));
503 if (in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {
504 virtio_error(vdev, "virtio-blk request inhdr too short");
505 return -1;
508 /* We always touch the last byte, so just see how big in_iov is. */
509 req->in_len = iov_size(in_iov, in_num);
510 req->in = (void *)in_iov[in_num - 1].iov_base
511 + in_iov[in_num - 1].iov_len
512 - sizeof(struct virtio_blk_inhdr);
513 iov_discard_back(in_iov, &in_num, sizeof(struct virtio_blk_inhdr));
515 type = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);
517 /* VIRTIO_BLK_T_OUT defines the command direction. VIRTIO_BLK_T_BARRIER
518 * is an optional flag. Although a guest should not send this flag if
519 * not negotiated we ignored it in the past. So keep ignoring it. */
520 switch (type & ~(VIRTIO_BLK_T_OUT | VIRTIO_BLK_T_BARRIER)) {
521 case VIRTIO_BLK_T_IN:
523 bool is_write = type & VIRTIO_BLK_T_OUT;
524 req->sector_num = virtio_ldq_p(VIRTIO_DEVICE(req->dev),
525 &req->out.sector);
527 if (is_write) {
528 qemu_iovec_init_external(&req->qiov, iov, out_num);
529 trace_virtio_blk_handle_write(req, req->sector_num,
530 req->qiov.size / BDRV_SECTOR_SIZE);
531 } else {
532 qemu_iovec_init_external(&req->qiov, in_iov, in_num);
533 trace_virtio_blk_handle_read(req, req->sector_num,
534 req->qiov.size / BDRV_SECTOR_SIZE);
537 if (!virtio_blk_sect_range_ok(req->dev, req->sector_num,
538 req->qiov.size)) {
539 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
540 block_acct_invalid(blk_get_stats(req->dev->blk),
541 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
542 virtio_blk_free_request(req);
543 return 0;
546 block_acct_start(blk_get_stats(req->dev->blk),
547 &req->acct, req->qiov.size,
548 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
550 /* merge would exceed maximum number of requests or IO direction
551 * changes */
552 if (mrb->num_reqs > 0 && (mrb->num_reqs == VIRTIO_BLK_MAX_MERGE_REQS ||
553 is_write != mrb->is_write ||
554 !req->dev->conf.request_merging)) {
555 virtio_blk_submit_multireq(req->dev->blk, mrb);
558 assert(mrb->num_reqs < VIRTIO_BLK_MAX_MERGE_REQS);
559 mrb->reqs[mrb->num_reqs++] = req;
560 mrb->is_write = is_write;
561 break;
563 case VIRTIO_BLK_T_FLUSH:
564 virtio_blk_handle_flush(req, mrb);
565 break;
566 case VIRTIO_BLK_T_SCSI_CMD:
567 virtio_blk_handle_scsi(req);
568 break;
569 case VIRTIO_BLK_T_GET_ID:
571 VirtIOBlock *s = req->dev;
574 * NB: per existing s/n string convention the string is
575 * terminated by '\0' only when shorter than buffer.
577 const char *serial = s->conf.serial ? s->conf.serial : "";
578 size_t size = MIN(strlen(serial) + 1,
579 MIN(iov_size(in_iov, in_num),
580 VIRTIO_BLK_ID_BYTES));
581 iov_from_buf(in_iov, in_num, 0, serial, size);
582 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
583 virtio_blk_free_request(req);
584 break;
586 default:
587 virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
588 virtio_blk_free_request(req);
590 return 0;
593 bool virtio_blk_handle_vq(VirtIOBlock *s, VirtQueue *vq)
595 VirtIOBlockReq *req;
596 MultiReqBuffer mrb = {};
597 bool progress = false;
599 aio_context_acquire(blk_get_aio_context(s->blk));
600 blk_io_plug(s->blk);
602 do {
603 virtio_queue_set_notification(vq, 0);
605 while ((req = virtio_blk_get_request(s, vq))) {
606 progress = true;
607 if (virtio_blk_handle_request(req, &mrb)) {
608 virtqueue_detach_element(req->vq, &req->elem, 0);
609 virtio_blk_free_request(req);
610 break;
614 virtio_queue_set_notification(vq, 1);
615 } while (!virtio_queue_empty(vq));
617 if (mrb.num_reqs) {
618 virtio_blk_submit_multireq(s->blk, &mrb);
621 blk_io_unplug(s->blk);
622 aio_context_release(blk_get_aio_context(s->blk));
623 return progress;
626 static void virtio_blk_handle_output_do(VirtIOBlock *s, VirtQueue *vq)
628 virtio_blk_handle_vq(s, vq);
631 static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)
633 VirtIOBlock *s = (VirtIOBlock *)vdev;
635 if (s->dataplane) {
636 /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start
637 * dataplane here instead of waiting for .set_status().
639 virtio_device_start_ioeventfd(vdev);
640 if (!s->dataplane_disabled) {
641 return;
644 virtio_blk_handle_output_do(s, vq);
647 static void virtio_blk_dma_restart_bh(void *opaque)
649 VirtIOBlock *s = opaque;
650 VirtIOBlockReq *req = s->rq;
651 MultiReqBuffer mrb = {};
653 qemu_bh_delete(s->bh);
654 s->bh = NULL;
656 s->rq = NULL;
658 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
659 while (req) {
660 VirtIOBlockReq *next = req->next;
661 if (virtio_blk_handle_request(req, &mrb)) {
662 /* Device is now broken and won't do any processing until it gets
663 * reset. Already queued requests will be lost: let's purge them.
665 while (req) {
666 next = req->next;
667 virtqueue_detach_element(req->vq, &req->elem, 0);
668 virtio_blk_free_request(req);
669 req = next;
671 break;
673 req = next;
676 if (mrb.num_reqs) {
677 virtio_blk_submit_multireq(s->blk, &mrb);
679 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
682 static void virtio_blk_dma_restart_cb(void *opaque, int running,
683 RunState state)
685 VirtIOBlock *s = opaque;
687 if (!running) {
688 return;
691 if (!s->bh) {
692 s->bh = aio_bh_new(blk_get_aio_context(s->conf.conf.blk),
693 virtio_blk_dma_restart_bh, s);
694 qemu_bh_schedule(s->bh);
698 static void virtio_blk_reset(VirtIODevice *vdev)
700 VirtIOBlock *s = VIRTIO_BLK(vdev);
701 AioContext *ctx;
702 VirtIOBlockReq *req;
704 ctx = blk_get_aio_context(s->blk);
705 aio_context_acquire(ctx);
706 blk_drain(s->blk);
708 /* We drop queued requests after blk_drain() because blk_drain() itself can
709 * produce them. */
710 while (s->rq) {
711 req = s->rq;
712 s->rq = req->next;
713 virtqueue_detach_element(req->vq, &req->elem, 0);
714 virtio_blk_free_request(req);
717 aio_context_release(ctx);
719 assert(!s->dataplane_started);
720 blk_set_enable_write_cache(s->blk, s->original_wce);
723 /* coalesce internal state, copy to pci i/o region 0
725 static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
727 VirtIOBlock *s = VIRTIO_BLK(vdev);
728 BlockConf *conf = &s->conf.conf;
729 struct virtio_blk_config blkcfg;
730 uint64_t capacity;
731 int blk_size = conf->logical_block_size;
733 blk_get_geometry(s->blk, &capacity);
734 memset(&blkcfg, 0, sizeof(blkcfg));
735 virtio_stq_p(vdev, &blkcfg.capacity, capacity);
736 virtio_stl_p(vdev, &blkcfg.seg_max, 128 - 2);
737 virtio_stw_p(vdev, &blkcfg.geometry.cylinders, conf->cyls);
738 virtio_stl_p(vdev, &blkcfg.blk_size, blk_size);
739 virtio_stw_p(vdev, &blkcfg.min_io_size, conf->min_io_size / blk_size);
740 virtio_stw_p(vdev, &blkcfg.opt_io_size, conf->opt_io_size / blk_size);
741 blkcfg.geometry.heads = conf->heads;
743 * We must ensure that the block device capacity is a multiple of
744 * the logical block size. If that is not the case, let's use
745 * sector_mask to adopt the geometry to have a correct picture.
746 * For those devices where the capacity is ok for the given geometry
747 * we don't touch the sector value of the geometry, since some devices
748 * (like s390 dasd) need a specific value. Here the capacity is already
749 * cyls*heads*secs*blk_size and the sector value is not block size
750 * divided by 512 - instead it is the amount of blk_size blocks
751 * per track (cylinder).
753 if (blk_getlength(s->blk) / conf->heads / conf->secs % blk_size) {
754 blkcfg.geometry.sectors = conf->secs & ~s->sector_mask;
755 } else {
756 blkcfg.geometry.sectors = conf->secs;
758 blkcfg.size_max = 0;
759 blkcfg.physical_block_exp = get_physical_block_exp(conf);
760 blkcfg.alignment_offset = 0;
761 blkcfg.wce = blk_enable_write_cache(s->blk);
762 virtio_stw_p(vdev, &blkcfg.num_queues, s->conf.num_queues);
763 memcpy(config, &blkcfg, sizeof(struct virtio_blk_config));
766 static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config)
768 VirtIOBlock *s = VIRTIO_BLK(vdev);
769 struct virtio_blk_config blkcfg;
771 memcpy(&blkcfg, config, sizeof(blkcfg));
773 aio_context_acquire(blk_get_aio_context(s->blk));
774 blk_set_enable_write_cache(s->blk, blkcfg.wce != 0);
775 aio_context_release(blk_get_aio_context(s->blk));
778 static uint64_t virtio_blk_get_features(VirtIODevice *vdev, uint64_t features,
779 Error **errp)
781 VirtIOBlock *s = VIRTIO_BLK(vdev);
783 virtio_add_feature(&features, VIRTIO_BLK_F_SEG_MAX);
784 virtio_add_feature(&features, VIRTIO_BLK_F_GEOMETRY);
785 virtio_add_feature(&features, VIRTIO_BLK_F_TOPOLOGY);
786 virtio_add_feature(&features, VIRTIO_BLK_F_BLK_SIZE);
787 if (virtio_has_feature(features, VIRTIO_F_VERSION_1)) {
788 if (s->conf.scsi) {
789 error_setg(errp, "Please set scsi=off for virtio-blk devices in order to use virtio 1.0");
790 return 0;
792 } else {
793 virtio_clear_feature(&features, VIRTIO_F_ANY_LAYOUT);
794 virtio_add_feature(&features, VIRTIO_BLK_F_SCSI);
797 if (s->conf.config_wce) {
798 virtio_add_feature(&features, VIRTIO_BLK_F_CONFIG_WCE);
800 if (blk_enable_write_cache(s->blk)) {
801 virtio_add_feature(&features, VIRTIO_BLK_F_WCE);
803 if (blk_is_read_only(s->blk)) {
804 virtio_add_feature(&features, VIRTIO_BLK_F_RO);
806 if (s->conf.num_queues > 1) {
807 virtio_add_feature(&features, VIRTIO_BLK_F_MQ);
810 return features;
813 static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)
815 VirtIOBlock *s = VIRTIO_BLK(vdev);
817 if (!(status & (VIRTIO_CONFIG_S_DRIVER | VIRTIO_CONFIG_S_DRIVER_OK))) {
818 assert(!s->dataplane_started);
821 if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
822 return;
825 /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send
826 * cache flushes. Thus, the "auto writethrough" behavior is never
827 * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.
828 * Leaving it enabled would break the following sequence:
830 * Guest started with "-drive cache=writethrough"
831 * Guest sets status to 0
832 * Guest sets DRIVER bit in status field
833 * Guest reads host features (WCE=0, CONFIG_WCE=1)
834 * Guest writes guest features (WCE=0, CONFIG_WCE=1)
835 * Guest writes 1 to the WCE configuration field (writeback mode)
836 * Guest sets DRIVER_OK bit in status field
838 * s->blk would erroneously be placed in writethrough mode.
840 if (!virtio_vdev_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE)) {
841 aio_context_acquire(blk_get_aio_context(s->blk));
842 blk_set_enable_write_cache(s->blk,
843 virtio_vdev_has_feature(vdev,
844 VIRTIO_BLK_F_WCE));
845 aio_context_release(blk_get_aio_context(s->blk));
849 static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f)
851 VirtIOBlock *s = VIRTIO_BLK(vdev);
852 VirtIOBlockReq *req = s->rq;
854 while (req) {
855 qemu_put_sbyte(f, 1);
857 if (s->conf.num_queues > 1) {
858 qemu_put_be32(f, virtio_get_queue_index(req->vq));
861 qemu_put_virtqueue_element(f, &req->elem);
862 req = req->next;
864 qemu_put_sbyte(f, 0);
867 static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f,
868 int version_id)
870 VirtIOBlock *s = VIRTIO_BLK(vdev);
872 while (qemu_get_sbyte(f)) {
873 unsigned nvqs = s->conf.num_queues;
874 unsigned vq_idx = 0;
875 VirtIOBlockReq *req;
877 if (nvqs > 1) {
878 vq_idx = qemu_get_be32(f);
880 if (vq_idx >= nvqs) {
881 error_report("Invalid virtqueue index in request list: %#x",
882 vq_idx);
883 return -EINVAL;
887 req = qemu_get_virtqueue_element(vdev, f, sizeof(VirtIOBlockReq));
888 virtio_blk_init_request(s, virtio_get_queue(vdev, vq_idx), req);
889 req->next = s->rq;
890 s->rq = req;
893 return 0;
896 static void virtio_blk_resize(void *opaque)
898 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
900 virtio_notify_config(vdev);
903 static const BlockDevOps virtio_block_ops = {
904 .resize_cb = virtio_blk_resize,
907 static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
909 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
910 VirtIOBlock *s = VIRTIO_BLK(dev);
911 VirtIOBlkConf *conf = &s->conf;
912 Error *err = NULL;
913 unsigned i;
915 if (!conf->conf.blk) {
916 error_setg(errp, "drive property not set");
917 return;
919 if (!blk_is_inserted(conf->conf.blk)) {
920 error_setg(errp, "Device needs media, but drive is empty");
921 return;
923 if (!conf->num_queues) {
924 error_setg(errp, "num-queues property must be larger than 0");
925 return;
928 blkconf_serial(&conf->conf, &conf->serial);
929 blkconf_apply_backend_options(&conf->conf,
930 blk_is_read_only(conf->conf.blk), true,
931 &err);
932 if (err) {
933 error_propagate(errp, err);
934 return;
936 s->original_wce = blk_enable_write_cache(conf->conf.blk);
937 blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, &err);
938 if (err) {
939 error_propagate(errp, err);
940 return;
942 blkconf_blocksizes(&conf->conf);
944 virtio_init(vdev, "virtio-blk", VIRTIO_ID_BLOCK,
945 sizeof(struct virtio_blk_config));
947 s->blk = conf->conf.blk;
948 s->rq = NULL;
949 s->sector_mask = (s->conf.conf.logical_block_size / BDRV_SECTOR_SIZE) - 1;
951 for (i = 0; i < conf->num_queues; i++) {
952 virtio_add_queue(vdev, 128, virtio_blk_handle_output);
954 virtio_blk_data_plane_create(vdev, conf, &s->dataplane, &err);
955 if (err != NULL) {
956 error_propagate(errp, err);
957 virtio_cleanup(vdev);
958 return;
961 s->change = qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);
962 blk_set_dev_ops(s->blk, &virtio_block_ops, s);
963 blk_set_guest_block_size(s->blk, s->conf.conf.logical_block_size);
965 blk_iostatus_enable(s->blk);
968 static void virtio_blk_device_unrealize(DeviceState *dev, Error **errp)
970 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
971 VirtIOBlock *s = VIRTIO_BLK(dev);
973 virtio_blk_data_plane_destroy(s->dataplane);
974 s->dataplane = NULL;
975 qemu_del_vm_change_state_handler(s->change);
976 blockdev_mark_auto_del(s->blk);
977 virtio_cleanup(vdev);
980 static void virtio_blk_instance_init(Object *obj)
982 VirtIOBlock *s = VIRTIO_BLK(obj);
984 object_property_add_link(obj, "iothread", TYPE_IOTHREAD,
985 (Object **)&s->conf.iothread,
986 qdev_prop_allow_set_link_before_realize,
987 OBJ_PROP_LINK_UNREF_ON_RELEASE, NULL);
988 device_add_bootindex_property(obj, &s->conf.conf.bootindex,
989 "bootindex", "/disk@0,0",
990 DEVICE(obj), NULL);
993 static const VMStateDescription vmstate_virtio_blk = {
994 .name = "virtio-blk",
995 .minimum_version_id = 2,
996 .version_id = 2,
997 .fields = (VMStateField[]) {
998 VMSTATE_VIRTIO_DEVICE,
999 VMSTATE_END_OF_LIST()
1003 static Property virtio_blk_properties[] = {
1004 DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf),
1005 DEFINE_BLOCK_ERROR_PROPERTIES(VirtIOBlock, conf.conf),
1006 DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf),
1007 DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial),
1008 DEFINE_PROP_BIT("config-wce", VirtIOBlock, conf.config_wce, 0, true),
1009 #ifdef __linux__
1010 DEFINE_PROP_BIT("scsi", VirtIOBlock, conf.scsi, 0, false),
1011 #endif
1012 DEFINE_PROP_BIT("request-merging", VirtIOBlock, conf.request_merging, 0,
1013 true),
1014 DEFINE_PROP_UINT16("num-queues", VirtIOBlock, conf.num_queues, 1),
1015 DEFINE_PROP_END_OF_LIST(),
1018 static void virtio_blk_class_init(ObjectClass *klass, void *data)
1020 DeviceClass *dc = DEVICE_CLASS(klass);
1021 VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1023 dc->props = virtio_blk_properties;
1024 dc->vmsd = &vmstate_virtio_blk;
1025 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1026 vdc->realize = virtio_blk_device_realize;
1027 vdc->unrealize = virtio_blk_device_unrealize;
1028 vdc->get_config = virtio_blk_update_config;
1029 vdc->set_config = virtio_blk_set_config;
1030 vdc->get_features = virtio_blk_get_features;
1031 vdc->set_status = virtio_blk_set_status;
1032 vdc->reset = virtio_blk_reset;
1033 vdc->save = virtio_blk_save_device;
1034 vdc->load = virtio_blk_load_device;
1035 vdc->start_ioeventfd = virtio_blk_data_plane_start;
1036 vdc->stop_ioeventfd = virtio_blk_data_plane_stop;
1039 static const TypeInfo virtio_blk_info = {
1040 .name = TYPE_VIRTIO_BLK,
1041 .parent = TYPE_VIRTIO_DEVICE,
1042 .instance_size = sizeof(VirtIOBlock),
1043 .instance_init = virtio_blk_instance_init,
1044 .class_init = virtio_blk_class_init,
1047 static void virtio_register_types(void)
1049 type_register_static(&virtio_blk_info);
1052 type_init(virtio_register_types)