nvme: fix write zeroes offset and count
[qemu/ar7.git] / hw / block / virtio-blk.c
blob06e57a4d395d51e42cab346ac98207dfc894ad05
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/blockdev.h"
22 #include "hw/virtio/virtio-blk.h"
23 #include "dataplane/virtio-blk.h"
24 #include "scsi/constants.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 /* Config size before the discard support (hide associated config fields) */
32 #define VIRTIO_BLK_CFG_SIZE offsetof(struct virtio_blk_config, \
33 max_discard_sectors)
35 * Starting from the discard feature, we can use this array to properly
36 * set the config size depending on the features enabled.
38 static VirtIOFeature feature_sizes[] = {
39 {.flags = 1ULL << VIRTIO_BLK_F_DISCARD,
40 .end = virtio_endof(struct virtio_blk_config, discard_sector_alignment)},
41 {.flags = 1ULL << VIRTIO_BLK_F_WRITE_ZEROES,
42 .end = virtio_endof(struct virtio_blk_config, write_zeroes_may_unmap)},
46 static void virtio_blk_set_config_size(VirtIOBlock *s, uint64_t host_features)
48 s->config_size = MAX(VIRTIO_BLK_CFG_SIZE,
49 virtio_feature_get_config_size(feature_sizes, host_features));
51 assert(s->config_size <= sizeof(struct virtio_blk_config));
54 static void virtio_blk_init_request(VirtIOBlock *s, VirtQueue *vq,
55 VirtIOBlockReq *req)
57 req->dev = s;
58 req->vq = vq;
59 req->qiov.size = 0;
60 req->in_len = 0;
61 req->next = NULL;
62 req->mr_next = NULL;
65 static void virtio_blk_free_request(VirtIOBlockReq *req)
67 g_free(req);
70 static void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
72 VirtIOBlock *s = req->dev;
73 VirtIODevice *vdev = VIRTIO_DEVICE(s);
75 trace_virtio_blk_req_complete(vdev, req, status);
77 stb_p(&req->in->status, status);
78 virtqueue_push(req->vq, &req->elem, req->in_len);
79 if (s->dataplane_started && !s->dataplane_disabled) {
80 virtio_blk_data_plane_notify(s->dataplane, req->vq);
81 } else {
82 virtio_notify(vdev, req->vq);
86 static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
87 bool is_read, bool acct_failed)
89 VirtIOBlock *s = req->dev;
90 BlockErrorAction action = blk_get_error_action(s->blk, is_read, error);
92 if (action == BLOCK_ERROR_ACTION_STOP) {
93 /* Break the link as the next request is going to be parsed from the
94 * ring again. Otherwise we may end up doing a double completion! */
95 req->mr_next = NULL;
96 req->next = s->rq;
97 s->rq = req;
98 } else if (action == BLOCK_ERROR_ACTION_REPORT) {
99 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
100 if (acct_failed) {
101 block_acct_failed(blk_get_stats(s->blk), &req->acct);
103 virtio_blk_free_request(req);
106 blk_error_action(s->blk, action, is_read, error);
107 return action != BLOCK_ERROR_ACTION_IGNORE;
110 static void virtio_blk_rw_complete(void *opaque, int ret)
112 VirtIOBlockReq *next = opaque;
113 VirtIOBlock *s = next->dev;
114 VirtIODevice *vdev = VIRTIO_DEVICE(s);
116 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
117 while (next) {
118 VirtIOBlockReq *req = next;
119 next = req->mr_next;
120 trace_virtio_blk_rw_complete(vdev, req, ret);
122 if (req->qiov.nalloc != -1) {
123 /* If nalloc is != -1 req->qiov is a local copy of the original
124 * external iovec. It was allocated in submit_requests to be
125 * able to merge requests. */
126 qemu_iovec_destroy(&req->qiov);
129 if (ret) {
130 int p = virtio_ldl_p(VIRTIO_DEVICE(s), &req->out.type);
131 bool is_read = !(p & VIRTIO_BLK_T_OUT);
132 /* Note that memory may be dirtied on read failure. If the
133 * virtio request is not completed here, as is the case for
134 * BLOCK_ERROR_ACTION_STOP, the memory may not be copied
135 * correctly during live migration. While this is ugly,
136 * it is acceptable because the device is free to write to
137 * the memory until the request is completed (which will
138 * happen on the other side of the migration).
140 if (virtio_blk_handle_rw_error(req, -ret, is_read, true)) {
141 continue;
145 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
146 block_acct_done(blk_get_stats(s->blk), &req->acct);
147 virtio_blk_free_request(req);
149 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
152 static void virtio_blk_flush_complete(void *opaque, int ret)
154 VirtIOBlockReq *req = opaque;
155 VirtIOBlock *s = req->dev;
157 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
158 if (ret) {
159 if (virtio_blk_handle_rw_error(req, -ret, 0, true)) {
160 goto out;
164 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
165 block_acct_done(blk_get_stats(s->blk), &req->acct);
166 virtio_blk_free_request(req);
168 out:
169 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
172 static void virtio_blk_discard_write_zeroes_complete(void *opaque, int ret)
174 VirtIOBlockReq *req = opaque;
175 VirtIOBlock *s = req->dev;
176 bool is_write_zeroes = (virtio_ldl_p(VIRTIO_DEVICE(s), &req->out.type) &
177 ~VIRTIO_BLK_T_BARRIER) == VIRTIO_BLK_T_WRITE_ZEROES;
179 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
180 if (ret) {
181 if (virtio_blk_handle_rw_error(req, -ret, false, is_write_zeroes)) {
182 goto out;
186 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
187 if (is_write_zeroes) {
188 block_acct_done(blk_get_stats(s->blk), &req->acct);
190 virtio_blk_free_request(req);
192 out:
193 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
196 #ifdef __linux__
198 typedef struct {
199 VirtIOBlockReq *req;
200 struct sg_io_hdr hdr;
201 } VirtIOBlockIoctlReq;
203 static void virtio_blk_ioctl_complete(void *opaque, int status)
205 VirtIOBlockIoctlReq *ioctl_req = opaque;
206 VirtIOBlockReq *req = ioctl_req->req;
207 VirtIOBlock *s = req->dev;
208 VirtIODevice *vdev = VIRTIO_DEVICE(s);
209 struct virtio_scsi_inhdr *scsi;
210 struct sg_io_hdr *hdr;
212 scsi = (void *)req->elem.in_sg[req->elem.in_num - 2].iov_base;
214 if (status) {
215 status = VIRTIO_BLK_S_UNSUPP;
216 virtio_stl_p(vdev, &scsi->errors, 255);
217 goto out;
220 hdr = &ioctl_req->hdr;
222 * From SCSI-Generic-HOWTO: "Some lower level drivers (e.g. ide-scsi)
223 * clear the masked_status field [hence status gets cleared too, see
224 * block/scsi_ioctl.c] even when a CHECK_CONDITION or COMMAND_TERMINATED
225 * status has occurred. However they do set DRIVER_SENSE in driver_status
226 * field. Also a (sb_len_wr > 0) indicates there is a sense buffer.
228 if (hdr->status == 0 && hdr->sb_len_wr > 0) {
229 hdr->status = CHECK_CONDITION;
232 virtio_stl_p(vdev, &scsi->errors,
233 hdr->status | (hdr->msg_status << 8) |
234 (hdr->host_status << 16) | (hdr->driver_status << 24));
235 virtio_stl_p(vdev, &scsi->residual, hdr->resid);
236 virtio_stl_p(vdev, &scsi->sense_len, hdr->sb_len_wr);
237 virtio_stl_p(vdev, &scsi->data_len, hdr->dxfer_len);
239 out:
240 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
241 virtio_blk_req_complete(req, status);
242 virtio_blk_free_request(req);
243 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
244 g_free(ioctl_req);
247 #endif
249 static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s, VirtQueue *vq)
251 VirtIOBlockReq *req = virtqueue_pop(vq, sizeof(VirtIOBlockReq));
253 if (req) {
254 virtio_blk_init_request(s, vq, req);
256 return req;
259 static int virtio_blk_handle_scsi_req(VirtIOBlockReq *req)
261 int status = VIRTIO_BLK_S_OK;
262 struct virtio_scsi_inhdr *scsi = NULL;
263 VirtIOBlock *blk = req->dev;
264 VirtIODevice *vdev = VIRTIO_DEVICE(blk);
265 VirtQueueElement *elem = &req->elem;
267 #ifdef __linux__
268 int i;
269 VirtIOBlockIoctlReq *ioctl_req;
270 BlockAIOCB *acb;
271 #endif
274 * We require at least one output segment each for the virtio_blk_outhdr
275 * and the SCSI command block.
277 * We also at least require the virtio_blk_inhdr, the virtio_scsi_inhdr
278 * and the sense buffer pointer in the input segments.
280 if (elem->out_num < 2 || elem->in_num < 3) {
281 status = VIRTIO_BLK_S_IOERR;
282 goto fail;
286 * The scsi inhdr is placed in the second-to-last input segment, just
287 * before the regular inhdr.
289 scsi = (void *)elem->in_sg[elem->in_num - 2].iov_base;
291 if (!virtio_has_feature(blk->host_features, VIRTIO_BLK_F_SCSI)) {
292 status = VIRTIO_BLK_S_UNSUPP;
293 goto fail;
297 * No support for bidirection commands yet.
299 if (elem->out_num > 2 && elem->in_num > 3) {
300 status = VIRTIO_BLK_S_UNSUPP;
301 goto fail;
304 #ifdef __linux__
305 ioctl_req = g_new0(VirtIOBlockIoctlReq, 1);
306 ioctl_req->req = req;
307 ioctl_req->hdr.interface_id = 'S';
308 ioctl_req->hdr.cmd_len = elem->out_sg[1].iov_len;
309 ioctl_req->hdr.cmdp = elem->out_sg[1].iov_base;
310 ioctl_req->hdr.dxfer_len = 0;
312 if (elem->out_num > 2) {
314 * If there are more than the minimally required 2 output segments
315 * there is write payload starting from the third iovec.
317 ioctl_req->hdr.dxfer_direction = SG_DXFER_TO_DEV;
318 ioctl_req->hdr.iovec_count = elem->out_num - 2;
320 for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
321 ioctl_req->hdr.dxfer_len += elem->out_sg[i + 2].iov_len;
324 ioctl_req->hdr.dxferp = elem->out_sg + 2;
326 } else if (elem->in_num > 3) {
328 * If we have more than 3 input segments the guest wants to actually
329 * read data.
331 ioctl_req->hdr.dxfer_direction = SG_DXFER_FROM_DEV;
332 ioctl_req->hdr.iovec_count = elem->in_num - 3;
333 for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
334 ioctl_req->hdr.dxfer_len += elem->in_sg[i].iov_len;
337 ioctl_req->hdr.dxferp = elem->in_sg;
338 } else {
340 * Some SCSI commands don't actually transfer any data.
342 ioctl_req->hdr.dxfer_direction = SG_DXFER_NONE;
345 ioctl_req->hdr.sbp = elem->in_sg[elem->in_num - 3].iov_base;
346 ioctl_req->hdr.mx_sb_len = elem->in_sg[elem->in_num - 3].iov_len;
348 acb = blk_aio_ioctl(blk->blk, SG_IO, &ioctl_req->hdr,
349 virtio_blk_ioctl_complete, ioctl_req);
350 if (!acb) {
351 g_free(ioctl_req);
352 status = VIRTIO_BLK_S_UNSUPP;
353 goto fail;
355 return -EINPROGRESS;
356 #else
357 abort();
358 #endif
360 fail:
361 /* Just put anything nonzero so that the ioctl fails in the guest. */
362 if (scsi) {
363 virtio_stl_p(vdev, &scsi->errors, 255);
365 return status;
368 static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
370 int status;
372 status = virtio_blk_handle_scsi_req(req);
373 if (status != -EINPROGRESS) {
374 virtio_blk_req_complete(req, status);
375 virtio_blk_free_request(req);
379 static inline void submit_requests(BlockBackend *blk, MultiReqBuffer *mrb,
380 int start, int num_reqs, int niov)
382 QEMUIOVector *qiov = &mrb->reqs[start]->qiov;
383 int64_t sector_num = mrb->reqs[start]->sector_num;
384 bool is_write = mrb->is_write;
386 if (num_reqs > 1) {
387 int i;
388 struct iovec *tmp_iov = qiov->iov;
389 int tmp_niov = qiov->niov;
391 /* mrb->reqs[start]->qiov was initialized from external so we can't
392 * modify it here. We need to initialize it locally and then add the
393 * external iovecs. */
394 qemu_iovec_init(qiov, niov);
396 for (i = 0; i < tmp_niov; i++) {
397 qemu_iovec_add(qiov, tmp_iov[i].iov_base, tmp_iov[i].iov_len);
400 for (i = start + 1; i < start + num_reqs; i++) {
401 qemu_iovec_concat(qiov, &mrb->reqs[i]->qiov, 0,
402 mrb->reqs[i]->qiov.size);
403 mrb->reqs[i - 1]->mr_next = mrb->reqs[i];
406 trace_virtio_blk_submit_multireq(VIRTIO_DEVICE(mrb->reqs[start]->dev),
407 mrb, start, num_reqs,
408 sector_num << BDRV_SECTOR_BITS,
409 qiov->size, is_write);
410 block_acct_merge_done(blk_get_stats(blk),
411 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ,
412 num_reqs - 1);
415 if (is_write) {
416 blk_aio_pwritev(blk, sector_num << BDRV_SECTOR_BITS, qiov, 0,
417 virtio_blk_rw_complete, mrb->reqs[start]);
418 } else {
419 blk_aio_preadv(blk, sector_num << BDRV_SECTOR_BITS, qiov, 0,
420 virtio_blk_rw_complete, mrb->reqs[start]);
424 static int multireq_compare(const void *a, const void *b)
426 const VirtIOBlockReq *req1 = *(VirtIOBlockReq **)a,
427 *req2 = *(VirtIOBlockReq **)b;
430 * Note that we can't simply subtract sector_num1 from sector_num2
431 * here as that could overflow the return value.
433 if (req1->sector_num > req2->sector_num) {
434 return 1;
435 } else if (req1->sector_num < req2->sector_num) {
436 return -1;
437 } else {
438 return 0;
442 static void virtio_blk_submit_multireq(BlockBackend *blk, MultiReqBuffer *mrb)
444 int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
445 uint32_t max_transfer;
446 int64_t sector_num = 0;
448 if (mrb->num_reqs == 1) {
449 submit_requests(blk, mrb, 0, 1, -1);
450 mrb->num_reqs = 0;
451 return;
454 max_transfer = blk_get_max_transfer(mrb->reqs[0]->dev->blk);
456 qsort(mrb->reqs, mrb->num_reqs, sizeof(*mrb->reqs),
457 &multireq_compare);
459 for (i = 0; i < mrb->num_reqs; i++) {
460 VirtIOBlockReq *req = mrb->reqs[i];
461 if (num_reqs > 0) {
463 * NOTE: We cannot merge the requests in below situations:
464 * 1. requests are not sequential
465 * 2. merge would exceed maximum number of IOVs
466 * 3. merge would exceed maximum transfer length of backend device
468 if (sector_num + nb_sectors != req->sector_num ||
469 niov > blk_get_max_iov(blk) - req->qiov.niov ||
470 req->qiov.size > max_transfer ||
471 nb_sectors > (max_transfer -
472 req->qiov.size) / BDRV_SECTOR_SIZE) {
473 submit_requests(blk, mrb, start, num_reqs, niov);
474 num_reqs = 0;
478 if (num_reqs == 0) {
479 sector_num = req->sector_num;
480 nb_sectors = niov = 0;
481 start = i;
484 nb_sectors += req->qiov.size / BDRV_SECTOR_SIZE;
485 niov += req->qiov.niov;
486 num_reqs++;
489 submit_requests(blk, mrb, start, num_reqs, niov);
490 mrb->num_reqs = 0;
493 static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
495 VirtIOBlock *s = req->dev;
497 block_acct_start(blk_get_stats(s->blk), &req->acct, 0,
498 BLOCK_ACCT_FLUSH);
501 * Make sure all outstanding writes are posted to the backing device.
503 if (mrb->is_write && mrb->num_reqs > 0) {
504 virtio_blk_submit_multireq(s->blk, mrb);
506 blk_aio_flush(s->blk, virtio_blk_flush_complete, req);
509 static bool virtio_blk_sect_range_ok(VirtIOBlock *dev,
510 uint64_t sector, size_t size)
512 uint64_t nb_sectors = size >> BDRV_SECTOR_BITS;
513 uint64_t total_sectors;
515 if (nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
516 return false;
518 if (sector & dev->sector_mask) {
519 return false;
521 if (size % dev->conf.conf.logical_block_size) {
522 return false;
524 blk_get_geometry(dev->blk, &total_sectors);
525 if (sector > total_sectors || nb_sectors > total_sectors - sector) {
526 return false;
528 return true;
531 static uint8_t virtio_blk_handle_discard_write_zeroes(VirtIOBlockReq *req,
532 struct virtio_blk_discard_write_zeroes *dwz_hdr, bool is_write_zeroes)
534 VirtIOBlock *s = req->dev;
535 VirtIODevice *vdev = VIRTIO_DEVICE(s);
536 uint64_t sector;
537 uint32_t num_sectors, flags, max_sectors;
538 uint8_t err_status;
539 int bytes;
541 sector = virtio_ldq_p(vdev, &dwz_hdr->sector);
542 num_sectors = virtio_ldl_p(vdev, &dwz_hdr->num_sectors);
543 flags = virtio_ldl_p(vdev, &dwz_hdr->flags);
544 max_sectors = is_write_zeroes ? s->conf.max_write_zeroes_sectors :
545 s->conf.max_discard_sectors;
548 * max_sectors is at most BDRV_REQUEST_MAX_SECTORS, this check
549 * make us sure that "num_sectors << BDRV_SECTOR_BITS" can fit in
550 * the integer variable.
552 if (unlikely(num_sectors > max_sectors)) {
553 err_status = VIRTIO_BLK_S_IOERR;
554 goto err;
557 bytes = num_sectors << BDRV_SECTOR_BITS;
559 if (unlikely(!virtio_blk_sect_range_ok(s, sector, bytes))) {
560 err_status = VIRTIO_BLK_S_IOERR;
561 goto err;
565 * The device MUST set the status byte to VIRTIO_BLK_S_UNSUPP for discard
566 * and write zeroes commands if any unknown flag is set.
568 if (unlikely(flags & ~VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP)) {
569 err_status = VIRTIO_BLK_S_UNSUPP;
570 goto err;
573 if (is_write_zeroes) { /* VIRTIO_BLK_T_WRITE_ZEROES */
574 int blk_aio_flags = 0;
576 if (flags & VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP) {
577 blk_aio_flags |= BDRV_REQ_MAY_UNMAP;
580 block_acct_start(blk_get_stats(s->blk), &req->acct, bytes,
581 BLOCK_ACCT_WRITE);
583 blk_aio_pwrite_zeroes(s->blk, sector << BDRV_SECTOR_BITS,
584 bytes, blk_aio_flags,
585 virtio_blk_discard_write_zeroes_complete, req);
586 } else { /* VIRTIO_BLK_T_DISCARD */
588 * The device MUST set the status byte to VIRTIO_BLK_S_UNSUPP for
589 * discard commands if the unmap flag is set.
591 if (unlikely(flags & VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP)) {
592 err_status = VIRTIO_BLK_S_UNSUPP;
593 goto err;
596 blk_aio_pdiscard(s->blk, sector << BDRV_SECTOR_BITS, bytes,
597 virtio_blk_discard_write_zeroes_complete, req);
600 return VIRTIO_BLK_S_OK;
602 err:
603 if (is_write_zeroes) {
604 block_acct_invalid(blk_get_stats(s->blk), BLOCK_ACCT_WRITE);
606 return err_status;
609 static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
611 uint32_t type;
612 struct iovec *in_iov = req->elem.in_sg;
613 struct iovec *out_iov = req->elem.out_sg;
614 unsigned in_num = req->elem.in_num;
615 unsigned out_num = req->elem.out_num;
616 VirtIOBlock *s = req->dev;
617 VirtIODevice *vdev = VIRTIO_DEVICE(s);
619 if (req->elem.out_num < 1 || req->elem.in_num < 1) {
620 virtio_error(vdev, "virtio-blk missing headers");
621 return -1;
624 if (unlikely(iov_to_buf(out_iov, out_num, 0, &req->out,
625 sizeof(req->out)) != sizeof(req->out))) {
626 virtio_error(vdev, "virtio-blk request outhdr too short");
627 return -1;
630 iov_discard_front(&out_iov, &out_num, sizeof(req->out));
632 if (in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {
633 virtio_error(vdev, "virtio-blk request inhdr too short");
634 return -1;
637 /* We always touch the last byte, so just see how big in_iov is. */
638 req->in_len = iov_size(in_iov, in_num);
639 req->in = (void *)in_iov[in_num - 1].iov_base
640 + in_iov[in_num - 1].iov_len
641 - sizeof(struct virtio_blk_inhdr);
642 iov_discard_back(in_iov, &in_num, sizeof(struct virtio_blk_inhdr));
644 type = virtio_ldl_p(vdev, &req->out.type);
646 /* VIRTIO_BLK_T_OUT defines the command direction. VIRTIO_BLK_T_BARRIER
647 * is an optional flag. Although a guest should not send this flag if
648 * not negotiated we ignored it in the past. So keep ignoring it. */
649 switch (type & ~(VIRTIO_BLK_T_OUT | VIRTIO_BLK_T_BARRIER)) {
650 case VIRTIO_BLK_T_IN:
652 bool is_write = type & VIRTIO_BLK_T_OUT;
653 req->sector_num = virtio_ldq_p(vdev, &req->out.sector);
655 if (is_write) {
656 qemu_iovec_init_external(&req->qiov, out_iov, out_num);
657 trace_virtio_blk_handle_write(vdev, req, req->sector_num,
658 req->qiov.size / BDRV_SECTOR_SIZE);
659 } else {
660 qemu_iovec_init_external(&req->qiov, in_iov, in_num);
661 trace_virtio_blk_handle_read(vdev, req, req->sector_num,
662 req->qiov.size / BDRV_SECTOR_SIZE);
665 if (!virtio_blk_sect_range_ok(s, req->sector_num, req->qiov.size)) {
666 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
667 block_acct_invalid(blk_get_stats(s->blk),
668 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
669 virtio_blk_free_request(req);
670 return 0;
673 block_acct_start(blk_get_stats(s->blk), &req->acct, req->qiov.size,
674 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
676 /* merge would exceed maximum number of requests or IO direction
677 * changes */
678 if (mrb->num_reqs > 0 && (mrb->num_reqs == VIRTIO_BLK_MAX_MERGE_REQS ||
679 is_write != mrb->is_write ||
680 !s->conf.request_merging)) {
681 virtio_blk_submit_multireq(s->blk, mrb);
684 assert(mrb->num_reqs < VIRTIO_BLK_MAX_MERGE_REQS);
685 mrb->reqs[mrb->num_reqs++] = req;
686 mrb->is_write = is_write;
687 break;
689 case VIRTIO_BLK_T_FLUSH:
690 virtio_blk_handle_flush(req, mrb);
691 break;
692 case VIRTIO_BLK_T_SCSI_CMD:
693 virtio_blk_handle_scsi(req);
694 break;
695 case VIRTIO_BLK_T_GET_ID:
698 * NB: per existing s/n string convention the string is
699 * terminated by '\0' only when shorter than buffer.
701 const char *serial = s->conf.serial ? s->conf.serial : "";
702 size_t size = MIN(strlen(serial) + 1,
703 MIN(iov_size(in_iov, in_num),
704 VIRTIO_BLK_ID_BYTES));
705 iov_from_buf(in_iov, in_num, 0, serial, size);
706 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
707 virtio_blk_free_request(req);
708 break;
711 * VIRTIO_BLK_T_DISCARD and VIRTIO_BLK_T_WRITE_ZEROES are defined with
712 * VIRTIO_BLK_T_OUT flag set. We masked this flag in the switch statement,
713 * so we must mask it for these requests, then we will check if it is set.
715 case VIRTIO_BLK_T_DISCARD & ~VIRTIO_BLK_T_OUT:
716 case VIRTIO_BLK_T_WRITE_ZEROES & ~VIRTIO_BLK_T_OUT:
718 struct virtio_blk_discard_write_zeroes dwz_hdr;
719 size_t out_len = iov_size(out_iov, out_num);
720 bool is_write_zeroes = (type & ~VIRTIO_BLK_T_BARRIER) ==
721 VIRTIO_BLK_T_WRITE_ZEROES;
722 uint8_t err_status;
725 * Unsupported if VIRTIO_BLK_T_OUT is not set or the request contains
726 * more than one segment.
728 if (unlikely(!(type & VIRTIO_BLK_T_OUT) ||
729 out_len > sizeof(dwz_hdr))) {
730 virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
731 virtio_blk_free_request(req);
732 return 0;
735 if (unlikely(iov_to_buf(out_iov, out_num, 0, &dwz_hdr,
736 sizeof(dwz_hdr)) != sizeof(dwz_hdr))) {
737 virtio_error(vdev, "virtio-blk discard/write_zeroes header"
738 " too short");
739 return -1;
742 err_status = virtio_blk_handle_discard_write_zeroes(req, &dwz_hdr,
743 is_write_zeroes);
744 if (err_status != VIRTIO_BLK_S_OK) {
745 virtio_blk_req_complete(req, err_status);
746 virtio_blk_free_request(req);
749 break;
751 default:
752 virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
753 virtio_blk_free_request(req);
755 return 0;
758 bool virtio_blk_handle_vq(VirtIOBlock *s, VirtQueue *vq)
760 VirtIOBlockReq *req;
761 MultiReqBuffer mrb = {};
762 bool progress = false;
764 aio_context_acquire(blk_get_aio_context(s->blk));
765 blk_io_plug(s->blk);
767 do {
768 virtio_queue_set_notification(vq, 0);
770 while ((req = virtio_blk_get_request(s, vq))) {
771 progress = true;
772 if (virtio_blk_handle_request(req, &mrb)) {
773 virtqueue_detach_element(req->vq, &req->elem, 0);
774 virtio_blk_free_request(req);
775 break;
779 virtio_queue_set_notification(vq, 1);
780 } while (!virtio_queue_empty(vq));
782 if (mrb.num_reqs) {
783 virtio_blk_submit_multireq(s->blk, &mrb);
786 blk_io_unplug(s->blk);
787 aio_context_release(blk_get_aio_context(s->blk));
788 return progress;
791 static void virtio_blk_handle_output_do(VirtIOBlock *s, VirtQueue *vq)
793 virtio_blk_handle_vq(s, vq);
796 static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)
798 VirtIOBlock *s = (VirtIOBlock *)vdev;
800 if (s->dataplane) {
801 /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start
802 * dataplane here instead of waiting for .set_status().
804 virtio_device_start_ioeventfd(vdev);
805 if (!s->dataplane_disabled) {
806 return;
809 virtio_blk_handle_output_do(s, vq);
812 static void virtio_blk_dma_restart_bh(void *opaque)
814 VirtIOBlock *s = opaque;
815 VirtIOBlockReq *req = s->rq;
816 MultiReqBuffer mrb = {};
818 qemu_bh_delete(s->bh);
819 s->bh = NULL;
821 s->rq = NULL;
823 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
824 while (req) {
825 VirtIOBlockReq *next = req->next;
826 if (virtio_blk_handle_request(req, &mrb)) {
827 /* Device is now broken and won't do any processing until it gets
828 * reset. Already queued requests will be lost: let's purge them.
830 while (req) {
831 next = req->next;
832 virtqueue_detach_element(req->vq, &req->elem, 0);
833 virtio_blk_free_request(req);
834 req = next;
836 break;
838 req = next;
841 if (mrb.num_reqs) {
842 virtio_blk_submit_multireq(s->blk, &mrb);
844 blk_dec_in_flight(s->conf.conf.blk);
845 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
848 static void virtio_blk_dma_restart_cb(void *opaque, int running,
849 RunState state)
851 VirtIOBlock *s = opaque;
853 if (!running) {
854 return;
857 if (!s->bh) {
858 /* FIXME The data plane is not started yet, so these requests are
859 * processed in the main thread. */
860 s->bh = aio_bh_new(blk_get_aio_context(s->conf.conf.blk),
861 virtio_blk_dma_restart_bh, s);
862 blk_inc_in_flight(s->conf.conf.blk);
863 qemu_bh_schedule(s->bh);
867 static void virtio_blk_reset(VirtIODevice *vdev)
869 VirtIOBlock *s = VIRTIO_BLK(vdev);
870 AioContext *ctx;
871 VirtIOBlockReq *req;
873 ctx = blk_get_aio_context(s->blk);
874 aio_context_acquire(ctx);
875 blk_drain(s->blk);
877 /* We drop queued requests after blk_drain() because blk_drain() itself can
878 * produce them. */
879 while (s->rq) {
880 req = s->rq;
881 s->rq = req->next;
882 virtqueue_detach_element(req->vq, &req->elem, 0);
883 virtio_blk_free_request(req);
886 aio_context_release(ctx);
888 assert(!s->dataplane_started);
889 blk_set_enable_write_cache(s->blk, s->original_wce);
892 /* coalesce internal state, copy to pci i/o region 0
894 static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
896 VirtIOBlock *s = VIRTIO_BLK(vdev);
897 BlockConf *conf = &s->conf.conf;
898 struct virtio_blk_config blkcfg;
899 uint64_t capacity;
900 int64_t length;
901 int blk_size = conf->logical_block_size;
903 blk_get_geometry(s->blk, &capacity);
904 memset(&blkcfg, 0, sizeof(blkcfg));
905 virtio_stq_p(vdev, &blkcfg.capacity, capacity);
906 virtio_stl_p(vdev, &blkcfg.seg_max, 128 - 2);
907 virtio_stw_p(vdev, &blkcfg.geometry.cylinders, conf->cyls);
908 virtio_stl_p(vdev, &blkcfg.blk_size, blk_size);
909 virtio_stw_p(vdev, &blkcfg.min_io_size, conf->min_io_size / blk_size);
910 virtio_stw_p(vdev, &blkcfg.opt_io_size, conf->opt_io_size / blk_size);
911 blkcfg.geometry.heads = conf->heads;
913 * We must ensure that the block device capacity is a multiple of
914 * the logical block size. If that is not the case, let's use
915 * sector_mask to adopt the geometry to have a correct picture.
916 * For those devices where the capacity is ok for the given geometry
917 * we don't touch the sector value of the geometry, since some devices
918 * (like s390 dasd) need a specific value. Here the capacity is already
919 * cyls*heads*secs*blk_size and the sector value is not block size
920 * divided by 512 - instead it is the amount of blk_size blocks
921 * per track (cylinder).
923 length = blk_getlength(s->blk);
924 if (length > 0 && length / conf->heads / conf->secs % blk_size) {
925 blkcfg.geometry.sectors = conf->secs & ~s->sector_mask;
926 } else {
927 blkcfg.geometry.sectors = conf->secs;
929 blkcfg.size_max = 0;
930 blkcfg.physical_block_exp = get_physical_block_exp(conf);
931 blkcfg.alignment_offset = 0;
932 blkcfg.wce = blk_enable_write_cache(s->blk);
933 virtio_stw_p(vdev, &blkcfg.num_queues, s->conf.num_queues);
934 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_DISCARD)) {
935 virtio_stl_p(vdev, &blkcfg.max_discard_sectors,
936 s->conf.max_discard_sectors);
937 virtio_stl_p(vdev, &blkcfg.discard_sector_alignment,
938 blk_size >> BDRV_SECTOR_BITS);
940 * We support only one segment per request since multiple segments
941 * are not widely used and there are no userspace APIs that allow
942 * applications to submit multiple segments in a single call.
944 virtio_stl_p(vdev, &blkcfg.max_discard_seg, 1);
946 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_WRITE_ZEROES)) {
947 virtio_stl_p(vdev, &blkcfg.max_write_zeroes_sectors,
948 s->conf.max_write_zeroes_sectors);
949 blkcfg.write_zeroes_may_unmap = 1;
950 virtio_stl_p(vdev, &blkcfg.max_write_zeroes_seg, 1);
952 memcpy(config, &blkcfg, s->config_size);
955 static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config)
957 VirtIOBlock *s = VIRTIO_BLK(vdev);
958 struct virtio_blk_config blkcfg;
960 memcpy(&blkcfg, config, s->config_size);
962 aio_context_acquire(blk_get_aio_context(s->blk));
963 blk_set_enable_write_cache(s->blk, blkcfg.wce != 0);
964 aio_context_release(blk_get_aio_context(s->blk));
967 static uint64_t virtio_blk_get_features(VirtIODevice *vdev, uint64_t features,
968 Error **errp)
970 VirtIOBlock *s = VIRTIO_BLK(vdev);
972 /* Firstly sync all virtio-blk possible supported features */
973 features |= s->host_features;
975 virtio_add_feature(&features, VIRTIO_BLK_F_SEG_MAX);
976 virtio_add_feature(&features, VIRTIO_BLK_F_GEOMETRY);
977 virtio_add_feature(&features, VIRTIO_BLK_F_TOPOLOGY);
978 virtio_add_feature(&features, VIRTIO_BLK_F_BLK_SIZE);
979 if (virtio_has_feature(features, VIRTIO_F_VERSION_1)) {
980 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_SCSI)) {
981 error_setg(errp, "Please set scsi=off for virtio-blk devices in order to use virtio 1.0");
982 return 0;
984 } else {
985 virtio_clear_feature(&features, VIRTIO_F_ANY_LAYOUT);
986 virtio_add_feature(&features, VIRTIO_BLK_F_SCSI);
989 if (blk_enable_write_cache(s->blk)) {
990 virtio_add_feature(&features, VIRTIO_BLK_F_WCE);
992 if (blk_is_read_only(s->blk)) {
993 virtio_add_feature(&features, VIRTIO_BLK_F_RO);
995 if (s->conf.num_queues > 1) {
996 virtio_add_feature(&features, VIRTIO_BLK_F_MQ);
999 return features;
1002 static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)
1004 VirtIOBlock *s = VIRTIO_BLK(vdev);
1006 if (!(status & (VIRTIO_CONFIG_S_DRIVER | VIRTIO_CONFIG_S_DRIVER_OK))) {
1007 assert(!s->dataplane_started);
1010 if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
1011 return;
1014 /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send
1015 * cache flushes. Thus, the "auto writethrough" behavior is never
1016 * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.
1017 * Leaving it enabled would break the following sequence:
1019 * Guest started with "-drive cache=writethrough"
1020 * Guest sets status to 0
1021 * Guest sets DRIVER bit in status field
1022 * Guest reads host features (WCE=0, CONFIG_WCE=1)
1023 * Guest writes guest features (WCE=0, CONFIG_WCE=1)
1024 * Guest writes 1 to the WCE configuration field (writeback mode)
1025 * Guest sets DRIVER_OK bit in status field
1027 * s->blk would erroneously be placed in writethrough mode.
1029 if (!virtio_vdev_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE)) {
1030 aio_context_acquire(blk_get_aio_context(s->blk));
1031 blk_set_enable_write_cache(s->blk,
1032 virtio_vdev_has_feature(vdev,
1033 VIRTIO_BLK_F_WCE));
1034 aio_context_release(blk_get_aio_context(s->blk));
1038 static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f)
1040 VirtIOBlock *s = VIRTIO_BLK(vdev);
1041 VirtIOBlockReq *req = s->rq;
1043 while (req) {
1044 qemu_put_sbyte(f, 1);
1046 if (s->conf.num_queues > 1) {
1047 qemu_put_be32(f, virtio_get_queue_index(req->vq));
1050 qemu_put_virtqueue_element(f, &req->elem);
1051 req = req->next;
1053 qemu_put_sbyte(f, 0);
1056 static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f,
1057 int version_id)
1059 VirtIOBlock *s = VIRTIO_BLK(vdev);
1061 while (qemu_get_sbyte(f)) {
1062 unsigned nvqs = s->conf.num_queues;
1063 unsigned vq_idx = 0;
1064 VirtIOBlockReq *req;
1066 if (nvqs > 1) {
1067 vq_idx = qemu_get_be32(f);
1069 if (vq_idx >= nvqs) {
1070 error_report("Invalid virtqueue index in request list: %#x",
1071 vq_idx);
1072 return -EINVAL;
1076 req = qemu_get_virtqueue_element(vdev, f, sizeof(VirtIOBlockReq));
1077 virtio_blk_init_request(s, virtio_get_queue(vdev, vq_idx), req);
1078 req->next = s->rq;
1079 s->rq = req;
1082 return 0;
1085 static void virtio_blk_resize(void *opaque)
1087 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
1089 virtio_notify_config(vdev);
1092 static const BlockDevOps virtio_block_ops = {
1093 .resize_cb = virtio_blk_resize,
1096 static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
1098 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1099 VirtIOBlock *s = VIRTIO_BLK(dev);
1100 VirtIOBlkConf *conf = &s->conf;
1101 Error *err = NULL;
1102 unsigned i;
1104 if (!conf->conf.blk) {
1105 error_setg(errp, "drive property not set");
1106 return;
1108 if (!blk_is_inserted(conf->conf.blk)) {
1109 error_setg(errp, "Device needs media, but drive is empty");
1110 return;
1112 if (!conf->num_queues) {
1113 error_setg(errp, "num-queues property must be larger than 0");
1114 return;
1116 if (!is_power_of_2(conf->queue_size) ||
1117 conf->queue_size > VIRTQUEUE_MAX_SIZE) {
1118 error_setg(errp, "invalid queue-size property (%" PRIu16 "), "
1119 "must be a power of 2 (max %d)",
1120 conf->queue_size, VIRTQUEUE_MAX_SIZE);
1121 return;
1124 if (!blkconf_apply_backend_options(&conf->conf,
1125 blk_is_read_only(conf->conf.blk), true,
1126 errp)) {
1127 return;
1129 s->original_wce = blk_enable_write_cache(conf->conf.blk);
1130 if (!blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, errp)) {
1131 return;
1134 blkconf_blocksizes(&conf->conf);
1136 if (conf->conf.logical_block_size >
1137 conf->conf.physical_block_size) {
1138 error_setg(errp,
1139 "logical_block_size > physical_block_size not supported");
1140 return;
1143 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_DISCARD) &&
1144 (!conf->max_discard_sectors ||
1145 conf->max_discard_sectors > BDRV_REQUEST_MAX_SECTORS)) {
1146 error_setg(errp, "invalid max-discard-sectors property (%" PRIu32 ")"
1147 ", must be between 1 and %d",
1148 conf->max_discard_sectors, (int)BDRV_REQUEST_MAX_SECTORS);
1149 return;
1152 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_WRITE_ZEROES) &&
1153 (!conf->max_write_zeroes_sectors ||
1154 conf->max_write_zeroes_sectors > BDRV_REQUEST_MAX_SECTORS)) {
1155 error_setg(errp, "invalid max-write-zeroes-sectors property (%" PRIu32
1156 "), must be between 1 and %d",
1157 conf->max_write_zeroes_sectors,
1158 (int)BDRV_REQUEST_MAX_SECTORS);
1159 return;
1162 virtio_blk_set_config_size(s, s->host_features);
1164 virtio_init(vdev, "virtio-blk", VIRTIO_ID_BLOCK, s->config_size);
1166 s->blk = conf->conf.blk;
1167 s->rq = NULL;
1168 s->sector_mask = (s->conf.conf.logical_block_size / BDRV_SECTOR_SIZE) - 1;
1170 for (i = 0; i < conf->num_queues; i++) {
1171 virtio_add_queue(vdev, conf->queue_size, virtio_blk_handle_output);
1173 virtio_blk_data_plane_create(vdev, conf, &s->dataplane, &err);
1174 if (err != NULL) {
1175 error_propagate(errp, err);
1176 virtio_cleanup(vdev);
1177 return;
1180 s->change = qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);
1181 blk_set_dev_ops(s->blk, &virtio_block_ops, s);
1182 blk_set_guest_block_size(s->blk, s->conf.conf.logical_block_size);
1184 blk_iostatus_enable(s->blk);
1187 static void virtio_blk_device_unrealize(DeviceState *dev, Error **errp)
1189 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1190 VirtIOBlock *s = VIRTIO_BLK(dev);
1192 virtio_blk_data_plane_destroy(s->dataplane);
1193 s->dataplane = NULL;
1194 qemu_del_vm_change_state_handler(s->change);
1195 blockdev_mark_auto_del(s->blk);
1196 virtio_cleanup(vdev);
1199 static void virtio_blk_instance_init(Object *obj)
1201 VirtIOBlock *s = VIRTIO_BLK(obj);
1203 device_add_bootindex_property(obj, &s->conf.conf.bootindex,
1204 "bootindex", "/disk@0,0",
1205 DEVICE(obj), NULL);
1208 static const VMStateDescription vmstate_virtio_blk = {
1209 .name = "virtio-blk",
1210 .minimum_version_id = 2,
1211 .version_id = 2,
1212 .fields = (VMStateField[]) {
1213 VMSTATE_VIRTIO_DEVICE,
1214 VMSTATE_END_OF_LIST()
1218 static Property virtio_blk_properties[] = {
1219 DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf),
1220 DEFINE_BLOCK_ERROR_PROPERTIES(VirtIOBlock, conf.conf),
1221 DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf),
1222 DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial),
1223 DEFINE_PROP_BIT64("config-wce", VirtIOBlock, host_features,
1224 VIRTIO_BLK_F_CONFIG_WCE, true),
1225 #ifdef __linux__
1226 DEFINE_PROP_BIT64("scsi", VirtIOBlock, host_features,
1227 VIRTIO_BLK_F_SCSI, false),
1228 #endif
1229 DEFINE_PROP_BIT("request-merging", VirtIOBlock, conf.request_merging, 0,
1230 true),
1231 DEFINE_PROP_UINT16("num-queues", VirtIOBlock, conf.num_queues, 1),
1232 DEFINE_PROP_UINT16("queue-size", VirtIOBlock, conf.queue_size, 128),
1233 DEFINE_PROP_LINK("iothread", VirtIOBlock, conf.iothread, TYPE_IOTHREAD,
1234 IOThread *),
1235 DEFINE_PROP_BIT64("discard", VirtIOBlock, host_features,
1236 VIRTIO_BLK_F_DISCARD, true),
1237 DEFINE_PROP_BIT64("write-zeroes", VirtIOBlock, host_features,
1238 VIRTIO_BLK_F_WRITE_ZEROES, true),
1239 DEFINE_PROP_UINT32("max-discard-sectors", VirtIOBlock,
1240 conf.max_discard_sectors, BDRV_REQUEST_MAX_SECTORS),
1241 DEFINE_PROP_UINT32("max-write-zeroes-sectors", VirtIOBlock,
1242 conf.max_write_zeroes_sectors, BDRV_REQUEST_MAX_SECTORS),
1243 DEFINE_PROP_END_OF_LIST(),
1246 static void virtio_blk_class_init(ObjectClass *klass, void *data)
1248 DeviceClass *dc = DEVICE_CLASS(klass);
1249 VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1251 dc->props = virtio_blk_properties;
1252 dc->vmsd = &vmstate_virtio_blk;
1253 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1254 vdc->realize = virtio_blk_device_realize;
1255 vdc->unrealize = virtio_blk_device_unrealize;
1256 vdc->get_config = virtio_blk_update_config;
1257 vdc->set_config = virtio_blk_set_config;
1258 vdc->get_features = virtio_blk_get_features;
1259 vdc->set_status = virtio_blk_set_status;
1260 vdc->reset = virtio_blk_reset;
1261 vdc->save = virtio_blk_save_device;
1262 vdc->load = virtio_blk_load_device;
1263 vdc->start_ioeventfd = virtio_blk_data_plane_start;
1264 vdc->stop_ioeventfd = virtio_blk_data_plane_stop;
1267 static const TypeInfo virtio_blk_info = {
1268 .name = TYPE_VIRTIO_BLK,
1269 .parent = TYPE_VIRTIO_DEVICE,
1270 .instance_size = sizeof(VirtIOBlock),
1271 .instance_init = virtio_blk_instance_init,
1272 .class_init = virtio_blk_class_init,
1275 static void virtio_register_types(void)
1277 type_register_static(&virtio_blk_info);
1280 type_init(virtio_register_types)