]> git.proxmox.com Git - mirror_qemu.git/blame - hw/block/virtio-blk.c
hw: fix using 4.2 compat in 5.0 machine types for i440fx/q35
[mirror_qemu.git] / hw / block / virtio-blk.c
CommitLineData
6e02c38d
AL
1/*
2 * Virtio Block Device
3 *
4 * Copyright IBM, Corp. 2007
5 *
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
11 *
12 */
13
80c71a24 14#include "qemu/osdep.h"
da34e65c 15#include "qapi/error.h"
827805a2 16#include "qemu/iov.h"
0b8fa32f 17#include "qemu/module.h"
1de7afc9 18#include "qemu/error-report.h"
9b92fbcf 19#include "qemu/main-loop.h"
6d519a5f 20#include "trace.h"
0d09e41a 21#include "hw/block/block.h"
a27bd6c7 22#include "hw/qdev-properties.h"
9c17d615 23#include "sysemu/blockdev.h"
2f780b6a 24#include "sysemu/sysemu.h"
54d31236 25#include "sysemu/runstate.h"
0d09e41a 26#include "hw/virtio/virtio-blk.h"
52b53c04 27#include "dataplane/virtio-blk.h"
08e2c9f1 28#include "scsi/constants.h"
1063b8b1
CH
29#ifdef __linux__
30# include <scsi/sg.h>
31#endif
0d09e41a 32#include "hw/virtio/virtio-bus.h"
ca77ee28 33#include "migration/qemu-file-types.h"
783d1897 34#include "hw/virtio/virtio-access.h"
6e02c38d 35
20764be0 36/* Config size before the discard support (hide associated config fields) */
42824b4d
CL
37#define VIRTIO_BLK_CFG_SIZE offsetof(struct virtio_blk_config, \
38 max_discard_sectors)
20764be0
SG
39/*
40 * Starting from the discard feature, we can use this array to properly
41 * set the config size depending on the features enabled.
42 */
43static VirtIOFeature feature_sizes[] = {
44 {.flags = 1ULL << VIRTIO_BLK_F_DISCARD,
5d5b33c0 45 .end = endof(struct virtio_blk_config, discard_sector_alignment)},
20764be0 46 {.flags = 1ULL << VIRTIO_BLK_F_WRITE_ZEROES,
5d5b33c0 47 .end = endof(struct virtio_blk_config, write_zeroes_may_unmap)},
20764be0
SG
48 {}
49};
50
51static void virtio_blk_set_config_size(VirtIOBlock *s, uint64_t host_features)
52{
53 s->config_size = MAX(VIRTIO_BLK_CFG_SIZE,
54 virtio_feature_get_config_size(feature_sizes, host_features));
55
56 assert(s->config_size <= sizeof(struct virtio_blk_config));
57}
42824b4d 58
d14dde5e
GK
59static void virtio_blk_init_request(VirtIOBlock *s, VirtQueue *vq,
60 VirtIOBlockReq *req)
671ec3f0 61{
671ec3f0 62 req->dev = s;
edaffd9f 63 req->vq = vq;
869d66af 64 req->qiov.size = 0;
2a6cdd6d 65 req->in_len = 0;
869d66af 66 req->next = NULL;
95f7142a 67 req->mr_next = NULL;
671ec3f0
FZ
68}
69
d14dde5e 70static void virtio_blk_free_request(VirtIOBlockReq *req)
671ec3f0 71{
1d29b5b0 72 g_free(req);
671ec3f0
FZ
73}
74
03de2f52 75static void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
869a5c6d
AL
76{
77 VirtIOBlock *s = req->dev;
1cc91b7d 78 VirtIODevice *vdev = VIRTIO_DEVICE(s);
869a5c6d 79
a576ceac 80 trace_virtio_blk_req_complete(vdev, req, status);
6d519a5f 81
92e3c2a3 82 stb_p(&req->in->status, status);
edaffd9f 83 virtqueue_push(req->vq, &req->elem, req->in_len);
eb41cf78 84 if (s->dataplane_started && !s->dataplane_disabled) {
edaffd9f 85 virtio_blk_data_plane_notify(s->dataplane, req->vq);
03de2f52 86 } else {
edaffd9f 87 virtio_notify(vdev, req->vq);
03de2f52 88 }
bf4bd461
FZ
89}
90
f35d68f0 91static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
00f639fb 92 bool is_read, bool acct_failed)
869a5c6d 93{
869a5c6d 94 VirtIOBlock *s = req->dev;
9a6719d5 95 BlockErrorAction action = blk_get_error_action(s->blk, is_read, error);
869a5c6d 96
a589569f 97 if (action == BLOCK_ERROR_ACTION_STOP) {
466138dc
FZ
98 /* Break the link as the next request is going to be parsed from the
99 * ring again. Otherwise we may end up doing a double completion! */
100 req->mr_next = NULL;
869a5c6d
AL
101 req->next = s->rq;
102 s->rq = req;
a589569f 103 } else if (action == BLOCK_ERROR_ACTION_REPORT) {
869a5c6d 104 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
00f639fb
SG
105 if (acct_failed) {
106 block_acct_failed(blk_get_stats(s->blk), &req->acct);
107 }
671ec3f0 108 virtio_blk_free_request(req);
869a5c6d
AL
109 }
110
4be74634 111 blk_error_action(s->blk, action, is_read, error);
a589569f 112 return action != BLOCK_ERROR_ACTION_IGNORE;
869a5c6d
AL
113}
114
6e02c38d
AL
115static void virtio_blk_rw_complete(void *opaque, int ret)
116{
95f7142a 117 VirtIOBlockReq *next = opaque;
b9e413dd 118 VirtIOBlock *s = next->dev;
a576ceac 119 VirtIODevice *vdev = VIRTIO_DEVICE(s);
95f7142a 120
b9e413dd 121 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
95f7142a
PL
122 while (next) {
123 VirtIOBlockReq *req = next;
124 next = req->mr_next;
a576ceac 125 trace_virtio_blk_rw_complete(vdev, req, ret);
95f7142a
PL
126
127 if (req->qiov.nalloc != -1) {
e61809ed 128 /* If nalloc is != -1 req->qiov is a local copy of the original
9bb192a4
YB
129 * external iovec. It was allocated in submit_requests to be
130 * able to merge requests. */
95f7142a
PL
131 qemu_iovec_destroy(&req->qiov);
132 }
6e02c38d 133
95f7142a 134 if (ret) {
bf4069fb 135 int p = virtio_ldl_p(VIRTIO_DEVICE(s), &req->out.type);
95f7142a 136 bool is_read = !(p & VIRTIO_BLK_T_OUT);
2a6cdd6d
PB
137 /* Note that memory may be dirtied on read failure. If the
138 * virtio request is not completed here, as is the case for
139 * BLOCK_ERROR_ACTION_STOP, the memory may not be copied
140 * correctly during live migration. While this is ugly,
141 * it is acceptable because the device is free to write to
142 * the memory until the request is completed (which will
143 * happen on the other side of the migration).
144 */
00f639fb 145 if (virtio_blk_handle_rw_error(req, -ret, is_read, true)) {
95f7142a
PL
146 continue;
147 }
148 }
6d519a5f 149
95f7142a 150 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
bf4069fb 151 block_acct_done(blk_get_stats(s->blk), &req->acct);
95f7142a 152 virtio_blk_free_request(req);
6e02c38d 153 }
b9e413dd 154 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
869a5c6d 155}
6e02c38d 156
aa659be3
CH
157static void virtio_blk_flush_complete(void *opaque, int ret)
158{
159 VirtIOBlockReq *req = opaque;
b9e413dd 160 VirtIOBlock *s = req->dev;
aa659be3 161
b9e413dd 162 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
8c269b54 163 if (ret) {
00f639fb 164 if (virtio_blk_handle_rw_error(req, -ret, 0, true)) {
b9e413dd 165 goto out;
8c269b54
KW
166 }
167 }
168
169 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
9a6719d5 170 block_acct_done(blk_get_stats(s->blk), &req->acct);
671ec3f0 171 virtio_blk_free_request(req);
b9e413dd
PB
172
173out:
174 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
6e02c38d
AL
175}
176
37b06f8d
SG
177static void virtio_blk_discard_write_zeroes_complete(void *opaque, int ret)
178{
179 VirtIOBlockReq *req = opaque;
180 VirtIOBlock *s = req->dev;
181 bool is_write_zeroes = (virtio_ldl_p(VIRTIO_DEVICE(s), &req->out.type) &
182 ~VIRTIO_BLK_T_BARRIER) == VIRTIO_BLK_T_WRITE_ZEROES;
183
184 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
185 if (ret) {
186 if (virtio_blk_handle_rw_error(req, -ret, false, is_write_zeroes)) {
187 goto out;
188 }
189 }
190
191 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
192 if (is_write_zeroes) {
193 block_acct_done(blk_get_stats(s->blk), &req->acct);
194 }
195 virtio_blk_free_request(req);
196
197out:
198 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
199}
200
1dc936aa
FZ
201#ifdef __linux__
202
203typedef struct {
204 VirtIOBlockReq *req;
205 struct sg_io_hdr hdr;
206} VirtIOBlockIoctlReq;
207
208static void virtio_blk_ioctl_complete(void *opaque, int status)
209{
210 VirtIOBlockIoctlReq *ioctl_req = opaque;
211 VirtIOBlockReq *req = ioctl_req->req;
9d456654
PB
212 VirtIOBlock *s = req->dev;
213 VirtIODevice *vdev = VIRTIO_DEVICE(s);
1dc936aa
FZ
214 struct virtio_scsi_inhdr *scsi;
215 struct sg_io_hdr *hdr;
216
217 scsi = (void *)req->elem.in_sg[req->elem.in_num - 2].iov_base;
218
219 if (status) {
220 status = VIRTIO_BLK_S_UNSUPP;
221 virtio_stl_p(vdev, &scsi->errors, 255);
222 goto out;
223 }
224
225 hdr = &ioctl_req->hdr;
226 /*
227 * From SCSI-Generic-HOWTO: "Some lower level drivers (e.g. ide-scsi)
228 * clear the masked_status field [hence status gets cleared too, see
229 * block/scsi_ioctl.c] even when a CHECK_CONDITION or COMMAND_TERMINATED
230 * status has occurred. However they do set DRIVER_SENSE in driver_status
231 * field. Also a (sb_len_wr > 0) indicates there is a sense buffer.
232 */
233 if (hdr->status == 0 && hdr->sb_len_wr > 0) {
234 hdr->status = CHECK_CONDITION;
235 }
236
237 virtio_stl_p(vdev, &scsi->errors,
238 hdr->status | (hdr->msg_status << 8) |
239 (hdr->host_status << 16) | (hdr->driver_status << 24));
240 virtio_stl_p(vdev, &scsi->residual, hdr->resid);
241 virtio_stl_p(vdev, &scsi->sense_len, hdr->sb_len_wr);
242 virtio_stl_p(vdev, &scsi->data_len, hdr->dxfer_len);
243
244out:
b9e413dd 245 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
1dc936aa
FZ
246 virtio_blk_req_complete(req, status);
247 virtio_blk_free_request(req);
b9e413dd 248 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
1dc936aa
FZ
249 g_free(ioctl_req);
250}
251
252#endif
253
edaffd9f 254static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s, VirtQueue *vq)
6e02c38d 255{
edaffd9f 256 VirtIOBlockReq *req = virtqueue_pop(vq, sizeof(VirtIOBlockReq));
6e02c38d 257
51b19ebe 258 if (req) {
edaffd9f 259 virtio_blk_init_request(s, vq, req);
6e02c38d 260 }
6e02c38d
AL
261 return req;
262}
263
75344fa4 264static int virtio_blk_handle_scsi_req(VirtIOBlockReq *req)
1063b8b1 265{
5a05cbee
FZ
266 int status = VIRTIO_BLK_S_OK;
267 struct virtio_scsi_inhdr *scsi = NULL;
75344fa4 268 VirtIOBlock *blk = req->dev;
bf4069fb
AR
269 VirtIODevice *vdev = VIRTIO_DEVICE(blk);
270 VirtQueueElement *elem = &req->elem;
783d1897 271
47ce9ef7 272#ifdef __linux__
1063b8b1 273 int i;
1dc936aa 274 VirtIOBlockIoctlReq *ioctl_req;
a209f461 275 BlockAIOCB *acb;
47ce9ef7 276#endif
1063b8b1
CH
277
278 /*
279 * We require at least one output segment each for the virtio_blk_outhdr
280 * and the SCSI command block.
281 *
282 * We also at least require the virtio_blk_inhdr, the virtio_scsi_inhdr
283 * and the sense buffer pointer in the input segments.
284 */
5a05cbee
FZ
285 if (elem->out_num < 2 || elem->in_num < 3) {
286 status = VIRTIO_BLK_S_IOERR;
287 goto fail;
1063b8b1
CH
288 }
289
290 /*
f34e73cd
PB
291 * The scsi inhdr is placed in the second-to-last input segment, just
292 * before the regular inhdr.
1063b8b1 293 */
5a05cbee 294 scsi = (void *)elem->in_sg[elem->in_num - 2].iov_base;
f34e73cd 295
bbe8bd4d 296 if (!virtio_has_feature(blk->host_features, VIRTIO_BLK_F_SCSI)) {
f34e73cd
PB
297 status = VIRTIO_BLK_S_UNSUPP;
298 goto fail;
1063b8b1
CH
299 }
300
301 /*
f34e73cd 302 * No support for bidirection commands yet.
1063b8b1 303 */
5a05cbee 304 if (elem->out_num > 2 && elem->in_num > 3) {
f34e73cd
PB
305 status = VIRTIO_BLK_S_UNSUPP;
306 goto fail;
307 }
1063b8b1 308
f34e73cd 309#ifdef __linux__
1dc936aa
FZ
310 ioctl_req = g_new0(VirtIOBlockIoctlReq, 1);
311 ioctl_req->req = req;
312 ioctl_req->hdr.interface_id = 'S';
313 ioctl_req->hdr.cmd_len = elem->out_sg[1].iov_len;
314 ioctl_req->hdr.cmdp = elem->out_sg[1].iov_base;
315 ioctl_req->hdr.dxfer_len = 0;
1063b8b1 316
5a05cbee 317 if (elem->out_num > 2) {
1063b8b1
CH
318 /*
319 * If there are more than the minimally required 2 output segments
320 * there is write payload starting from the third iovec.
321 */
1dc936aa
FZ
322 ioctl_req->hdr.dxfer_direction = SG_DXFER_TO_DEV;
323 ioctl_req->hdr.iovec_count = elem->out_num - 2;
1063b8b1 324
1dc936aa
FZ
325 for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
326 ioctl_req->hdr.dxfer_len += elem->out_sg[i + 2].iov_len;
327 }
1063b8b1 328
1dc936aa 329 ioctl_req->hdr.dxferp = elem->out_sg + 2;
1063b8b1 330
5a05cbee 331 } else if (elem->in_num > 3) {
1063b8b1
CH
332 /*
333 * If we have more than 3 input segments the guest wants to actually
334 * read data.
335 */
1dc936aa
FZ
336 ioctl_req->hdr.dxfer_direction = SG_DXFER_FROM_DEV;
337 ioctl_req->hdr.iovec_count = elem->in_num - 3;
338 for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
339 ioctl_req->hdr.dxfer_len += elem->in_sg[i].iov_len;
340 }
1063b8b1 341
1dc936aa 342 ioctl_req->hdr.dxferp = elem->in_sg;
1063b8b1
CH
343 } else {
344 /*
345 * Some SCSI commands don't actually transfer any data.
346 */
1dc936aa 347 ioctl_req->hdr.dxfer_direction = SG_DXFER_NONE;
1063b8b1
CH
348 }
349
1dc936aa
FZ
350 ioctl_req->hdr.sbp = elem->in_sg[elem->in_num - 3].iov_base;
351 ioctl_req->hdr.mx_sb_len = elem->in_sg[elem->in_num - 3].iov_len;
1063b8b1 352
a209f461
FZ
353 acb = blk_aio_ioctl(blk->blk, SG_IO, &ioctl_req->hdr,
354 virtio_blk_ioctl_complete, ioctl_req);
355 if (!acb) {
356 g_free(ioctl_req);
357 status = VIRTIO_BLK_S_UNSUPP;
358 goto fail;
359 }
1dc936aa 360 return -EINPROGRESS;
1063b8b1 361#else
f34e73cd
PB
362 abort();
363#endif
364
365fail:
366 /* Just put anything nonzero so that the ioctl fails in the guest. */
5a05cbee 367 if (scsi) {
783d1897 368 virtio_stl_p(vdev, &scsi->errors, 255);
5a05cbee
FZ
369 }
370 return status;
371}
372
373static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
374{
375 int status;
376
75344fa4 377 status = virtio_blk_handle_scsi_req(req);
1dc936aa
FZ
378 if (status != -EINPROGRESS) {
379 virtio_blk_req_complete(req, status);
380 virtio_blk_free_request(req);
381 }
1063b8b1 382}
1063b8b1 383
95f7142a
PL
384static inline void submit_requests(BlockBackend *blk, MultiReqBuffer *mrb,
385 int start, int num_reqs, int niov)
869a5c6d 386{
95f7142a
PL
387 QEMUIOVector *qiov = &mrb->reqs[start]->qiov;
388 int64_t sector_num = mrb->reqs[start]->sector_num;
95f7142a
PL
389 bool is_write = mrb->is_write;
390
391 if (num_reqs > 1) {
392 int i;
393 struct iovec *tmp_iov = qiov->iov;
394 int tmp_niov = qiov->niov;
395
396 /* mrb->reqs[start]->qiov was initialized from external so we can't
b5772fdd 397 * modify it here. We need to initialize it locally and then add the
95f7142a
PL
398 * external iovecs. */
399 qemu_iovec_init(qiov, niov);
400
401 for (i = 0; i < tmp_niov; i++) {
402 qemu_iovec_add(qiov, tmp_iov[i].iov_base, tmp_iov[i].iov_len);
403 }
404
405 for (i = start + 1; i < start + num_reqs; i++) {
406 qemu_iovec_concat(qiov, &mrb->reqs[i]->qiov, 0,
407 mrb->reqs[i]->qiov.size);
408 mrb->reqs[i - 1]->mr_next = mrb->reqs[i];
95f7142a 409 }
95f7142a 410
a576ceac
SH
411 trace_virtio_blk_submit_multireq(VIRTIO_DEVICE(mrb->reqs[start]->dev),
412 mrb, start, num_reqs,
b5772fdd
EB
413 sector_num << BDRV_SECTOR_BITS,
414 qiov->size, is_write);
95f7142a
PL
415 block_acct_merge_done(blk_get_stats(blk),
416 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ,
417 num_reqs - 1);
418 }
91553dcc 419
95f7142a 420 if (is_write) {
b5772fdd
EB
421 blk_aio_pwritev(blk, sector_num << BDRV_SECTOR_BITS, qiov, 0,
422 virtio_blk_rw_complete, mrb->reqs[start]);
95f7142a 423 } else {
b5772fdd
EB
424 blk_aio_preadv(blk, sector_num << BDRV_SECTOR_BITS, qiov, 0,
425 virtio_blk_rw_complete, mrb->reqs[start]);
95f7142a
PL
426 }
427}
428
429static int multireq_compare(const void *a, const void *b)
430{
431 const VirtIOBlockReq *req1 = *(VirtIOBlockReq **)a,
432 *req2 = *(VirtIOBlockReq **)b;
433
434 /*
435 * Note that we can't simply subtract sector_num1 from sector_num2
436 * here as that could overflow the return value.
437 */
438 if (req1->sector_num > req2->sector_num) {
439 return 1;
440 } else if (req1->sector_num < req2->sector_num) {
441 return -1;
442 } else {
443 return 0;
444 }
445}
446
d14dde5e 447static void virtio_blk_submit_multireq(BlockBackend *blk, MultiReqBuffer *mrb)
95f7142a
PL
448{
449 int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
5def6b80 450 uint32_t max_transfer;
95f7142a
PL
451 int64_t sector_num = 0;
452
453 if (mrb->num_reqs == 1) {
454 submit_requests(blk, mrb, 0, 1, -1);
455 mrb->num_reqs = 0;
c20fd872
CH
456 return;
457 }
458
5def6b80 459 max_transfer = blk_get_max_transfer(mrb->reqs[0]->dev->blk);
95f7142a
PL
460
461 qsort(mrb->reqs, mrb->num_reqs, sizeof(*mrb->reqs),
462 &multireq_compare);
463
464 for (i = 0; i < mrb->num_reqs; i++) {
465 VirtIOBlockReq *req = mrb->reqs[i];
466 if (num_reqs > 0) {
49cffbc6
GA
467 /*
468 * NOTE: We cannot merge the requests in below situations:
469 * 1. requests are not sequential
470 * 2. merge would exceed maximum number of IOVs
471 * 3. merge would exceed maximum transfer length of backend device
472 */
473 if (sector_num + nb_sectors != req->sector_num ||
222565f6 474 niov > blk_get_max_iov(blk) - req->qiov.niov ||
5def6b80
EB
475 req->qiov.size > max_transfer ||
476 nb_sectors > (max_transfer -
477 req->qiov.size) / BDRV_SECTOR_SIZE) {
95f7142a
PL
478 submit_requests(blk, mrb, start, num_reqs, niov);
479 num_reqs = 0;
91553dcc
KW
480 }
481 }
95f7142a
PL
482
483 if (num_reqs == 0) {
484 sector_num = req->sector_num;
485 nb_sectors = niov = 0;
486 start = i;
487 }
488
489 nb_sectors += req->qiov.size / BDRV_SECTOR_SIZE;
490 niov += req->qiov.niov;
491 num_reqs++;
91553dcc 492 }
c20fd872 493
95f7142a
PL
494 submit_requests(blk, mrb, start, num_reqs, niov);
495 mrb->num_reqs = 0;
91553dcc 496}
87b245db 497
c20fd872 498static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
aa659be3 499{
bf4069fb
AR
500 VirtIOBlock *s = req->dev;
501
502 block_acct_start(blk_get_stats(s->blk), &req->acct, 0,
5366d0c8 503 BLOCK_ACCT_FLUSH);
a597e79c 504
618fbb84
CH
505 /*
506 * Make sure all outstanding writes are posted to the backing device.
507 */
95f7142a 508 if (mrb->is_write && mrb->num_reqs > 0) {
bf4069fb 509 virtio_blk_submit_multireq(s->blk, mrb);
95f7142a 510 }
bf4069fb 511 blk_aio_flush(s->blk, virtio_blk_flush_complete, req);
aa659be3
CH
512}
513
d0e14376
MA
514static bool virtio_blk_sect_range_ok(VirtIOBlock *dev,
515 uint64_t sector, size_t size)
516{
3c2daac0
MA
517 uint64_t nb_sectors = size >> BDRV_SECTOR_BITS;
518 uint64_t total_sectors;
519
75af1f34 520 if (nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
95f7142a
PL
521 return false;
522 }
d0e14376
MA
523 if (sector & dev->sector_mask) {
524 return false;
525 }
2a30307f 526 if (size % dev->conf.conf.logical_block_size) {
d0e14376
MA
527 return false;
528 }
4be74634 529 blk_get_geometry(dev->blk, &total_sectors);
3c2daac0
MA
530 if (sector > total_sectors || nb_sectors > total_sectors - sector) {
531 return false;
532 }
d0e14376
MA
533 return true;
534}
535
37b06f8d
SG
536static uint8_t virtio_blk_handle_discard_write_zeroes(VirtIOBlockReq *req,
537 struct virtio_blk_discard_write_zeroes *dwz_hdr, bool is_write_zeroes)
538{
539 VirtIOBlock *s = req->dev;
540 VirtIODevice *vdev = VIRTIO_DEVICE(s);
541 uint64_t sector;
542 uint32_t num_sectors, flags, max_sectors;
543 uint8_t err_status;
544 int bytes;
545
546 sector = virtio_ldq_p(vdev, &dwz_hdr->sector);
547 num_sectors = virtio_ldl_p(vdev, &dwz_hdr->num_sectors);
548 flags = virtio_ldl_p(vdev, &dwz_hdr->flags);
549 max_sectors = is_write_zeroes ? s->conf.max_write_zeroes_sectors :
550 s->conf.max_discard_sectors;
551
552 /*
553 * max_sectors is at most BDRV_REQUEST_MAX_SECTORS, this check
554 * make us sure that "num_sectors << BDRV_SECTOR_BITS" can fit in
555 * the integer variable.
556 */
557 if (unlikely(num_sectors > max_sectors)) {
558 err_status = VIRTIO_BLK_S_IOERR;
559 goto err;
560 }
561
562 bytes = num_sectors << BDRV_SECTOR_BITS;
563
564 if (unlikely(!virtio_blk_sect_range_ok(s, sector, bytes))) {
565 err_status = VIRTIO_BLK_S_IOERR;
566 goto err;
567 }
568
569 /*
570 * The device MUST set the status byte to VIRTIO_BLK_S_UNSUPP for discard
571 * and write zeroes commands if any unknown flag is set.
572 */
573 if (unlikely(flags & ~VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP)) {
574 err_status = VIRTIO_BLK_S_UNSUPP;
575 goto err;
576 }
577
578 if (is_write_zeroes) { /* VIRTIO_BLK_T_WRITE_ZEROES */
579 int blk_aio_flags = 0;
580
581 if (flags & VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP) {
582 blk_aio_flags |= BDRV_REQ_MAY_UNMAP;
583 }
584
585 block_acct_start(blk_get_stats(s->blk), &req->acct, bytes,
586 BLOCK_ACCT_WRITE);
587
588 blk_aio_pwrite_zeroes(s->blk, sector << BDRV_SECTOR_BITS,
589 bytes, blk_aio_flags,
590 virtio_blk_discard_write_zeroes_complete, req);
591 } else { /* VIRTIO_BLK_T_DISCARD */
592 /*
593 * The device MUST set the status byte to VIRTIO_BLK_S_UNSUPP for
594 * discard commands if the unmap flag is set.
595 */
596 if (unlikely(flags & VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP)) {
597 err_status = VIRTIO_BLK_S_UNSUPP;
598 goto err;
599 }
600
601 blk_aio_pdiscard(s->blk, sector << BDRV_SECTOR_BITS, bytes,
602 virtio_blk_discard_write_zeroes_complete, req);
603 }
604
605 return VIRTIO_BLK_S_OK;
606
607err:
608 if (is_write_zeroes) {
609 block_acct_invalid(blk_get_stats(s->blk), BLOCK_ACCT_WRITE);
610 }
611 return err_status;
612}
613
20ea686a 614static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
bc6694d4 615{
92e3c2a3 616 uint32_t type;
f897bf75 617 struct iovec *in_iov = req->elem.in_sg;
5636da76 618 struct iovec *out_iov = req->elem.out_sg;
f897bf75
SH
619 unsigned in_num = req->elem.in_num;
620 unsigned out_num = req->elem.out_num;
20ea686a
GK
621 VirtIOBlock *s = req->dev;
622 VirtIODevice *vdev = VIRTIO_DEVICE(s);
92e3c2a3 623
f897bf75 624 if (req->elem.out_num < 1 || req->elem.in_num < 1) {
20ea686a
GK
625 virtio_error(vdev, "virtio-blk missing headers");
626 return -1;
bc6694d4
KW
627 }
628
5636da76 629 if (unlikely(iov_to_buf(out_iov, out_num, 0, &req->out,
827805a2 630 sizeof(req->out)) != sizeof(req->out))) {
20ea686a
GK
631 virtio_error(vdev, "virtio-blk request outhdr too short");
632 return -1;
827805a2 633 }
ee17e848 634
5636da76 635 iov_discard_front(&out_iov, &out_num, sizeof(req->out));
ee17e848 636
12048545 637 if (in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {
20ea686a
GK
638 virtio_error(vdev, "virtio-blk request inhdr too short");
639 return -1;
ee17e848
FZ
640 }
641
2a6cdd6d
PB
642 /* We always touch the last byte, so just see how big in_iov is. */
643 req->in_len = iov_size(in_iov, in_num);
ee17e848
FZ
644 req->in = (void *)in_iov[in_num - 1].iov_base
645 + in_iov[in_num - 1].iov_len
646 - sizeof(struct virtio_blk_inhdr);
647 iov_discard_back(in_iov, &in_num, sizeof(struct virtio_blk_inhdr));
bc6694d4 648
9a6719d5 649 type = virtio_ldl_p(vdev, &req->out.type);
92e3c2a3 650
95f7142a 651 /* VIRTIO_BLK_T_OUT defines the command direction. VIRTIO_BLK_T_BARRIER
631b22ea 652 * is an optional flag. Although a guest should not send this flag if
95f7142a
PL
653 * not negotiated we ignored it in the past. So keep ignoring it. */
654 switch (type & ~(VIRTIO_BLK_T_OUT | VIRTIO_BLK_T_BARRIER)) {
655 case VIRTIO_BLK_T_IN:
656 {
657 bool is_write = type & VIRTIO_BLK_T_OUT;
9a6719d5 658 req->sector_num = virtio_ldq_p(vdev, &req->out.sector);
95f7142a
PL
659
660 if (is_write) {
5636da76 661 qemu_iovec_init_external(&req->qiov, out_iov, out_num);
a576ceac 662 trace_virtio_blk_handle_write(vdev, req, req->sector_num,
95f7142a
PL
663 req->qiov.size / BDRV_SECTOR_SIZE);
664 } else {
665 qemu_iovec_init_external(&req->qiov, in_iov, in_num);
a576ceac 666 trace_virtio_blk_handle_read(vdev, req, req->sector_num,
95f7142a
PL
667 req->qiov.size / BDRV_SECTOR_SIZE);
668 }
669
9a6719d5 670 if (!virtio_blk_sect_range_ok(s, req->sector_num, req->qiov.size)) {
95f7142a 671 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
9a6719d5 672 block_acct_invalid(blk_get_stats(s->blk),
01762e03 673 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
95f7142a 674 virtio_blk_free_request(req);
20ea686a 675 return 0;
95f7142a
PL
676 }
677
9a6719d5 678 block_acct_start(blk_get_stats(s->blk), &req->acct, req->qiov.size,
95f7142a
PL
679 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
680
681 /* merge would exceed maximum number of requests or IO direction
682 * changes */
683 if (mrb->num_reqs > 0 && (mrb->num_reqs == VIRTIO_BLK_MAX_MERGE_REQS ||
c99495ac 684 is_write != mrb->is_write ||
9a6719d5
SG
685 !s->conf.request_merging)) {
686 virtio_blk_submit_multireq(s->blk, mrb);
95f7142a
PL
687 }
688
689 assert(mrb->num_reqs < VIRTIO_BLK_MAX_MERGE_REQS);
690 mrb->reqs[mrb->num_reqs++] = req;
691 mrb->is_write = is_write;
692 break;
693 }
694 case VIRTIO_BLK_T_FLUSH:
c20fd872 695 virtio_blk_handle_flush(req, mrb);
95f7142a
PL
696 break;
697 case VIRTIO_BLK_T_SCSI_CMD:
bc6694d4 698 virtio_blk_handle_scsi(req);
95f7142a
PL
699 break;
700 case VIRTIO_BLK_T_GET_ID:
701 {
a8686a9b
MA
702 /*
703 * NB: per existing s/n string convention the string is
704 * terminated by '\0' only when shorter than buffer.
705 */
2a30307f 706 const char *serial = s->conf.serial ? s->conf.serial : "";
a83ceea8
MM
707 size_t size = MIN(strlen(serial) + 1,
708 MIN(iov_size(in_iov, in_num),
709 VIRTIO_BLK_ID_BYTES));
710 iov_from_buf(in_iov, in_num, 0, serial, size);
2930b313 711 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
671ec3f0 712 virtio_blk_free_request(req);
95f7142a
PL
713 break;
714 }
37b06f8d
SG
715 /*
716 * VIRTIO_BLK_T_DISCARD and VIRTIO_BLK_T_WRITE_ZEROES are defined with
717 * VIRTIO_BLK_T_OUT flag set. We masked this flag in the switch statement,
718 * so we must mask it for these requests, then we will check if it is set.
719 */
720 case VIRTIO_BLK_T_DISCARD & ~VIRTIO_BLK_T_OUT:
721 case VIRTIO_BLK_T_WRITE_ZEROES & ~VIRTIO_BLK_T_OUT:
722 {
723 struct virtio_blk_discard_write_zeroes dwz_hdr;
724 size_t out_len = iov_size(out_iov, out_num);
725 bool is_write_zeroes = (type & ~VIRTIO_BLK_T_BARRIER) ==
726 VIRTIO_BLK_T_WRITE_ZEROES;
727 uint8_t err_status;
728
729 /*
730 * Unsupported if VIRTIO_BLK_T_OUT is not set or the request contains
731 * more than one segment.
732 */
733 if (unlikely(!(type & VIRTIO_BLK_T_OUT) ||
734 out_len > sizeof(dwz_hdr))) {
735 virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
736 virtio_blk_free_request(req);
737 return 0;
738 }
739
740 if (unlikely(iov_to_buf(out_iov, out_num, 0, &dwz_hdr,
741 sizeof(dwz_hdr)) != sizeof(dwz_hdr))) {
742 virtio_error(vdev, "virtio-blk discard/write_zeroes header"
743 " too short");
744 return -1;
745 }
746
747 err_status = virtio_blk_handle_discard_write_zeroes(req, &dwz_hdr,
748 is_write_zeroes);
749 if (err_status != VIRTIO_BLK_S_OK) {
750 virtio_blk_req_complete(req, err_status);
751 virtio_blk_free_request(req);
752 }
753
754 break;
755 }
95f7142a 756 default:
9e72c450 757 virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
671ec3f0 758 virtio_blk_free_request(req);
bc6694d4 759 }
20ea686a 760 return 0;
bc6694d4
KW
761}
762
07931698 763bool virtio_blk_handle_vq(VirtIOBlock *s, VirtQueue *vq)
6e02c38d 764{
6e02c38d 765 VirtIOBlockReq *req;
95f7142a 766 MultiReqBuffer mrb = {};
d0435bc5 767 bool suppress_notifications = virtio_queue_get_notification(vq);
07931698 768 bool progress = false;
6e02c38d 769
9d456654 770 aio_context_acquire(blk_get_aio_context(s->blk));
fc73548e
SH
771 blk_io_plug(s->blk);
772
9ef9d402 773 do {
d0435bc5
SH
774 if (suppress_notifications) {
775 virtio_queue_set_notification(vq, 0);
776 }
9ef9d402
SH
777
778 while ((req = virtio_blk_get_request(s, vq))) {
07931698 779 progress = true;
9ef9d402
SH
780 if (virtio_blk_handle_request(req, &mrb)) {
781 virtqueue_detach_element(req->vq, &req->elem, 0);
782 virtio_blk_free_request(req);
783 break;
784 }
20ea686a 785 }
9ef9d402 786
d0435bc5
SH
787 if (suppress_notifications) {
788 virtio_queue_set_notification(vq, 1);
789 }
9ef9d402 790 } while (!virtio_queue_empty(vq));
91553dcc 791
95f7142a
PL
792 if (mrb.num_reqs) {
793 virtio_blk_submit_multireq(s->blk, &mrb);
794 }
fc73548e
SH
795
796 blk_io_unplug(s->blk);
9d456654 797 aio_context_release(blk_get_aio_context(s->blk));
07931698
FZ
798 return progress;
799}
800
801static void virtio_blk_handle_output_do(VirtIOBlock *s, VirtQueue *vq)
802{
803 virtio_blk_handle_vq(s, vq);
6e02c38d
AL
804}
805
8a2fad57
MT
806static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)
807{
808 VirtIOBlock *s = (VirtIOBlock *)vdev;
809
810 if (s->dataplane) {
811 /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start
812 * dataplane here instead of waiting for .set_status().
813 */
9ffe337c 814 virtio_device_start_ioeventfd(vdev);
8a2fad57
MT
815 if (!s->dataplane_disabled) {
816 return;
817 }
818 }
07931698 819 virtio_blk_handle_output_do(s, vq);
8a2fad57
MT
820}
821
213189ab 822static void virtio_blk_dma_restart_bh(void *opaque)
869a5c6d
AL
823{
824 VirtIOBlock *s = opaque;
825 VirtIOBlockReq *req = s->rq;
95f7142a 826 MultiReqBuffer mrb = {};
869a5c6d 827
213189ab
MA
828 qemu_bh_delete(s->bh);
829 s->bh = NULL;
869a5c6d
AL
830
831 s->rq = NULL;
832
1919631e 833 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
869a5c6d 834 while (req) {
1bdb176a 835 VirtIOBlockReq *next = req->next;
20ea686a
GK
836 if (virtio_blk_handle_request(req, &mrb)) {
837 /* Device is now broken and won't do any processing until it gets
838 * reset. Already queued requests will be lost: let's purge them.
839 */
840 while (req) {
841 next = req->next;
842 virtqueue_detach_element(req->vq, &req->elem, 0);
843 virtio_blk_free_request(req);
844 req = next;
845 }
846 break;
847 }
1bdb176a 848 req = next;
869a5c6d 849 }
f1b52868 850
95f7142a
PL
851 if (mrb.num_reqs) {
852 virtio_blk_submit_multireq(s->blk, &mrb);
853 }
680f2002 854 blk_dec_in_flight(s->conf.conf.blk);
1919631e 855 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
869a5c6d
AL
856}
857
1dfb4dd9
LC
858static void virtio_blk_dma_restart_cb(void *opaque, int running,
859 RunState state)
213189ab
MA
860{
861 VirtIOBlock *s = opaque;
862
392808b4 863 if (!running) {
213189ab 864 return;
392808b4 865 }
213189ab
MA
866
867 if (!s->bh) {
680f2002
KW
868 /* FIXME The data plane is not started yet, so these requests are
869 * processed in the main thread. */
4be74634 870 s->bh = aio_bh_new(blk_get_aio_context(s->conf.conf.blk),
4407c1c5 871 virtio_blk_dma_restart_bh, s);
680f2002 872 blk_inc_in_flight(s->conf.conf.blk);
213189ab
MA
873 qemu_bh_schedule(s->bh);
874 }
875}
876
6e02c38d
AL
877static void virtio_blk_reset(VirtIODevice *vdev)
878{
1cc91b7d 879 VirtIOBlock *s = VIRTIO_BLK(vdev);
6e40b3bf 880 AioContext *ctx;
26307f6a 881 VirtIOBlockReq *req;
392808b4 882
6e40b3bf
AY
883 ctx = blk_get_aio_context(s->blk);
884 aio_context_acquire(ctx);
885 blk_drain(s->blk);
886
26307f6a
FZ
887 /* We drop queued requests after blk_drain() because blk_drain() itself can
888 * produce them. */
889 while (s->rq) {
890 req = s->rq;
891 s->rq = req->next;
97b93c8a 892 virtqueue_detach_element(req->vq, &req->elem, 0);
26307f6a
FZ
893 virtio_blk_free_request(req);
894 }
895
6e40b3bf
AY
896 aio_context_release(ctx);
897
9ffe337c 898 assert(!s->dataplane_started);
4be74634 899 blk_set_enable_write_cache(s->blk, s->original_wce);
6e02c38d
AL
900}
901
bf011293 902/* coalesce internal state, copy to pci i/o region 0
903 */
6e02c38d
AL
904static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
905{
1cc91b7d 906 VirtIOBlock *s = VIRTIO_BLK(vdev);
2a30307f 907 BlockConf *conf = &s->conf.conf;
6e02c38d
AL
908 struct virtio_blk_config blkcfg;
909 uint64_t capacity;
17d0bc01 910 int64_t length;
f7516731 911 int blk_size = conf->logical_block_size;
6e02c38d 912
4be74634 913 blk_get_geometry(s->blk, &capacity);
5c5dafdc 914 memset(&blkcfg, 0, sizeof(blkcfg));
783d1897
RR
915 virtio_stq_p(vdev, &blkcfg.capacity, capacity);
916 virtio_stl_p(vdev, &blkcfg.seg_max, 128 - 2);
907eb3e5 917 virtio_stw_p(vdev, &blkcfg.geometry.cylinders, conf->cyls);
783d1897 918 virtio_stl_p(vdev, &blkcfg.blk_size, blk_size);
f7516731
MA
919 virtio_stw_p(vdev, &blkcfg.min_io_size, conf->min_io_size / blk_size);
920 virtio_stw_p(vdev, &blkcfg.opt_io_size, conf->opt_io_size / blk_size);
907eb3e5 921 blkcfg.geometry.heads = conf->heads;
136be99e
CB
922 /*
923 * We must ensure that the block device capacity is a multiple of
e03ba136 924 * the logical block size. If that is not the case, let's use
136be99e
CB
925 * sector_mask to adopt the geometry to have a correct picture.
926 * For those devices where the capacity is ok for the given geometry
e03ba136 927 * we don't touch the sector value of the geometry, since some devices
136be99e
CB
928 * (like s390 dasd) need a specific value. Here the capacity is already
929 * cyls*heads*secs*blk_size and the sector value is not block size
930 * divided by 512 - instead it is the amount of blk_size blocks
931 * per track (cylinder).
932 */
17d0bc01
SH
933 length = blk_getlength(s->blk);
934 if (length > 0 && length / conf->heads / conf->secs % blk_size) {
907eb3e5 935 blkcfg.geometry.sectors = conf->secs & ~s->sector_mask;
136be99e 936 } else {
907eb3e5 937 blkcfg.geometry.sectors = conf->secs;
136be99e 938 }
c7085da7 939 blkcfg.size_max = 0;
f7516731 940 blkcfg.physical_block_exp = get_physical_block_exp(conf);
9752c371 941 blkcfg.alignment_offset = 0;
4be74634 942 blkcfg.wce = blk_enable_write_cache(s->blk);
2f270590 943 virtio_stw_p(vdev, &blkcfg.num_queues, s->conf.num_queues);
37b06f8d
SG
944 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_DISCARD)) {
945 virtio_stl_p(vdev, &blkcfg.max_discard_sectors,
946 s->conf.max_discard_sectors);
947 virtio_stl_p(vdev, &blkcfg.discard_sector_alignment,
948 blk_size >> BDRV_SECTOR_BITS);
949 /*
950 * We support only one segment per request since multiple segments
951 * are not widely used and there are no userspace APIs that allow
952 * applications to submit multiple segments in a single call.
953 */
954 virtio_stl_p(vdev, &blkcfg.max_discard_seg, 1);
955 }
956 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_WRITE_ZEROES)) {
957 virtio_stl_p(vdev, &blkcfg.max_write_zeroes_sectors,
958 s->conf.max_write_zeroes_sectors);
959 blkcfg.write_zeroes_may_unmap = 1;
960 virtio_stl_p(vdev, &blkcfg.max_write_zeroes_seg, 1);
961 }
20764be0 962 memcpy(config, &blkcfg, s->config_size);
6e02c38d
AL
963}
964
13e3dce0
PB
965static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config)
966{
1cc91b7d 967 VirtIOBlock *s = VIRTIO_BLK(vdev);
13e3dce0
PB
968 struct virtio_blk_config blkcfg;
969
20764be0 970 memcpy(&blkcfg, config, s->config_size);
6d7e73d6 971
4be74634
MA
972 aio_context_acquire(blk_get_aio_context(s->blk));
973 blk_set_enable_write_cache(s->blk, blkcfg.wce != 0);
974 aio_context_release(blk_get_aio_context(s->blk));
13e3dce0
PB
975}
976
9d5b731d
JW
977static uint64_t virtio_blk_get_features(VirtIODevice *vdev, uint64_t features,
978 Error **errp)
6e02c38d 979{
1cc91b7d 980 VirtIOBlock *s = VIRTIO_BLK(vdev);
1063b8b1 981
bbe8bd4d
SG
982 /* Firstly sync all virtio-blk possible supported features */
983 features |= s->host_features;
984
0cd09c3a
CH
985 virtio_add_feature(&features, VIRTIO_BLK_F_SEG_MAX);
986 virtio_add_feature(&features, VIRTIO_BLK_F_GEOMETRY);
987 virtio_add_feature(&features, VIRTIO_BLK_F_TOPOLOGY);
988 virtio_add_feature(&features, VIRTIO_BLK_F_BLK_SIZE);
95129d6f 989 if (virtio_has_feature(features, VIRTIO_F_VERSION_1)) {
bbe8bd4d 990 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_SCSI)) {
efb8206c
JW
991 error_setg(errp, "Please set scsi=off for virtio-blk devices in order to use virtio 1.0");
992 return 0;
993 }
efb8206c 994 } else {
c9b11f97 995 virtio_clear_feature(&features, VIRTIO_F_ANY_LAYOUT);
efb8206c
JW
996 virtio_add_feature(&features, VIRTIO_BLK_F_SCSI);
997 }
aa659be3 998
5f258577
EY
999 if (blk_enable_write_cache(s->blk) ||
1000 (s->conf.x_enable_wce_if_config_wce &&
1001 virtio_has_feature(features, VIRTIO_BLK_F_CONFIG_WCE))) {
0cd09c3a 1002 virtio_add_feature(&features, VIRTIO_BLK_F_WCE);
4be74634
MA
1003 }
1004 if (blk_is_read_only(s->blk)) {
0cd09c3a 1005 virtio_add_feature(&features, VIRTIO_BLK_F_RO);
4be74634 1006 }
2f270590
SH
1007 if (s->conf.num_queues > 1) {
1008 virtio_add_feature(&features, VIRTIO_BLK_F_MQ);
1009 }
1063b8b1
CH
1010
1011 return features;
6e02c38d
AL
1012}
1013
9315cbfd
PB
1014static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)
1015{
1cc91b7d 1016 VirtIOBlock *s = VIRTIO_BLK(vdev);
9315cbfd 1017
9ffe337c
PB
1018 if (!(status & (VIRTIO_CONFIG_S_DRIVER | VIRTIO_CONFIG_S_DRIVER_OK))) {
1019 assert(!s->dataplane_started);
392808b4 1020 }
392808b4 1021
9315cbfd
PB
1022 if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
1023 return;
1024 }
1025
ef5bc962
PB
1026 /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send
1027 * cache flushes. Thus, the "auto writethrough" behavior is never
1028 * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.
1029 * Leaving it enabled would break the following sequence:
1030 *
1031 * Guest started with "-drive cache=writethrough"
1032 * Guest sets status to 0
1033 * Guest sets DRIVER bit in status field
1034 * Guest reads host features (WCE=0, CONFIG_WCE=1)
1035 * Guest writes guest features (WCE=0, CONFIG_WCE=1)
1036 * Guest writes 1 to the WCE configuration field (writeback mode)
1037 * Guest sets DRIVER_OK bit in status field
1038 *
4be74634 1039 * s->blk would erroneously be placed in writethrough mode.
ef5bc962 1040 */
95129d6f 1041 if (!virtio_vdev_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE)) {
4be74634
MA
1042 aio_context_acquire(blk_get_aio_context(s->blk));
1043 blk_set_enable_write_cache(s->blk,
95129d6f
CH
1044 virtio_vdev_has_feature(vdev,
1045 VIRTIO_BLK_F_WCE));
4be74634 1046 aio_context_release(blk_get_aio_context(s->blk));
ef5bc962 1047 }
9315cbfd
PB
1048}
1049
b2b295a7
GK
1050static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f)
1051{
1052 VirtIOBlock *s = VIRTIO_BLK(vdev);
1053 VirtIOBlockReq *req = s->rq;
1054
869a5c6d
AL
1055 while (req) {
1056 qemu_put_sbyte(f, 1);
30d8bf6d
SH
1057
1058 if (s->conf.num_queues > 1) {
1059 qemu_put_be32(f, virtio_get_queue_index(req->vq));
1060 }
1061
86044b24 1062 qemu_put_virtqueue_element(vdev, f, &req->elem);
869a5c6d
AL
1063 req = req->next;
1064 }
1065 qemu_put_sbyte(f, 0);
6e02c38d
AL
1066}
1067
b2b295a7
GK
1068static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f,
1069 int version_id)
1070{
1071 VirtIOBlock *s = VIRTIO_BLK(vdev);
2a633c46 1072
869a5c6d 1073 while (qemu_get_sbyte(f)) {
30d8bf6d
SH
1074 unsigned nvqs = s->conf.num_queues;
1075 unsigned vq_idx = 0;
ab281c17 1076 VirtIOBlockReq *req;
30d8bf6d
SH
1077
1078 if (nvqs > 1) {
1079 vq_idx = qemu_get_be32(f);
1080
1081 if (vq_idx >= nvqs) {
1082 error_report("Invalid virtqueue index in request list: %#x",
1083 vq_idx);
1084 return -EINVAL;
1085 }
1086 }
1087
8607f5c3 1088 req = qemu_get_virtqueue_element(vdev, f, sizeof(VirtIOBlockReq));
30d8bf6d 1089 virtio_blk_init_request(s, virtio_get_queue(vdev, vq_idx), req);
869a5c6d 1090 req->next = s->rq;
20a81e4d 1091 s->rq = req;
869a5c6d 1092 }
6e02c38d
AL
1093
1094 return 0;
1095}
1096
9b92fbcf
SL
1097static void virtio_resize_cb(void *opaque)
1098{
1099 VirtIODevice *vdev = opaque;
1100
1101 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1102 virtio_notify_config(vdev);
1103}
1104
145feb17 1105static void virtio_blk_resize(void *opaque)
e5051fc7 1106{
1cc91b7d 1107 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
e5051fc7 1108
9b92fbcf
SL
1109 /*
1110 * virtio_notify_config() needs to acquire the global mutex,
1111 * so it can't be called from an iothread. Instead, schedule
1112 * it to be run in the main context BH.
1113 */
1114 aio_bh_schedule_oneshot(qemu_get_aio_context(), virtio_resize_cb, vdev);
e5051fc7
CH
1115}
1116
0e49de52 1117static const BlockDevOps virtio_block_ops = {
145feb17 1118 .resize_cb = virtio_blk_resize,
0e49de52
MA
1119};
1120
75884afd 1121static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
1c028ddf 1122{
75884afd 1123 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
179b417e 1124 VirtIOBlock *s = VIRTIO_BLK(dev);
2a30307f 1125 VirtIOBlkConf *conf = &s->conf;
3ffeeef7 1126 Error *err = NULL;
2f270590 1127 unsigned i;
cf21e106 1128
4be74634 1129 if (!conf->conf.blk) {
75884afd
AF
1130 error_setg(errp, "drive property not set");
1131 return;
d75d25e3 1132 }
4be74634 1133 if (!blk_is_inserted(conf->conf.blk)) {
75884afd
AF
1134 error_setg(errp, "Device needs media, but drive is empty");
1135 return;
98f28ad7 1136 }
2f270590
SH
1137 if (!conf->num_queues) {
1138 error_setg(errp, "num-queues property must be larger than 0");
1139 return;
1140 }
6040aedd
MK
1141 if (!is_power_of_2(conf->queue_size) ||
1142 conf->queue_size > VIRTQUEUE_MAX_SIZE) {
1143 error_setg(errp, "invalid queue-size property (%" PRIu16 "), "
1144 "must be a power of 2 (max %d)",
1145 conf->queue_size, VIRTQUEUE_MAX_SIZE);
1146 return;
1147 }
d75d25e3 1148
ceff3e1f
MZ
1149 if (!blkconf_apply_backend_options(&conf->conf,
1150 blk_is_read_only(conf->conf.blk), true,
1151 errp)) {
a17c17a2
KW
1152 return;
1153 }
4be74634 1154 s->original_wce = blk_enable_write_cache(conf->conf.blk);
ceff3e1f 1155 if (!blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, errp)) {
75884afd 1156 return;
b7eb0c9f 1157 }
ceff3e1f 1158
0eb28a42 1159 blkconf_blocksizes(&conf->conf);
a8686a9b 1160
0a75b60c
MK
1161 if (conf->conf.logical_block_size >
1162 conf->conf.physical_block_size) {
1163 error_setg(errp,
1164 "logical_block_size > physical_block_size not supported");
1165 return;
1166 }
1167
37b06f8d
SG
1168 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_DISCARD) &&
1169 (!conf->max_discard_sectors ||
1170 conf->max_discard_sectors > BDRV_REQUEST_MAX_SECTORS)) {
1171 error_setg(errp, "invalid max-discard-sectors property (%" PRIu32 ")"
1172 ", must be between 1 and %d",
1173 conf->max_discard_sectors, (int)BDRV_REQUEST_MAX_SECTORS);
1174 return;
1175 }
1176
1177 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_WRITE_ZEROES) &&
1178 (!conf->max_write_zeroes_sectors ||
1179 conf->max_write_zeroes_sectors > BDRV_REQUEST_MAX_SECTORS)) {
1180 error_setg(errp, "invalid max-write-zeroes-sectors property (%" PRIu32
1181 "), must be between 1 and %d",
1182 conf->max_write_zeroes_sectors,
1183 (int)BDRV_REQUEST_MAX_SECTORS);
1184 return;
1185 }
1186
20764be0
SG
1187 virtio_blk_set_config_size(s, s->host_features);
1188
1189 virtio_init(vdev, "virtio-blk", VIRTIO_ID_BLOCK, s->config_size);
6e02c38d 1190
4be74634 1191 s->blk = conf->conf.blk;
869a5c6d 1192 s->rq = NULL;
2a30307f 1193 s->sector_mask = (s->conf.conf.logical_block_size / BDRV_SECTOR_SIZE) - 1;
e63e7fde 1194
2f270590 1195 for (i = 0; i < conf->num_queues; i++) {
6040aedd 1196 virtio_add_queue(vdev, conf->queue_size, virtio_blk_handle_output);
2f270590 1197 }
2a30307f 1198 virtio_blk_data_plane_create(vdev, conf, &s->dataplane, &err);
3ffeeef7 1199 if (err != NULL) {
75884afd 1200 error_propagate(errp, err);
6a1a8cc7 1201 virtio_cleanup(vdev);
75884afd 1202 return;
392808b4 1203 }
6e02c38d 1204
69b302b2 1205 s->change = qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);
4be74634
MA
1206 blk_set_dev_ops(s->blk, &virtio_block_ops, s);
1207 blk_set_guest_block_size(s->blk, s->conf.conf.logical_block_size);
6e02c38d 1208
4be74634 1209 blk_iostatus_enable(s->blk);
71f571a2
SE
1210
1211 add_boot_device_lchs(dev, "/disk@0,0",
1212 conf->conf.lcyls,
1213 conf->conf.lheads,
1214 conf->conf.lsecs);
1c028ddf
FK
1215}
1216
306ec6c3 1217static void virtio_blk_device_unrealize(DeviceState *dev, Error **errp)
1c028ddf 1218{
306ec6c3
AF
1219 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1220 VirtIOBlock *s = VIRTIO_BLK(dev);
4a0117cf
EP
1221 VirtIOBlkConf *conf = &s->conf;
1222 unsigned i;
306ec6c3 1223
7bfde688 1224 blk_drain(s->blk);
71f571a2 1225 del_boot_device_lchs(dev, "/disk@0,0");
1c028ddf
FK
1226 virtio_blk_data_plane_destroy(s->dataplane);
1227 s->dataplane = NULL;
4a0117cf
EP
1228 for (i = 0; i < conf->num_queues; i++) {
1229 virtio_del_queue(vdev, i);
1230 }
1c028ddf 1231 qemu_del_vm_change_state_handler(s->change);
4be74634 1232 blockdev_mark_auto_del(s->blk);
6a1a8cc7 1233 virtio_cleanup(vdev);
1c028ddf
FK
1234}
1235
467b3f33
SH
1236static void virtio_blk_instance_init(Object *obj)
1237{
1238 VirtIOBlock *s = VIRTIO_BLK(obj);
1239
2a30307f 1240 device_add_bootindex_property(obj, &s->conf.conf.bootindex,
3342ec32
GA
1241 "bootindex", "/disk@0,0",
1242 DEVICE(obj), NULL);
467b3f33
SH
1243}
1244
977a117f
HP
1245static const VMStateDescription vmstate_virtio_blk = {
1246 .name = "virtio-blk",
1247 .minimum_version_id = 2,
1248 .version_id = 2,
1249 .fields = (VMStateField[]) {
1250 VMSTATE_VIRTIO_DEVICE,
1251 VMSTATE_END_OF_LIST()
1252 },
1253};
bbded32c 1254
1c028ddf 1255static Property virtio_blk_properties[] = {
2a30307f 1256 DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf),
8c398252 1257 DEFINE_BLOCK_ERROR_PROPERTIES(VirtIOBlock, conf.conf),
2a30307f
MA
1258 DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf),
1259 DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial),
bbe8bd4d
SG
1260 DEFINE_PROP_BIT64("config-wce", VirtIOBlock, host_features,
1261 VIRTIO_BLK_F_CONFIG_WCE, true),
32a877e4 1262#ifdef __linux__
bbe8bd4d
SG
1263 DEFINE_PROP_BIT64("scsi", VirtIOBlock, host_features,
1264 VIRTIO_BLK_F_SCSI, false),
32a877e4 1265#endif
c99495ac
PL
1266 DEFINE_PROP_BIT("request-merging", VirtIOBlock, conf.request_merging, 0,
1267 true),
2f270590 1268 DEFINE_PROP_UINT16("num-queues", VirtIOBlock, conf.num_queues, 1),
6040aedd 1269 DEFINE_PROP_UINT16("queue-size", VirtIOBlock, conf.queue_size, 128),
d679ac09
FZ
1270 DEFINE_PROP_LINK("iothread", VirtIOBlock, conf.iothread, TYPE_IOTHREAD,
1271 IOThread *),
5c81161f
SG
1272 DEFINE_PROP_BIT64("discard", VirtIOBlock, host_features,
1273 VIRTIO_BLK_F_DISCARD, true),
1274 DEFINE_PROP_BIT64("write-zeroes", VirtIOBlock, host_features,
1275 VIRTIO_BLK_F_WRITE_ZEROES, true),
37b06f8d
SG
1276 DEFINE_PROP_UINT32("max-discard-sectors", VirtIOBlock,
1277 conf.max_discard_sectors, BDRV_REQUEST_MAX_SECTORS),
1278 DEFINE_PROP_UINT32("max-write-zeroes-sectors", VirtIOBlock,
1279 conf.max_write_zeroes_sectors, BDRV_REQUEST_MAX_SECTORS),
5f258577
EY
1280 DEFINE_PROP_BOOL("x-enable-wce-if-config-wce", VirtIOBlock,
1281 conf.x_enable_wce_if_config_wce, true),
1c028ddf
FK
1282 DEFINE_PROP_END_OF_LIST(),
1283};
1284
1285static void virtio_blk_class_init(ObjectClass *klass, void *data)
1286{
1287 DeviceClass *dc = DEVICE_CLASS(klass);
1288 VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
75884afd 1289
1c028ddf 1290 dc->props = virtio_blk_properties;
bbded32c 1291 dc->vmsd = &vmstate_virtio_blk;
125ee0ed 1292 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
75884afd 1293 vdc->realize = virtio_blk_device_realize;
306ec6c3 1294 vdc->unrealize = virtio_blk_device_unrealize;
1c028ddf
FK
1295 vdc->get_config = virtio_blk_update_config;
1296 vdc->set_config = virtio_blk_set_config;
1297 vdc->get_features = virtio_blk_get_features;
1298 vdc->set_status = virtio_blk_set_status;
1299 vdc->reset = virtio_blk_reset;
b2b295a7
GK
1300 vdc->save = virtio_blk_save_device;
1301 vdc->load = virtio_blk_load_device;
9ffe337c
PB
1302 vdc->start_ioeventfd = virtio_blk_data_plane_start;
1303 vdc->stop_ioeventfd = virtio_blk_data_plane_stop;
1c028ddf
FK
1304}
1305
b5c7ceaf 1306static const TypeInfo virtio_blk_info = {
1c028ddf
FK
1307 .name = TYPE_VIRTIO_BLK,
1308 .parent = TYPE_VIRTIO_DEVICE,
1309 .instance_size = sizeof(VirtIOBlock),
467b3f33 1310 .instance_init = virtio_blk_instance_init,
1c028ddf
FK
1311 .class_init = virtio_blk_class_init,
1312};
1313
1314static void virtio_register_types(void)
1315{
b5c7ceaf 1316 type_register_static(&virtio_blk_info);
1c028ddf
FK
1317}
1318
1319type_init(virtio_register_types)