xref: /openbmc/qemu/hw/block/virtio-blk.c (revision f702e62a)
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 
14 #include "qemu-common.h"
15 #include "qemu/iov.h"
16 #include "qemu/error-report.h"
17 #include "trace.h"
18 #include "hw/block/block.h"
19 #include "sysemu/blockdev.h"
20 #include "hw/virtio/virtio-blk.h"
21 #ifdef CONFIG_VIRTIO_BLK_DATA_PLANE
22 # include "dataplane/virtio-blk.h"
23 # include "migration/migration.h"
24 #endif
25 #include "block/scsi.h"
26 #ifdef __linux__
27 # include <scsi/sg.h>
28 #endif
29 #include "hw/virtio/virtio-bus.h"
30 #include "hw/virtio/virtio-access.h"
31 
32 static VirtIOBlockReq *virtio_blk_alloc_request(VirtIOBlock *s)
33 {
34     VirtIOBlockReq *req = g_slice_new0(VirtIOBlockReq);
35     req->dev = s;
36     req->elem = g_slice_new0(VirtQueueElement);
37     return req;
38 }
39 
40 static void virtio_blk_free_request(VirtIOBlockReq *req)
41 {
42     if (req) {
43         g_slice_free(VirtQueueElement, req->elem);
44         g_slice_free(VirtIOBlockReq, req);
45     }
46 }
47 
48 static void virtio_blk_complete_request(VirtIOBlockReq *req,
49                                         unsigned char status)
50 {
51     VirtIOBlock *s = req->dev;
52     VirtIODevice *vdev = VIRTIO_DEVICE(s);
53 
54     trace_virtio_blk_req_complete(req, status);
55 
56     stb_p(&req->in->status, status);
57     virtqueue_push(s->vq, req->elem, req->qiov.size + sizeof(*req->in));
58     virtio_notify(vdev, s->vq);
59 }
60 
61 static void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
62 {
63     req->dev->complete_request(req, status);
64 }
65 
66 static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
67     bool is_read)
68 {
69     BlockErrorAction action = bdrv_get_error_action(req->dev->bs, is_read, error);
70     VirtIOBlock *s = req->dev;
71 
72     if (action == BLOCK_ERROR_ACTION_STOP) {
73         req->next = s->rq;
74         s->rq = req;
75     } else if (action == BLOCK_ERROR_ACTION_REPORT) {
76         virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
77         bdrv_acct_done(s->bs, &req->acct);
78         virtio_blk_free_request(req);
79     }
80 
81     bdrv_error_action(s->bs, action, is_read, error);
82     return action != BLOCK_ERROR_ACTION_IGNORE;
83 }
84 
85 static void virtio_blk_rw_complete(void *opaque, int ret)
86 {
87     VirtIOBlockReq *req = opaque;
88 
89     trace_virtio_blk_rw_complete(req, ret);
90 
91     if (ret) {
92         int p = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);
93         bool is_read = !(p & VIRTIO_BLK_T_OUT);
94         if (virtio_blk_handle_rw_error(req, -ret, is_read))
95             return;
96     }
97 
98     virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
99     bdrv_acct_done(req->dev->bs, &req->acct);
100     virtio_blk_free_request(req);
101 }
102 
103 static void virtio_blk_flush_complete(void *opaque, int ret)
104 {
105     VirtIOBlockReq *req = opaque;
106 
107     if (ret) {
108         if (virtio_blk_handle_rw_error(req, -ret, 0)) {
109             return;
110         }
111     }
112 
113     virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
114     bdrv_acct_done(req->dev->bs, &req->acct);
115     virtio_blk_free_request(req);
116 }
117 
118 static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s)
119 {
120     VirtIOBlockReq *req = virtio_blk_alloc_request(s);
121 
122     if (!virtqueue_pop(s->vq, req->elem)) {
123         virtio_blk_free_request(req);
124         return NULL;
125     }
126 
127     return req;
128 }
129 
130 int virtio_blk_handle_scsi_req(VirtIOBlock *blk,
131                                VirtQueueElement *elem)
132 {
133     int status = VIRTIO_BLK_S_OK;
134     struct virtio_scsi_inhdr *scsi = NULL;
135     VirtIODevice *vdev = VIRTIO_DEVICE(blk);
136 
137 #ifdef __linux__
138     int i;
139     struct sg_io_hdr hdr;
140 #endif
141 
142     /*
143      * We require at least one output segment each for the virtio_blk_outhdr
144      * and the SCSI command block.
145      *
146      * We also at least require the virtio_blk_inhdr, the virtio_scsi_inhdr
147      * and the sense buffer pointer in the input segments.
148      */
149     if (elem->out_num < 2 || elem->in_num < 3) {
150         status = VIRTIO_BLK_S_IOERR;
151         goto fail;
152     }
153 
154     /*
155      * The scsi inhdr is placed in the second-to-last input segment, just
156      * before the regular inhdr.
157      */
158     scsi = (void *)elem->in_sg[elem->in_num - 2].iov_base;
159 
160     if (!blk->blk.scsi) {
161         status = VIRTIO_BLK_S_UNSUPP;
162         goto fail;
163     }
164 
165     /*
166      * No support for bidirection commands yet.
167      */
168     if (elem->out_num > 2 && elem->in_num > 3) {
169         status = VIRTIO_BLK_S_UNSUPP;
170         goto fail;
171     }
172 
173 #ifdef __linux__
174     memset(&hdr, 0, sizeof(struct sg_io_hdr));
175     hdr.interface_id = 'S';
176     hdr.cmd_len = elem->out_sg[1].iov_len;
177     hdr.cmdp = elem->out_sg[1].iov_base;
178     hdr.dxfer_len = 0;
179 
180     if (elem->out_num > 2) {
181         /*
182          * If there are more than the minimally required 2 output segments
183          * there is write payload starting from the third iovec.
184          */
185         hdr.dxfer_direction = SG_DXFER_TO_DEV;
186         hdr.iovec_count = elem->out_num - 2;
187 
188         for (i = 0; i < hdr.iovec_count; i++)
189             hdr.dxfer_len += elem->out_sg[i + 2].iov_len;
190 
191         hdr.dxferp = elem->out_sg + 2;
192 
193     } else if (elem->in_num > 3) {
194         /*
195          * If we have more than 3 input segments the guest wants to actually
196          * read data.
197          */
198         hdr.dxfer_direction = SG_DXFER_FROM_DEV;
199         hdr.iovec_count = elem->in_num - 3;
200         for (i = 0; i < hdr.iovec_count; i++)
201             hdr.dxfer_len += elem->in_sg[i].iov_len;
202 
203         hdr.dxferp = elem->in_sg;
204     } else {
205         /*
206          * Some SCSI commands don't actually transfer any data.
207          */
208         hdr.dxfer_direction = SG_DXFER_NONE;
209     }
210 
211     hdr.sbp = elem->in_sg[elem->in_num - 3].iov_base;
212     hdr.mx_sb_len = elem->in_sg[elem->in_num - 3].iov_len;
213 
214     status = bdrv_ioctl(blk->bs, SG_IO, &hdr);
215     if (status) {
216         status = VIRTIO_BLK_S_UNSUPP;
217         goto fail;
218     }
219 
220     /*
221      * From SCSI-Generic-HOWTO: "Some lower level drivers (e.g. ide-scsi)
222      * clear the masked_status field [hence status gets cleared too, see
223      * block/scsi_ioctl.c] even when a CHECK_CONDITION or COMMAND_TERMINATED
224      * status has occurred.  However they do set DRIVER_SENSE in driver_status
225      * field. Also a (sb_len_wr > 0) indicates there is a sense buffer.
226      */
227     if (hdr.status == 0 && hdr.sb_len_wr > 0) {
228         hdr.status = CHECK_CONDITION;
229     }
230 
231     virtio_stl_p(vdev, &scsi->errors,
232                  hdr.status | (hdr.msg_status << 8) |
233                  (hdr.host_status << 16) | (hdr.driver_status << 24));
234     virtio_stl_p(vdev, &scsi->residual, hdr.resid);
235     virtio_stl_p(vdev, &scsi->sense_len, hdr.sb_len_wr);
236     virtio_stl_p(vdev, &scsi->data_len, hdr.dxfer_len);
237 
238     return status;
239 #else
240     abort();
241 #endif
242 
243 fail:
244     /* Just put anything nonzero so that the ioctl fails in the guest.  */
245     if (scsi) {
246         virtio_stl_p(vdev, &scsi->errors, 255);
247     }
248     return status;
249 }
250 
251 static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
252 {
253     int status;
254 
255     status = virtio_blk_handle_scsi_req(req->dev, req->elem);
256     virtio_blk_req_complete(req, status);
257     virtio_blk_free_request(req);
258 }
259 
260 void virtio_submit_multiwrite(BlockDriverState *bs, MultiReqBuffer *mrb)
261 {
262     int i, ret;
263 
264     if (!mrb->num_writes) {
265         return;
266     }
267 
268     ret = bdrv_aio_multiwrite(bs, mrb->blkreq, mrb->num_writes);
269     if (ret != 0) {
270         for (i = 0; i < mrb->num_writes; i++) {
271             if (mrb->blkreq[i].error) {
272                 virtio_blk_rw_complete(mrb->blkreq[i].opaque, -EIO);
273             }
274         }
275     }
276 
277     mrb->num_writes = 0;
278 }
279 
280 static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
281 {
282     bdrv_acct_start(req->dev->bs, &req->acct, 0, BDRV_ACCT_FLUSH);
283 
284     /*
285      * Make sure all outstanding writes are posted to the backing device.
286      */
287     virtio_submit_multiwrite(req->dev->bs, mrb);
288     bdrv_aio_flush(req->dev->bs, virtio_blk_flush_complete, req);
289 }
290 
291 static void virtio_blk_handle_write(VirtIOBlockReq *req, MultiReqBuffer *mrb)
292 {
293     BlockRequest *blkreq;
294     uint64_t sector;
295 
296     sector = virtio_ldq_p(VIRTIO_DEVICE(req->dev), &req->out.sector);
297 
298     bdrv_acct_start(req->dev->bs, &req->acct, req->qiov.size, BDRV_ACCT_WRITE);
299 
300     trace_virtio_blk_handle_write(req, sector, req->qiov.size / 512);
301 
302     if (sector & req->dev->sector_mask) {
303         virtio_blk_rw_complete(req, -EIO);
304         return;
305     }
306     if (req->qiov.size % req->dev->conf->logical_block_size) {
307         virtio_blk_rw_complete(req, -EIO);
308         return;
309     }
310 
311     if (mrb->num_writes == 32) {
312         virtio_submit_multiwrite(req->dev->bs, mrb);
313     }
314 
315     blkreq = &mrb->blkreq[mrb->num_writes];
316     blkreq->sector = sector;
317     blkreq->nb_sectors = req->qiov.size / BDRV_SECTOR_SIZE;
318     blkreq->qiov = &req->qiov;
319     blkreq->cb = virtio_blk_rw_complete;
320     blkreq->opaque = req;
321     blkreq->error = 0;
322 
323     mrb->num_writes++;
324 }
325 
326 static void virtio_blk_handle_read(VirtIOBlockReq *req)
327 {
328     uint64_t sector;
329 
330     sector = virtio_ldq_p(VIRTIO_DEVICE(req->dev), &req->out.sector);
331 
332     bdrv_acct_start(req->dev->bs, &req->acct, req->qiov.size, BDRV_ACCT_READ);
333 
334     trace_virtio_blk_handle_read(req, sector, req->qiov.size / 512);
335 
336     if (sector & req->dev->sector_mask) {
337         virtio_blk_rw_complete(req, -EIO);
338         return;
339     }
340     if (req->qiov.size % req->dev->conf->logical_block_size) {
341         virtio_blk_rw_complete(req, -EIO);
342         return;
343     }
344     bdrv_aio_readv(req->dev->bs, sector, &req->qiov,
345                    req->qiov.size / BDRV_SECTOR_SIZE,
346                    virtio_blk_rw_complete, req);
347 }
348 
349 void virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
350 {
351     uint32_t type;
352     struct iovec *in_iov = req->elem->in_sg;
353     struct iovec *iov = req->elem->out_sg;
354     unsigned in_num = req->elem->in_num;
355     unsigned out_num = req->elem->out_num;
356 
357     if (req->elem->out_num < 1 || req->elem->in_num < 1) {
358         error_report("virtio-blk missing headers");
359         exit(1);
360     }
361 
362     if (unlikely(iov_to_buf(iov, out_num, 0, &req->out,
363                             sizeof(req->out)) != sizeof(req->out))) {
364         error_report("virtio-blk request outhdr too short");
365         exit(1);
366     }
367 
368     iov_discard_front(&iov, &out_num, sizeof(req->out));
369 
370     if (in_num < 1 ||
371         in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {
372         error_report("virtio-blk request inhdr too short");
373         exit(1);
374     }
375 
376     req->in = (void *)in_iov[in_num - 1].iov_base
377               + in_iov[in_num - 1].iov_len
378               - sizeof(struct virtio_blk_inhdr);
379     iov_discard_back(in_iov, &in_num, sizeof(struct virtio_blk_inhdr));
380 
381     type = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);
382 
383     if (type & VIRTIO_BLK_T_FLUSH) {
384         virtio_blk_handle_flush(req, mrb);
385     } else if (type & VIRTIO_BLK_T_SCSI_CMD) {
386         virtio_blk_handle_scsi(req);
387     } else if (type & VIRTIO_BLK_T_GET_ID) {
388         VirtIOBlock *s = req->dev;
389 
390         /*
391          * NB: per existing s/n string convention the string is
392          * terminated by '\0' only when shorter than buffer.
393          */
394         strncpy(req->elem->in_sg[0].iov_base,
395                 s->blk.serial ? s->blk.serial : "",
396                 MIN(req->elem->in_sg[0].iov_len, VIRTIO_BLK_ID_BYTES));
397         virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
398         virtio_blk_free_request(req);
399     } else if (type & VIRTIO_BLK_T_OUT) {
400         qemu_iovec_init_external(&req->qiov, &req->elem->out_sg[1],
401                                  req->elem->out_num - 1);
402         virtio_blk_handle_write(req, mrb);
403     } else if (type == VIRTIO_BLK_T_IN || type == VIRTIO_BLK_T_BARRIER) {
404         /* VIRTIO_BLK_T_IN is 0, so we can't just & it. */
405         qemu_iovec_init_external(&req->qiov, &req->elem->in_sg[0],
406                                  req->elem->in_num - 1);
407         virtio_blk_handle_read(req);
408     } else {
409         virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
410         virtio_blk_free_request(req);
411     }
412 }
413 
414 static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)
415 {
416     VirtIOBlock *s = VIRTIO_BLK(vdev);
417     VirtIOBlockReq *req;
418     MultiReqBuffer mrb = {
419         .num_writes = 0,
420     };
421 
422 #ifdef CONFIG_VIRTIO_BLK_DATA_PLANE
423     /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start
424      * dataplane here instead of waiting for .set_status().
425      */
426     if (s->dataplane) {
427         virtio_blk_data_plane_start(s->dataplane);
428         return;
429     }
430 #endif
431 
432     while ((req = virtio_blk_get_request(s))) {
433         virtio_blk_handle_request(req, &mrb);
434     }
435 
436     virtio_submit_multiwrite(s->bs, &mrb);
437 
438     /*
439      * FIXME: Want to check for completions before returning to guest mode,
440      * so cached reads and writes are reported as quickly as possible. But
441      * that should be done in the generic block layer.
442      */
443 }
444 
445 static void virtio_blk_dma_restart_bh(void *opaque)
446 {
447     VirtIOBlock *s = opaque;
448     VirtIOBlockReq *req = s->rq;
449     MultiReqBuffer mrb = {
450         .num_writes = 0,
451     };
452 
453     qemu_bh_delete(s->bh);
454     s->bh = NULL;
455 
456     s->rq = NULL;
457 
458     while (req) {
459         virtio_blk_handle_request(req, &mrb);
460         req = req->next;
461     }
462 
463     virtio_submit_multiwrite(s->bs, &mrb);
464 }
465 
466 static void virtio_blk_dma_restart_cb(void *opaque, int running,
467                                       RunState state)
468 {
469     VirtIOBlock *s = opaque;
470 
471     if (!running) {
472         return;
473     }
474 
475     if (!s->bh) {
476         s->bh = aio_bh_new(bdrv_get_aio_context(s->blk.conf.bs),
477                            virtio_blk_dma_restart_bh, s);
478         qemu_bh_schedule(s->bh);
479     }
480 }
481 
482 static void virtio_blk_reset(VirtIODevice *vdev)
483 {
484     VirtIOBlock *s = VIRTIO_BLK(vdev);
485 
486 #ifdef CONFIG_VIRTIO_BLK_DATA_PLANE
487     if (s->dataplane) {
488         virtio_blk_data_plane_stop(s->dataplane);
489     }
490 #endif
491 
492     /*
493      * This should cancel pending requests, but can't do nicely until there
494      * are per-device request lists.
495      */
496     bdrv_drain_all();
497     bdrv_set_enable_write_cache(s->bs, s->original_wce);
498 }
499 
500 /* coalesce internal state, copy to pci i/o region 0
501  */
502 static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
503 {
504     VirtIOBlock *s = VIRTIO_BLK(vdev);
505     struct virtio_blk_config blkcfg;
506     uint64_t capacity;
507     int blk_size = s->conf->logical_block_size;
508 
509     bdrv_get_geometry(s->bs, &capacity);
510     memset(&blkcfg, 0, sizeof(blkcfg));
511     virtio_stq_p(vdev, &blkcfg.capacity, capacity);
512     virtio_stl_p(vdev, &blkcfg.seg_max, 128 - 2);
513     virtio_stw_p(vdev, &blkcfg.cylinders, s->conf->cyls);
514     virtio_stl_p(vdev, &blkcfg.blk_size, blk_size);
515     virtio_stw_p(vdev, &blkcfg.min_io_size, s->conf->min_io_size / blk_size);
516     virtio_stw_p(vdev, &blkcfg.opt_io_size, s->conf->opt_io_size / blk_size);
517     blkcfg.heads = s->conf->heads;
518     /*
519      * We must ensure that the block device capacity is a multiple of
520      * the logical block size. If that is not the case, let's use
521      * sector_mask to adopt the geometry to have a correct picture.
522      * For those devices where the capacity is ok for the given geometry
523      * we don't touch the sector value of the geometry, since some devices
524      * (like s390 dasd) need a specific value. Here the capacity is already
525      * cyls*heads*secs*blk_size and the sector value is not block size
526      * divided by 512 - instead it is the amount of blk_size blocks
527      * per track (cylinder).
528      */
529     if (bdrv_getlength(s->bs) /  s->conf->heads / s->conf->secs % blk_size) {
530         blkcfg.sectors = s->conf->secs & ~s->sector_mask;
531     } else {
532         blkcfg.sectors = s->conf->secs;
533     }
534     blkcfg.size_max = 0;
535     blkcfg.physical_block_exp = get_physical_block_exp(s->conf);
536     blkcfg.alignment_offset = 0;
537     blkcfg.wce = bdrv_enable_write_cache(s->bs);
538     memcpy(config, &blkcfg, sizeof(struct virtio_blk_config));
539 }
540 
541 static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config)
542 {
543     VirtIOBlock *s = VIRTIO_BLK(vdev);
544     struct virtio_blk_config blkcfg;
545 
546     memcpy(&blkcfg, config, sizeof(blkcfg));
547 
548     aio_context_acquire(bdrv_get_aio_context(s->bs));
549     bdrv_set_enable_write_cache(s->bs, blkcfg.wce != 0);
550     aio_context_release(bdrv_get_aio_context(s->bs));
551 }
552 
553 static uint32_t virtio_blk_get_features(VirtIODevice *vdev, uint32_t features)
554 {
555     VirtIOBlock *s = VIRTIO_BLK(vdev);
556 
557     features |= (1 << VIRTIO_BLK_F_SEG_MAX);
558     features |= (1 << VIRTIO_BLK_F_GEOMETRY);
559     features |= (1 << VIRTIO_BLK_F_TOPOLOGY);
560     features |= (1 << VIRTIO_BLK_F_BLK_SIZE);
561     features |= (1 << VIRTIO_BLK_F_SCSI);
562 
563     if (s->blk.config_wce) {
564         features |= (1 << VIRTIO_BLK_F_CONFIG_WCE);
565     }
566     if (bdrv_enable_write_cache(s->bs))
567         features |= (1 << VIRTIO_BLK_F_WCE);
568 
569     if (bdrv_is_read_only(s->bs))
570         features |= 1 << VIRTIO_BLK_F_RO;
571 
572     return features;
573 }
574 
575 static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)
576 {
577     VirtIOBlock *s = VIRTIO_BLK(vdev);
578     uint32_t features;
579 
580 #ifdef CONFIG_VIRTIO_BLK_DATA_PLANE
581     if (s->dataplane && !(status & (VIRTIO_CONFIG_S_DRIVER |
582                                     VIRTIO_CONFIG_S_DRIVER_OK))) {
583         virtio_blk_data_plane_stop(s->dataplane);
584     }
585 #endif
586 
587     if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
588         return;
589     }
590 
591     features = vdev->guest_features;
592 
593     /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send
594      * cache flushes.  Thus, the "auto writethrough" behavior is never
595      * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.
596      * Leaving it enabled would break the following sequence:
597      *
598      *     Guest started with "-drive cache=writethrough"
599      *     Guest sets status to 0
600      *     Guest sets DRIVER bit in status field
601      *     Guest reads host features (WCE=0, CONFIG_WCE=1)
602      *     Guest writes guest features (WCE=0, CONFIG_WCE=1)
603      *     Guest writes 1 to the WCE configuration field (writeback mode)
604      *     Guest sets DRIVER_OK bit in status field
605      *
606      * s->bs would erroneously be placed in writethrough mode.
607      */
608     if (!(features & (1 << VIRTIO_BLK_F_CONFIG_WCE))) {
609         aio_context_acquire(bdrv_get_aio_context(s->bs));
610         bdrv_set_enable_write_cache(s->bs,
611                                     !!(features & (1 << VIRTIO_BLK_F_WCE)));
612         aio_context_release(bdrv_get_aio_context(s->bs));
613     }
614 }
615 
616 static void virtio_blk_save(QEMUFile *f, void *opaque)
617 {
618     VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
619 
620     virtio_save(vdev, f);
621 }
622 
623 static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f)
624 {
625     VirtIOBlock *s = VIRTIO_BLK(vdev);
626     VirtIOBlockReq *req = s->rq;
627 
628     while (req) {
629         qemu_put_sbyte(f, 1);
630         qemu_put_buffer(f, (unsigned char *)req->elem,
631                         sizeof(VirtQueueElement));
632         req = req->next;
633     }
634     qemu_put_sbyte(f, 0);
635 }
636 
637 static int virtio_blk_load(QEMUFile *f, void *opaque, int version_id)
638 {
639     VirtIOBlock *s = opaque;
640     VirtIODevice *vdev = VIRTIO_DEVICE(s);
641 
642     if (version_id != 2)
643         return -EINVAL;
644 
645     return virtio_load(vdev, f, version_id);
646 }
647 
648 static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f,
649                                   int version_id)
650 {
651     VirtIOBlock *s = VIRTIO_BLK(vdev);
652 
653     while (qemu_get_sbyte(f)) {
654         VirtIOBlockReq *req = virtio_blk_alloc_request(s);
655         qemu_get_buffer(f, (unsigned char *)req->elem,
656                         sizeof(VirtQueueElement));
657         req->next = s->rq;
658         s->rq = req;
659 
660         virtqueue_map_sg(req->elem->in_sg, req->elem->in_addr,
661             req->elem->in_num, 1);
662         virtqueue_map_sg(req->elem->out_sg, req->elem->out_addr,
663             req->elem->out_num, 0);
664     }
665 
666     return 0;
667 }
668 
669 static void virtio_blk_resize(void *opaque)
670 {
671     VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
672 
673     virtio_notify_config(vdev);
674 }
675 
676 static const BlockDevOps virtio_block_ops = {
677     .resize_cb = virtio_blk_resize,
678 };
679 
680 #ifdef CONFIG_VIRTIO_BLK_DATA_PLANE
681 /* Disable dataplane thread during live migration since it does not
682  * update the dirty memory bitmap yet.
683  */
684 static void virtio_blk_migration_state_changed(Notifier *notifier, void *data)
685 {
686     VirtIOBlock *s = container_of(notifier, VirtIOBlock,
687                                   migration_state_notifier);
688     MigrationState *mig = data;
689     Error *err = NULL;
690 
691     if (migration_in_setup(mig)) {
692         if (!s->dataplane) {
693             return;
694         }
695         virtio_blk_data_plane_destroy(s->dataplane);
696         s->dataplane = NULL;
697     } else if (migration_has_finished(mig) ||
698                migration_has_failed(mig)) {
699         if (s->dataplane) {
700             return;
701         }
702         bdrv_drain_all(); /* complete in-flight non-dataplane requests */
703         virtio_blk_data_plane_create(VIRTIO_DEVICE(s), &s->blk,
704                                      &s->dataplane, &err);
705         if (err != NULL) {
706             error_report("%s", error_get_pretty(err));
707             error_free(err);
708         }
709     }
710 }
711 #endif /* CONFIG_VIRTIO_BLK_DATA_PLANE */
712 
713 static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
714 {
715     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
716     VirtIOBlock *s = VIRTIO_BLK(dev);
717     VirtIOBlkConf *blk = &(s->blk);
718 #ifdef CONFIG_VIRTIO_BLK_DATA_PLANE
719     Error *err = NULL;
720 #endif
721     static int virtio_blk_id;
722 
723     if (!blk->conf.bs) {
724         error_setg(errp, "drive property not set");
725         return;
726     }
727     if (!bdrv_is_inserted(blk->conf.bs)) {
728         error_setg(errp, "Device needs media, but drive is empty");
729         return;
730     }
731 
732     blkconf_serial(&blk->conf, &blk->serial);
733     s->original_wce = bdrv_enable_write_cache(blk->conf.bs);
734     if (blkconf_geometry(&blk->conf, NULL, 65535, 255, 255) < 0) {
735         error_setg(errp, "Error setting geometry");
736         return;
737     }
738 
739     virtio_init(vdev, "virtio-blk", VIRTIO_ID_BLOCK,
740                 sizeof(struct virtio_blk_config));
741 
742     s->bs = blk->conf.bs;
743     s->conf = &blk->conf;
744     s->rq = NULL;
745     s->sector_mask = (s->conf->logical_block_size / BDRV_SECTOR_SIZE) - 1;
746 
747     s->vq = virtio_add_queue(vdev, 128, virtio_blk_handle_output);
748     s->complete_request = virtio_blk_complete_request;
749 #ifdef CONFIG_VIRTIO_BLK_DATA_PLANE
750     virtio_blk_data_plane_create(vdev, blk, &s->dataplane, &err);
751     if (err != NULL) {
752         error_propagate(errp, err);
753         virtio_cleanup(vdev);
754         return;
755     }
756     s->migration_state_notifier.notify = virtio_blk_migration_state_changed;
757     add_migration_state_change_notifier(&s->migration_state_notifier);
758 #endif
759 
760     s->change = qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);
761     register_savevm(dev, "virtio-blk", virtio_blk_id++, 2,
762                     virtio_blk_save, virtio_blk_load, s);
763     bdrv_set_dev_ops(s->bs, &virtio_block_ops, s);
764     bdrv_set_guest_block_size(s->bs, s->conf->logical_block_size);
765 
766     bdrv_iostatus_enable(s->bs);
767 
768     add_boot_device_path(s->conf->bootindex, dev, "/disk@0,0");
769 }
770 
771 static void virtio_blk_device_unrealize(DeviceState *dev, Error **errp)
772 {
773     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
774     VirtIOBlock *s = VIRTIO_BLK(dev);
775 
776 #ifdef CONFIG_VIRTIO_BLK_DATA_PLANE
777     remove_migration_state_change_notifier(&s->migration_state_notifier);
778     virtio_blk_data_plane_destroy(s->dataplane);
779     s->dataplane = NULL;
780 #endif
781     qemu_del_vm_change_state_handler(s->change);
782     unregister_savevm(dev, "virtio-blk", s);
783     blockdev_mark_auto_del(s->bs);
784     virtio_cleanup(vdev);
785 }
786 
787 static void virtio_blk_instance_init(Object *obj)
788 {
789     VirtIOBlock *s = VIRTIO_BLK(obj);
790 
791     object_property_add_link(obj, "iothread", TYPE_IOTHREAD,
792                              (Object **)&s->blk.iothread,
793                              qdev_prop_allow_set_link_before_realize,
794                              OBJ_PROP_LINK_UNREF_ON_RELEASE, NULL);
795 }
796 
797 static Property virtio_blk_properties[] = {
798     DEFINE_BLOCK_PROPERTIES(VirtIOBlock, blk.conf),
799     DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, blk.conf),
800     DEFINE_PROP_STRING("serial", VirtIOBlock, blk.serial),
801     DEFINE_PROP_BIT("config-wce", VirtIOBlock, blk.config_wce, 0, true),
802 #ifdef __linux__
803     DEFINE_PROP_BIT("scsi", VirtIOBlock, blk.scsi, 0, true),
804 #endif
805 #ifdef CONFIG_VIRTIO_BLK_DATA_PLANE
806     DEFINE_PROP_BIT("x-data-plane", VirtIOBlock, blk.data_plane, 0, false),
807 #endif
808     DEFINE_PROP_END_OF_LIST(),
809 };
810 
811 static void virtio_blk_class_init(ObjectClass *klass, void *data)
812 {
813     DeviceClass *dc = DEVICE_CLASS(klass);
814     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
815 
816     dc->props = virtio_blk_properties;
817     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
818     vdc->realize = virtio_blk_device_realize;
819     vdc->unrealize = virtio_blk_device_unrealize;
820     vdc->get_config = virtio_blk_update_config;
821     vdc->set_config = virtio_blk_set_config;
822     vdc->get_features = virtio_blk_get_features;
823     vdc->set_status = virtio_blk_set_status;
824     vdc->reset = virtio_blk_reset;
825     vdc->save = virtio_blk_save_device;
826     vdc->load = virtio_blk_load_device;
827 }
828 
829 static const TypeInfo virtio_device_info = {
830     .name = TYPE_VIRTIO_BLK,
831     .parent = TYPE_VIRTIO_DEVICE,
832     .instance_size = sizeof(VirtIOBlock),
833     .instance_init = virtio_blk_instance_init,
834     .class_init = virtio_blk_class_init,
835 };
836 
837 static void virtio_register_types(void)
838 {
839     type_register_static(&virtio_device_info);
840 }
841 
842 type_init(virtio_register_types)
843