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