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