]> git.proxmox.com Git - mirror_qemu.git/blame - hw/block/virtio-blk.c
block: rename blk_io_plug_call() API to defer_call()
[mirror_qemu.git] / hw / block / virtio-blk.c
CommitLineData
6e02c38d
AL
1/*
2 * Virtio Block Device
3 *
4 * Copyright IBM, Corp. 2007
5 *
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
11 *
12 */
13
80c71a24 14#include "qemu/osdep.h"
da34e65c 15#include "qapi/error.h"
827805a2 16#include "qemu/iov.h"
0b8fa32f 17#include "qemu/module.h"
1de7afc9 18#include "qemu/error-report.h"
9b92fbcf 19#include "qemu/main-loop.h"
4f736650 20#include "block/block_int.h"
6d519a5f 21#include "trace.h"
0d09e41a 22#include "hw/block/block.h"
a27bd6c7 23#include "hw/qdev-properties.h"
9c17d615 24#include "sysemu/blockdev.h"
baf42268 25#include "sysemu/block-ram-registrar.h"
2f780b6a 26#include "sysemu/sysemu.h"
54d31236 27#include "sysemu/runstate.h"
0d09e41a 28#include "hw/virtio/virtio-blk.h"
52b53c04 29#include "dataplane/virtio-blk.h"
08e2c9f1 30#include "scsi/constants.h"
1063b8b1
CH
31#ifdef __linux__
32# include <scsi/sg.h>
33#endif
0d09e41a 34#include "hw/virtio/virtio-bus.h"
ca77ee28 35#include "migration/qemu-file-types.h"
783d1897 36#include "hw/virtio/virtio-access.h"
d9cf55a8 37#include "hw/virtio/virtio-blk-common.h"
4c41c69e 38#include "qemu/coroutine.h"
6e02c38d 39
d14dde5e
GK
40static void virtio_blk_init_request(VirtIOBlock *s, VirtQueue *vq,
41 VirtIOBlockReq *req)
671ec3f0 42{
671ec3f0 43 req->dev = s;
edaffd9f 44 req->vq = vq;
869d66af 45 req->qiov.size = 0;
2a6cdd6d 46 req->in_len = 0;
869d66af 47 req->next = NULL;
95f7142a 48 req->mr_next = NULL;
671ec3f0
FZ
49}
50
d14dde5e 51static void virtio_blk_free_request(VirtIOBlockReq *req)
671ec3f0 52{
1d29b5b0 53 g_free(req);
671ec3f0
FZ
54}
55
03de2f52 56static void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
869a5c6d
AL
57{
58 VirtIOBlock *s = req->dev;
1cc91b7d 59 VirtIODevice *vdev = VIRTIO_DEVICE(s);
869a5c6d 60
a576ceac 61 trace_virtio_blk_req_complete(vdev, req, status);
6d519a5f 62
92e3c2a3 63 stb_p(&req->in->status, status);
7bd04a04
SH
64 iov_discard_undo(&req->inhdr_undo);
65 iov_discard_undo(&req->outhdr_undo);
edaffd9f 66 virtqueue_push(req->vq, &req->elem, req->in_len);
eb41cf78 67 if (s->dataplane_started && !s->dataplane_disabled) {
edaffd9f 68 virtio_blk_data_plane_notify(s->dataplane, req->vq);
03de2f52 69 } else {
edaffd9f 70 virtio_notify(vdev, req->vq);
03de2f52 71 }
bf4bd461
FZ
72}
73
f35d68f0 74static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
00f639fb 75 bool is_read, bool acct_failed)
869a5c6d 76{
869a5c6d 77 VirtIOBlock *s = req->dev;
9a6719d5 78 BlockErrorAction action = blk_get_error_action(s->blk, is_read, error);
869a5c6d 79
a589569f 80 if (action == BLOCK_ERROR_ACTION_STOP) {
466138dc
FZ
81 /* Break the link as the next request is going to be parsed from the
82 * ring again. Otherwise we may end up doing a double completion! */
83 req->mr_next = NULL;
869a5c6d
AL
84 req->next = s->rq;
85 s->rq = req;
a589569f 86 } else if (action == BLOCK_ERROR_ACTION_REPORT) {
869a5c6d 87 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
00f639fb
SG
88 if (acct_failed) {
89 block_acct_failed(blk_get_stats(s->blk), &req->acct);
90 }
671ec3f0 91 virtio_blk_free_request(req);
869a5c6d
AL
92 }
93
4be74634 94 blk_error_action(s->blk, action, is_read, error);
a589569f 95 return action != BLOCK_ERROR_ACTION_IGNORE;
869a5c6d
AL
96}
97
6e02c38d
AL
98static void virtio_blk_rw_complete(void *opaque, int ret)
99{
95f7142a 100 VirtIOBlockReq *next = opaque;
b9e413dd 101 VirtIOBlock *s = next->dev;
a576ceac 102 VirtIODevice *vdev = VIRTIO_DEVICE(s);
95f7142a 103
b9e413dd 104 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
95f7142a
PL
105 while (next) {
106 VirtIOBlockReq *req = next;
107 next = req->mr_next;
a576ceac 108 trace_virtio_blk_rw_complete(vdev, req, ret);
95f7142a
PL
109
110 if (req->qiov.nalloc != -1) {
e61809ed 111 /* If nalloc is != -1 req->qiov is a local copy of the original
9bb192a4
YB
112 * external iovec. It was allocated in submit_requests to be
113 * able to merge requests. */
95f7142a
PL
114 qemu_iovec_destroy(&req->qiov);
115 }
6e02c38d 116
95f7142a 117 if (ret) {
bf4069fb 118 int p = virtio_ldl_p(VIRTIO_DEVICE(s), &req->out.type);
95f7142a 119 bool is_read = !(p & VIRTIO_BLK_T_OUT);
2a6cdd6d
PB
120 /* Note that memory may be dirtied on read failure. If the
121 * virtio request is not completed here, as is the case for
122 * BLOCK_ERROR_ACTION_STOP, the memory may not be copied
123 * correctly during live migration. While this is ugly,
124 * it is acceptable because the device is free to write to
125 * the memory until the request is completed (which will
126 * happen on the other side of the migration).
127 */
00f639fb 128 if (virtio_blk_handle_rw_error(req, -ret, is_read, true)) {
95f7142a
PL
129 continue;
130 }
131 }
6d519a5f 132
95f7142a 133 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
bf4069fb 134 block_acct_done(blk_get_stats(s->blk), &req->acct);
95f7142a 135 virtio_blk_free_request(req);
6e02c38d 136 }
b9e413dd 137 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
869a5c6d 138}
6e02c38d 139
aa659be3
CH
140static void virtio_blk_flush_complete(void *opaque, int ret)
141{
142 VirtIOBlockReq *req = opaque;
b9e413dd 143 VirtIOBlock *s = req->dev;
aa659be3 144
b9e413dd 145 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
8c269b54 146 if (ret) {
00f639fb 147 if (virtio_blk_handle_rw_error(req, -ret, 0, true)) {
b9e413dd 148 goto out;
8c269b54
KW
149 }
150 }
151
152 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
9a6719d5 153 block_acct_done(blk_get_stats(s->blk), &req->acct);
671ec3f0 154 virtio_blk_free_request(req);
b9e413dd
PB
155
156out:
157 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
6e02c38d
AL
158}
159
37b06f8d
SG
160static void virtio_blk_discard_write_zeroes_complete(void *opaque, int ret)
161{
162 VirtIOBlockReq *req = opaque;
163 VirtIOBlock *s = req->dev;
164 bool is_write_zeroes = (virtio_ldl_p(VIRTIO_DEVICE(s), &req->out.type) &
165 ~VIRTIO_BLK_T_BARRIER) == VIRTIO_BLK_T_WRITE_ZEROES;
166
167 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
168 if (ret) {
169 if (virtio_blk_handle_rw_error(req, -ret, false, is_write_zeroes)) {
170 goto out;
171 }
172 }
173
174 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
175 if (is_write_zeroes) {
176 block_acct_done(blk_get_stats(s->blk), &req->acct);
177 }
178 virtio_blk_free_request(req);
179
180out:
181 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
182}
183
1dc936aa
FZ
184#ifdef __linux__
185
186typedef struct {
187 VirtIOBlockReq *req;
188 struct sg_io_hdr hdr;
189} VirtIOBlockIoctlReq;
190
191static void virtio_blk_ioctl_complete(void *opaque, int status)
192{
193 VirtIOBlockIoctlReq *ioctl_req = opaque;
194 VirtIOBlockReq *req = ioctl_req->req;
9d456654
PB
195 VirtIOBlock *s = req->dev;
196 VirtIODevice *vdev = VIRTIO_DEVICE(s);
1dc936aa
FZ
197 struct virtio_scsi_inhdr *scsi;
198 struct sg_io_hdr *hdr;
199
200 scsi = (void *)req->elem.in_sg[req->elem.in_num - 2].iov_base;
201
202 if (status) {
203 status = VIRTIO_BLK_S_UNSUPP;
204 virtio_stl_p(vdev, &scsi->errors, 255);
205 goto out;
206 }
207
208 hdr = &ioctl_req->hdr;
209 /*
210 * From SCSI-Generic-HOWTO: "Some lower level drivers (e.g. ide-scsi)
211 * clear the masked_status field [hence status gets cleared too, see
212 * block/scsi_ioctl.c] even when a CHECK_CONDITION or COMMAND_TERMINATED
213 * status has occurred. However they do set DRIVER_SENSE in driver_status
214 * field. Also a (sb_len_wr > 0) indicates there is a sense buffer.
215 */
216 if (hdr->status == 0 && hdr->sb_len_wr > 0) {
217 hdr->status = CHECK_CONDITION;
218 }
219
220 virtio_stl_p(vdev, &scsi->errors,
221 hdr->status | (hdr->msg_status << 8) |
222 (hdr->host_status << 16) | (hdr->driver_status << 24));
223 virtio_stl_p(vdev, &scsi->residual, hdr->resid);
224 virtio_stl_p(vdev, &scsi->sense_len, hdr->sb_len_wr);
225 virtio_stl_p(vdev, &scsi->data_len, hdr->dxfer_len);
226
227out:
b9e413dd 228 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
1dc936aa
FZ
229 virtio_blk_req_complete(req, status);
230 virtio_blk_free_request(req);
b9e413dd 231 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
1dc936aa
FZ
232 g_free(ioctl_req);
233}
234
235#endif
236
edaffd9f 237static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s, VirtQueue *vq)
6e02c38d 238{
edaffd9f 239 VirtIOBlockReq *req = virtqueue_pop(vq, sizeof(VirtIOBlockReq));
6e02c38d 240
51b19ebe 241 if (req) {
edaffd9f 242 virtio_blk_init_request(s, vq, req);
6e02c38d 243 }
6e02c38d
AL
244 return req;
245}
246
75344fa4 247static int virtio_blk_handle_scsi_req(VirtIOBlockReq *req)
1063b8b1 248{
5a05cbee
FZ
249 int status = VIRTIO_BLK_S_OK;
250 struct virtio_scsi_inhdr *scsi = NULL;
75344fa4 251 VirtIOBlock *blk = req->dev;
bf4069fb
AR
252 VirtIODevice *vdev = VIRTIO_DEVICE(blk);
253 VirtQueueElement *elem = &req->elem;
783d1897 254
47ce9ef7 255#ifdef __linux__
1063b8b1 256 int i;
1dc936aa 257 VirtIOBlockIoctlReq *ioctl_req;
a209f461 258 BlockAIOCB *acb;
47ce9ef7 259#endif
1063b8b1
CH
260
261 /*
262 * We require at least one output segment each for the virtio_blk_outhdr
263 * and the SCSI command block.
264 *
265 * We also at least require the virtio_blk_inhdr, the virtio_scsi_inhdr
266 * and the sense buffer pointer in the input segments.
267 */
5a05cbee
FZ
268 if (elem->out_num < 2 || elem->in_num < 3) {
269 status = VIRTIO_BLK_S_IOERR;
270 goto fail;
1063b8b1
CH
271 }
272
273 /*
f34e73cd
PB
274 * The scsi inhdr is placed in the second-to-last input segment, just
275 * before the regular inhdr.
1063b8b1 276 */
5a05cbee 277 scsi = (void *)elem->in_sg[elem->in_num - 2].iov_base;
f34e73cd 278
bbe8bd4d 279 if (!virtio_has_feature(blk->host_features, VIRTIO_BLK_F_SCSI)) {
f34e73cd
PB
280 status = VIRTIO_BLK_S_UNSUPP;
281 goto fail;
1063b8b1
CH
282 }
283
284 /*
f34e73cd 285 * No support for bidirection commands yet.
1063b8b1 286 */
5a05cbee 287 if (elem->out_num > 2 && elem->in_num > 3) {
f34e73cd
PB
288 status = VIRTIO_BLK_S_UNSUPP;
289 goto fail;
290 }
1063b8b1 291
f34e73cd 292#ifdef __linux__
1dc936aa
FZ
293 ioctl_req = g_new0(VirtIOBlockIoctlReq, 1);
294 ioctl_req->req = req;
295 ioctl_req->hdr.interface_id = 'S';
296 ioctl_req->hdr.cmd_len = elem->out_sg[1].iov_len;
297 ioctl_req->hdr.cmdp = elem->out_sg[1].iov_base;
298 ioctl_req->hdr.dxfer_len = 0;
1063b8b1 299
5a05cbee 300 if (elem->out_num > 2) {
1063b8b1
CH
301 /*
302 * If there are more than the minimally required 2 output segments
303 * there is write payload starting from the third iovec.
304 */
1dc936aa
FZ
305 ioctl_req->hdr.dxfer_direction = SG_DXFER_TO_DEV;
306 ioctl_req->hdr.iovec_count = elem->out_num - 2;
1063b8b1 307
1dc936aa
FZ
308 for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
309 ioctl_req->hdr.dxfer_len += elem->out_sg[i + 2].iov_len;
310 }
1063b8b1 311
1dc936aa 312 ioctl_req->hdr.dxferp = elem->out_sg + 2;
1063b8b1 313
5a05cbee 314 } else if (elem->in_num > 3) {
1063b8b1
CH
315 /*
316 * If we have more than 3 input segments the guest wants to actually
317 * read data.
318 */
1dc936aa
FZ
319 ioctl_req->hdr.dxfer_direction = SG_DXFER_FROM_DEV;
320 ioctl_req->hdr.iovec_count = elem->in_num - 3;
321 for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
322 ioctl_req->hdr.dxfer_len += elem->in_sg[i].iov_len;
323 }
1063b8b1 324
1dc936aa 325 ioctl_req->hdr.dxferp = elem->in_sg;
1063b8b1
CH
326 } else {
327 /*
328 * Some SCSI commands don't actually transfer any data.
329 */
1dc936aa 330 ioctl_req->hdr.dxfer_direction = SG_DXFER_NONE;
1063b8b1
CH
331 }
332
1dc936aa
FZ
333 ioctl_req->hdr.sbp = elem->in_sg[elem->in_num - 3].iov_base;
334 ioctl_req->hdr.mx_sb_len = elem->in_sg[elem->in_num - 3].iov_len;
1063b8b1 335
a209f461
FZ
336 acb = blk_aio_ioctl(blk->blk, SG_IO, &ioctl_req->hdr,
337 virtio_blk_ioctl_complete, ioctl_req);
338 if (!acb) {
339 g_free(ioctl_req);
340 status = VIRTIO_BLK_S_UNSUPP;
341 goto fail;
342 }
1dc936aa 343 return -EINPROGRESS;
1063b8b1 344#else
f34e73cd
PB
345 abort();
346#endif
347
348fail:
349 /* Just put anything nonzero so that the ioctl fails in the guest. */
5a05cbee 350 if (scsi) {
783d1897 351 virtio_stl_p(vdev, &scsi->errors, 255);
5a05cbee
FZ
352 }
353 return status;
354}
355
356static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
357{
358 int status;
359
75344fa4 360 status = virtio_blk_handle_scsi_req(req);
1dc936aa
FZ
361 if (status != -EINPROGRESS) {
362 virtio_blk_req_complete(req, status);
363 virtio_blk_free_request(req);
364 }
1063b8b1 365}
1063b8b1 366
baf42268 367static inline void submit_requests(VirtIOBlock *s, MultiReqBuffer *mrb,
95f7142a 368 int start, int num_reqs, int niov)
869a5c6d 369{
baf42268 370 BlockBackend *blk = s->blk;
95f7142a
PL
371 QEMUIOVector *qiov = &mrb->reqs[start]->qiov;
372 int64_t sector_num = mrb->reqs[start]->sector_num;
95f7142a 373 bool is_write = mrb->is_write;
baf42268 374 BdrvRequestFlags flags = 0;
95f7142a
PL
375
376 if (num_reqs > 1) {
377 int i;
378 struct iovec *tmp_iov = qiov->iov;
379 int tmp_niov = qiov->niov;
380
381 /* mrb->reqs[start]->qiov was initialized from external so we can't
b5772fdd 382 * modify it here. We need to initialize it locally and then add the
95f7142a
PL
383 * external iovecs. */
384 qemu_iovec_init(qiov, niov);
385
386 for (i = 0; i < tmp_niov; i++) {
387 qemu_iovec_add(qiov, tmp_iov[i].iov_base, tmp_iov[i].iov_len);
388 }
389
390 for (i = start + 1; i < start + num_reqs; i++) {
391 qemu_iovec_concat(qiov, &mrb->reqs[i]->qiov, 0,
392 mrb->reqs[i]->qiov.size);
393 mrb->reqs[i - 1]->mr_next = mrb->reqs[i];
95f7142a 394 }
95f7142a 395
a576ceac
SH
396 trace_virtio_blk_submit_multireq(VIRTIO_DEVICE(mrb->reqs[start]->dev),
397 mrb, start, num_reqs,
b5772fdd
EB
398 sector_num << BDRV_SECTOR_BITS,
399 qiov->size, is_write);
95f7142a
PL
400 block_acct_merge_done(blk_get_stats(blk),
401 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ,
402 num_reqs - 1);
403 }
91553dcc 404
baf42268
SH
405 if (blk_ram_registrar_ok(&s->blk_ram_registrar)) {
406 flags |= BDRV_REQ_REGISTERED_BUF;
407 }
408
95f7142a 409 if (is_write) {
baf42268
SH
410 blk_aio_pwritev(blk, sector_num << BDRV_SECTOR_BITS, qiov,
411 flags, virtio_blk_rw_complete,
412 mrb->reqs[start]);
95f7142a 413 } else {
baf42268
SH
414 blk_aio_preadv(blk, sector_num << BDRV_SECTOR_BITS, qiov,
415 flags, virtio_blk_rw_complete,
416 mrb->reqs[start]);
95f7142a
PL
417 }
418}
419
420static int multireq_compare(const void *a, const void *b)
421{
422 const VirtIOBlockReq *req1 = *(VirtIOBlockReq **)a,
423 *req2 = *(VirtIOBlockReq **)b;
424
425 /*
426 * Note that we can't simply subtract sector_num1 from sector_num2
427 * here as that could overflow the return value.
428 */
429 if (req1->sector_num > req2->sector_num) {
430 return 1;
431 } else if (req1->sector_num < req2->sector_num) {
432 return -1;
433 } else {
434 return 0;
435 }
436}
437
baf42268 438static void virtio_blk_submit_multireq(VirtIOBlock *s, MultiReqBuffer *mrb)
95f7142a
PL
439{
440 int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
5def6b80 441 uint32_t max_transfer;
95f7142a
PL
442 int64_t sector_num = 0;
443
444 if (mrb->num_reqs == 1) {
baf42268 445 submit_requests(s, mrb, 0, 1, -1);
95f7142a 446 mrb->num_reqs = 0;
c20fd872
CH
447 return;
448 }
449
5def6b80 450 max_transfer = blk_get_max_transfer(mrb->reqs[0]->dev->blk);
95f7142a
PL
451
452 qsort(mrb->reqs, mrb->num_reqs, sizeof(*mrb->reqs),
453 &multireq_compare);
454
455 for (i = 0; i < mrb->num_reqs; i++) {
456 VirtIOBlockReq *req = mrb->reqs[i];
457 if (num_reqs > 0) {
49cffbc6
GA
458 /*
459 * NOTE: We cannot merge the requests in below situations:
460 * 1. requests are not sequential
461 * 2. merge would exceed maximum number of IOVs
462 * 3. merge would exceed maximum transfer length of backend device
463 */
464 if (sector_num + nb_sectors != req->sector_num ||
baf42268 465 niov > blk_get_max_iov(s->blk) - req->qiov.niov ||
5def6b80
EB
466 req->qiov.size > max_transfer ||
467 nb_sectors > (max_transfer -
468 req->qiov.size) / BDRV_SECTOR_SIZE) {
baf42268 469 submit_requests(s, mrb, start, num_reqs, niov);
95f7142a 470 num_reqs = 0;
91553dcc
KW
471 }
472 }
95f7142a
PL
473
474 if (num_reqs == 0) {
475 sector_num = req->sector_num;
476 nb_sectors = niov = 0;
477 start = i;
478 }
479
480 nb_sectors += req->qiov.size / BDRV_SECTOR_SIZE;
481 niov += req->qiov.niov;
482 num_reqs++;
91553dcc 483 }
c20fd872 484
baf42268 485 submit_requests(s, mrb, start, num_reqs, niov);
95f7142a 486 mrb->num_reqs = 0;
91553dcc 487}
87b245db 488
c20fd872 489static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
aa659be3 490{
bf4069fb
AR
491 VirtIOBlock *s = req->dev;
492
493 block_acct_start(blk_get_stats(s->blk), &req->acct, 0,
5366d0c8 494 BLOCK_ACCT_FLUSH);
a597e79c 495
618fbb84
CH
496 /*
497 * Make sure all outstanding writes are posted to the backing device.
498 */
95f7142a 499 if (mrb->is_write && mrb->num_reqs > 0) {
baf42268 500 virtio_blk_submit_multireq(s, mrb);
95f7142a 501 }
bf4069fb 502 blk_aio_flush(s->blk, virtio_blk_flush_complete, req);
aa659be3
CH
503}
504
d0e14376
MA
505static bool virtio_blk_sect_range_ok(VirtIOBlock *dev,
506 uint64_t sector, size_t size)
507{
3c2daac0
MA
508 uint64_t nb_sectors = size >> BDRV_SECTOR_BITS;
509 uint64_t total_sectors;
510
75af1f34 511 if (nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
95f7142a
PL
512 return false;
513 }
d0e14376
MA
514 if (sector & dev->sector_mask) {
515 return false;
516 }
2a30307f 517 if (size % dev->conf.conf.logical_block_size) {
d0e14376
MA
518 return false;
519 }
4be74634 520 blk_get_geometry(dev->blk, &total_sectors);
3c2daac0
MA
521 if (sector > total_sectors || nb_sectors > total_sectors - sector) {
522 return false;
523 }
d0e14376
MA
524 return true;
525}
526
37b06f8d
SG
527static uint8_t virtio_blk_handle_discard_write_zeroes(VirtIOBlockReq *req,
528 struct virtio_blk_discard_write_zeroes *dwz_hdr, bool is_write_zeroes)
529{
530 VirtIOBlock *s = req->dev;
531 VirtIODevice *vdev = VIRTIO_DEVICE(s);
532 uint64_t sector;
533 uint32_t num_sectors, flags, max_sectors;
534 uint8_t err_status;
535 int bytes;
536
537 sector = virtio_ldq_p(vdev, &dwz_hdr->sector);
538 num_sectors = virtio_ldl_p(vdev, &dwz_hdr->num_sectors);
539 flags = virtio_ldl_p(vdev, &dwz_hdr->flags);
540 max_sectors = is_write_zeroes ? s->conf.max_write_zeroes_sectors :
541 s->conf.max_discard_sectors;
542
543 /*
544 * max_sectors is at most BDRV_REQUEST_MAX_SECTORS, this check
545 * make us sure that "num_sectors << BDRV_SECTOR_BITS" can fit in
546 * the integer variable.
547 */
548 if (unlikely(num_sectors > max_sectors)) {
549 err_status = VIRTIO_BLK_S_IOERR;
550 goto err;
551 }
552
553 bytes = num_sectors << BDRV_SECTOR_BITS;
554
555 if (unlikely(!virtio_blk_sect_range_ok(s, sector, bytes))) {
556 err_status = VIRTIO_BLK_S_IOERR;
557 goto err;
558 }
559
560 /*
561 * The device MUST set the status byte to VIRTIO_BLK_S_UNSUPP for discard
562 * and write zeroes commands if any unknown flag is set.
563 */
564 if (unlikely(flags & ~VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP)) {
565 err_status = VIRTIO_BLK_S_UNSUPP;
566 goto err;
567 }
568
569 if (is_write_zeroes) { /* VIRTIO_BLK_T_WRITE_ZEROES */
570 int blk_aio_flags = 0;
571
572 if (flags & VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP) {
573 blk_aio_flags |= BDRV_REQ_MAY_UNMAP;
574 }
575
576 block_acct_start(blk_get_stats(s->blk), &req->acct, bytes,
577 BLOCK_ACCT_WRITE);
578
579 blk_aio_pwrite_zeroes(s->blk, sector << BDRV_SECTOR_BITS,
580 bytes, blk_aio_flags,
581 virtio_blk_discard_write_zeroes_complete, req);
582 } else { /* VIRTIO_BLK_T_DISCARD */
583 /*
584 * The device MUST set the status byte to VIRTIO_BLK_S_UNSUPP for
585 * discard commands if the unmap flag is set.
586 */
587 if (unlikely(flags & VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP)) {
588 err_status = VIRTIO_BLK_S_UNSUPP;
589 goto err;
590 }
591
592 blk_aio_pdiscard(s->blk, sector << BDRV_SECTOR_BITS, bytes,
593 virtio_blk_discard_write_zeroes_complete, req);
594 }
595
596 return VIRTIO_BLK_S_OK;
597
598err:
599 if (is_write_zeroes) {
600 block_acct_invalid(blk_get_stats(s->blk), BLOCK_ACCT_WRITE);
601 }
602 return err_status;
603}
604
4f736650
SL
605typedef struct ZoneCmdData {
606 VirtIOBlockReq *req;
607 struct iovec *in_iov;
608 unsigned in_num;
609 union {
610 struct {
611 unsigned int nr_zones;
612 BlockZoneDescriptor *zones;
613 } zone_report_data;
614 struct {
615 int64_t offset;
616 } zone_append_data;
617 };
618} ZoneCmdData;
619
620/*
621 * check zoned_request: error checking before issuing requests. If all checks
622 * passed, return true.
623 * append: true if only zone append requests issued.
624 */
625static bool check_zoned_request(VirtIOBlock *s, int64_t offset, int64_t len,
626 bool append, uint8_t *status) {
627 BlockDriverState *bs = blk_bs(s->blk);
628 int index;
629
630 if (!virtio_has_feature(s->host_features, VIRTIO_BLK_F_ZONED)) {
631 *status = VIRTIO_BLK_S_UNSUPP;
632 return false;
633 }
634
635 if (offset < 0 || len < 0 || len > (bs->total_sectors << BDRV_SECTOR_BITS)
636 || offset > (bs->total_sectors << BDRV_SECTOR_BITS) - len) {
637 *status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
638 return false;
639 }
640
641 if (append) {
642 if (bs->bl.write_granularity) {
643 if ((offset % bs->bl.write_granularity) != 0) {
644 *status = VIRTIO_BLK_S_ZONE_UNALIGNED_WP;
645 return false;
646 }
647 }
648
649 index = offset / bs->bl.zone_size;
650 if (BDRV_ZT_IS_CONV(bs->wps->wp[index])) {
651 *status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
652 return false;
653 }
654
655 if (len / 512 > bs->bl.max_append_sectors) {
656 if (bs->bl.max_append_sectors == 0) {
657 *status = VIRTIO_BLK_S_UNSUPP;
658 } else {
659 *status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
660 }
661 return false;
662 }
663 }
664 return true;
665}
666
667static void virtio_blk_zone_report_complete(void *opaque, int ret)
668{
669 ZoneCmdData *data = opaque;
670 VirtIOBlockReq *req = data->req;
671 VirtIOBlock *s = req->dev;
672 VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
673 struct iovec *in_iov = data->in_iov;
674 unsigned in_num = data->in_num;
675 int64_t zrp_size, n, j = 0;
676 int64_t nz = data->zone_report_data.nr_zones;
677 int8_t err_status = VIRTIO_BLK_S_OK;
678
4e92acf7 679 trace_virtio_blk_zone_report_complete(vdev, req, nz, ret);
4f736650
SL
680 if (ret) {
681 err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
682 goto out;
683 }
684
685 struct virtio_blk_zone_report zrp_hdr = (struct virtio_blk_zone_report) {
686 .nr_zones = cpu_to_le64(nz),
687 };
688 zrp_size = sizeof(struct virtio_blk_zone_report)
689 + sizeof(struct virtio_blk_zone_descriptor) * nz;
690 n = iov_from_buf(in_iov, in_num, 0, &zrp_hdr, sizeof(zrp_hdr));
691 if (n != sizeof(zrp_hdr)) {
692 virtio_error(vdev, "Driver provided input buffer that is too small!");
693 err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
694 goto out;
695 }
696
697 for (size_t i = sizeof(zrp_hdr); i < zrp_size;
698 i += sizeof(struct virtio_blk_zone_descriptor), ++j) {
699 struct virtio_blk_zone_descriptor desc =
700 (struct virtio_blk_zone_descriptor) {
701 .z_start = cpu_to_le64(data->zone_report_data.zones[j].start
702 >> BDRV_SECTOR_BITS),
703 .z_cap = cpu_to_le64(data->zone_report_data.zones[j].cap
704 >> BDRV_SECTOR_BITS),
705 .z_wp = cpu_to_le64(data->zone_report_data.zones[j].wp
706 >> BDRV_SECTOR_BITS),
707 };
708
709 switch (data->zone_report_data.zones[j].type) {
710 case BLK_ZT_CONV:
711 desc.z_type = VIRTIO_BLK_ZT_CONV;
712 break;
713 case BLK_ZT_SWR:
714 desc.z_type = VIRTIO_BLK_ZT_SWR;
715 break;
716 case BLK_ZT_SWP:
717 desc.z_type = VIRTIO_BLK_ZT_SWP;
718 break;
719 default:
720 g_assert_not_reached();
721 }
722
723 switch (data->zone_report_data.zones[j].state) {
724 case BLK_ZS_RDONLY:
725 desc.z_state = VIRTIO_BLK_ZS_RDONLY;
726 break;
727 case BLK_ZS_OFFLINE:
728 desc.z_state = VIRTIO_BLK_ZS_OFFLINE;
729 break;
730 case BLK_ZS_EMPTY:
731 desc.z_state = VIRTIO_BLK_ZS_EMPTY;
732 break;
733 case BLK_ZS_CLOSED:
734 desc.z_state = VIRTIO_BLK_ZS_CLOSED;
735 break;
736 case BLK_ZS_FULL:
737 desc.z_state = VIRTIO_BLK_ZS_FULL;
738 break;
739 case BLK_ZS_EOPEN:
740 desc.z_state = VIRTIO_BLK_ZS_EOPEN;
741 break;
742 case BLK_ZS_IOPEN:
743 desc.z_state = VIRTIO_BLK_ZS_IOPEN;
744 break;
745 case BLK_ZS_NOT_WP:
746 desc.z_state = VIRTIO_BLK_ZS_NOT_WP;
747 break;
748 default:
749 g_assert_not_reached();
750 }
751
752 /* TODO: it takes O(n^2) time complexity. Optimizations required. */
753 n = iov_from_buf(in_iov, in_num, i, &desc, sizeof(desc));
754 if (n != sizeof(desc)) {
755 virtio_error(vdev, "Driver provided input buffer "
756 "for descriptors that is too small!");
757 err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
758 }
759 }
760
761out:
762 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
763 virtio_blk_req_complete(req, err_status);
764 virtio_blk_free_request(req);
765 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
766 g_free(data->zone_report_data.zones);
767 g_free(data);
768}
769
770static void virtio_blk_handle_zone_report(VirtIOBlockReq *req,
771 struct iovec *in_iov,
772 unsigned in_num)
773{
774 VirtIOBlock *s = req->dev;
775 VirtIODevice *vdev = VIRTIO_DEVICE(s);
776 unsigned int nr_zones;
777 ZoneCmdData *data;
778 int64_t zone_size, offset;
779 uint8_t err_status;
780
781 if (req->in_len < sizeof(struct virtio_blk_inhdr) +
782 sizeof(struct virtio_blk_zone_report) +
783 sizeof(struct virtio_blk_zone_descriptor)) {
784 virtio_error(vdev, "in buffer too small for zone report");
785 return;
786 }
787
788 /* start byte offset of the zone report */
789 offset = virtio_ldq_p(vdev, &req->out.sector) << BDRV_SECTOR_BITS;
790 if (!check_zoned_request(s, offset, 0, false, &err_status)) {
791 goto out;
792 }
793 nr_zones = (req->in_len - sizeof(struct virtio_blk_inhdr) -
794 sizeof(struct virtio_blk_zone_report)) /
795 sizeof(struct virtio_blk_zone_descriptor);
4e92acf7
SL
796 trace_virtio_blk_handle_zone_report(vdev, req,
797 offset >> BDRV_SECTOR_BITS, nr_zones);
4f736650
SL
798
799 zone_size = sizeof(BlockZoneDescriptor) * nr_zones;
800 data = g_malloc(sizeof(ZoneCmdData));
801 data->req = req;
802 data->in_iov = in_iov;
803 data->in_num = in_num;
804 data->zone_report_data.nr_zones = nr_zones;
805 data->zone_report_data.zones = g_malloc(zone_size),
806
807 blk_aio_zone_report(s->blk, offset, &data->zone_report_data.nr_zones,
808 data->zone_report_data.zones,
809 virtio_blk_zone_report_complete, data);
810 return;
811out:
812 virtio_blk_req_complete(req, err_status);
813 virtio_blk_free_request(req);
814}
815
816static void virtio_blk_zone_mgmt_complete(void *opaque, int ret)
817{
818 VirtIOBlockReq *req = opaque;
819 VirtIOBlock *s = req->dev;
4e92acf7 820 VirtIODevice *vdev = VIRTIO_DEVICE(s);
4f736650 821 int8_t err_status = VIRTIO_BLK_S_OK;
4e92acf7 822 trace_virtio_blk_zone_mgmt_complete(vdev, req,ret);
4f736650
SL
823
824 if (ret) {
825 err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
826 }
827
828 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
829 virtio_blk_req_complete(req, err_status);
830 virtio_blk_free_request(req);
831 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
832}
833
834static int virtio_blk_handle_zone_mgmt(VirtIOBlockReq *req, BlockZoneOp op)
835{
836 VirtIOBlock *s = req->dev;
837 VirtIODevice *vdev = VIRTIO_DEVICE(s);
838 BlockDriverState *bs = blk_bs(s->blk);
839 int64_t offset = virtio_ldq_p(vdev, &req->out.sector) << BDRV_SECTOR_BITS;
840 uint64_t len;
841 uint64_t capacity = bs->total_sectors << BDRV_SECTOR_BITS;
842 uint8_t err_status = VIRTIO_BLK_S_OK;
843
844 uint32_t type = virtio_ldl_p(vdev, &req->out.type);
845 if (type == VIRTIO_BLK_T_ZONE_RESET_ALL) {
846 /* Entire drive capacity */
847 offset = 0;
848 len = capacity;
4e92acf7
SL
849 trace_virtio_blk_handle_zone_reset_all(vdev, req, 0,
850 bs->total_sectors);
4f736650
SL
851 } else {
852 if (bs->bl.zone_size > capacity - offset) {
853 /* The zoned device allows the last smaller zone. */
854 len = capacity - bs->bl.zone_size * (bs->bl.nr_zones - 1);
855 } else {
856 len = bs->bl.zone_size;
857 }
4e92acf7
SL
858 trace_virtio_blk_handle_zone_mgmt(vdev, req, op,
859 offset >> BDRV_SECTOR_BITS,
860 len >> BDRV_SECTOR_BITS);
4f736650
SL
861 }
862
863 if (!check_zoned_request(s, offset, len, false, &err_status)) {
864 goto out;
865 }
866
867 blk_aio_zone_mgmt(s->blk, op, offset, len,
868 virtio_blk_zone_mgmt_complete, req);
869
870 return 0;
871out:
872 virtio_blk_req_complete(req, err_status);
873 virtio_blk_free_request(req);
874 return err_status;
875}
876
877static void virtio_blk_zone_append_complete(void *opaque, int ret)
878{
879 ZoneCmdData *data = opaque;
880 VirtIOBlockReq *req = data->req;
881 VirtIOBlock *s = req->dev;
882 VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
883 int64_t append_sector, n;
884 uint8_t err_status = VIRTIO_BLK_S_OK;
885
886 if (ret) {
887 err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
888 goto out;
889 }
890
891 virtio_stq_p(vdev, &append_sector,
892 data->zone_append_data.offset >> BDRV_SECTOR_BITS);
893 n = iov_from_buf(data->in_iov, data->in_num, 0, &append_sector,
894 sizeof(append_sector));
895 if (n != sizeof(append_sector)) {
896 virtio_error(vdev, "Driver provided input buffer less than size of "
897 "append_sector");
898 err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
899 goto out;
900 }
4e92acf7 901 trace_virtio_blk_zone_append_complete(vdev, req, append_sector, ret);
4f736650
SL
902
903out:
904 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
905 virtio_blk_req_complete(req, err_status);
906 virtio_blk_free_request(req);
907 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
908 g_free(data);
909}
910
911static int virtio_blk_handle_zone_append(VirtIOBlockReq *req,
912 struct iovec *out_iov,
913 struct iovec *in_iov,
914 uint64_t out_num,
915 unsigned in_num) {
916 VirtIOBlock *s = req->dev;
917 VirtIODevice *vdev = VIRTIO_DEVICE(s);
918 uint8_t err_status = VIRTIO_BLK_S_OK;
919
920 int64_t offset = virtio_ldq_p(vdev, &req->out.sector) << BDRV_SECTOR_BITS;
921 int64_t len = iov_size(out_iov, out_num);
922
4e92acf7 923 trace_virtio_blk_handle_zone_append(vdev, req, offset >> BDRV_SECTOR_BITS);
4f736650
SL
924 if (!check_zoned_request(s, offset, len, true, &err_status)) {
925 goto out;
926 }
927
928 ZoneCmdData *data = g_malloc(sizeof(ZoneCmdData));
929 data->req = req;
930 data->in_iov = in_iov;
931 data->in_num = in_num;
932 data->zone_append_data.offset = offset;
933 qemu_iovec_init_external(&req->qiov, out_iov, out_num);
52eb76f4
SL
934
935 block_acct_start(blk_get_stats(s->blk), &req->acct, len,
936 BLOCK_ACCT_ZONE_APPEND);
937
4f736650
SL
938 blk_aio_zone_append(s->blk, &data->zone_append_data.offset, &req->qiov, 0,
939 virtio_blk_zone_append_complete, data);
940 return 0;
941
942out:
943 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
944 virtio_blk_req_complete(req, err_status);
945 virtio_blk_free_request(req);
946 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
947 return err_status;
948}
949
20ea686a 950static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
bc6694d4 951{
92e3c2a3 952 uint32_t type;
f897bf75 953 struct iovec *in_iov = req->elem.in_sg;
5636da76 954 struct iovec *out_iov = req->elem.out_sg;
f897bf75
SH
955 unsigned in_num = req->elem.in_num;
956 unsigned out_num = req->elem.out_num;
20ea686a
GK
957 VirtIOBlock *s = req->dev;
958 VirtIODevice *vdev = VIRTIO_DEVICE(s);
92e3c2a3 959
f897bf75 960 if (req->elem.out_num < 1 || req->elem.in_num < 1) {
20ea686a
GK
961 virtio_error(vdev, "virtio-blk missing headers");
962 return -1;
bc6694d4
KW
963 }
964
5636da76 965 if (unlikely(iov_to_buf(out_iov, out_num, 0, &req->out,
827805a2 966 sizeof(req->out)) != sizeof(req->out))) {
20ea686a
GK
967 virtio_error(vdev, "virtio-blk request outhdr too short");
968 return -1;
827805a2 969 }
ee17e848 970
7bd04a04
SH
971 iov_discard_front_undoable(&out_iov, &out_num, sizeof(req->out),
972 &req->outhdr_undo);
ee17e848 973
12048545 974 if (in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {
20ea686a 975 virtio_error(vdev, "virtio-blk request inhdr too short");
7bd04a04 976 iov_discard_undo(&req->outhdr_undo);
20ea686a 977 return -1;
ee17e848
FZ
978 }
979
2a6cdd6d
PB
980 /* We always touch the last byte, so just see how big in_iov is. */
981 req->in_len = iov_size(in_iov, in_num);
ee17e848
FZ
982 req->in = (void *)in_iov[in_num - 1].iov_base
983 + in_iov[in_num - 1].iov_len
984 - sizeof(struct virtio_blk_inhdr);
7bd04a04
SH
985 iov_discard_back_undoable(in_iov, &in_num, sizeof(struct virtio_blk_inhdr),
986 &req->inhdr_undo);
bc6694d4 987
9a6719d5 988 type = virtio_ldl_p(vdev, &req->out.type);
92e3c2a3 989
95f7142a 990 /* VIRTIO_BLK_T_OUT defines the command direction. VIRTIO_BLK_T_BARRIER
631b22ea 991 * is an optional flag. Although a guest should not send this flag if
95f7142a
PL
992 * not negotiated we ignored it in the past. So keep ignoring it. */
993 switch (type & ~(VIRTIO_BLK_T_OUT | VIRTIO_BLK_T_BARRIER)) {
994 case VIRTIO_BLK_T_IN:
995 {
996 bool is_write = type & VIRTIO_BLK_T_OUT;
9a6719d5 997 req->sector_num = virtio_ldq_p(vdev, &req->out.sector);
95f7142a
PL
998
999 if (is_write) {
5636da76 1000 qemu_iovec_init_external(&req->qiov, out_iov, out_num);
a576ceac 1001 trace_virtio_blk_handle_write(vdev, req, req->sector_num,
95f7142a
PL
1002 req->qiov.size / BDRV_SECTOR_SIZE);
1003 } else {
1004 qemu_iovec_init_external(&req->qiov, in_iov, in_num);
a576ceac 1005 trace_virtio_blk_handle_read(vdev, req, req->sector_num,
95f7142a
PL
1006 req->qiov.size / BDRV_SECTOR_SIZE);
1007 }
1008
9a6719d5 1009 if (!virtio_blk_sect_range_ok(s, req->sector_num, req->qiov.size)) {
95f7142a 1010 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
9a6719d5 1011 block_acct_invalid(blk_get_stats(s->blk),
01762e03 1012 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
95f7142a 1013 virtio_blk_free_request(req);
20ea686a 1014 return 0;
95f7142a
PL
1015 }
1016
9a6719d5 1017 block_acct_start(blk_get_stats(s->blk), &req->acct, req->qiov.size,
95f7142a
PL
1018 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
1019
1020 /* merge would exceed maximum number of requests or IO direction
1021 * changes */
1022 if (mrb->num_reqs > 0 && (mrb->num_reqs == VIRTIO_BLK_MAX_MERGE_REQS ||
c99495ac 1023 is_write != mrb->is_write ||
9a6719d5 1024 !s->conf.request_merging)) {
baf42268 1025 virtio_blk_submit_multireq(s, mrb);
95f7142a
PL
1026 }
1027
1028 assert(mrb->num_reqs < VIRTIO_BLK_MAX_MERGE_REQS);
1029 mrb->reqs[mrb->num_reqs++] = req;
1030 mrb->is_write = is_write;
1031 break;
1032 }
1033 case VIRTIO_BLK_T_FLUSH:
c20fd872 1034 virtio_blk_handle_flush(req, mrb);
95f7142a 1035 break;
4f736650
SL
1036 case VIRTIO_BLK_T_ZONE_REPORT:
1037 virtio_blk_handle_zone_report(req, in_iov, in_num);
1038 break;
1039 case VIRTIO_BLK_T_ZONE_OPEN:
1040 virtio_blk_handle_zone_mgmt(req, BLK_ZO_OPEN);
1041 break;
1042 case VIRTIO_BLK_T_ZONE_CLOSE:
1043 virtio_blk_handle_zone_mgmt(req, BLK_ZO_CLOSE);
1044 break;
1045 case VIRTIO_BLK_T_ZONE_FINISH:
1046 virtio_blk_handle_zone_mgmt(req, BLK_ZO_FINISH);
1047 break;
1048 case VIRTIO_BLK_T_ZONE_RESET:
1049 virtio_blk_handle_zone_mgmt(req, BLK_ZO_RESET);
1050 break;
1051 case VIRTIO_BLK_T_ZONE_RESET_ALL:
1052 virtio_blk_handle_zone_mgmt(req, BLK_ZO_RESET);
1053 break;
95f7142a 1054 case VIRTIO_BLK_T_SCSI_CMD:
bc6694d4 1055 virtio_blk_handle_scsi(req);
95f7142a
PL
1056 break;
1057 case VIRTIO_BLK_T_GET_ID:
1058 {
a8686a9b
MA
1059 /*
1060 * NB: per existing s/n string convention the string is
1061 * terminated by '\0' only when shorter than buffer.
1062 */
2a30307f 1063 const char *serial = s->conf.serial ? s->conf.serial : "";
a83ceea8
MM
1064 size_t size = MIN(strlen(serial) + 1,
1065 MIN(iov_size(in_iov, in_num),
1066 VIRTIO_BLK_ID_BYTES));
1067 iov_from_buf(in_iov, in_num, 0, serial, size);
2930b313 1068 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
671ec3f0 1069 virtio_blk_free_request(req);
95f7142a
PL
1070 break;
1071 }
4f736650
SL
1072 case VIRTIO_BLK_T_ZONE_APPEND & ~VIRTIO_BLK_T_OUT:
1073 /*
1074 * Passing out_iov/out_num and in_iov/in_num is not safe
1075 * to access req->elem.out_sg directly because it may be
1076 * modified by virtio_blk_handle_request().
1077 */
1078 virtio_blk_handle_zone_append(req, out_iov, in_iov, out_num, in_num);
1079 break;
37b06f8d
SG
1080 /*
1081 * VIRTIO_BLK_T_DISCARD and VIRTIO_BLK_T_WRITE_ZEROES are defined with
1082 * VIRTIO_BLK_T_OUT flag set. We masked this flag in the switch statement,
1083 * so we must mask it for these requests, then we will check if it is set.
1084 */
1085 case VIRTIO_BLK_T_DISCARD & ~VIRTIO_BLK_T_OUT:
1086 case VIRTIO_BLK_T_WRITE_ZEROES & ~VIRTIO_BLK_T_OUT:
1087 {
1088 struct virtio_blk_discard_write_zeroes dwz_hdr;
1089 size_t out_len = iov_size(out_iov, out_num);
1090 bool is_write_zeroes = (type & ~VIRTIO_BLK_T_BARRIER) ==
1091 VIRTIO_BLK_T_WRITE_ZEROES;
1092 uint8_t err_status;
1093
1094 /*
1095 * Unsupported if VIRTIO_BLK_T_OUT is not set or the request contains
1096 * more than one segment.
1097 */
1098 if (unlikely(!(type & VIRTIO_BLK_T_OUT) ||
1099 out_len > sizeof(dwz_hdr))) {
1100 virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
1101 virtio_blk_free_request(req);
1102 return 0;
1103 }
1104
1105 if (unlikely(iov_to_buf(out_iov, out_num, 0, &dwz_hdr,
1106 sizeof(dwz_hdr)) != sizeof(dwz_hdr))) {
7bd04a04
SH
1107 iov_discard_undo(&req->inhdr_undo);
1108 iov_discard_undo(&req->outhdr_undo);
37b06f8d
SG
1109 virtio_error(vdev, "virtio-blk discard/write_zeroes header"
1110 " too short");
1111 return -1;
1112 }
1113
1114 err_status = virtio_blk_handle_discard_write_zeroes(req, &dwz_hdr,
1115 is_write_zeroes);
1116 if (err_status != VIRTIO_BLK_S_OK) {
1117 virtio_blk_req_complete(req, err_status);
1118 virtio_blk_free_request(req);
1119 }
1120
1121 break;
1122 }
95f7142a 1123 default:
9e72c450 1124 virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
671ec3f0 1125 virtio_blk_free_request(req);
bc6694d4 1126 }
20ea686a 1127 return 0;
bc6694d4
KW
1128}
1129
186b9691 1130void virtio_blk_handle_vq(VirtIOBlock *s, VirtQueue *vq)
6e02c38d 1131{
6e02c38d 1132 VirtIOBlockReq *req;
95f7142a 1133 MultiReqBuffer mrb = {};
d0435bc5 1134 bool suppress_notifications = virtio_queue_get_notification(vq);
6e02c38d 1135
9d456654 1136 aio_context_acquire(blk_get_aio_context(s->blk));
ccee48aa 1137 defer_call_begin();
fc73548e 1138
9ef9d402 1139 do {
d0435bc5
SH
1140 if (suppress_notifications) {
1141 virtio_queue_set_notification(vq, 0);
1142 }
9ef9d402
SH
1143
1144 while ((req = virtio_blk_get_request(s, vq))) {
1145 if (virtio_blk_handle_request(req, &mrb)) {
1146 virtqueue_detach_element(req->vq, &req->elem, 0);
1147 virtio_blk_free_request(req);
1148 break;
1149 }
20ea686a 1150 }
9ef9d402 1151
d0435bc5
SH
1152 if (suppress_notifications) {
1153 virtio_queue_set_notification(vq, 1);
1154 }
9ef9d402 1155 } while (!virtio_queue_empty(vq));
91553dcc 1156
95f7142a 1157 if (mrb.num_reqs) {
baf42268 1158 virtio_blk_submit_multireq(s, &mrb);
95f7142a 1159 }
fc73548e 1160
ccee48aa 1161 defer_call_end();
9d456654 1162 aio_context_release(blk_get_aio_context(s->blk));
6e02c38d
AL
1163}
1164
8a2fad57
MT
1165static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)
1166{
1167 VirtIOBlock *s = (VirtIOBlock *)vdev;
1168
186b9691 1169 if (s->dataplane && !s->dataplane_started) {
8a2fad57
MT
1170 /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start
1171 * dataplane here instead of waiting for .set_status().
1172 */
9ffe337c 1173 virtio_device_start_ioeventfd(vdev);
8a2fad57
MT
1174 if (!s->dataplane_disabled) {
1175 return;
1176 }
1177 }
186b9691 1178 virtio_blk_handle_vq(s, vq);
8a2fad57
MT
1179}
1180
a937f8e8 1181static void virtio_blk_dma_restart_bh(void *opaque)
869a5c6d 1182{
a937f8e8
SH
1183 VirtIOBlock *s = opaque;
1184
869a5c6d 1185 VirtIOBlockReq *req = s->rq;
95f7142a 1186 MultiReqBuffer mrb = {};
869a5c6d 1187
869a5c6d
AL
1188 s->rq = NULL;
1189
1919631e 1190 aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
869a5c6d 1191 while (req) {
1bdb176a 1192 VirtIOBlockReq *next = req->next;
20ea686a
GK
1193 if (virtio_blk_handle_request(req, &mrb)) {
1194 /* Device is now broken and won't do any processing until it gets
1195 * reset. Already queued requests will be lost: let's purge them.
1196 */
1197 while (req) {
1198 next = req->next;
1199 virtqueue_detach_element(req->vq, &req->elem, 0);
1200 virtio_blk_free_request(req);
1201 req = next;
1202 }
1203 break;
1204 }
1bdb176a 1205 req = next;
869a5c6d 1206 }
f1b52868 1207
95f7142a 1208 if (mrb.num_reqs) {
baf42268 1209 virtio_blk_submit_multireq(s, &mrb);
95f7142a 1210 }
7aa1c247 1211
a937f8e8
SH
1212 /* Paired with inc in virtio_blk_dma_restart_cb() */
1213 blk_dec_in_flight(s->conf.conf.blk);
7aa1c247 1214
a937f8e8 1215 aio_context_release(blk_get_aio_context(s->conf.conf.blk));
7aa1c247
SL
1216}
1217
538f0497 1218static void virtio_blk_dma_restart_cb(void *opaque, bool running,
1dfb4dd9 1219 RunState state)
213189ab
MA
1220{
1221 VirtIOBlock *s = opaque;
1222
392808b4 1223 if (!running) {
213189ab 1224 return;
392808b4 1225 }
213189ab 1226
a937f8e8
SH
1227 /* Paired with dec in virtio_blk_dma_restart_bh() */
1228 blk_inc_in_flight(s->conf.conf.blk);
1229
1230 aio_bh_schedule_oneshot(blk_get_aio_context(s->conf.conf.blk),
1231 virtio_blk_dma_restart_bh, s);
213189ab
MA
1232}
1233
6e02c38d
AL
1234static void virtio_blk_reset(VirtIODevice *vdev)
1235{
1cc91b7d 1236 VirtIOBlock *s = VIRTIO_BLK(vdev);
6e40b3bf 1237 AioContext *ctx;
26307f6a 1238 VirtIOBlockReq *req;
392808b4 1239
6e40b3bf
AY
1240 ctx = blk_get_aio_context(s->blk);
1241 aio_context_acquire(ctx);
1242 blk_drain(s->blk);
1243
26307f6a
FZ
1244 /* We drop queued requests after blk_drain() because blk_drain() itself can
1245 * produce them. */
1246 while (s->rq) {
1247 req = s->rq;
1248 s->rq = req->next;
97b93c8a 1249 virtqueue_detach_element(req->vq, &req->elem, 0);
26307f6a
FZ
1250 virtio_blk_free_request(req);
1251 }
1252
6e40b3bf
AY
1253 aio_context_release(ctx);
1254
9ffe337c 1255 assert(!s->dataplane_started);
4be74634 1256 blk_set_enable_write_cache(s->blk, s->original_wce);
6e02c38d
AL
1257}
1258
bf011293 1259/* coalesce internal state, copy to pci i/o region 0
1260 */
6e02c38d
AL
1261static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
1262{
1cc91b7d 1263 VirtIOBlock *s = VIRTIO_BLK(vdev);
2a30307f 1264 BlockConf *conf = &s->conf.conf;
4f736650 1265 BlockDriverState *bs = blk_bs(s->blk);
6e02c38d
AL
1266 struct virtio_blk_config blkcfg;
1267 uint64_t capacity;
17d0bc01 1268 int64_t length;
f7516731 1269 int blk_size = conf->logical_block_size;
1f433e84
EGE
1270 AioContext *ctx;
1271
1272 ctx = blk_get_aio_context(s->blk);
1273 aio_context_acquire(ctx);
6e02c38d 1274
4be74634 1275 blk_get_geometry(s->blk, &capacity);
5c5dafdc 1276 memset(&blkcfg, 0, sizeof(blkcfg));
783d1897 1277 virtio_stq_p(vdev, &blkcfg.capacity, capacity);
1bf8a989
DP
1278 virtio_stl_p(vdev, &blkcfg.seg_max,
1279 s->conf.seg_max_adjust ? s->conf.queue_size - 2 : 128 - 2);
907eb3e5 1280 virtio_stw_p(vdev, &blkcfg.geometry.cylinders, conf->cyls);
783d1897 1281 virtio_stl_p(vdev, &blkcfg.blk_size, blk_size);
f7516731 1282 virtio_stw_p(vdev, &blkcfg.min_io_size, conf->min_io_size / blk_size);
6abee260 1283 virtio_stl_p(vdev, &blkcfg.opt_io_size, conf->opt_io_size / blk_size);
907eb3e5 1284 blkcfg.geometry.heads = conf->heads;
136be99e
CB
1285 /*
1286 * We must ensure that the block device capacity is a multiple of
e03ba136 1287 * the logical block size. If that is not the case, let's use
136be99e
CB
1288 * sector_mask to adopt the geometry to have a correct picture.
1289 * For those devices where the capacity is ok for the given geometry
e03ba136 1290 * we don't touch the sector value of the geometry, since some devices
136be99e
CB
1291 * (like s390 dasd) need a specific value. Here the capacity is already
1292 * cyls*heads*secs*blk_size and the sector value is not block size
1293 * divided by 512 - instead it is the amount of blk_size blocks
1294 * per track (cylinder).
1295 */
17d0bc01 1296 length = blk_getlength(s->blk);
1f433e84 1297 aio_context_release(ctx);
17d0bc01 1298 if (length > 0 && length / conf->heads / conf->secs % blk_size) {
907eb3e5 1299 blkcfg.geometry.sectors = conf->secs & ~s->sector_mask;
136be99e 1300 } else {
907eb3e5 1301 blkcfg.geometry.sectors = conf->secs;
136be99e 1302 }
c7085da7 1303 blkcfg.size_max = 0;
f7516731 1304 blkcfg.physical_block_exp = get_physical_block_exp(conf);
9752c371 1305 blkcfg.alignment_offset = 0;
4be74634 1306 blkcfg.wce = blk_enable_write_cache(s->blk);
2f270590 1307 virtio_stw_p(vdev, &blkcfg.num_queues, s->conf.num_queues);
37b06f8d 1308 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_DISCARD)) {
fb0b154c
AO
1309 uint32_t discard_granularity = conf->discard_granularity;
1310 if (discard_granularity == -1 || !s->conf.report_discard_granularity) {
1311 discard_granularity = blk_size;
1312 }
37b06f8d
SG
1313 virtio_stl_p(vdev, &blkcfg.max_discard_sectors,
1314 s->conf.max_discard_sectors);
1315 virtio_stl_p(vdev, &blkcfg.discard_sector_alignment,
fb0b154c 1316 discard_granularity >> BDRV_SECTOR_BITS);
37b06f8d
SG
1317 /*
1318 * We support only one segment per request since multiple segments
1319 * are not widely used and there are no userspace APIs that allow
1320 * applications to submit multiple segments in a single call.
1321 */
1322 virtio_stl_p(vdev, &blkcfg.max_discard_seg, 1);
1323 }
1324 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_WRITE_ZEROES)) {
1325 virtio_stl_p(vdev, &blkcfg.max_write_zeroes_sectors,
1326 s->conf.max_write_zeroes_sectors);
1327 blkcfg.write_zeroes_may_unmap = 1;
1328 virtio_stl_p(vdev, &blkcfg.max_write_zeroes_seg, 1);
1329 }
4f736650
SL
1330 if (bs->bl.zoned != BLK_Z_NONE) {
1331 switch (bs->bl.zoned) {
1332 case BLK_Z_HM:
1333 blkcfg.zoned.model = VIRTIO_BLK_Z_HM;
1334 break;
1335 case BLK_Z_HA:
1336 blkcfg.zoned.model = VIRTIO_BLK_Z_HA;
1337 break;
1338 default:
1339 g_assert_not_reached();
1340 }
1341
1342 virtio_stl_p(vdev, &blkcfg.zoned.zone_sectors,
1343 bs->bl.zone_size / 512);
1344 virtio_stl_p(vdev, &blkcfg.zoned.max_active_zones,
1345 bs->bl.max_active_zones);
1346 virtio_stl_p(vdev, &blkcfg.zoned.max_open_zones,
1347 bs->bl.max_open_zones);
1348 virtio_stl_p(vdev, &blkcfg.zoned.write_granularity, blk_size);
1349 virtio_stl_p(vdev, &blkcfg.zoned.max_append_sectors,
1350 bs->bl.max_append_sectors);
1351 } else {
1352 blkcfg.zoned.model = VIRTIO_BLK_Z_NONE;
1353 }
20764be0 1354 memcpy(config, &blkcfg, s->config_size);
6e02c38d
AL
1355}
1356
13e3dce0
PB
1357static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config)
1358{
1cc91b7d 1359 VirtIOBlock *s = VIRTIO_BLK(vdev);
13e3dce0
PB
1360 struct virtio_blk_config blkcfg;
1361
20764be0 1362 memcpy(&blkcfg, config, s->config_size);
6d7e73d6 1363
4be74634
MA
1364 aio_context_acquire(blk_get_aio_context(s->blk));
1365 blk_set_enable_write_cache(s->blk, blkcfg.wce != 0);
1366 aio_context_release(blk_get_aio_context(s->blk));
13e3dce0
PB
1367}
1368
9d5b731d
JW
1369static uint64_t virtio_blk_get_features(VirtIODevice *vdev, uint64_t features,
1370 Error **errp)
6e02c38d 1371{
1cc91b7d 1372 VirtIOBlock *s = VIRTIO_BLK(vdev);
1063b8b1 1373
bbe8bd4d
SG
1374 /* Firstly sync all virtio-blk possible supported features */
1375 features |= s->host_features;
1376
0cd09c3a
CH
1377 virtio_add_feature(&features, VIRTIO_BLK_F_SEG_MAX);
1378 virtio_add_feature(&features, VIRTIO_BLK_F_GEOMETRY);
1379 virtio_add_feature(&features, VIRTIO_BLK_F_TOPOLOGY);
1380 virtio_add_feature(&features, VIRTIO_BLK_F_BLK_SIZE);
95129d6f 1381 if (virtio_has_feature(features, VIRTIO_F_VERSION_1)) {
bbe8bd4d 1382 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_SCSI)) {
efb8206c
JW
1383 error_setg(errp, "Please set scsi=off for virtio-blk devices in order to use virtio 1.0");
1384 return 0;
1385 }
efb8206c 1386 } else {
c9b11f97 1387 virtio_clear_feature(&features, VIRTIO_F_ANY_LAYOUT);
efb8206c
JW
1388 virtio_add_feature(&features, VIRTIO_BLK_F_SCSI);
1389 }
aa659be3 1390
5f258577
EY
1391 if (blk_enable_write_cache(s->blk) ||
1392 (s->conf.x_enable_wce_if_config_wce &&
1393 virtio_has_feature(features, VIRTIO_BLK_F_CONFIG_WCE))) {
0cd09c3a 1394 virtio_add_feature(&features, VIRTIO_BLK_F_WCE);
4be74634 1395 }
86b1cf32 1396 if (!blk_is_writable(s->blk)) {
0cd09c3a 1397 virtio_add_feature(&features, VIRTIO_BLK_F_RO);
4be74634 1398 }
2f270590
SH
1399 if (s->conf.num_queues > 1) {
1400 virtio_add_feature(&features, VIRTIO_BLK_F_MQ);
1401 }
1063b8b1
CH
1402
1403 return features;
6e02c38d
AL
1404}
1405
9315cbfd
PB
1406static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)
1407{
1cc91b7d 1408 VirtIOBlock *s = VIRTIO_BLK(vdev);
9315cbfd 1409
9ffe337c
PB
1410 if (!(status & (VIRTIO_CONFIG_S_DRIVER | VIRTIO_CONFIG_S_DRIVER_OK))) {
1411 assert(!s->dataplane_started);
392808b4 1412 }
392808b4 1413
9315cbfd
PB
1414 if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
1415 return;
1416 }
1417
ef5bc962
PB
1418 /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send
1419 * cache flushes. Thus, the "auto writethrough" behavior is never
1420 * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.
1421 * Leaving it enabled would break the following sequence:
1422 *
1423 * Guest started with "-drive cache=writethrough"
1424 * Guest sets status to 0
1425 * Guest sets DRIVER bit in status field
1426 * Guest reads host features (WCE=0, CONFIG_WCE=1)
1427 * Guest writes guest features (WCE=0, CONFIG_WCE=1)
1428 * Guest writes 1 to the WCE configuration field (writeback mode)
1429 * Guest sets DRIVER_OK bit in status field
1430 *
4be74634 1431 * s->blk would erroneously be placed in writethrough mode.
ef5bc962 1432 */
95129d6f 1433 if (!virtio_vdev_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE)) {
4be74634
MA
1434 aio_context_acquire(blk_get_aio_context(s->blk));
1435 blk_set_enable_write_cache(s->blk,
95129d6f
CH
1436 virtio_vdev_has_feature(vdev,
1437 VIRTIO_BLK_F_WCE));
4be74634 1438 aio_context_release(blk_get_aio_context(s->blk));
ef5bc962 1439 }
9315cbfd
PB
1440}
1441
b2b295a7
GK
1442static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f)
1443{
1444 VirtIOBlock *s = VIRTIO_BLK(vdev);
1445 VirtIOBlockReq *req = s->rq;
1446
869a5c6d
AL
1447 while (req) {
1448 qemu_put_sbyte(f, 1);
30d8bf6d
SH
1449
1450 if (s->conf.num_queues > 1) {
1451 qemu_put_be32(f, virtio_get_queue_index(req->vq));
1452 }
1453
86044b24 1454 qemu_put_virtqueue_element(vdev, f, &req->elem);
869a5c6d
AL
1455 req = req->next;
1456 }
1457 qemu_put_sbyte(f, 0);
6e02c38d
AL
1458}
1459
b2b295a7
GK
1460static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f,
1461 int version_id)
1462{
1463 VirtIOBlock *s = VIRTIO_BLK(vdev);
2a633c46 1464
869a5c6d 1465 while (qemu_get_sbyte(f)) {
30d8bf6d
SH
1466 unsigned nvqs = s->conf.num_queues;
1467 unsigned vq_idx = 0;
ab281c17 1468 VirtIOBlockReq *req;
30d8bf6d
SH
1469
1470 if (nvqs > 1) {
1471 vq_idx = qemu_get_be32(f);
1472
1473 if (vq_idx >= nvqs) {
1474 error_report("Invalid virtqueue index in request list: %#x",
1475 vq_idx);
1476 return -EINVAL;
1477 }
1478 }
1479
8607f5c3 1480 req = qemu_get_virtqueue_element(vdev, f, sizeof(VirtIOBlockReq));
30d8bf6d 1481 virtio_blk_init_request(s, virtio_get_queue(vdev, vq_idx), req);
869a5c6d 1482 req->next = s->rq;
20a81e4d 1483 s->rq = req;
869a5c6d 1484 }
6e02c38d
AL
1485
1486 return 0;
1487}
1488
9b92fbcf
SL
1489static void virtio_resize_cb(void *opaque)
1490{
1491 VirtIODevice *vdev = opaque;
1492
1493 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1494 virtio_notify_config(vdev);
1495}
1496
145feb17 1497static void virtio_blk_resize(void *opaque)
e5051fc7 1498{
1cc91b7d 1499 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
e5051fc7 1500
9b92fbcf
SL
1501 /*
1502 * virtio_notify_config() needs to acquire the global mutex,
1503 * so it can't be called from an iothread. Instead, schedule
1504 * it to be run in the main context BH.
1505 */
1506 aio_bh_schedule_oneshot(qemu_get_aio_context(), virtio_resize_cb, vdev);
e5051fc7
CH
1507}
1508
1665d932
SH
1509/* Suspend virtqueue ioeventfd processing during drain */
1510static void virtio_blk_drained_begin(void *opaque)
1511{
1512 VirtIOBlock *s = opaque;
1513 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
1514 AioContext *ctx = blk_get_aio_context(s->conf.conf.blk);
1515
1516 if (!s->dataplane || !s->dataplane_started) {
1517 return;
1518 }
1519
1520 for (uint16_t i = 0; i < s->conf.num_queues; i++) {
1521 VirtQueue *vq = virtio_get_queue(vdev, i);
1522 virtio_queue_aio_detach_host_notifier(vq, ctx);
1523 }
1524}
1525
1526/* Resume virtqueue ioeventfd processing after drain */
1527static void virtio_blk_drained_end(void *opaque)
1528{
1529 VirtIOBlock *s = opaque;
1530 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
1531 AioContext *ctx = blk_get_aio_context(s->conf.conf.blk);
1532
1533 if (!s->dataplane || !s->dataplane_started) {
1534 return;
1535 }
1536
1537 for (uint16_t i = 0; i < s->conf.num_queues; i++) {
1538 VirtQueue *vq = virtio_get_queue(vdev, i);
1539 virtio_queue_aio_attach_host_notifier(vq, ctx);
1540 }
1541}
1542
0e49de52 1543static const BlockDevOps virtio_block_ops = {
1665d932
SH
1544 .resize_cb = virtio_blk_resize,
1545 .drained_begin = virtio_blk_drained_begin,
1546 .drained_end = virtio_blk_drained_end,
0e49de52
MA
1547};
1548
75884afd 1549static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
1c028ddf 1550{
75884afd 1551 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
179b417e 1552 VirtIOBlock *s = VIRTIO_BLK(dev);
2a30307f 1553 VirtIOBlkConf *conf = &s->conf;
3ffeeef7 1554 Error *err = NULL;
2f270590 1555 unsigned i;
cf21e106 1556
4be74634 1557 if (!conf->conf.blk) {
75884afd
AF
1558 error_setg(errp, "drive property not set");
1559 return;
d75d25e3 1560 }
4be74634 1561 if (!blk_is_inserted(conf->conf.blk)) {
75884afd
AF
1562 error_setg(errp, "Device needs media, but drive is empty");
1563 return;
98f28ad7 1564 }
9445e1e1
SH
1565 if (conf->num_queues == VIRTIO_BLK_AUTO_NUM_QUEUES) {
1566 conf->num_queues = 1;
1567 }
2f270590
SH
1568 if (!conf->num_queues) {
1569 error_setg(errp, "num-queues property must be larger than 0");
1570 return;
1571 }
1bf8a989
DP
1572 if (conf->queue_size <= 2) {
1573 error_setg(errp, "invalid queue-size property (%" PRIu16 "), "
1574 "must be > 2", conf->queue_size);
1575 return;
1576 }
6040aedd
MK
1577 if (!is_power_of_2(conf->queue_size) ||
1578 conf->queue_size > VIRTQUEUE_MAX_SIZE) {
1579 error_setg(errp, "invalid queue-size property (%" PRIu16 "), "
1580 "must be a power of 2 (max %d)",
1581 conf->queue_size, VIRTQUEUE_MAX_SIZE);
1582 return;
1583 }
d75d25e3 1584
ceff3e1f 1585 if (!blkconf_apply_backend_options(&conf->conf,
86b1cf32
KW
1586 !blk_supports_write_perm(conf->conf.blk),
1587 true, errp)) {
a17c17a2
KW
1588 return;
1589 }
4be74634 1590 s->original_wce = blk_enable_write_cache(conf->conf.blk);
ceff3e1f 1591 if (!blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, errp)) {
75884afd 1592 return;
b7eb0c9f 1593 }
ceff3e1f 1594
c56ee92f 1595 if (!blkconf_blocksizes(&conf->conf, errp)) {
0a75b60c
MK
1596 return;
1597 }
1598
4f736650
SL
1599 BlockDriverState *bs = blk_bs(conf->conf.blk);
1600 if (bs->bl.zoned != BLK_Z_NONE) {
1601 virtio_add_feature(&s->host_features, VIRTIO_BLK_F_ZONED);
1602 if (bs->bl.zoned == BLK_Z_HM) {
1603 virtio_clear_feature(&s->host_features, VIRTIO_BLK_F_DISCARD);
1604 }
1605 }
1606
37b06f8d
SG
1607 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_DISCARD) &&
1608 (!conf->max_discard_sectors ||
1609 conf->max_discard_sectors > BDRV_REQUEST_MAX_SECTORS)) {
1610 error_setg(errp, "invalid max-discard-sectors property (%" PRIu32 ")"
1611 ", must be between 1 and %d",
1612 conf->max_discard_sectors, (int)BDRV_REQUEST_MAX_SECTORS);
1613 return;
1614 }
1615
1616 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_WRITE_ZEROES) &&
1617 (!conf->max_write_zeroes_sectors ||
1618 conf->max_write_zeroes_sectors > BDRV_REQUEST_MAX_SECTORS)) {
1619 error_setg(errp, "invalid max-write-zeroes-sectors property (%" PRIu32
1620 "), must be between 1 and %d",
1621 conf->max_write_zeroes_sectors,
1622 (int)BDRV_REQUEST_MAX_SECTORS);
1623 return;
1624 }
1625
d9cf55a8 1626 s->config_size = virtio_get_config_size(&virtio_blk_cfg_size_params,
d74c30c8 1627 s->host_features);
3857cd5c 1628 virtio_init(vdev, VIRTIO_ID_BLOCK, s->config_size);
6e02c38d 1629
4be74634 1630 s->blk = conf->conf.blk;
869a5c6d 1631 s->rq = NULL;
2a30307f 1632 s->sector_mask = (s->conf.conf.logical_block_size / BDRV_SECTOR_SIZE) - 1;
e63e7fde 1633
2f270590 1634 for (i = 0; i < conf->num_queues; i++) {
6040aedd 1635 virtio_add_queue(vdev, conf->queue_size, virtio_blk_handle_output);
2f270590 1636 }
98e3ab35 1637 qemu_coroutine_inc_pool_size(conf->num_queues * conf->queue_size / 2);
2a30307f 1638 virtio_blk_data_plane_create(vdev, conf, &s->dataplane, &err);
3ffeeef7 1639 if (err != NULL) {
75884afd 1640 error_propagate(errp, err);
cfaf757e
PN
1641 for (i = 0; i < conf->num_queues; i++) {
1642 virtio_del_queue(vdev, i);
1643 }
6a1a8cc7 1644 virtio_cleanup(vdev);
75884afd 1645 return;
392808b4 1646 }
6e02c38d 1647
a937f8e8
SH
1648 /*
1649 * This must be after virtio_init() so virtio_blk_dma_restart_cb() gets
1650 * called after ->start_ioeventfd() has already set blk's AioContext.
1651 */
1652 s->change =
1653 qdev_add_vm_change_state_handler(dev, virtio_blk_dma_restart_cb, s);
1654
baf42268 1655 blk_ram_registrar_init(&s->blk_ram_registrar, s->blk);
4be74634 1656 blk_set_dev_ops(s->blk, &virtio_block_ops, s);
6e02c38d 1657
4be74634 1658 blk_iostatus_enable(s->blk);
71f571a2
SE
1659
1660 add_boot_device_lchs(dev, "/disk@0,0",
1661 conf->conf.lcyls,
1662 conf->conf.lheads,
1663 conf->conf.lsecs);
1c028ddf
FK
1664}
1665
b69c3c21 1666static void virtio_blk_device_unrealize(DeviceState *dev)
1c028ddf 1667{
306ec6c3
AF
1668 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1669 VirtIOBlock *s = VIRTIO_BLK(dev);
4a0117cf
EP
1670 VirtIOBlkConf *conf = &s->conf;
1671 unsigned i;
306ec6c3 1672
7bfde688 1673 blk_drain(s->blk);
71f571a2 1674 del_boot_device_lchs(dev, "/disk@0,0");
1c028ddf
FK
1675 virtio_blk_data_plane_destroy(s->dataplane);
1676 s->dataplane = NULL;
4a0117cf
EP
1677 for (i = 0; i < conf->num_queues; i++) {
1678 virtio_del_queue(vdev, i);
1679 }
98e3ab35 1680 qemu_coroutine_dec_pool_size(conf->num_queues * conf->queue_size / 2);
baf42268 1681 blk_ram_registrar_destroy(&s->blk_ram_registrar);
1c028ddf 1682 qemu_del_vm_change_state_handler(s->change);
4be74634 1683 blockdev_mark_auto_del(s->blk);
6a1a8cc7 1684 virtio_cleanup(vdev);
1c028ddf
FK
1685}
1686
467b3f33
SH
1687static void virtio_blk_instance_init(Object *obj)
1688{
1689 VirtIOBlock *s = VIRTIO_BLK(obj);
1690
2a30307f 1691 device_add_bootindex_property(obj, &s->conf.conf.bootindex,
3342ec32 1692 "bootindex", "/disk@0,0",
40c2281c 1693 DEVICE(obj));
467b3f33
SH
1694}
1695
977a117f
HP
1696static const VMStateDescription vmstate_virtio_blk = {
1697 .name = "virtio-blk",
1698 .minimum_version_id = 2,
1699 .version_id = 2,
1700 .fields = (VMStateField[]) {
1701 VMSTATE_VIRTIO_DEVICE,
1702 VMSTATE_END_OF_LIST()
1703 },
1704};
bbded32c 1705
1c028ddf 1706static Property virtio_blk_properties[] = {
2a30307f 1707 DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf),
8c398252 1708 DEFINE_BLOCK_ERROR_PROPERTIES(VirtIOBlock, conf.conf),
2a30307f
MA
1709 DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf),
1710 DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial),
bbe8bd4d
SG
1711 DEFINE_PROP_BIT64("config-wce", VirtIOBlock, host_features,
1712 VIRTIO_BLK_F_CONFIG_WCE, true),
32a877e4 1713#ifdef __linux__
bbe8bd4d
SG
1714 DEFINE_PROP_BIT64("scsi", VirtIOBlock, host_features,
1715 VIRTIO_BLK_F_SCSI, false),
32a877e4 1716#endif
c99495ac
PL
1717 DEFINE_PROP_BIT("request-merging", VirtIOBlock, conf.request_merging, 0,
1718 true),
9445e1e1
SH
1719 DEFINE_PROP_UINT16("num-queues", VirtIOBlock, conf.num_queues,
1720 VIRTIO_BLK_AUTO_NUM_QUEUES),
c9b7d9ec 1721 DEFINE_PROP_UINT16("queue-size", VirtIOBlock, conf.queue_size, 256),
1bf8a989 1722 DEFINE_PROP_BOOL("seg-max-adjust", VirtIOBlock, conf.seg_max_adjust, true),
d679ac09
FZ
1723 DEFINE_PROP_LINK("iothread", VirtIOBlock, conf.iothread, TYPE_IOTHREAD,
1724 IOThread *),
5c81161f
SG
1725 DEFINE_PROP_BIT64("discard", VirtIOBlock, host_features,
1726 VIRTIO_BLK_F_DISCARD, true),
fb0b154c
AO
1727 DEFINE_PROP_BOOL("report-discard-granularity", VirtIOBlock,
1728 conf.report_discard_granularity, true),
5c81161f
SG
1729 DEFINE_PROP_BIT64("write-zeroes", VirtIOBlock, host_features,
1730 VIRTIO_BLK_F_WRITE_ZEROES, true),
37b06f8d
SG
1731 DEFINE_PROP_UINT32("max-discard-sectors", VirtIOBlock,
1732 conf.max_discard_sectors, BDRV_REQUEST_MAX_SECTORS),
1733 DEFINE_PROP_UINT32("max-write-zeroes-sectors", VirtIOBlock,
1734 conf.max_write_zeroes_sectors, BDRV_REQUEST_MAX_SECTORS),
5f258577
EY
1735 DEFINE_PROP_BOOL("x-enable-wce-if-config-wce", VirtIOBlock,
1736 conf.x_enable_wce_if_config_wce, true),
1c028ddf
FK
1737 DEFINE_PROP_END_OF_LIST(),
1738};
1739
1740static void virtio_blk_class_init(ObjectClass *klass, void *data)
1741{
1742 DeviceClass *dc = DEVICE_CLASS(klass);
1743 VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
75884afd 1744
4f67d30b 1745 device_class_set_props(dc, virtio_blk_properties);
bbded32c 1746 dc->vmsd = &vmstate_virtio_blk;
125ee0ed 1747 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
75884afd 1748 vdc->realize = virtio_blk_device_realize;
306ec6c3 1749 vdc->unrealize = virtio_blk_device_unrealize;
1c028ddf
FK
1750 vdc->get_config = virtio_blk_update_config;
1751 vdc->set_config = virtio_blk_set_config;
1752 vdc->get_features = virtio_blk_get_features;
1753 vdc->set_status = virtio_blk_set_status;
1754 vdc->reset = virtio_blk_reset;
b2b295a7
GK
1755 vdc->save = virtio_blk_save_device;
1756 vdc->load = virtio_blk_load_device;
9ffe337c
PB
1757 vdc->start_ioeventfd = virtio_blk_data_plane_start;
1758 vdc->stop_ioeventfd = virtio_blk_data_plane_stop;
1c028ddf
FK
1759}
1760
b5c7ceaf 1761static const TypeInfo virtio_blk_info = {
1c028ddf
FK
1762 .name = TYPE_VIRTIO_BLK,
1763 .parent = TYPE_VIRTIO_DEVICE,
1764 .instance_size = sizeof(VirtIOBlock),
467b3f33 1765 .instance_init = virtio_blk_instance_init,
1c028ddf
FK
1766 .class_init = virtio_blk_class_init,
1767};
1768
1769static void virtio_register_types(void)
1770{
b5c7ceaf 1771 type_register_static(&virtio_blk_info);
1c028ddf
FK
1772}
1773
1774type_init(virtio_register_types)