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