]> git.proxmox.com Git - mirror_qemu.git/blame - hw/block/virtio-blk.c
virtio: move VirtQueueElement at the beginning of the structs
[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"
5a61cb60 15#include "qemu-common.h"
827805a2 16#include "qemu/iov.h"
1de7afc9 17#include "qemu/error-report.h"
6d519a5f 18#include "trace.h"
0d09e41a 19#include "hw/block/block.h"
4be74634 20#include "sysemu/block-backend.h"
9c17d615 21#include "sysemu/blockdev.h"
0d09e41a 22#include "hw/virtio/virtio-blk.h"
52b53c04
FZ
23#include "dataplane/virtio-blk.h"
24#include "migration/migration.h"
0d09e41a 25#include "block/scsi.h"
1063b8b1
CH
26#ifdef __linux__
27# include <scsi/sg.h>
28#endif
0d09e41a 29#include "hw/virtio/virtio-bus.h"
783d1897 30#include "hw/virtio/virtio-access.h"
6e02c38d 31
f897bf75 32VirtIOBlockReq *virtio_blk_alloc_request(VirtIOBlock *s)
671ec3f0 33{
c84b3192 34 VirtIOBlockReq *req = g_new(VirtIOBlockReq, 1);
671ec3f0 35 req->dev = s;
869d66af 36 req->qiov.size = 0;
2a6cdd6d 37 req->in_len = 0;
869d66af 38 req->next = NULL;
95f7142a 39 req->mr_next = NULL;
671ec3f0
FZ
40 return req;
41}
42
f897bf75 43void virtio_blk_free_request(VirtIOBlockReq *req)
671ec3f0
FZ
44{
45 if (req) {
c84b3192 46 g_free(req);
671ec3f0
FZ
47 }
48}
49
bf4bd461
FZ
50static void virtio_blk_complete_request(VirtIOBlockReq *req,
51 unsigned char status)
869a5c6d
AL
52{
53 VirtIOBlock *s = req->dev;
1cc91b7d 54 VirtIODevice *vdev = VIRTIO_DEVICE(s);
869a5c6d 55
6d519a5f
SH
56 trace_virtio_blk_req_complete(req, status);
57
92e3c2a3 58 stb_p(&req->in->status, status);
2a6cdd6d 59 virtqueue_push(s->vq, &req->elem, req->in_len);
1cc91b7d 60 virtio_notify(vdev, s->vq);
869a5c6d
AL
61}
62
bf4bd461
FZ
63static void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
64{
65 req->dev->complete_request(req, status);
66}
67
f35d68f0 68static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
1ceee0d5 69 bool is_read)
869a5c6d 70{
4be74634
MA
71 BlockErrorAction action = blk_get_error_action(req->dev->blk,
72 is_read, error);
869a5c6d
AL
73 VirtIOBlock *s = req->dev;
74
a589569f 75 if (action == BLOCK_ERROR_ACTION_STOP) {
466138dc
FZ
76 /* Break the link as the next request is going to be parsed from the
77 * ring again. Otherwise we may end up doing a double completion! */
78 req->mr_next = NULL;
869a5c6d
AL
79 req->next = s->rq;
80 s->rq = req;
a589569f 81 } else if (action == BLOCK_ERROR_ACTION_REPORT) {
869a5c6d 82 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
01762e03 83 block_acct_failed(blk_get_stats(s->blk), &req->acct);
671ec3f0 84 virtio_blk_free_request(req);
869a5c6d
AL
85 }
86
4be74634 87 blk_error_action(s->blk, action, is_read, error);
a589569f 88 return action != BLOCK_ERROR_ACTION_IGNORE;
869a5c6d
AL
89}
90
6e02c38d
AL
91static void virtio_blk_rw_complete(void *opaque, int ret)
92{
95f7142a
PL
93 VirtIOBlockReq *next = opaque;
94
95 while (next) {
96 VirtIOBlockReq *req = next;
97 next = req->mr_next;
98 trace_virtio_blk_rw_complete(req, ret);
99
100 if (req->qiov.nalloc != -1) {
101 /* If nalloc is != 1 req->qiov is a local copy of the original
102 * external iovec. It was allocated in submit_merged_requests
103 * to be able to merge requests. */
104 qemu_iovec_destroy(&req->qiov);
105 }
6e02c38d 106
95f7142a
PL
107 if (ret) {
108 int p = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);
109 bool is_read = !(p & VIRTIO_BLK_T_OUT);
2a6cdd6d
PB
110 /* Note that memory may be dirtied on read failure. If the
111 * virtio request is not completed here, as is the case for
112 * BLOCK_ERROR_ACTION_STOP, the memory may not be copied
113 * correctly during live migration. While this is ugly,
114 * it is acceptable because the device is free to write to
115 * the memory until the request is completed (which will
116 * happen on the other side of the migration).
117 */
95f7142a
PL
118 if (virtio_blk_handle_rw_error(req, -ret, is_read)) {
119 continue;
120 }
121 }
6d519a5f 122
95f7142a
PL
123 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
124 block_acct_done(blk_get_stats(req->dev->blk), &req->acct);
125 virtio_blk_free_request(req);
6e02c38d 126 }
869a5c6d 127}
6e02c38d 128
aa659be3
CH
129static void virtio_blk_flush_complete(void *opaque, int ret)
130{
131 VirtIOBlockReq *req = opaque;
132
8c269b54
KW
133 if (ret) {
134 if (virtio_blk_handle_rw_error(req, -ret, 0)) {
135 return;
136 }
137 }
138
139 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
4be74634 140 block_acct_done(blk_get_stats(req->dev->blk), &req->acct);
671ec3f0 141 virtio_blk_free_request(req);
6e02c38d
AL
142}
143
1dc936aa
FZ
144#ifdef __linux__
145
146typedef struct {
147 VirtIOBlockReq *req;
148 struct sg_io_hdr hdr;
149} VirtIOBlockIoctlReq;
150
151static void virtio_blk_ioctl_complete(void *opaque, int status)
152{
153 VirtIOBlockIoctlReq *ioctl_req = opaque;
154 VirtIOBlockReq *req = ioctl_req->req;
155 VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
156 struct virtio_scsi_inhdr *scsi;
157 struct sg_io_hdr *hdr;
158
159 scsi = (void *)req->elem.in_sg[req->elem.in_num - 2].iov_base;
160
161 if (status) {
162 status = VIRTIO_BLK_S_UNSUPP;
163 virtio_stl_p(vdev, &scsi->errors, 255);
164 goto out;
165 }
166
167 hdr = &ioctl_req->hdr;
168 /*
169 * From SCSI-Generic-HOWTO: "Some lower level drivers (e.g. ide-scsi)
170 * clear the masked_status field [hence status gets cleared too, see
171 * block/scsi_ioctl.c] even when a CHECK_CONDITION or COMMAND_TERMINATED
172 * status has occurred. However they do set DRIVER_SENSE in driver_status
173 * field. Also a (sb_len_wr > 0) indicates there is a sense buffer.
174 */
175 if (hdr->status == 0 && hdr->sb_len_wr > 0) {
176 hdr->status = CHECK_CONDITION;
177 }
178
179 virtio_stl_p(vdev, &scsi->errors,
180 hdr->status | (hdr->msg_status << 8) |
181 (hdr->host_status << 16) | (hdr->driver_status << 24));
182 virtio_stl_p(vdev, &scsi->residual, hdr->resid);
183 virtio_stl_p(vdev, &scsi->sense_len, hdr->sb_len_wr);
184 virtio_stl_p(vdev, &scsi->data_len, hdr->dxfer_len);
185
186out:
187 virtio_blk_req_complete(req, status);
188 virtio_blk_free_request(req);
189 g_free(ioctl_req);
190}
191
192#endif
193
6e02c38d
AL
194static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s)
195{
869a5c6d 196 VirtIOBlockReq *req = virtio_blk_alloc_request(s);
6e02c38d 197
f897bf75 198 if (!virtqueue_pop(s->vq, &req->elem)) {
671ec3f0
FZ
199 virtio_blk_free_request(req);
200 return NULL;
6e02c38d
AL
201 }
202
203 return req;
204}
205
75344fa4 206static int virtio_blk_handle_scsi_req(VirtIOBlockReq *req)
1063b8b1 207{
5a05cbee
FZ
208 int status = VIRTIO_BLK_S_OK;
209 struct virtio_scsi_inhdr *scsi = NULL;
75344fa4
FZ
210 VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
211 VirtQueueElement *elem = &req->elem;
212 VirtIOBlock *blk = req->dev;
783d1897 213
47ce9ef7 214#ifdef __linux__
1063b8b1 215 int i;
1dc936aa 216 VirtIOBlockIoctlReq *ioctl_req;
a209f461 217 BlockAIOCB *acb;
47ce9ef7 218#endif
1063b8b1
CH
219
220 /*
221 * We require at least one output segment each for the virtio_blk_outhdr
222 * and the SCSI command block.
223 *
224 * We also at least require the virtio_blk_inhdr, the virtio_scsi_inhdr
225 * and the sense buffer pointer in the input segments.
226 */
5a05cbee
FZ
227 if (elem->out_num < 2 || elem->in_num < 3) {
228 status = VIRTIO_BLK_S_IOERR;
229 goto fail;
1063b8b1
CH
230 }
231
232 /*
f34e73cd
PB
233 * The scsi inhdr is placed in the second-to-last input segment, just
234 * before the regular inhdr.
1063b8b1 235 */
5a05cbee 236 scsi = (void *)elem->in_sg[elem->in_num - 2].iov_base;
f34e73cd 237
2a30307f 238 if (!blk->conf.scsi) {
f34e73cd
PB
239 status = VIRTIO_BLK_S_UNSUPP;
240 goto fail;
1063b8b1
CH
241 }
242
243 /*
f34e73cd 244 * No support for bidirection commands yet.
1063b8b1 245 */
5a05cbee 246 if (elem->out_num > 2 && elem->in_num > 3) {
f34e73cd
PB
247 status = VIRTIO_BLK_S_UNSUPP;
248 goto fail;
249 }
1063b8b1 250
f34e73cd 251#ifdef __linux__
1dc936aa
FZ
252 ioctl_req = g_new0(VirtIOBlockIoctlReq, 1);
253 ioctl_req->req = req;
254 ioctl_req->hdr.interface_id = 'S';
255 ioctl_req->hdr.cmd_len = elem->out_sg[1].iov_len;
256 ioctl_req->hdr.cmdp = elem->out_sg[1].iov_base;
257 ioctl_req->hdr.dxfer_len = 0;
1063b8b1 258
5a05cbee 259 if (elem->out_num > 2) {
1063b8b1
CH
260 /*
261 * If there are more than the minimally required 2 output segments
262 * there is write payload starting from the third iovec.
263 */
1dc936aa
FZ
264 ioctl_req->hdr.dxfer_direction = SG_DXFER_TO_DEV;
265 ioctl_req->hdr.iovec_count = elem->out_num - 2;
1063b8b1 266
1dc936aa
FZ
267 for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
268 ioctl_req->hdr.dxfer_len += elem->out_sg[i + 2].iov_len;
269 }
1063b8b1 270
1dc936aa 271 ioctl_req->hdr.dxferp = elem->out_sg + 2;
1063b8b1 272
5a05cbee 273 } else if (elem->in_num > 3) {
1063b8b1
CH
274 /*
275 * If we have more than 3 input segments the guest wants to actually
276 * read data.
277 */
1dc936aa
FZ
278 ioctl_req->hdr.dxfer_direction = SG_DXFER_FROM_DEV;
279 ioctl_req->hdr.iovec_count = elem->in_num - 3;
280 for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
281 ioctl_req->hdr.dxfer_len += elem->in_sg[i].iov_len;
282 }
1063b8b1 283
1dc936aa 284 ioctl_req->hdr.dxferp = elem->in_sg;
1063b8b1
CH
285 } else {
286 /*
287 * Some SCSI commands don't actually transfer any data.
288 */
1dc936aa 289 ioctl_req->hdr.dxfer_direction = SG_DXFER_NONE;
1063b8b1
CH
290 }
291
1dc936aa
FZ
292 ioctl_req->hdr.sbp = elem->in_sg[elem->in_num - 3].iov_base;
293 ioctl_req->hdr.mx_sb_len = elem->in_sg[elem->in_num - 3].iov_len;
1063b8b1 294
a209f461
FZ
295 acb = blk_aio_ioctl(blk->blk, SG_IO, &ioctl_req->hdr,
296 virtio_blk_ioctl_complete, ioctl_req);
297 if (!acb) {
298 g_free(ioctl_req);
299 status = VIRTIO_BLK_S_UNSUPP;
300 goto fail;
301 }
1dc936aa 302 return -EINPROGRESS;
1063b8b1 303#else
f34e73cd
PB
304 abort();
305#endif
306
307fail:
308 /* Just put anything nonzero so that the ioctl fails in the guest. */
5a05cbee 309 if (scsi) {
783d1897 310 virtio_stl_p(vdev, &scsi->errors, 255);
5a05cbee
FZ
311 }
312 return status;
313}
314
315static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
316{
317 int status;
318
75344fa4 319 status = virtio_blk_handle_scsi_req(req);
1dc936aa
FZ
320 if (status != -EINPROGRESS) {
321 virtio_blk_req_complete(req, status);
322 virtio_blk_free_request(req);
323 }
1063b8b1 324}
1063b8b1 325
95f7142a
PL
326static inline void submit_requests(BlockBackend *blk, MultiReqBuffer *mrb,
327 int start, int num_reqs, int niov)
869a5c6d 328{
95f7142a
PL
329 QEMUIOVector *qiov = &mrb->reqs[start]->qiov;
330 int64_t sector_num = mrb->reqs[start]->sector_num;
331 int nb_sectors = mrb->reqs[start]->qiov.size / BDRV_SECTOR_SIZE;
332 bool is_write = mrb->is_write;
333
334 if (num_reqs > 1) {
335 int i;
336 struct iovec *tmp_iov = qiov->iov;
337 int tmp_niov = qiov->niov;
338
339 /* mrb->reqs[start]->qiov was initialized from external so we can't
340 * modifiy it here. We need to initialize it locally and then add the
341 * external iovecs. */
342 qemu_iovec_init(qiov, niov);
343
344 for (i = 0; i < tmp_niov; i++) {
345 qemu_iovec_add(qiov, tmp_iov[i].iov_base, tmp_iov[i].iov_len);
346 }
347
348 for (i = start + 1; i < start + num_reqs; i++) {
349 qemu_iovec_concat(qiov, &mrb->reqs[i]->qiov, 0,
350 mrb->reqs[i]->qiov.size);
351 mrb->reqs[i - 1]->mr_next = mrb->reqs[i];
352 nb_sectors += mrb->reqs[i]->qiov.size / BDRV_SECTOR_SIZE;
353 }
354 assert(nb_sectors == qiov->size / BDRV_SECTOR_SIZE);
355
356 trace_virtio_blk_submit_multireq(mrb, start, num_reqs, sector_num,
357 nb_sectors, is_write);
358 block_acct_merge_done(blk_get_stats(blk),
359 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ,
360 num_reqs - 1);
361 }
91553dcc 362
95f7142a
PL
363 if (is_write) {
364 blk_aio_writev(blk, sector_num, qiov, nb_sectors,
365 virtio_blk_rw_complete, mrb->reqs[start]);
366 } else {
367 blk_aio_readv(blk, sector_num, qiov, nb_sectors,
368 virtio_blk_rw_complete, mrb->reqs[start]);
369 }
370}
371
372static int multireq_compare(const void *a, const void *b)
373{
374 const VirtIOBlockReq *req1 = *(VirtIOBlockReq **)a,
375 *req2 = *(VirtIOBlockReq **)b;
376
377 /*
378 * Note that we can't simply subtract sector_num1 from sector_num2
379 * here as that could overflow the return value.
380 */
381 if (req1->sector_num > req2->sector_num) {
382 return 1;
383 } else if (req1->sector_num < req2->sector_num) {
384 return -1;
385 } else {
386 return 0;
387 }
388}
389
390void virtio_blk_submit_multireq(BlockBackend *blk, MultiReqBuffer *mrb)
391{
392 int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
393 int max_xfer_len = 0;
394 int64_t sector_num = 0;
395
396 if (mrb->num_reqs == 1) {
397 submit_requests(blk, mrb, 0, 1, -1);
398 mrb->num_reqs = 0;
c20fd872
CH
399 return;
400 }
401
95f7142a 402 max_xfer_len = blk_get_max_transfer_length(mrb->reqs[0]->dev->blk);
75af1f34 403 max_xfer_len = MIN_NON_ZERO(max_xfer_len, BDRV_REQUEST_MAX_SECTORS);
95f7142a
PL
404
405 qsort(mrb->reqs, mrb->num_reqs, sizeof(*mrb->reqs),
406 &multireq_compare);
407
408 for (i = 0; i < mrb->num_reqs; i++) {
409 VirtIOBlockReq *req = mrb->reqs[i];
410 if (num_reqs > 0) {
49cffbc6
GA
411 /*
412 * NOTE: We cannot merge the requests in below situations:
413 * 1. requests are not sequential
414 * 2. merge would exceed maximum number of IOVs
415 * 3. merge would exceed maximum transfer length of backend device
416 */
417 if (sector_num + nb_sectors != req->sector_num ||
222565f6 418 niov > blk_get_max_iov(blk) - req->qiov.niov ||
49cffbc6
GA
419 req->qiov.size / BDRV_SECTOR_SIZE > max_xfer_len ||
420 nb_sectors > max_xfer_len - req->qiov.size / BDRV_SECTOR_SIZE) {
95f7142a
PL
421 submit_requests(blk, mrb, start, num_reqs, niov);
422 num_reqs = 0;
91553dcc
KW
423 }
424 }
95f7142a
PL
425
426 if (num_reqs == 0) {
427 sector_num = req->sector_num;
428 nb_sectors = niov = 0;
429 start = i;
430 }
431
432 nb_sectors += req->qiov.size / BDRV_SECTOR_SIZE;
433 niov += req->qiov.niov;
434 num_reqs++;
91553dcc 435 }
c20fd872 436
95f7142a
PL
437 submit_requests(blk, mrb, start, num_reqs, niov);
438 mrb->num_reqs = 0;
91553dcc 439}
87b245db 440
c20fd872 441static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
aa659be3 442{
4be74634 443 block_acct_start(blk_get_stats(req->dev->blk), &req->acct, 0,
5366d0c8 444 BLOCK_ACCT_FLUSH);
a597e79c 445
618fbb84
CH
446 /*
447 * Make sure all outstanding writes are posted to the backing device.
448 */
95f7142a
PL
449 if (mrb->is_write && mrb->num_reqs > 0) {
450 virtio_blk_submit_multireq(req->dev->blk, mrb);
451 }
4be74634 452 blk_aio_flush(req->dev->blk, virtio_blk_flush_complete, req);
aa659be3
CH
453}
454
d0e14376
MA
455static bool virtio_blk_sect_range_ok(VirtIOBlock *dev,
456 uint64_t sector, size_t size)
457{
3c2daac0
MA
458 uint64_t nb_sectors = size >> BDRV_SECTOR_BITS;
459 uint64_t total_sectors;
460
75af1f34 461 if (nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
95f7142a
PL
462 return false;
463 }
d0e14376
MA
464 if (sector & dev->sector_mask) {
465 return false;
466 }
2a30307f 467 if (size % dev->conf.conf.logical_block_size) {
d0e14376
MA
468 return false;
469 }
4be74634 470 blk_get_geometry(dev->blk, &total_sectors);
3c2daac0
MA
471 if (sector > total_sectors || nb_sectors > total_sectors - sector) {
472 return false;
473 }
d0e14376
MA
474 return true;
475}
476
fee65db7 477void virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
bc6694d4 478{
92e3c2a3 479 uint32_t type;
f897bf75
SH
480 struct iovec *in_iov = req->elem.in_sg;
481 struct iovec *iov = req->elem.out_sg;
482 unsigned in_num = req->elem.in_num;
483 unsigned out_num = req->elem.out_num;
92e3c2a3 484
f897bf75 485 if (req->elem.out_num < 1 || req->elem.in_num < 1) {
870cef1d 486 error_report("virtio-blk missing headers");
bc6694d4
KW
487 exit(1);
488 }
489
827805a2
FZ
490 if (unlikely(iov_to_buf(iov, out_num, 0, &req->out,
491 sizeof(req->out)) != sizeof(req->out))) {
492 error_report("virtio-blk request outhdr too short");
493 exit(1);
494 }
ee17e848 495
827805a2 496 iov_discard_front(&iov, &out_num, sizeof(req->out));
ee17e848 497
12048545 498 if (in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {
ee17e848
FZ
499 error_report("virtio-blk request inhdr too short");
500 exit(1);
501 }
502
2a6cdd6d
PB
503 /* We always touch the last byte, so just see how big in_iov is. */
504 req->in_len = iov_size(in_iov, in_num);
ee17e848
FZ
505 req->in = (void *)in_iov[in_num - 1].iov_base
506 + in_iov[in_num - 1].iov_len
507 - sizeof(struct virtio_blk_inhdr);
508 iov_discard_back(in_iov, &in_num, sizeof(struct virtio_blk_inhdr));
bc6694d4 509
783d1897 510 type = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);
92e3c2a3 511
95f7142a 512 /* VIRTIO_BLK_T_OUT defines the command direction. VIRTIO_BLK_T_BARRIER
631b22ea 513 * is an optional flag. Although a guest should not send this flag if
95f7142a
PL
514 * not negotiated we ignored it in the past. So keep ignoring it. */
515 switch (type & ~(VIRTIO_BLK_T_OUT | VIRTIO_BLK_T_BARRIER)) {
516 case VIRTIO_BLK_T_IN:
517 {
518 bool is_write = type & VIRTIO_BLK_T_OUT;
519 req->sector_num = virtio_ldq_p(VIRTIO_DEVICE(req->dev),
520 &req->out.sector);
521
522 if (is_write) {
523 qemu_iovec_init_external(&req->qiov, iov, out_num);
524 trace_virtio_blk_handle_write(req, req->sector_num,
525 req->qiov.size / BDRV_SECTOR_SIZE);
526 } else {
527 qemu_iovec_init_external(&req->qiov, in_iov, in_num);
528 trace_virtio_blk_handle_read(req, req->sector_num,
529 req->qiov.size / BDRV_SECTOR_SIZE);
530 }
531
532 if (!virtio_blk_sect_range_ok(req->dev, req->sector_num,
533 req->qiov.size)) {
534 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
01762e03
AG
535 block_acct_invalid(blk_get_stats(req->dev->blk),
536 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
95f7142a
PL
537 virtio_blk_free_request(req);
538 return;
539 }
540
541 block_acct_start(blk_get_stats(req->dev->blk),
542 &req->acct, req->qiov.size,
543 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
544
545 /* merge would exceed maximum number of requests or IO direction
546 * changes */
547 if (mrb->num_reqs > 0 && (mrb->num_reqs == VIRTIO_BLK_MAX_MERGE_REQS ||
c99495ac
PL
548 is_write != mrb->is_write ||
549 !req->dev->conf.request_merging)) {
95f7142a
PL
550 virtio_blk_submit_multireq(req->dev->blk, mrb);
551 }
552
553 assert(mrb->num_reqs < VIRTIO_BLK_MAX_MERGE_REQS);
554 mrb->reqs[mrb->num_reqs++] = req;
555 mrb->is_write = is_write;
556 break;
557 }
558 case VIRTIO_BLK_T_FLUSH:
c20fd872 559 virtio_blk_handle_flush(req, mrb);
95f7142a
PL
560 break;
561 case VIRTIO_BLK_T_SCSI_CMD:
bc6694d4 562 virtio_blk_handle_scsi(req);
95f7142a
PL
563 break;
564 case VIRTIO_BLK_T_GET_ID:
565 {
2930b313 566 VirtIOBlock *s = req->dev;
567
a8686a9b
MA
568 /*
569 * NB: per existing s/n string convention the string is
570 * terminated by '\0' only when shorter than buffer.
571 */
2a30307f 572 const char *serial = s->conf.serial ? s->conf.serial : "";
a83ceea8
MM
573 size_t size = MIN(strlen(serial) + 1,
574 MIN(iov_size(in_iov, in_num),
575 VIRTIO_BLK_ID_BYTES));
576 iov_from_buf(in_iov, in_num, 0, serial, size);
2930b313 577 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
671ec3f0 578 virtio_blk_free_request(req);
95f7142a
PL
579 break;
580 }
581 default:
9e72c450 582 virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
671ec3f0 583 virtio_blk_free_request(req);
bc6694d4
KW
584 }
585}
586
6e02c38d
AL
587static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)
588{
1cc91b7d 589 VirtIOBlock *s = VIRTIO_BLK(vdev);
6e02c38d 590 VirtIOBlockReq *req;
95f7142a 591 MultiReqBuffer mrb = {};
6e02c38d 592
392808b4
SH
593 /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start
594 * dataplane here instead of waiting for .set_status().
595 */
596 if (s->dataplane) {
597 virtio_blk_data_plane_start(s->dataplane);
598 return;
599 }
392808b4 600
fc73548e
SH
601 blk_io_plug(s->blk);
602
6e02c38d 603 while ((req = virtio_blk_get_request(s))) {
bc6694d4 604 virtio_blk_handle_request(req, &mrb);
6e02c38d 605 }
91553dcc 606
95f7142a
PL
607 if (mrb.num_reqs) {
608 virtio_blk_submit_multireq(s->blk, &mrb);
609 }
fc73548e
SH
610
611 blk_io_unplug(s->blk);
6e02c38d
AL
612}
613
213189ab 614static void virtio_blk_dma_restart_bh(void *opaque)
869a5c6d
AL
615{
616 VirtIOBlock *s = opaque;
617 VirtIOBlockReq *req = s->rq;
95f7142a 618 MultiReqBuffer mrb = {};
869a5c6d 619
213189ab
MA
620 qemu_bh_delete(s->bh);
621 s->bh = NULL;
869a5c6d
AL
622
623 s->rq = NULL;
624
625 while (req) {
1bdb176a 626 VirtIOBlockReq *next = req->next;
f1b52868 627 virtio_blk_handle_request(req, &mrb);
1bdb176a 628 req = next;
869a5c6d 629 }
f1b52868 630
95f7142a
PL
631 if (mrb.num_reqs) {
632 virtio_blk_submit_multireq(s->blk, &mrb);
633 }
869a5c6d
AL
634}
635
1dfb4dd9
LC
636static void virtio_blk_dma_restart_cb(void *opaque, int running,
637 RunState state)
213189ab
MA
638{
639 VirtIOBlock *s = opaque;
640
392808b4 641 if (!running) {
213189ab 642 return;
392808b4 643 }
213189ab
MA
644
645 if (!s->bh) {
4be74634 646 s->bh = aio_bh_new(blk_get_aio_context(s->conf.conf.blk),
4407c1c5 647 virtio_blk_dma_restart_bh, s);
213189ab
MA
648 qemu_bh_schedule(s->bh);
649 }
650}
651
6e02c38d
AL
652static void virtio_blk_reset(VirtIODevice *vdev)
653{
1cc91b7d 654 VirtIOBlock *s = VIRTIO_BLK(vdev);
6e40b3bf 655 AioContext *ctx;
392808b4 656
6e02c38d
AL
657 /*
658 * This should cancel pending requests, but can't do nicely until there
659 * are per-device request lists.
660 */
6e40b3bf
AY
661 ctx = blk_get_aio_context(s->blk);
662 aio_context_acquire(ctx);
663 blk_drain(s->blk);
664
665 if (s->dataplane) {
666 virtio_blk_data_plane_stop(s->dataplane);
667 }
668 aio_context_release(ctx);
669
4be74634 670 blk_set_enable_write_cache(s->blk, s->original_wce);
6e02c38d
AL
671}
672
bf011293 673/* coalesce internal state, copy to pci i/o region 0
674 */
6e02c38d
AL
675static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
676{
1cc91b7d 677 VirtIOBlock *s = VIRTIO_BLK(vdev);
2a30307f 678 BlockConf *conf = &s->conf.conf;
6e02c38d
AL
679 struct virtio_blk_config blkcfg;
680 uint64_t capacity;
f7516731 681 int blk_size = conf->logical_block_size;
6e02c38d 682
4be74634 683 blk_get_geometry(s->blk, &capacity);
5c5dafdc 684 memset(&blkcfg, 0, sizeof(blkcfg));
783d1897
RR
685 virtio_stq_p(vdev, &blkcfg.capacity, capacity);
686 virtio_stl_p(vdev, &blkcfg.seg_max, 128 - 2);
907eb3e5 687 virtio_stw_p(vdev, &blkcfg.geometry.cylinders, conf->cyls);
783d1897 688 virtio_stl_p(vdev, &blkcfg.blk_size, blk_size);
f7516731
MA
689 virtio_stw_p(vdev, &blkcfg.min_io_size, conf->min_io_size / blk_size);
690 virtio_stw_p(vdev, &blkcfg.opt_io_size, conf->opt_io_size / blk_size);
907eb3e5 691 blkcfg.geometry.heads = conf->heads;
136be99e
CB
692 /*
693 * We must ensure that the block device capacity is a multiple of
e03ba136 694 * the logical block size. If that is not the case, let's use
136be99e
CB
695 * sector_mask to adopt the geometry to have a correct picture.
696 * For those devices where the capacity is ok for the given geometry
e03ba136 697 * we don't touch the sector value of the geometry, since some devices
136be99e
CB
698 * (like s390 dasd) need a specific value. Here the capacity is already
699 * cyls*heads*secs*blk_size and the sector value is not block size
700 * divided by 512 - instead it is the amount of blk_size blocks
701 * per track (cylinder).
702 */
4be74634 703 if (blk_getlength(s->blk) / conf->heads / conf->secs % blk_size) {
907eb3e5 704 blkcfg.geometry.sectors = conf->secs & ~s->sector_mask;
136be99e 705 } else {
907eb3e5 706 blkcfg.geometry.sectors = conf->secs;
136be99e 707 }
c7085da7 708 blkcfg.size_max = 0;
f7516731 709 blkcfg.physical_block_exp = get_physical_block_exp(conf);
9752c371 710 blkcfg.alignment_offset = 0;
4be74634 711 blkcfg.wce = blk_enable_write_cache(s->blk);
37d5ddd6 712 memcpy(config, &blkcfg, sizeof(struct virtio_blk_config));
6e02c38d
AL
713}
714
13e3dce0
PB
715static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config)
716{
1cc91b7d 717 VirtIOBlock *s = VIRTIO_BLK(vdev);
13e3dce0
PB
718 struct virtio_blk_config blkcfg;
719
720 memcpy(&blkcfg, config, sizeof(blkcfg));
6d7e73d6 721
4be74634
MA
722 aio_context_acquire(blk_get_aio_context(s->blk));
723 blk_set_enable_write_cache(s->blk, blkcfg.wce != 0);
724 aio_context_release(blk_get_aio_context(s->blk));
13e3dce0
PB
725}
726
9d5b731d
JW
727static uint64_t virtio_blk_get_features(VirtIODevice *vdev, uint64_t features,
728 Error **errp)
6e02c38d 729{
1cc91b7d 730 VirtIOBlock *s = VIRTIO_BLK(vdev);
1063b8b1 731
0cd09c3a
CH
732 virtio_add_feature(&features, VIRTIO_BLK_F_SEG_MAX);
733 virtio_add_feature(&features, VIRTIO_BLK_F_GEOMETRY);
734 virtio_add_feature(&features, VIRTIO_BLK_F_TOPOLOGY);
735 virtio_add_feature(&features, VIRTIO_BLK_F_BLK_SIZE);
95129d6f 736 if (virtio_has_feature(features, VIRTIO_F_VERSION_1)) {
efb8206c
JW
737 if (s->conf.scsi) {
738 error_setg(errp, "Please set scsi=off for virtio-blk devices in order to use virtio 1.0");
739 return 0;
740 }
efb8206c 741 } else {
c9b11f97 742 virtio_clear_feature(&features, VIRTIO_F_ANY_LAYOUT);
efb8206c
JW
743 virtio_add_feature(&features, VIRTIO_BLK_F_SCSI);
744 }
aa659be3 745
2a30307f 746 if (s->conf.config_wce) {
0cd09c3a 747 virtio_add_feature(&features, VIRTIO_BLK_F_CONFIG_WCE);
8a873ba7 748 }
4be74634 749 if (blk_enable_write_cache(s->blk)) {
0cd09c3a 750 virtio_add_feature(&features, VIRTIO_BLK_F_WCE);
4be74634
MA
751 }
752 if (blk_is_read_only(s->blk)) {
0cd09c3a 753 virtio_add_feature(&features, VIRTIO_BLK_F_RO);
4be74634 754 }
1063b8b1
CH
755
756 return features;
6e02c38d
AL
757}
758
9315cbfd
PB
759static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)
760{
1cc91b7d 761 VirtIOBlock *s = VIRTIO_BLK(vdev);
9315cbfd 762
cf139388
SH
763 if (s->dataplane && !(status & (VIRTIO_CONFIG_S_DRIVER |
764 VIRTIO_CONFIG_S_DRIVER_OK))) {
392808b4
SH
765 virtio_blk_data_plane_stop(s->dataplane);
766 }
392808b4 767
9315cbfd
PB
768 if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
769 return;
770 }
771
ef5bc962
PB
772 /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send
773 * cache flushes. Thus, the "auto writethrough" behavior is never
774 * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.
775 * Leaving it enabled would break the following sequence:
776 *
777 * Guest started with "-drive cache=writethrough"
778 * Guest sets status to 0
779 * Guest sets DRIVER bit in status field
780 * Guest reads host features (WCE=0, CONFIG_WCE=1)
781 * Guest writes guest features (WCE=0, CONFIG_WCE=1)
782 * Guest writes 1 to the WCE configuration field (writeback mode)
783 * Guest sets DRIVER_OK bit in status field
784 *
4be74634 785 * s->blk would erroneously be placed in writethrough mode.
ef5bc962 786 */
95129d6f 787 if (!virtio_vdev_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE)) {
4be74634
MA
788 aio_context_acquire(blk_get_aio_context(s->blk));
789 blk_set_enable_write_cache(s->blk,
95129d6f
CH
790 virtio_vdev_has_feature(vdev,
791 VIRTIO_BLK_F_WCE));
4be74634 792 aio_context_release(blk_get_aio_context(s->blk));
ef5bc962 793 }
9315cbfd
PB
794}
795
6e02c38d
AL
796static void virtio_blk_save(QEMUFile *f, void *opaque)
797{
b2b295a7 798 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
10a06fd6
PB
799 VirtIOBlock *s = VIRTIO_BLK(vdev);
800
801 if (s->dataplane) {
802 virtio_blk_data_plane_stop(s->dataplane);
803 }
869a5c6d 804
1cc91b7d 805 virtio_save(vdev, f);
b2b295a7 806}
869a5c6d 807
b2b295a7
GK
808static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f)
809{
810 VirtIOBlock *s = VIRTIO_BLK(vdev);
811 VirtIOBlockReq *req = s->rq;
812
869a5c6d
AL
813 while (req) {
814 qemu_put_sbyte(f, 1);
f897bf75 815 qemu_put_buffer(f, (unsigned char *)&req->elem,
671ec3f0 816 sizeof(VirtQueueElement));
869a5c6d
AL
817 req = req->next;
818 }
819 qemu_put_sbyte(f, 0);
6e02c38d
AL
820}
821
822static int virtio_blk_load(QEMUFile *f, void *opaque, int version_id)
823{
824 VirtIOBlock *s = opaque;
1cc91b7d 825 VirtIODevice *vdev = VIRTIO_DEVICE(s);
6e02c38d 826
869a5c6d 827 if (version_id != 2)
6e02c38d
AL
828 return -EINVAL;
829
b2b295a7
GK
830 return virtio_load(vdev, f, version_id);
831}
832
833static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f,
834 int version_id)
835{
836 VirtIOBlock *s = VIRTIO_BLK(vdev);
2a633c46 837
869a5c6d
AL
838 while (qemu_get_sbyte(f)) {
839 VirtIOBlockReq *req = virtio_blk_alloc_request(s);
f897bf75 840 qemu_get_buffer(f, (unsigned char *)&req->elem,
671ec3f0 841 sizeof(VirtQueueElement));
869a5c6d 842 req->next = s->rq;
20a81e4d 843 s->rq = req;
b6a4805b 844
3d8db153 845 virtqueue_map(&req->elem);
869a5c6d 846 }
6e02c38d
AL
847
848 return 0;
849}
850
145feb17 851static void virtio_blk_resize(void *opaque)
e5051fc7 852{
1cc91b7d 853 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
e5051fc7 854
1cc91b7d 855 virtio_notify_config(vdev);
e5051fc7
CH
856}
857
0e49de52 858static const BlockDevOps virtio_block_ops = {
145feb17 859 .resize_cb = virtio_blk_resize,
0e49de52
MA
860};
861
84db52d0
SH
862/* Disable dataplane thread during live migration since it does not
863 * update the dirty memory bitmap yet.
864 */
865static void virtio_blk_migration_state_changed(Notifier *notifier, void *data)
866{
867 VirtIOBlock *s = container_of(notifier, VirtIOBlock,
868 migration_state_notifier);
869 MigrationState *mig = data;
3ffeeef7 870 Error *err = NULL;
84db52d0
SH
871
872 if (migration_in_setup(mig)) {
873 if (!s->dataplane) {
874 return;
875 }
876 virtio_blk_data_plane_destroy(s->dataplane);
877 s->dataplane = NULL;
878 } else if (migration_has_finished(mig) ||
879 migration_has_failed(mig)) {
880 if (s->dataplane) {
881 return;
882 }
4be74634 883 blk_drain_all(); /* complete in-flight non-dataplane requests */
2a30307f 884 virtio_blk_data_plane_create(VIRTIO_DEVICE(s), &s->conf,
3ffeeef7
AF
885 &s->dataplane, &err);
886 if (err != NULL) {
565f65d2 887 error_report_err(err);
3ffeeef7 888 }
84db52d0
SH
889 }
890}
84db52d0 891
75884afd 892static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
1c028ddf 893{
75884afd 894 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
179b417e 895 VirtIOBlock *s = VIRTIO_BLK(dev);
2a30307f 896 VirtIOBlkConf *conf = &s->conf;
3ffeeef7 897 Error *err = NULL;
6e02c38d 898 static int virtio_blk_id;
cf21e106 899
4be74634 900 if (!conf->conf.blk) {
75884afd
AF
901 error_setg(errp, "drive property not set");
902 return;
d75d25e3 903 }
4be74634 904 if (!blk_is_inserted(conf->conf.blk)) {
75884afd
AF
905 error_setg(errp, "Device needs media, but drive is empty");
906 return;
98f28ad7 907 }
d75d25e3 908
2a30307f 909 blkconf_serial(&conf->conf, &conf->serial);
4be74634 910 s->original_wce = blk_enable_write_cache(conf->conf.blk);
2a30307f 911 blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, &err);
5ff5efb4
FZ
912 if (err) {
913 error_propagate(errp, err);
75884afd 914 return;
b7eb0c9f 915 }
0eb28a42 916 blkconf_blocksizes(&conf->conf);
a8686a9b 917
05ff6865
FK
918 virtio_init(vdev, "virtio-blk", VIRTIO_ID_BLOCK,
919 sizeof(struct virtio_blk_config));
6e02c38d 920
4be74634 921 s->blk = conf->conf.blk;
869a5c6d 922 s->rq = NULL;
2a30307f 923 s->sector_mask = (s->conf.conf.logical_block_size / BDRV_SECTOR_SIZE) - 1;
e63e7fde 924
05ff6865 925 s->vq = virtio_add_queue(vdev, 128, virtio_blk_handle_output);
bf4bd461 926 s->complete_request = virtio_blk_complete_request;
2a30307f 927 virtio_blk_data_plane_create(vdev, conf, &s->dataplane, &err);
3ffeeef7 928 if (err != NULL) {
75884afd 929 error_propagate(errp, err);
6a1a8cc7 930 virtio_cleanup(vdev);
75884afd 931 return;
392808b4 932 }
84db52d0
SH
933 s->migration_state_notifier.notify = virtio_blk_migration_state_changed;
934 add_migration_state_change_notifier(&s->migration_state_notifier);
6e02c38d 935
69b302b2 936 s->change = qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);
179b417e 937 register_savevm(dev, "virtio-blk", virtio_blk_id++, 2,
6e02c38d 938 virtio_blk_save, virtio_blk_load, s);
4be74634
MA
939 blk_set_dev_ops(s->blk, &virtio_block_ops, s);
940 blk_set_guest_block_size(s->blk, s->conf.conf.logical_block_size);
6e02c38d 941
4be74634 942 blk_iostatus_enable(s->blk);
1c028ddf
FK
943}
944
306ec6c3 945static void virtio_blk_device_unrealize(DeviceState *dev, Error **errp)
1c028ddf 946{
306ec6c3
AF
947 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
948 VirtIOBlock *s = VIRTIO_BLK(dev);
949
84db52d0 950 remove_migration_state_change_notifier(&s->migration_state_notifier);
1c028ddf
FK
951 virtio_blk_data_plane_destroy(s->dataplane);
952 s->dataplane = NULL;
1c028ddf 953 qemu_del_vm_change_state_handler(s->change);
306ec6c3 954 unregister_savevm(dev, "virtio-blk", s);
4be74634 955 blockdev_mark_auto_del(s->blk);
6a1a8cc7 956 virtio_cleanup(vdev);
1c028ddf
FK
957}
958
467b3f33
SH
959static void virtio_blk_instance_init(Object *obj)
960{
961 VirtIOBlock *s = VIRTIO_BLK(obj);
962
963 object_property_add_link(obj, "iothread", TYPE_IOTHREAD,
2a30307f 964 (Object **)&s->conf.iothread,
467b3f33
SH
965 qdev_prop_allow_set_link_before_realize,
966 OBJ_PROP_LINK_UNREF_ON_RELEASE, NULL);
2a30307f 967 device_add_bootindex_property(obj, &s->conf.conf.bootindex,
3342ec32
GA
968 "bootindex", "/disk@0,0",
969 DEVICE(obj), NULL);
467b3f33
SH
970}
971
1c028ddf 972static Property virtio_blk_properties[] = {
2a30307f
MA
973 DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf),
974 DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf),
975 DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial),
976 DEFINE_PROP_BIT("config-wce", VirtIOBlock, conf.config_wce, 0, true),
32a877e4 977#ifdef __linux__
ed65fd1a 978 DEFINE_PROP_BIT("scsi", VirtIOBlock, conf.scsi, 0, false),
32a877e4 979#endif
c99495ac
PL
980 DEFINE_PROP_BIT("request-merging", VirtIOBlock, conf.request_merging, 0,
981 true),
1c028ddf
FK
982 DEFINE_PROP_END_OF_LIST(),
983};
984
985static void virtio_blk_class_init(ObjectClass *klass, void *data)
986{
987 DeviceClass *dc = DEVICE_CLASS(klass);
988 VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
75884afd 989
1c028ddf 990 dc->props = virtio_blk_properties;
125ee0ed 991 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
75884afd 992 vdc->realize = virtio_blk_device_realize;
306ec6c3 993 vdc->unrealize = virtio_blk_device_unrealize;
1c028ddf
FK
994 vdc->get_config = virtio_blk_update_config;
995 vdc->set_config = virtio_blk_set_config;
996 vdc->get_features = virtio_blk_get_features;
997 vdc->set_status = virtio_blk_set_status;
998 vdc->reset = virtio_blk_reset;
b2b295a7
GK
999 vdc->save = virtio_blk_save_device;
1000 vdc->load = virtio_blk_load_device;
1c028ddf
FK
1001}
1002
1003static const TypeInfo virtio_device_info = {
1004 .name = TYPE_VIRTIO_BLK,
1005 .parent = TYPE_VIRTIO_DEVICE,
1006 .instance_size = sizeof(VirtIOBlock),
467b3f33 1007 .instance_init = virtio_blk_instance_init,
1c028ddf
FK
1008 .class_init = virtio_blk_class_init,
1009};
1010
1011static void virtio_register_types(void)
1012{
1013 type_register_static(&virtio_device_info);
1014}
1015
1016type_init(virtio_register_types)