block: Give nonzero result to blk_get_max_transfer_length()
[qemu/rayw.git] / hw / block / virtio-blk.c
blobdd94cd4dc70adafe8e164b07f716a542923f27f7
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 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 void virtio_blk_free_request(VirtIOBlockReq *req)
45 if (req) {
46 g_free(req);
50 static void virtio_blk_req_complete(VirtIOBlockReq *req, 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(req->vq, &req->elem, req->in_len);
59 if (s->dataplane_started && !s->dataplane_disabled) {
60 virtio_blk_data_plane_notify(s->dataplane, req->vq);
61 } else {
62 virtio_notify(vdev, req->vq);
66 static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
67 bool is_read)
69 BlockErrorAction action = blk_get_error_action(req->dev->blk,
70 is_read, error);
71 VirtIOBlock *s = req->dev;
73 if (action == BLOCK_ERROR_ACTION_STOP) {
74 /* Break the link as the next request is going to be parsed from the
75 * ring again. Otherwise we may end up doing a double completion! */
76 req->mr_next = NULL;
77 req->next = s->rq;
78 s->rq = req;
79 } else if (action == BLOCK_ERROR_ACTION_REPORT) {
80 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
81 block_acct_failed(blk_get_stats(s->blk), &req->acct);
82 virtio_blk_free_request(req);
85 blk_error_action(s->blk, action, is_read, error);
86 return action != BLOCK_ERROR_ACTION_IGNORE;
89 static void virtio_blk_rw_complete(void *opaque, int ret)
91 VirtIOBlockReq *next = opaque;
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);
127 static void virtio_blk_flush_complete(void *opaque, int ret)
129 VirtIOBlockReq *req = opaque;
131 if (ret) {
132 if (virtio_blk_handle_rw_error(req, -ret, 0)) {
133 return;
137 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
138 block_acct_done(blk_get_stats(req->dev->blk), &req->acct);
139 virtio_blk_free_request(req);
142 #ifdef __linux__
144 typedef struct {
145 VirtIOBlockReq *req;
146 struct sg_io_hdr hdr;
147 } VirtIOBlockIoctlReq;
149 static void virtio_blk_ioctl_complete(void *opaque, int status)
151 VirtIOBlockIoctlReq *ioctl_req = opaque;
152 VirtIOBlockReq *req = ioctl_req->req;
153 VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
154 struct virtio_scsi_inhdr *scsi;
155 struct sg_io_hdr *hdr;
157 scsi = (void *)req->elem.in_sg[req->elem.in_num - 2].iov_base;
159 if (status) {
160 status = VIRTIO_BLK_S_UNSUPP;
161 virtio_stl_p(vdev, &scsi->errors, 255);
162 goto out;
165 hdr = &ioctl_req->hdr;
167 * From SCSI-Generic-HOWTO: "Some lower level drivers (e.g. ide-scsi)
168 * clear the masked_status field [hence status gets cleared too, see
169 * block/scsi_ioctl.c] even when a CHECK_CONDITION or COMMAND_TERMINATED
170 * status has occurred. However they do set DRIVER_SENSE in driver_status
171 * field. Also a (sb_len_wr > 0) indicates there is a sense buffer.
173 if (hdr->status == 0 && hdr->sb_len_wr > 0) {
174 hdr->status = CHECK_CONDITION;
177 virtio_stl_p(vdev, &scsi->errors,
178 hdr->status | (hdr->msg_status << 8) |
179 (hdr->host_status << 16) | (hdr->driver_status << 24));
180 virtio_stl_p(vdev, &scsi->residual, hdr->resid);
181 virtio_stl_p(vdev, &scsi->sense_len, hdr->sb_len_wr);
182 virtio_stl_p(vdev, &scsi->data_len, hdr->dxfer_len);
184 out:
185 virtio_blk_req_complete(req, status);
186 virtio_blk_free_request(req);
187 g_free(ioctl_req);
190 #endif
192 static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s, VirtQueue *vq)
194 VirtIOBlockReq *req = virtqueue_pop(vq, sizeof(VirtIOBlockReq));
196 if (req) {
197 virtio_blk_init_request(s, vq, req);
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 bool is_write = mrb->is_write;
329 if (num_reqs > 1) {
330 int i;
331 struct iovec *tmp_iov = qiov->iov;
332 int tmp_niov = qiov->niov;
334 /* mrb->reqs[start]->qiov was initialized from external so we can't
335 * modify it here. We need to initialize it locally and then add the
336 * external iovecs. */
337 qemu_iovec_init(qiov, niov);
339 for (i = 0; i < tmp_niov; i++) {
340 qemu_iovec_add(qiov, tmp_iov[i].iov_base, tmp_iov[i].iov_len);
343 for (i = start + 1; i < start + num_reqs; i++) {
344 qemu_iovec_concat(qiov, &mrb->reqs[i]->qiov, 0,
345 mrb->reqs[i]->qiov.size);
346 mrb->reqs[i - 1]->mr_next = mrb->reqs[i];
349 trace_virtio_blk_submit_multireq(mrb, start, num_reqs,
350 sector_num << BDRV_SECTOR_BITS,
351 qiov->size, is_write);
352 block_acct_merge_done(blk_get_stats(blk),
353 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ,
354 num_reqs - 1);
357 if (is_write) {
358 blk_aio_pwritev(blk, sector_num << BDRV_SECTOR_BITS, qiov, 0,
359 virtio_blk_rw_complete, mrb->reqs[start]);
360 } else {
361 blk_aio_preadv(blk, sector_num << BDRV_SECTOR_BITS, qiov, 0,
362 virtio_blk_rw_complete, mrb->reqs[start]);
366 static int multireq_compare(const void *a, const void *b)
368 const VirtIOBlockReq *req1 = *(VirtIOBlockReq **)a,
369 *req2 = *(VirtIOBlockReq **)b;
372 * Note that we can't simply subtract sector_num1 from sector_num2
373 * here as that could overflow the return value.
375 if (req1->sector_num > req2->sector_num) {
376 return 1;
377 } else if (req1->sector_num < req2->sector_num) {
378 return -1;
379 } else {
380 return 0;
384 void virtio_blk_submit_multireq(BlockBackend *blk, MultiReqBuffer *mrb)
386 int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
387 int max_xfer_len;
388 int64_t sector_num = 0;
390 if (mrb->num_reqs == 1) {
391 submit_requests(blk, mrb, 0, 1, -1);
392 mrb->num_reqs = 0;
393 return;
396 max_xfer_len = blk_get_max_transfer_length(mrb->reqs[0]->dev->blk);
398 qsort(mrb->reqs, mrb->num_reqs, sizeof(*mrb->reqs),
399 &multireq_compare);
401 for (i = 0; i < mrb->num_reqs; i++) {
402 VirtIOBlockReq *req = mrb->reqs[i];
403 if (num_reqs > 0) {
405 * NOTE: We cannot merge the requests in below situations:
406 * 1. requests are not sequential
407 * 2. merge would exceed maximum number of IOVs
408 * 3. merge would exceed maximum transfer length of backend device
410 if (sector_num + nb_sectors != req->sector_num ||
411 niov > blk_get_max_iov(blk) - req->qiov.niov ||
412 req->qiov.size / BDRV_SECTOR_SIZE > max_xfer_len ||
413 nb_sectors > max_xfer_len - req->qiov.size / BDRV_SECTOR_SIZE) {
414 submit_requests(blk, mrb, start, num_reqs, niov);
415 num_reqs = 0;
419 if (num_reqs == 0) {
420 sector_num = req->sector_num;
421 nb_sectors = niov = 0;
422 start = i;
425 nb_sectors += req->qiov.size / BDRV_SECTOR_SIZE;
426 niov += req->qiov.niov;
427 num_reqs++;
430 submit_requests(blk, mrb, start, num_reqs, niov);
431 mrb->num_reqs = 0;
434 static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
436 block_acct_start(blk_get_stats(req->dev->blk), &req->acct, 0,
437 BLOCK_ACCT_FLUSH);
440 * Make sure all outstanding writes are posted to the backing device.
442 if (mrb->is_write && mrb->num_reqs > 0) {
443 virtio_blk_submit_multireq(req->dev->blk, mrb);
445 blk_aio_flush(req->dev->blk, virtio_blk_flush_complete, req);
448 static bool virtio_blk_sect_range_ok(VirtIOBlock *dev,
449 uint64_t sector, size_t size)
451 uint64_t nb_sectors = size >> BDRV_SECTOR_BITS;
452 uint64_t total_sectors;
454 if (nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
455 return false;
457 if (sector & dev->sector_mask) {
458 return false;
460 if (size % dev->conf.conf.logical_block_size) {
461 return false;
463 blk_get_geometry(dev->blk, &total_sectors);
464 if (sector > total_sectors || nb_sectors > total_sectors - sector) {
465 return false;
467 return true;
470 void virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
472 uint32_t type;
473 struct iovec *in_iov = req->elem.in_sg;
474 struct iovec *iov = req->elem.out_sg;
475 unsigned in_num = req->elem.in_num;
476 unsigned out_num = req->elem.out_num;
478 if (req->elem.out_num < 1 || req->elem.in_num < 1) {
479 error_report("virtio-blk missing headers");
480 exit(1);
483 if (unlikely(iov_to_buf(iov, out_num, 0, &req->out,
484 sizeof(req->out)) != sizeof(req->out))) {
485 error_report("virtio-blk request outhdr too short");
486 exit(1);
489 iov_discard_front(&iov, &out_num, sizeof(req->out));
491 if (in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {
492 error_report("virtio-blk request inhdr too short");
493 exit(1);
496 /* We always touch the last byte, so just see how big in_iov is. */
497 req->in_len = iov_size(in_iov, in_num);
498 req->in = (void *)in_iov[in_num - 1].iov_base
499 + in_iov[in_num - 1].iov_len
500 - sizeof(struct virtio_blk_inhdr);
501 iov_discard_back(in_iov, &in_num, sizeof(struct virtio_blk_inhdr));
503 type = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);
505 /* VIRTIO_BLK_T_OUT defines the command direction. VIRTIO_BLK_T_BARRIER
506 * is an optional flag. Although a guest should not send this flag if
507 * not negotiated we ignored it in the past. So keep ignoring it. */
508 switch (type & ~(VIRTIO_BLK_T_OUT | VIRTIO_BLK_T_BARRIER)) {
509 case VIRTIO_BLK_T_IN:
511 bool is_write = type & VIRTIO_BLK_T_OUT;
512 req->sector_num = virtio_ldq_p(VIRTIO_DEVICE(req->dev),
513 &req->out.sector);
515 if (is_write) {
516 qemu_iovec_init_external(&req->qiov, iov, out_num);
517 trace_virtio_blk_handle_write(req, req->sector_num,
518 req->qiov.size / BDRV_SECTOR_SIZE);
519 } else {
520 qemu_iovec_init_external(&req->qiov, in_iov, in_num);
521 trace_virtio_blk_handle_read(req, req->sector_num,
522 req->qiov.size / BDRV_SECTOR_SIZE);
525 if (!virtio_blk_sect_range_ok(req->dev, req->sector_num,
526 req->qiov.size)) {
527 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
528 block_acct_invalid(blk_get_stats(req->dev->blk),
529 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
530 virtio_blk_free_request(req);
531 return;
534 block_acct_start(blk_get_stats(req->dev->blk),
535 &req->acct, req->qiov.size,
536 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
538 /* merge would exceed maximum number of requests or IO direction
539 * changes */
540 if (mrb->num_reqs > 0 && (mrb->num_reqs == VIRTIO_BLK_MAX_MERGE_REQS ||
541 is_write != mrb->is_write ||
542 !req->dev->conf.request_merging)) {
543 virtio_blk_submit_multireq(req->dev->blk, mrb);
546 assert(mrb->num_reqs < VIRTIO_BLK_MAX_MERGE_REQS);
547 mrb->reqs[mrb->num_reqs++] = req;
548 mrb->is_write = is_write;
549 break;
551 case VIRTIO_BLK_T_FLUSH:
552 virtio_blk_handle_flush(req, mrb);
553 break;
554 case VIRTIO_BLK_T_SCSI_CMD:
555 virtio_blk_handle_scsi(req);
556 break;
557 case VIRTIO_BLK_T_GET_ID:
559 VirtIOBlock *s = req->dev;
562 * NB: per existing s/n string convention the string is
563 * terminated by '\0' only when shorter than buffer.
565 const char *serial = s->conf.serial ? s->conf.serial : "";
566 size_t size = MIN(strlen(serial) + 1,
567 MIN(iov_size(in_iov, in_num),
568 VIRTIO_BLK_ID_BYTES));
569 iov_from_buf(in_iov, in_num, 0, serial, size);
570 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
571 virtio_blk_free_request(req);
572 break;
574 default:
575 virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
576 virtio_blk_free_request(req);
580 void virtio_blk_handle_vq(VirtIOBlock *s, VirtQueue *vq)
582 VirtIOBlockReq *req;
583 MultiReqBuffer mrb = {};
585 blk_io_plug(s->blk);
587 while ((req = virtio_blk_get_request(s, vq))) {
588 virtio_blk_handle_request(req, &mrb);
591 if (mrb.num_reqs) {
592 virtio_blk_submit_multireq(s->blk, &mrb);
595 blk_io_unplug(s->blk);
598 static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)
600 VirtIOBlock *s = (VirtIOBlock *)vdev;
602 if (s->dataplane) {
603 /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start
604 * dataplane here instead of waiting for .set_status().
606 virtio_blk_data_plane_start(s->dataplane);
607 if (!s->dataplane_disabled) {
608 return;
611 virtio_blk_handle_vq(s, vq);
614 static void virtio_blk_dma_restart_bh(void *opaque)
616 VirtIOBlock *s = opaque;
617 VirtIOBlockReq *req = s->rq;
618 MultiReqBuffer mrb = {};
620 qemu_bh_delete(s->bh);
621 s->bh = NULL;
623 s->rq = NULL;
625 while (req) {
626 VirtIOBlockReq *next = req->next;
627 virtio_blk_handle_request(req, &mrb);
628 req = next;
631 if (mrb.num_reqs) {
632 virtio_blk_submit_multireq(s->blk, &mrb);
636 static void virtio_blk_dma_restart_cb(void *opaque, int running,
637 RunState state)
639 VirtIOBlock *s = opaque;
641 if (!running) {
642 return;
645 if (!s->bh) {
646 s->bh = aio_bh_new(blk_get_aio_context(s->conf.conf.blk),
647 virtio_blk_dma_restart_bh, s);
648 qemu_bh_schedule(s->bh);
652 static void virtio_blk_reset(VirtIODevice *vdev)
654 VirtIOBlock *s = VIRTIO_BLK(vdev);
655 AioContext *ctx;
658 * This should cancel pending requests, but can't do nicely until there
659 * are per-device request lists.
661 ctx = blk_get_aio_context(s->blk);
662 aio_context_acquire(ctx);
663 blk_drain(s->blk);
665 if (s->dataplane) {
666 virtio_blk_data_plane_stop(s->dataplane);
668 aio_context_release(ctx);
670 blk_set_enable_write_cache(s->blk, s->original_wce);
673 /* coalesce internal state, copy to pci i/o region 0
675 static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
677 VirtIOBlock *s = VIRTIO_BLK(vdev);
678 BlockConf *conf = &s->conf.conf;
679 struct virtio_blk_config blkcfg;
680 uint64_t capacity;
681 int blk_size = conf->logical_block_size;
683 blk_get_geometry(s->blk, &capacity);
684 memset(&blkcfg, 0, sizeof(blkcfg));
685 virtio_stq_p(vdev, &blkcfg.capacity, capacity);
686 virtio_stl_p(vdev, &blkcfg.seg_max, 128 - 2);
687 virtio_stw_p(vdev, &blkcfg.geometry.cylinders, conf->cyls);
688 virtio_stl_p(vdev, &blkcfg.blk_size, blk_size);
689 virtio_stw_p(vdev, &blkcfg.min_io_size, conf->min_io_size / blk_size);
690 virtio_stw_p(vdev, &blkcfg.opt_io_size, conf->opt_io_size / blk_size);
691 blkcfg.geometry.heads = conf->heads;
693 * We must ensure that the block device capacity is a multiple of
694 * the logical block size. If that is not the case, let's use
695 * sector_mask to adopt the geometry to have a correct picture.
696 * For those devices where the capacity is ok for the given geometry
697 * we don't touch the sector value of the geometry, since some devices
698 * (like s390 dasd) need a specific value. Here the capacity is already
699 * cyls*heads*secs*blk_size and the sector value is not block size
700 * divided by 512 - instead it is the amount of blk_size blocks
701 * per track (cylinder).
703 if (blk_getlength(s->blk) / conf->heads / conf->secs % blk_size) {
704 blkcfg.geometry.sectors = conf->secs & ~s->sector_mask;
705 } else {
706 blkcfg.geometry.sectors = conf->secs;
708 blkcfg.size_max = 0;
709 blkcfg.physical_block_exp = get_physical_block_exp(conf);
710 blkcfg.alignment_offset = 0;
711 blkcfg.wce = blk_enable_write_cache(s->blk);
712 virtio_stw_p(vdev, &blkcfg.num_queues, s->conf.num_queues);
713 memcpy(config, &blkcfg, sizeof(struct virtio_blk_config));
716 static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config)
718 VirtIOBlock *s = VIRTIO_BLK(vdev);
719 struct virtio_blk_config blkcfg;
721 memcpy(&blkcfg, config, sizeof(blkcfg));
723 aio_context_acquire(blk_get_aio_context(s->blk));
724 blk_set_enable_write_cache(s->blk, blkcfg.wce != 0);
725 aio_context_release(blk_get_aio_context(s->blk));
728 static uint64_t virtio_blk_get_features(VirtIODevice *vdev, uint64_t features,
729 Error **errp)
731 VirtIOBlock *s = VIRTIO_BLK(vdev);
733 virtio_add_feature(&features, VIRTIO_BLK_F_SEG_MAX);
734 virtio_add_feature(&features, VIRTIO_BLK_F_GEOMETRY);
735 virtio_add_feature(&features, VIRTIO_BLK_F_TOPOLOGY);
736 virtio_add_feature(&features, VIRTIO_BLK_F_BLK_SIZE);
737 if (virtio_has_feature(features, VIRTIO_F_VERSION_1)) {
738 if (s->conf.scsi) {
739 error_setg(errp, "Please set scsi=off for virtio-blk devices in order to use virtio 1.0");
740 return 0;
742 } else {
743 virtio_clear_feature(&features, VIRTIO_F_ANY_LAYOUT);
744 virtio_add_feature(&features, VIRTIO_BLK_F_SCSI);
747 if (s->conf.config_wce) {
748 virtio_add_feature(&features, VIRTIO_BLK_F_CONFIG_WCE);
750 if (blk_enable_write_cache(s->blk)) {
751 virtio_add_feature(&features, VIRTIO_BLK_F_WCE);
753 if (blk_is_read_only(s->blk)) {
754 virtio_add_feature(&features, VIRTIO_BLK_F_RO);
756 if (s->conf.num_queues > 1) {
757 virtio_add_feature(&features, VIRTIO_BLK_F_MQ);
760 return features;
763 static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)
765 VirtIOBlock *s = VIRTIO_BLK(vdev);
767 if (s->dataplane && !(status & (VIRTIO_CONFIG_S_DRIVER |
768 VIRTIO_CONFIG_S_DRIVER_OK))) {
769 virtio_blk_data_plane_stop(s->dataplane);
772 if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
773 return;
776 /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send
777 * cache flushes. Thus, the "auto writethrough" behavior is never
778 * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.
779 * Leaving it enabled would break the following sequence:
781 * Guest started with "-drive cache=writethrough"
782 * Guest sets status to 0
783 * Guest sets DRIVER bit in status field
784 * Guest reads host features (WCE=0, CONFIG_WCE=1)
785 * Guest writes guest features (WCE=0, CONFIG_WCE=1)
786 * Guest writes 1 to the WCE configuration field (writeback mode)
787 * Guest sets DRIVER_OK bit in status field
789 * s->blk would erroneously be placed in writethrough mode.
791 if (!virtio_vdev_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE)) {
792 aio_context_acquire(blk_get_aio_context(s->blk));
793 blk_set_enable_write_cache(s->blk,
794 virtio_vdev_has_feature(vdev,
795 VIRTIO_BLK_F_WCE));
796 aio_context_release(blk_get_aio_context(s->blk));
800 static void virtio_blk_save(QEMUFile *f, void *opaque)
802 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
804 virtio_save(vdev, f);
807 static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f)
809 VirtIOBlock *s = VIRTIO_BLK(vdev);
810 VirtIOBlockReq *req = s->rq;
812 while (req) {
813 qemu_put_sbyte(f, 1);
815 if (s->conf.num_queues > 1) {
816 qemu_put_be32(f, virtio_get_queue_index(req->vq));
819 qemu_put_virtqueue_element(f, &req->elem);
820 req = req->next;
822 qemu_put_sbyte(f, 0);
825 static int virtio_blk_load(QEMUFile *f, void *opaque, int version_id)
827 VirtIOBlock *s = opaque;
828 VirtIODevice *vdev = VIRTIO_DEVICE(s);
830 if (version_id != 2)
831 return -EINVAL;
833 return virtio_load(vdev, f, version_id);
836 static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f,
837 int version_id)
839 VirtIOBlock *s = VIRTIO_BLK(vdev);
841 while (qemu_get_sbyte(f)) {
842 unsigned nvqs = s->conf.num_queues;
843 unsigned vq_idx = 0;
844 VirtIOBlockReq *req;
846 if (nvqs > 1) {
847 vq_idx = qemu_get_be32(f);
849 if (vq_idx >= nvqs) {
850 error_report("Invalid virtqueue index in request list: %#x",
851 vq_idx);
852 return -EINVAL;
856 req = qemu_get_virtqueue_element(f, sizeof(VirtIOBlockReq));
857 virtio_blk_init_request(s, virtio_get_queue(vdev, vq_idx), req);
858 req->next = s->rq;
859 s->rq = req;
862 return 0;
865 static void virtio_blk_resize(void *opaque)
867 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
869 virtio_notify_config(vdev);
872 static const BlockDevOps virtio_block_ops = {
873 .resize_cb = virtio_blk_resize,
876 static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
878 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
879 VirtIOBlock *s = VIRTIO_BLK(dev);
880 VirtIOBlkConf *conf = &s->conf;
881 Error *err = NULL;
882 static int virtio_blk_id;
883 unsigned i;
885 if (!conf->conf.blk) {
886 error_setg(errp, "drive property not set");
887 return;
889 if (!blk_is_inserted(conf->conf.blk)) {
890 error_setg(errp, "Device needs media, but drive is empty");
891 return;
893 if (!conf->num_queues) {
894 error_setg(errp, "num-queues property must be larger than 0");
895 return;
898 blkconf_serial(&conf->conf, &conf->serial);
899 s->original_wce = blk_enable_write_cache(conf->conf.blk);
900 blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, &err);
901 if (err) {
902 error_propagate(errp, err);
903 return;
905 blkconf_blocksizes(&conf->conf);
907 virtio_init(vdev, "virtio-blk", VIRTIO_ID_BLOCK,
908 sizeof(struct virtio_blk_config));
910 s->blk = conf->conf.blk;
911 s->rq = NULL;
912 s->sector_mask = (s->conf.conf.logical_block_size / BDRV_SECTOR_SIZE) - 1;
914 for (i = 0; i < conf->num_queues; i++) {
915 virtio_add_queue(vdev, 128, virtio_blk_handle_output);
917 virtio_blk_data_plane_create(vdev, conf, &s->dataplane, &err);
918 if (err != NULL) {
919 error_propagate(errp, err);
920 virtio_cleanup(vdev);
921 return;
924 s->change = qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);
925 register_savevm(dev, "virtio-blk", virtio_blk_id++, 2,
926 virtio_blk_save, virtio_blk_load, s);
927 blk_set_dev_ops(s->blk, &virtio_block_ops, s);
928 blk_set_guest_block_size(s->blk, s->conf.conf.logical_block_size);
930 blk_iostatus_enable(s->blk);
933 static void virtio_blk_device_unrealize(DeviceState *dev, Error **errp)
935 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
936 VirtIOBlock *s = VIRTIO_BLK(dev);
938 virtio_blk_data_plane_destroy(s->dataplane);
939 s->dataplane = NULL;
940 qemu_del_vm_change_state_handler(s->change);
941 unregister_savevm(dev, "virtio-blk", s);
942 blockdev_mark_auto_del(s->blk);
943 virtio_cleanup(vdev);
946 static void virtio_blk_instance_init(Object *obj)
948 VirtIOBlock *s = VIRTIO_BLK(obj);
950 object_property_add_link(obj, "iothread", TYPE_IOTHREAD,
951 (Object **)&s->conf.iothread,
952 qdev_prop_allow_set_link_before_realize,
953 OBJ_PROP_LINK_UNREF_ON_RELEASE, NULL);
954 device_add_bootindex_property(obj, &s->conf.conf.bootindex,
955 "bootindex", "/disk@0,0",
956 DEVICE(obj), NULL);
959 static Property virtio_blk_properties[] = {
960 DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf),
961 DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf),
962 DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial),
963 DEFINE_PROP_BIT("config-wce", VirtIOBlock, conf.config_wce, 0, true),
964 #ifdef __linux__
965 DEFINE_PROP_BIT("scsi", VirtIOBlock, conf.scsi, 0, false),
966 #endif
967 DEFINE_PROP_BIT("request-merging", VirtIOBlock, conf.request_merging, 0,
968 true),
969 DEFINE_PROP_UINT16("num-queues", VirtIOBlock, conf.num_queues, 1),
970 DEFINE_PROP_END_OF_LIST(),
973 static void virtio_blk_class_init(ObjectClass *klass, void *data)
975 DeviceClass *dc = DEVICE_CLASS(klass);
976 VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
978 dc->props = virtio_blk_properties;
979 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
980 vdc->realize = virtio_blk_device_realize;
981 vdc->unrealize = virtio_blk_device_unrealize;
982 vdc->get_config = virtio_blk_update_config;
983 vdc->set_config = virtio_blk_set_config;
984 vdc->get_features = virtio_blk_get_features;
985 vdc->set_status = virtio_blk_set_status;
986 vdc->reset = virtio_blk_reset;
987 vdc->save = virtio_blk_save_device;
988 vdc->load = virtio_blk_load_device;
991 static const TypeInfo virtio_device_info = {
992 .name = TYPE_VIRTIO_BLK,
993 .parent = TYPE_VIRTIO_DEVICE,
994 .instance_size = sizeof(VirtIOBlock),
995 .instance_init = virtio_blk_instance_init,
996 .class_init = virtio_blk_class_init,
999 static void virtio_register_types(void)
1001 type_register_static(&virtio_device_info);
1004 type_init(virtio_register_types)