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