virito-blk: drop duplicate check
[qemu/rayw.git] / hw / block / virtio-blk.c
blob6aefda4bf28be076af57ee72f22ddf75102c8b59
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-common.h"
15 #include "qemu/iov.h"
16 #include "qemu/error-report.h"
17 #include "trace.h"
18 #include "hw/block/block.h"
19 #include "sysemu/block-backend.h"
20 #include "sysemu/blockdev.h"
21 #include "hw/virtio/virtio-blk.h"
22 #include "dataplane/virtio-blk.h"
23 #include "migration/migration.h"
24 #include "block/scsi.h"
25 #ifdef __linux__
26 # include <scsi/sg.h>
27 #endif
28 #include "hw/virtio/virtio-bus.h"
29 #include "hw/virtio/virtio-access.h"
31 VirtIOBlockReq *virtio_blk_alloc_request(VirtIOBlock *s)
33 VirtIOBlockReq *req = g_slice_new(VirtIOBlockReq);
34 req->dev = s;
35 req->qiov.size = 0;
36 req->in_len = 0;
37 req->next = NULL;
38 req->mr_next = NULL;
39 return req;
42 void virtio_blk_free_request(VirtIOBlockReq *req)
44 if (req) {
45 g_slice_free(VirtIOBlockReq, req);
49 static void virtio_blk_complete_request(VirtIOBlockReq *req,
50 unsigned char status)
52 VirtIOBlock *s = req->dev;
53 VirtIODevice *vdev = VIRTIO_DEVICE(s);
55 trace_virtio_blk_req_complete(req, status);
57 stb_p(&req->in->status, status);
58 virtqueue_push(s->vq, &req->elem, req->in_len);
59 virtio_notify(vdev, s->vq);
62 static void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
64 req->dev->complete_request(req, status);
67 static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
68 bool is_read)
70 BlockErrorAction action = blk_get_error_action(req->dev->blk,
71 is_read, error);
72 VirtIOBlock *s = req->dev;
74 if (action == BLOCK_ERROR_ACTION_STOP) {
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_done(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;
91 while (next) {
92 VirtIOBlockReq *req = next;
93 next = req->mr_next;
94 trace_virtio_blk_rw_complete(req, ret);
96 if (req->qiov.nalloc != -1) {
97 /* If nalloc is != 1 req->qiov is a local copy of the original
98 * external iovec. It was allocated in submit_merged_requests
99 * to be able to merge requests. */
100 qemu_iovec_destroy(&req->qiov);
103 if (ret) {
104 int p = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);
105 bool is_read = !(p & VIRTIO_BLK_T_OUT);
106 /* Note that memory may be dirtied on read failure. If the
107 * virtio request is not completed here, as is the case for
108 * BLOCK_ERROR_ACTION_STOP, the memory may not be copied
109 * correctly during live migration. While this is ugly,
110 * it is acceptable because the device is free to write to
111 * the memory until the request is completed (which will
112 * happen on the other side of the migration).
114 if (virtio_blk_handle_rw_error(req, -ret, is_read)) {
115 continue;
119 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
120 block_acct_done(blk_get_stats(req->dev->blk), &req->acct);
121 virtio_blk_free_request(req);
125 static void virtio_blk_flush_complete(void *opaque, int ret)
127 VirtIOBlockReq *req = opaque;
129 if (ret) {
130 if (virtio_blk_handle_rw_error(req, -ret, 0)) {
131 return;
135 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
136 block_acct_done(blk_get_stats(req->dev->blk), &req->acct);
137 virtio_blk_free_request(req);
140 #ifdef __linux__
142 typedef struct {
143 VirtIOBlockReq *req;
144 struct sg_io_hdr hdr;
145 } VirtIOBlockIoctlReq;
147 static void virtio_blk_ioctl_complete(void *opaque, int status)
149 VirtIOBlockIoctlReq *ioctl_req = opaque;
150 VirtIOBlockReq *req = ioctl_req->req;
151 VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
152 struct virtio_scsi_inhdr *scsi;
153 struct sg_io_hdr *hdr;
155 scsi = (void *)req->elem.in_sg[req->elem.in_num - 2].iov_base;
157 if (status) {
158 status = VIRTIO_BLK_S_UNSUPP;
159 virtio_stl_p(vdev, &scsi->errors, 255);
160 goto out;
163 hdr = &ioctl_req->hdr;
165 * From SCSI-Generic-HOWTO: "Some lower level drivers (e.g. ide-scsi)
166 * clear the masked_status field [hence status gets cleared too, see
167 * block/scsi_ioctl.c] even when a CHECK_CONDITION or COMMAND_TERMINATED
168 * status has occurred. However they do set DRIVER_SENSE in driver_status
169 * field. Also a (sb_len_wr > 0) indicates there is a sense buffer.
171 if (hdr->status == 0 && hdr->sb_len_wr > 0) {
172 hdr->status = CHECK_CONDITION;
175 virtio_stl_p(vdev, &scsi->errors,
176 hdr->status | (hdr->msg_status << 8) |
177 (hdr->host_status << 16) | (hdr->driver_status << 24));
178 virtio_stl_p(vdev, &scsi->residual, hdr->resid);
179 virtio_stl_p(vdev, &scsi->sense_len, hdr->sb_len_wr);
180 virtio_stl_p(vdev, &scsi->data_len, hdr->dxfer_len);
182 out:
183 virtio_blk_req_complete(req, status);
184 virtio_blk_free_request(req);
185 g_free(ioctl_req);
188 #endif
190 static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s)
192 VirtIOBlockReq *req = virtio_blk_alloc_request(s);
194 if (!virtqueue_pop(s->vq, &req->elem)) {
195 virtio_blk_free_request(req);
196 return NULL;
199 return req;
202 static int virtio_blk_handle_scsi_req(VirtIOBlockReq *req)
204 int status = VIRTIO_BLK_S_OK;
205 struct virtio_scsi_inhdr *scsi = NULL;
206 VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
207 VirtQueueElement *elem = &req->elem;
208 VirtIOBlock *blk = req->dev;
210 #ifdef __linux__
211 int i;
212 VirtIOBlockIoctlReq *ioctl_req;
213 BlockAIOCB *acb;
214 #endif
217 * We require at least one output segment each for the virtio_blk_outhdr
218 * and the SCSI command block.
220 * We also at least require the virtio_blk_inhdr, the virtio_scsi_inhdr
221 * and the sense buffer pointer in the input segments.
223 if (elem->out_num < 2 || elem->in_num < 3) {
224 status = VIRTIO_BLK_S_IOERR;
225 goto fail;
229 * The scsi inhdr is placed in the second-to-last input segment, just
230 * before the regular inhdr.
232 scsi = (void *)elem->in_sg[elem->in_num - 2].iov_base;
234 if (!blk->conf.scsi) {
235 status = VIRTIO_BLK_S_UNSUPP;
236 goto fail;
240 * No support for bidirection commands yet.
242 if (elem->out_num > 2 && elem->in_num > 3) {
243 status = VIRTIO_BLK_S_UNSUPP;
244 goto fail;
247 #ifdef __linux__
248 ioctl_req = g_new0(VirtIOBlockIoctlReq, 1);
249 ioctl_req->req = req;
250 ioctl_req->hdr.interface_id = 'S';
251 ioctl_req->hdr.cmd_len = elem->out_sg[1].iov_len;
252 ioctl_req->hdr.cmdp = elem->out_sg[1].iov_base;
253 ioctl_req->hdr.dxfer_len = 0;
255 if (elem->out_num > 2) {
257 * If there are more than the minimally required 2 output segments
258 * there is write payload starting from the third iovec.
260 ioctl_req->hdr.dxfer_direction = SG_DXFER_TO_DEV;
261 ioctl_req->hdr.iovec_count = elem->out_num - 2;
263 for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
264 ioctl_req->hdr.dxfer_len += elem->out_sg[i + 2].iov_len;
267 ioctl_req->hdr.dxferp = elem->out_sg + 2;
269 } else if (elem->in_num > 3) {
271 * If we have more than 3 input segments the guest wants to actually
272 * read data.
274 ioctl_req->hdr.dxfer_direction = SG_DXFER_FROM_DEV;
275 ioctl_req->hdr.iovec_count = elem->in_num - 3;
276 for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
277 ioctl_req->hdr.dxfer_len += elem->in_sg[i].iov_len;
280 ioctl_req->hdr.dxferp = elem->in_sg;
281 } else {
283 * Some SCSI commands don't actually transfer any data.
285 ioctl_req->hdr.dxfer_direction = SG_DXFER_NONE;
288 ioctl_req->hdr.sbp = elem->in_sg[elem->in_num - 3].iov_base;
289 ioctl_req->hdr.mx_sb_len = elem->in_sg[elem->in_num - 3].iov_len;
291 acb = blk_aio_ioctl(blk->blk, SG_IO, &ioctl_req->hdr,
292 virtio_blk_ioctl_complete, ioctl_req);
293 if (!acb) {
294 g_free(ioctl_req);
295 status = VIRTIO_BLK_S_UNSUPP;
296 goto fail;
298 return -EINPROGRESS;
299 #else
300 abort();
301 #endif
303 fail:
304 /* Just put anything nonzero so that the ioctl fails in the guest. */
305 if (scsi) {
306 virtio_stl_p(vdev, &scsi->errors, 255);
308 return status;
311 static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
313 int status;
315 status = virtio_blk_handle_scsi_req(req);
316 if (status != -EINPROGRESS) {
317 virtio_blk_req_complete(req, status);
318 virtio_blk_free_request(req);
322 static inline void submit_requests(BlockBackend *blk, MultiReqBuffer *mrb,
323 int start, int num_reqs, int niov)
325 QEMUIOVector *qiov = &mrb->reqs[start]->qiov;
326 int64_t sector_num = mrb->reqs[start]->sector_num;
327 int nb_sectors = mrb->reqs[start]->qiov.size / BDRV_SECTOR_SIZE;
328 bool is_write = mrb->is_write;
330 if (num_reqs > 1) {
331 int i;
332 struct iovec *tmp_iov = qiov->iov;
333 int tmp_niov = qiov->niov;
335 /* mrb->reqs[start]->qiov was initialized from external so we can't
336 * modifiy it here. We need to initialize it locally and then add the
337 * external iovecs. */
338 qemu_iovec_init(qiov, niov);
340 for (i = 0; i < tmp_niov; i++) {
341 qemu_iovec_add(qiov, tmp_iov[i].iov_base, tmp_iov[i].iov_len);
344 for (i = start + 1; i < start + num_reqs; i++) {
345 qemu_iovec_concat(qiov, &mrb->reqs[i]->qiov, 0,
346 mrb->reqs[i]->qiov.size);
347 mrb->reqs[i - 1]->mr_next = mrb->reqs[i];
348 nb_sectors += mrb->reqs[i]->qiov.size / BDRV_SECTOR_SIZE;
350 assert(nb_sectors == qiov->size / BDRV_SECTOR_SIZE);
352 trace_virtio_blk_submit_multireq(mrb, start, num_reqs, sector_num,
353 nb_sectors, is_write);
354 block_acct_merge_done(blk_get_stats(blk),
355 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ,
356 num_reqs - 1);
359 if (is_write) {
360 blk_aio_writev(blk, sector_num, qiov, nb_sectors,
361 virtio_blk_rw_complete, mrb->reqs[start]);
362 } else {
363 blk_aio_readv(blk, sector_num, qiov, nb_sectors,
364 virtio_blk_rw_complete, mrb->reqs[start]);
368 static int multireq_compare(const void *a, const void *b)
370 const VirtIOBlockReq *req1 = *(VirtIOBlockReq **)a,
371 *req2 = *(VirtIOBlockReq **)b;
374 * Note that we can't simply subtract sector_num1 from sector_num2
375 * here as that could overflow the return value.
377 if (req1->sector_num > req2->sector_num) {
378 return 1;
379 } else if (req1->sector_num < req2->sector_num) {
380 return -1;
381 } else {
382 return 0;
386 void virtio_blk_submit_multireq(BlockBackend *blk, MultiReqBuffer *mrb)
388 int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
389 int max_xfer_len = 0;
390 int64_t sector_num = 0;
392 if (mrb->num_reqs == 1) {
393 submit_requests(blk, mrb, 0, 1, -1);
394 mrb->num_reqs = 0;
395 return;
398 max_xfer_len = blk_get_max_transfer_length(mrb->reqs[0]->dev->blk);
399 max_xfer_len = MIN_NON_ZERO(max_xfer_len, BDRV_REQUEST_MAX_SECTORS);
401 qsort(mrb->reqs, mrb->num_reqs, sizeof(*mrb->reqs),
402 &multireq_compare);
404 for (i = 0; i < mrb->num_reqs; i++) {
405 VirtIOBlockReq *req = mrb->reqs[i];
406 if (num_reqs > 0) {
407 bool merge = true;
409 /* merge would exceed maximum number of IOVs */
410 if (niov + req->qiov.niov > IOV_MAX) {
411 merge = false;
414 /* merge would exceed maximum transfer length of backend device */
415 if (req->qiov.size / BDRV_SECTOR_SIZE + nb_sectors > max_xfer_len) {
416 merge = false;
419 /* requests are not sequential */
420 if (sector_num + nb_sectors != req->sector_num) {
421 merge = false;
424 if (!merge) {
425 submit_requests(blk, mrb, start, num_reqs, niov);
426 num_reqs = 0;
430 if (num_reqs == 0) {
431 sector_num = req->sector_num;
432 nb_sectors = niov = 0;
433 start = i;
436 nb_sectors += req->qiov.size / BDRV_SECTOR_SIZE;
437 niov += req->qiov.niov;
438 num_reqs++;
441 submit_requests(blk, mrb, start, num_reqs, niov);
442 mrb->num_reqs = 0;
445 static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
447 block_acct_start(blk_get_stats(req->dev->blk), &req->acct, 0,
448 BLOCK_ACCT_FLUSH);
451 * Make sure all outstanding writes are posted to the backing device.
453 if (mrb->is_write && mrb->num_reqs > 0) {
454 virtio_blk_submit_multireq(req->dev->blk, mrb);
456 blk_aio_flush(req->dev->blk, virtio_blk_flush_complete, req);
459 static bool virtio_blk_sect_range_ok(VirtIOBlock *dev,
460 uint64_t sector, size_t size)
462 uint64_t nb_sectors = size >> BDRV_SECTOR_BITS;
463 uint64_t total_sectors;
465 if (nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
466 return false;
468 if (sector & dev->sector_mask) {
469 return false;
471 if (size % dev->conf.conf.logical_block_size) {
472 return false;
474 blk_get_geometry(dev->blk, &total_sectors);
475 if (sector > total_sectors || nb_sectors > total_sectors - sector) {
476 return false;
478 return true;
481 void virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
483 uint32_t type;
484 struct iovec *in_iov = req->elem.in_sg;
485 struct iovec *iov = req->elem.out_sg;
486 unsigned in_num = req->elem.in_num;
487 unsigned out_num = req->elem.out_num;
489 if (req->elem.out_num < 1 || req->elem.in_num < 1) {
490 error_report("virtio-blk missing headers");
491 exit(1);
494 if (unlikely(iov_to_buf(iov, out_num, 0, &req->out,
495 sizeof(req->out)) != sizeof(req->out))) {
496 error_report("virtio-blk request outhdr too short");
497 exit(1);
500 iov_discard_front(&iov, &out_num, sizeof(req->out));
502 if (in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {
503 error_report("virtio-blk request inhdr too short");
504 exit(1);
507 /* We always touch the last byte, so just see how big in_iov is. */
508 req->in_len = iov_size(in_iov, in_num);
509 req->in = (void *)in_iov[in_num - 1].iov_base
510 + in_iov[in_num - 1].iov_len
511 - sizeof(struct virtio_blk_inhdr);
512 iov_discard_back(in_iov, &in_num, sizeof(struct virtio_blk_inhdr));
514 type = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);
516 /* VIRTIO_BLK_T_OUT defines the command direction. VIRTIO_BLK_T_BARRIER
517 * is an optional flag. Although a guest should not send this flag if
518 * not negotiated we ignored it in the past. So keep ignoring it. */
519 switch (type & ~(VIRTIO_BLK_T_OUT | VIRTIO_BLK_T_BARRIER)) {
520 case VIRTIO_BLK_T_IN:
522 bool is_write = type & VIRTIO_BLK_T_OUT;
523 req->sector_num = virtio_ldq_p(VIRTIO_DEVICE(req->dev),
524 &req->out.sector);
526 if (is_write) {
527 qemu_iovec_init_external(&req->qiov, iov, out_num);
528 trace_virtio_blk_handle_write(req, req->sector_num,
529 req->qiov.size / BDRV_SECTOR_SIZE);
530 } else {
531 qemu_iovec_init_external(&req->qiov, in_iov, in_num);
532 trace_virtio_blk_handle_read(req, req->sector_num,
533 req->qiov.size / BDRV_SECTOR_SIZE);
536 if (!virtio_blk_sect_range_ok(req->dev, req->sector_num,
537 req->qiov.size)) {
538 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
539 virtio_blk_free_request(req);
540 return;
543 block_acct_start(blk_get_stats(req->dev->blk),
544 &req->acct, req->qiov.size,
545 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
547 /* merge would exceed maximum number of requests or IO direction
548 * changes */
549 if (mrb->num_reqs > 0 && (mrb->num_reqs == VIRTIO_BLK_MAX_MERGE_REQS ||
550 is_write != mrb->is_write ||
551 !req->dev->conf.request_merging)) {
552 virtio_blk_submit_multireq(req->dev->blk, mrb);
555 assert(mrb->num_reqs < VIRTIO_BLK_MAX_MERGE_REQS);
556 mrb->reqs[mrb->num_reqs++] = req;
557 mrb->is_write = is_write;
558 break;
560 case VIRTIO_BLK_T_FLUSH:
561 virtio_blk_handle_flush(req, mrb);
562 break;
563 case VIRTIO_BLK_T_SCSI_CMD:
564 virtio_blk_handle_scsi(req);
565 break;
566 case VIRTIO_BLK_T_GET_ID:
568 VirtIOBlock *s = req->dev;
571 * NB: per existing s/n string convention the string is
572 * terminated by '\0' only when shorter than buffer.
574 const char *serial = s->conf.serial ? s->conf.serial : "";
575 size_t size = MIN(strlen(serial) + 1,
576 MIN(iov_size(in_iov, in_num),
577 VIRTIO_BLK_ID_BYTES));
578 iov_from_buf(in_iov, in_num, 0, serial, size);
579 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
580 virtio_blk_free_request(req);
581 break;
583 default:
584 virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
585 virtio_blk_free_request(req);
589 static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)
591 VirtIOBlock *s = VIRTIO_BLK(vdev);
592 VirtIOBlockReq *req;
593 MultiReqBuffer mrb = {};
595 /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start
596 * dataplane here instead of waiting for .set_status().
598 if (s->dataplane) {
599 virtio_blk_data_plane_start(s->dataplane);
600 return;
603 while ((req = virtio_blk_get_request(s))) {
604 virtio_blk_handle_request(req, &mrb);
607 if (mrb.num_reqs) {
608 virtio_blk_submit_multireq(s->blk, &mrb);
612 static void virtio_blk_dma_restart_bh(void *opaque)
614 VirtIOBlock *s = opaque;
615 VirtIOBlockReq *req = s->rq;
616 MultiReqBuffer mrb = {};
618 qemu_bh_delete(s->bh);
619 s->bh = NULL;
621 s->rq = NULL;
623 while (req) {
624 VirtIOBlockReq *next = req->next;
625 virtio_blk_handle_request(req, &mrb);
626 req = next;
629 if (mrb.num_reqs) {
630 virtio_blk_submit_multireq(s->blk, &mrb);
634 static void virtio_blk_dma_restart_cb(void *opaque, int running,
635 RunState state)
637 VirtIOBlock *s = opaque;
639 if (!running) {
640 return;
643 if (!s->bh) {
644 s->bh = aio_bh_new(blk_get_aio_context(s->conf.conf.blk),
645 virtio_blk_dma_restart_bh, s);
646 qemu_bh_schedule(s->bh);
650 static void virtio_blk_reset(VirtIODevice *vdev)
652 VirtIOBlock *s = VIRTIO_BLK(vdev);
653 AioContext *ctx;
656 * This should cancel pending requests, but can't do nicely until there
657 * are per-device request lists.
659 ctx = blk_get_aio_context(s->blk);
660 aio_context_acquire(ctx);
661 blk_drain(s->blk);
663 if (s->dataplane) {
664 virtio_blk_data_plane_stop(s->dataplane);
666 aio_context_release(ctx);
668 blk_set_enable_write_cache(s->blk, s->original_wce);
671 /* coalesce internal state, copy to pci i/o region 0
673 static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
675 VirtIOBlock *s = VIRTIO_BLK(vdev);
676 BlockConf *conf = &s->conf.conf;
677 struct virtio_blk_config blkcfg;
678 uint64_t capacity;
679 int blk_size = conf->logical_block_size;
681 blk_get_geometry(s->blk, &capacity);
682 memset(&blkcfg, 0, sizeof(blkcfg));
683 virtio_stq_p(vdev, &blkcfg.capacity, capacity);
684 virtio_stl_p(vdev, &blkcfg.seg_max, 128 - 2);
685 virtio_stw_p(vdev, &blkcfg.geometry.cylinders, conf->cyls);
686 virtio_stl_p(vdev, &blkcfg.blk_size, blk_size);
687 virtio_stw_p(vdev, &blkcfg.min_io_size, conf->min_io_size / blk_size);
688 virtio_stw_p(vdev, &blkcfg.opt_io_size, conf->opt_io_size / blk_size);
689 blkcfg.geometry.heads = conf->heads;
691 * We must ensure that the block device capacity is a multiple of
692 * the logical block size. If that is not the case, let's use
693 * sector_mask to adopt the geometry to have a correct picture.
694 * For those devices where the capacity is ok for the given geometry
695 * we don't touch the sector value of the geometry, since some devices
696 * (like s390 dasd) need a specific value. Here the capacity is already
697 * cyls*heads*secs*blk_size and the sector value is not block size
698 * divided by 512 - instead it is the amount of blk_size blocks
699 * per track (cylinder).
701 if (blk_getlength(s->blk) / conf->heads / conf->secs % blk_size) {
702 blkcfg.geometry.sectors = conf->secs & ~s->sector_mask;
703 } else {
704 blkcfg.geometry.sectors = conf->secs;
706 blkcfg.size_max = 0;
707 blkcfg.physical_block_exp = get_physical_block_exp(conf);
708 blkcfg.alignment_offset = 0;
709 blkcfg.wce = blk_enable_write_cache(s->blk);
710 memcpy(config, &blkcfg, sizeof(struct virtio_blk_config));
713 static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config)
715 VirtIOBlock *s = VIRTIO_BLK(vdev);
716 struct virtio_blk_config blkcfg;
718 memcpy(&blkcfg, config, sizeof(blkcfg));
720 aio_context_acquire(blk_get_aio_context(s->blk));
721 blk_set_enable_write_cache(s->blk, blkcfg.wce != 0);
722 aio_context_release(blk_get_aio_context(s->blk));
725 static uint64_t virtio_blk_get_features(VirtIODevice *vdev, uint64_t features)
727 VirtIOBlock *s = VIRTIO_BLK(vdev);
729 virtio_add_feature(&features, VIRTIO_BLK_F_SEG_MAX);
730 virtio_add_feature(&features, VIRTIO_BLK_F_GEOMETRY);
731 virtio_add_feature(&features, VIRTIO_BLK_F_TOPOLOGY);
732 virtio_add_feature(&features, VIRTIO_BLK_F_BLK_SIZE);
733 virtio_add_feature(&features, VIRTIO_BLK_F_SCSI);
735 if (s->conf.config_wce) {
736 virtio_add_feature(&features, VIRTIO_BLK_F_CONFIG_WCE);
738 if (blk_enable_write_cache(s->blk)) {
739 virtio_add_feature(&features, VIRTIO_BLK_F_WCE);
741 if (blk_is_read_only(s->blk)) {
742 virtio_add_feature(&features, VIRTIO_BLK_F_RO);
745 return features;
748 static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)
750 VirtIOBlock *s = VIRTIO_BLK(vdev);
752 if (s->dataplane && !(status & (VIRTIO_CONFIG_S_DRIVER |
753 VIRTIO_CONFIG_S_DRIVER_OK))) {
754 virtio_blk_data_plane_stop(s->dataplane);
757 if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
758 return;
761 /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send
762 * cache flushes. Thus, the "auto writethrough" behavior is never
763 * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.
764 * Leaving it enabled would break the following sequence:
766 * Guest started with "-drive cache=writethrough"
767 * Guest sets status to 0
768 * Guest sets DRIVER bit in status field
769 * Guest reads host features (WCE=0, CONFIG_WCE=1)
770 * Guest writes guest features (WCE=0, CONFIG_WCE=1)
771 * Guest writes 1 to the WCE configuration field (writeback mode)
772 * Guest sets DRIVER_OK bit in status field
774 * s->blk would erroneously be placed in writethrough mode.
776 if (!virtio_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE)) {
777 aio_context_acquire(blk_get_aio_context(s->blk));
778 blk_set_enable_write_cache(s->blk,
779 virtio_has_feature(vdev, VIRTIO_BLK_F_WCE));
780 aio_context_release(blk_get_aio_context(s->blk));
784 static void virtio_blk_save(QEMUFile *f, void *opaque)
786 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
788 virtio_save(vdev, f);
791 static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f)
793 VirtIOBlock *s = VIRTIO_BLK(vdev);
794 VirtIOBlockReq *req = s->rq;
796 while (req) {
797 qemu_put_sbyte(f, 1);
798 qemu_put_buffer(f, (unsigned char *)&req->elem,
799 sizeof(VirtQueueElement));
800 req = req->next;
802 qemu_put_sbyte(f, 0);
805 static int virtio_blk_load(QEMUFile *f, void *opaque, int version_id)
807 VirtIOBlock *s = opaque;
808 VirtIODevice *vdev = VIRTIO_DEVICE(s);
810 if (version_id != 2)
811 return -EINVAL;
813 return virtio_load(vdev, f, version_id);
816 static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f,
817 int version_id)
819 VirtIOBlock *s = VIRTIO_BLK(vdev);
821 while (qemu_get_sbyte(f)) {
822 VirtIOBlockReq *req = virtio_blk_alloc_request(s);
823 qemu_get_buffer(f, (unsigned char *)&req->elem,
824 sizeof(VirtQueueElement));
825 req->next = s->rq;
826 s->rq = req;
828 virtqueue_map_sg(req->elem.in_sg, req->elem.in_addr,
829 req->elem.in_num, 1);
830 virtqueue_map_sg(req->elem.out_sg, req->elem.out_addr,
831 req->elem.out_num, 0);
834 return 0;
837 static void virtio_blk_resize(void *opaque)
839 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
841 virtio_notify_config(vdev);
844 static const BlockDevOps virtio_block_ops = {
845 .resize_cb = virtio_blk_resize,
848 /* Disable dataplane thread during live migration since it does not
849 * update the dirty memory bitmap yet.
851 static void virtio_blk_migration_state_changed(Notifier *notifier, void *data)
853 VirtIOBlock *s = container_of(notifier, VirtIOBlock,
854 migration_state_notifier);
855 MigrationState *mig = data;
856 Error *err = NULL;
858 if (migration_in_setup(mig)) {
859 if (!s->dataplane) {
860 return;
862 virtio_blk_data_plane_destroy(s->dataplane);
863 s->dataplane = NULL;
864 } else if (migration_has_finished(mig) ||
865 migration_has_failed(mig)) {
866 if (s->dataplane) {
867 return;
869 blk_drain_all(); /* complete in-flight non-dataplane requests */
870 virtio_blk_data_plane_create(VIRTIO_DEVICE(s), &s->conf,
871 &s->dataplane, &err);
872 if (err != NULL) {
873 error_report_err(err);
878 static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
880 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
881 VirtIOBlock *s = VIRTIO_BLK(dev);
882 VirtIOBlkConf *conf = &s->conf;
883 Error *err = NULL;
884 static int virtio_blk_id;
886 if (!conf->conf.blk) {
887 error_setg(errp, "drive property not set");
888 return;
890 if (!blk_is_inserted(conf->conf.blk)) {
891 error_setg(errp, "Device needs media, but drive is empty");
892 return;
895 blkconf_serial(&conf->conf, &conf->serial);
896 s->original_wce = blk_enable_write_cache(conf->conf.blk);
897 blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, &err);
898 if (err) {
899 error_propagate(errp, err);
900 return;
902 blkconf_blocksizes(&conf->conf);
904 virtio_init(vdev, "virtio-blk", VIRTIO_ID_BLOCK,
905 sizeof(struct virtio_blk_config));
907 s->blk = conf->conf.blk;
908 s->rq = NULL;
909 s->sector_mask = (s->conf.conf.logical_block_size / BDRV_SECTOR_SIZE) - 1;
911 s->vq = virtio_add_queue(vdev, 128, virtio_blk_handle_output);
912 s->complete_request = virtio_blk_complete_request;
913 virtio_blk_data_plane_create(vdev, conf, &s->dataplane, &err);
914 if (err != NULL) {
915 error_propagate(errp, err);
916 virtio_cleanup(vdev);
917 return;
919 s->migration_state_notifier.notify = virtio_blk_migration_state_changed;
920 add_migration_state_change_notifier(&s->migration_state_notifier);
922 s->change = qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);
923 register_savevm(dev, "virtio-blk", virtio_blk_id++, 2,
924 virtio_blk_save, virtio_blk_load, s);
925 blk_set_dev_ops(s->blk, &virtio_block_ops, s);
926 blk_set_guest_block_size(s->blk, s->conf.conf.logical_block_size);
928 blk_iostatus_enable(s->blk);
931 static void virtio_blk_device_unrealize(DeviceState *dev, Error **errp)
933 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
934 VirtIOBlock *s = VIRTIO_BLK(dev);
936 remove_migration_state_change_notifier(&s->migration_state_notifier);
937 virtio_blk_data_plane_destroy(s->dataplane);
938 s->dataplane = NULL;
939 qemu_del_vm_change_state_handler(s->change);
940 unregister_savevm(dev, "virtio-blk", s);
941 blockdev_mark_auto_del(s->blk);
942 virtio_cleanup(vdev);
945 static void virtio_blk_instance_init(Object *obj)
947 VirtIOBlock *s = VIRTIO_BLK(obj);
949 object_property_add_link(obj, "iothread", TYPE_IOTHREAD,
950 (Object **)&s->conf.iothread,
951 qdev_prop_allow_set_link_before_realize,
952 OBJ_PROP_LINK_UNREF_ON_RELEASE, NULL);
953 device_add_bootindex_property(obj, &s->conf.conf.bootindex,
954 "bootindex", "/disk@0,0",
955 DEVICE(obj), NULL);
958 static Property virtio_blk_properties[] = {
959 DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf),
960 DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf),
961 DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial),
962 DEFINE_PROP_BIT("config-wce", VirtIOBlock, conf.config_wce, 0, true),
963 #ifdef __linux__
964 DEFINE_PROP_BIT("scsi", VirtIOBlock, conf.scsi, 0, true),
965 #endif
966 DEFINE_PROP_BIT("request-merging", VirtIOBlock, conf.request_merging, 0,
967 true),
968 DEFINE_PROP_BIT("x-data-plane", VirtIOBlock, conf.data_plane, 0, false),
969 DEFINE_PROP_END_OF_LIST(),
972 static void virtio_blk_class_init(ObjectClass *klass, void *data)
974 DeviceClass *dc = DEVICE_CLASS(klass);
975 VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
977 dc->props = virtio_blk_properties;
978 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
979 vdc->realize = virtio_blk_device_realize;
980 vdc->unrealize = virtio_blk_device_unrealize;
981 vdc->get_config = virtio_blk_update_config;
982 vdc->set_config = virtio_blk_set_config;
983 vdc->get_features = virtio_blk_get_features;
984 vdc->set_status = virtio_blk_set_status;
985 vdc->reset = virtio_blk_reset;
986 vdc->save = virtio_blk_save_device;
987 vdc->load = virtio_blk_load_device;
990 static const TypeInfo virtio_device_info = {
991 .name = TYPE_VIRTIO_BLK,
992 .parent = TYPE_VIRTIO_DEVICE,
993 .instance_size = sizeof(VirtIOBlock),
994 .instance_init = virtio_blk_instance_init,
995 .class_init = virtio_blk_class_init,
998 static void virtio_register_types(void)
1000 type_register_static(&virtio_device_info);
1003 type_init(virtio_register_types)