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