xref: /openbmc/qemu/hw/block/virtio-blk.c (revision 64552b6b)
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/osdep.h"
15 #include "qapi/error.h"
16 #include "qemu/iov.h"
17 #include "qemu/module.h"
18 #include "qemu/error-report.h"
19 #include "trace.h"
20 #include "hw/block/block.h"
21 #include "sysemu/blockdev.h"
22 #include "hw/virtio/virtio-blk.h"
23 #include "dataplane/virtio-blk.h"
24 #include "scsi/constants.h"
25 #ifdef __linux__
26 # include <scsi/sg.h>
27 #endif
28 #include "hw/virtio/virtio-bus.h"
29 #include "migration/qemu-file-types.h"
30 #include "hw/virtio/virtio-access.h"
31 
32 /* Config size before the discard support (hide associated config fields) */
33 #define VIRTIO_BLK_CFG_SIZE offsetof(struct virtio_blk_config, \
34                                      max_discard_sectors)
35 /*
36  * Starting from the discard feature, we can use this array to properly
37  * set the config size depending on the features enabled.
38  */
39 static VirtIOFeature feature_sizes[] = {
40     {.flags = 1ULL << VIRTIO_BLK_F_DISCARD,
41      .end = virtio_endof(struct virtio_blk_config, discard_sector_alignment)},
42     {.flags = 1ULL << VIRTIO_BLK_F_WRITE_ZEROES,
43      .end = virtio_endof(struct virtio_blk_config, write_zeroes_may_unmap)},
44     {}
45 };
46 
47 static void virtio_blk_set_config_size(VirtIOBlock *s, uint64_t host_features)
48 {
49     s->config_size = MAX(VIRTIO_BLK_CFG_SIZE,
50         virtio_feature_get_config_size(feature_sizes, host_features));
51 
52     assert(s->config_size <= sizeof(struct virtio_blk_config));
53 }
54 
55 static void virtio_blk_init_request(VirtIOBlock *s, VirtQueue *vq,
56                                     VirtIOBlockReq *req)
57 {
58     req->dev = s;
59     req->vq = vq;
60     req->qiov.size = 0;
61     req->in_len = 0;
62     req->next = NULL;
63     req->mr_next = NULL;
64 }
65 
66 static void virtio_blk_free_request(VirtIOBlockReq *req)
67 {
68     g_free(req);
69 }
70 
71 static void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
72 {
73     VirtIOBlock *s = req->dev;
74     VirtIODevice *vdev = VIRTIO_DEVICE(s);
75 
76     trace_virtio_blk_req_complete(vdev, req, status);
77 
78     stb_p(&req->in->status, status);
79     virtqueue_push(req->vq, &req->elem, req->in_len);
80     if (s->dataplane_started && !s->dataplane_disabled) {
81         virtio_blk_data_plane_notify(s->dataplane, req->vq);
82     } else {
83         virtio_notify(vdev, req->vq);
84     }
85 }
86 
87 static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
88     bool is_read, bool acct_failed)
89 {
90     VirtIOBlock *s = req->dev;
91     BlockErrorAction action = blk_get_error_action(s->blk, is_read, error);
92 
93     if (action == BLOCK_ERROR_ACTION_STOP) {
94         /* Break the link as the next request is going to be parsed from the
95          * ring again. Otherwise we may end up doing a double completion! */
96         req->mr_next = NULL;
97         req->next = s->rq;
98         s->rq = req;
99     } else if (action == BLOCK_ERROR_ACTION_REPORT) {
100         virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
101         if (acct_failed) {
102             block_acct_failed(blk_get_stats(s->blk), &req->acct);
103         }
104         virtio_blk_free_request(req);
105     }
106 
107     blk_error_action(s->blk, action, is_read, error);
108     return action != BLOCK_ERROR_ACTION_IGNORE;
109 }
110 
111 static void virtio_blk_rw_complete(void *opaque, int ret)
112 {
113     VirtIOBlockReq *next = opaque;
114     VirtIOBlock *s = next->dev;
115     VirtIODevice *vdev = VIRTIO_DEVICE(s);
116 
117     aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
118     while (next) {
119         VirtIOBlockReq *req = next;
120         next = req->mr_next;
121         trace_virtio_blk_rw_complete(vdev, req, ret);
122 
123         if (req->qiov.nalloc != -1) {
124             /* If nalloc is != -1 req->qiov is a local copy of the original
125              * external iovec. It was allocated in submit_requests to be
126              * able to merge requests. */
127             qemu_iovec_destroy(&req->qiov);
128         }
129 
130         if (ret) {
131             int p = virtio_ldl_p(VIRTIO_DEVICE(s), &req->out.type);
132             bool is_read = !(p & VIRTIO_BLK_T_OUT);
133             /* Note that memory may be dirtied on read failure.  If the
134              * virtio request is not completed here, as is the case for
135              * BLOCK_ERROR_ACTION_STOP, the memory may not be copied
136              * correctly during live migration.  While this is ugly,
137              * it is acceptable because the device is free to write to
138              * the memory until the request is completed (which will
139              * happen on the other side of the migration).
140              */
141             if (virtio_blk_handle_rw_error(req, -ret, is_read, true)) {
142                 continue;
143             }
144         }
145 
146         virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
147         block_acct_done(blk_get_stats(s->blk), &req->acct);
148         virtio_blk_free_request(req);
149     }
150     aio_context_release(blk_get_aio_context(s->conf.conf.blk));
151 }
152 
153 static void virtio_blk_flush_complete(void *opaque, int ret)
154 {
155     VirtIOBlockReq *req = opaque;
156     VirtIOBlock *s = req->dev;
157 
158     aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
159     if (ret) {
160         if (virtio_blk_handle_rw_error(req, -ret, 0, true)) {
161             goto out;
162         }
163     }
164 
165     virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
166     block_acct_done(blk_get_stats(s->blk), &req->acct);
167     virtio_blk_free_request(req);
168 
169 out:
170     aio_context_release(blk_get_aio_context(s->conf.conf.blk));
171 }
172 
173 static void virtio_blk_discard_write_zeroes_complete(void *opaque, int ret)
174 {
175     VirtIOBlockReq *req = opaque;
176     VirtIOBlock *s = req->dev;
177     bool is_write_zeroes = (virtio_ldl_p(VIRTIO_DEVICE(s), &req->out.type) &
178                             ~VIRTIO_BLK_T_BARRIER) == VIRTIO_BLK_T_WRITE_ZEROES;
179 
180     aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
181     if (ret) {
182         if (virtio_blk_handle_rw_error(req, -ret, false, is_write_zeroes)) {
183             goto out;
184         }
185     }
186 
187     virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
188     if (is_write_zeroes) {
189         block_acct_done(blk_get_stats(s->blk), &req->acct);
190     }
191     virtio_blk_free_request(req);
192 
193 out:
194     aio_context_release(blk_get_aio_context(s->conf.conf.blk));
195 }
196 
197 #ifdef __linux__
198 
199 typedef struct {
200     VirtIOBlockReq *req;
201     struct sg_io_hdr hdr;
202 } VirtIOBlockIoctlReq;
203 
204 static void virtio_blk_ioctl_complete(void *opaque, int status)
205 {
206     VirtIOBlockIoctlReq *ioctl_req = opaque;
207     VirtIOBlockReq *req = ioctl_req->req;
208     VirtIOBlock *s = req->dev;
209     VirtIODevice *vdev = VIRTIO_DEVICE(s);
210     struct virtio_scsi_inhdr *scsi;
211     struct sg_io_hdr *hdr;
212 
213     scsi = (void *)req->elem.in_sg[req->elem.in_num - 2].iov_base;
214 
215     if (status) {
216         status = VIRTIO_BLK_S_UNSUPP;
217         virtio_stl_p(vdev, &scsi->errors, 255);
218         goto out;
219     }
220 
221     hdr = &ioctl_req->hdr;
222     /*
223      * From SCSI-Generic-HOWTO: "Some lower level drivers (e.g. ide-scsi)
224      * clear the masked_status field [hence status gets cleared too, see
225      * block/scsi_ioctl.c] even when a CHECK_CONDITION or COMMAND_TERMINATED
226      * status has occurred.  However they do set DRIVER_SENSE in driver_status
227      * field. Also a (sb_len_wr > 0) indicates there is a sense buffer.
228      */
229     if (hdr->status == 0 && hdr->sb_len_wr > 0) {
230         hdr->status = CHECK_CONDITION;
231     }
232 
233     virtio_stl_p(vdev, &scsi->errors,
234                  hdr->status | (hdr->msg_status << 8) |
235                  (hdr->host_status << 16) | (hdr->driver_status << 24));
236     virtio_stl_p(vdev, &scsi->residual, hdr->resid);
237     virtio_stl_p(vdev, &scsi->sense_len, hdr->sb_len_wr);
238     virtio_stl_p(vdev, &scsi->data_len, hdr->dxfer_len);
239 
240 out:
241     aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
242     virtio_blk_req_complete(req, status);
243     virtio_blk_free_request(req);
244     aio_context_release(blk_get_aio_context(s->conf.conf.blk));
245     g_free(ioctl_req);
246 }
247 
248 #endif
249 
250 static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s, VirtQueue *vq)
251 {
252     VirtIOBlockReq *req = virtqueue_pop(vq, sizeof(VirtIOBlockReq));
253 
254     if (req) {
255         virtio_blk_init_request(s, vq, req);
256     }
257     return req;
258 }
259 
260 static int virtio_blk_handle_scsi_req(VirtIOBlockReq *req)
261 {
262     int status = VIRTIO_BLK_S_OK;
263     struct virtio_scsi_inhdr *scsi = NULL;
264     VirtIOBlock *blk = req->dev;
265     VirtIODevice *vdev = VIRTIO_DEVICE(blk);
266     VirtQueueElement *elem = &req->elem;
267 
268 #ifdef __linux__
269     int i;
270     VirtIOBlockIoctlReq *ioctl_req;
271     BlockAIOCB *acb;
272 #endif
273 
274     /*
275      * We require at least one output segment each for the virtio_blk_outhdr
276      * and the SCSI command block.
277      *
278      * We also at least require the virtio_blk_inhdr, the virtio_scsi_inhdr
279      * and the sense buffer pointer in the input segments.
280      */
281     if (elem->out_num < 2 || elem->in_num < 3) {
282         status = VIRTIO_BLK_S_IOERR;
283         goto fail;
284     }
285 
286     /*
287      * The scsi inhdr is placed in the second-to-last input segment, just
288      * before the regular inhdr.
289      */
290     scsi = (void *)elem->in_sg[elem->in_num - 2].iov_base;
291 
292     if (!virtio_has_feature(blk->host_features, VIRTIO_BLK_F_SCSI)) {
293         status = VIRTIO_BLK_S_UNSUPP;
294         goto fail;
295     }
296 
297     /*
298      * No support for bidirection commands yet.
299      */
300     if (elem->out_num > 2 && elem->in_num > 3) {
301         status = VIRTIO_BLK_S_UNSUPP;
302         goto fail;
303     }
304 
305 #ifdef __linux__
306     ioctl_req = g_new0(VirtIOBlockIoctlReq, 1);
307     ioctl_req->req = req;
308     ioctl_req->hdr.interface_id = 'S';
309     ioctl_req->hdr.cmd_len = elem->out_sg[1].iov_len;
310     ioctl_req->hdr.cmdp = elem->out_sg[1].iov_base;
311     ioctl_req->hdr.dxfer_len = 0;
312 
313     if (elem->out_num > 2) {
314         /*
315          * If there are more than the minimally required 2 output segments
316          * there is write payload starting from the third iovec.
317          */
318         ioctl_req->hdr.dxfer_direction = SG_DXFER_TO_DEV;
319         ioctl_req->hdr.iovec_count = elem->out_num - 2;
320 
321         for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
322             ioctl_req->hdr.dxfer_len += elem->out_sg[i + 2].iov_len;
323         }
324 
325         ioctl_req->hdr.dxferp = elem->out_sg + 2;
326 
327     } else if (elem->in_num > 3) {
328         /*
329          * If we have more than 3 input segments the guest wants to actually
330          * read data.
331          */
332         ioctl_req->hdr.dxfer_direction = SG_DXFER_FROM_DEV;
333         ioctl_req->hdr.iovec_count = elem->in_num - 3;
334         for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
335             ioctl_req->hdr.dxfer_len += elem->in_sg[i].iov_len;
336         }
337 
338         ioctl_req->hdr.dxferp = elem->in_sg;
339     } else {
340         /*
341          * Some SCSI commands don't actually transfer any data.
342          */
343         ioctl_req->hdr.dxfer_direction = SG_DXFER_NONE;
344     }
345 
346     ioctl_req->hdr.sbp = elem->in_sg[elem->in_num - 3].iov_base;
347     ioctl_req->hdr.mx_sb_len = elem->in_sg[elem->in_num - 3].iov_len;
348 
349     acb = blk_aio_ioctl(blk->blk, SG_IO, &ioctl_req->hdr,
350                         virtio_blk_ioctl_complete, ioctl_req);
351     if (!acb) {
352         g_free(ioctl_req);
353         status = VIRTIO_BLK_S_UNSUPP;
354         goto fail;
355     }
356     return -EINPROGRESS;
357 #else
358     abort();
359 #endif
360 
361 fail:
362     /* Just put anything nonzero so that the ioctl fails in the guest.  */
363     if (scsi) {
364         virtio_stl_p(vdev, &scsi->errors, 255);
365     }
366     return status;
367 }
368 
369 static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
370 {
371     int status;
372 
373     status = virtio_blk_handle_scsi_req(req);
374     if (status != -EINPROGRESS) {
375         virtio_blk_req_complete(req, status);
376         virtio_blk_free_request(req);
377     }
378 }
379 
380 static inline void submit_requests(BlockBackend *blk, MultiReqBuffer *mrb,
381                                    int start, int num_reqs, int niov)
382 {
383     QEMUIOVector *qiov = &mrb->reqs[start]->qiov;
384     int64_t sector_num = mrb->reqs[start]->sector_num;
385     bool is_write = mrb->is_write;
386 
387     if (num_reqs > 1) {
388         int i;
389         struct iovec *tmp_iov = qiov->iov;
390         int tmp_niov = qiov->niov;
391 
392         /* mrb->reqs[start]->qiov was initialized from external so we can't
393          * modify it here. We need to initialize it locally and then add the
394          * external iovecs. */
395         qemu_iovec_init(qiov, niov);
396 
397         for (i = 0; i < tmp_niov; i++) {
398             qemu_iovec_add(qiov, tmp_iov[i].iov_base, tmp_iov[i].iov_len);
399         }
400 
401         for (i = start + 1; i < start + num_reqs; i++) {
402             qemu_iovec_concat(qiov, &mrb->reqs[i]->qiov, 0,
403                               mrb->reqs[i]->qiov.size);
404             mrb->reqs[i - 1]->mr_next = mrb->reqs[i];
405         }
406 
407         trace_virtio_blk_submit_multireq(VIRTIO_DEVICE(mrb->reqs[start]->dev),
408                                          mrb, start, num_reqs,
409                                          sector_num << BDRV_SECTOR_BITS,
410                                          qiov->size, is_write);
411         block_acct_merge_done(blk_get_stats(blk),
412                               is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ,
413                               num_reqs - 1);
414     }
415 
416     if (is_write) {
417         blk_aio_pwritev(blk, sector_num << BDRV_SECTOR_BITS, qiov, 0,
418                         virtio_blk_rw_complete, mrb->reqs[start]);
419     } else {
420         blk_aio_preadv(blk, sector_num << BDRV_SECTOR_BITS, qiov, 0,
421                        virtio_blk_rw_complete, mrb->reqs[start]);
422     }
423 }
424 
425 static int multireq_compare(const void *a, const void *b)
426 {
427     const VirtIOBlockReq *req1 = *(VirtIOBlockReq **)a,
428                          *req2 = *(VirtIOBlockReq **)b;
429 
430     /*
431      * Note that we can't simply subtract sector_num1 from sector_num2
432      * here as that could overflow the return value.
433      */
434     if (req1->sector_num > req2->sector_num) {
435         return 1;
436     } else if (req1->sector_num < req2->sector_num) {
437         return -1;
438     } else {
439         return 0;
440     }
441 }
442 
443 static void virtio_blk_submit_multireq(BlockBackend *blk, MultiReqBuffer *mrb)
444 {
445     int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
446     uint32_t max_transfer;
447     int64_t sector_num = 0;
448 
449     if (mrb->num_reqs == 1) {
450         submit_requests(blk, mrb, 0, 1, -1);
451         mrb->num_reqs = 0;
452         return;
453     }
454 
455     max_transfer = blk_get_max_transfer(mrb->reqs[0]->dev->blk);
456 
457     qsort(mrb->reqs, mrb->num_reqs, sizeof(*mrb->reqs),
458           &multireq_compare);
459 
460     for (i = 0; i < mrb->num_reqs; i++) {
461         VirtIOBlockReq *req = mrb->reqs[i];
462         if (num_reqs > 0) {
463             /*
464              * NOTE: We cannot merge the requests in below situations:
465              * 1. requests are not sequential
466              * 2. merge would exceed maximum number of IOVs
467              * 3. merge would exceed maximum transfer length of backend device
468              */
469             if (sector_num + nb_sectors != req->sector_num ||
470                 niov > blk_get_max_iov(blk) - req->qiov.niov ||
471                 req->qiov.size > max_transfer ||
472                 nb_sectors > (max_transfer -
473                               req->qiov.size) / BDRV_SECTOR_SIZE) {
474                 submit_requests(blk, mrb, start, num_reqs, niov);
475                 num_reqs = 0;
476             }
477         }
478 
479         if (num_reqs == 0) {
480             sector_num = req->sector_num;
481             nb_sectors = niov = 0;
482             start = i;
483         }
484 
485         nb_sectors += req->qiov.size / BDRV_SECTOR_SIZE;
486         niov += req->qiov.niov;
487         num_reqs++;
488     }
489 
490     submit_requests(blk, mrb, start, num_reqs, niov);
491     mrb->num_reqs = 0;
492 }
493 
494 static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
495 {
496     VirtIOBlock *s = req->dev;
497 
498     block_acct_start(blk_get_stats(s->blk), &req->acct, 0,
499                      BLOCK_ACCT_FLUSH);
500 
501     /*
502      * Make sure all outstanding writes are posted to the backing device.
503      */
504     if (mrb->is_write && mrb->num_reqs > 0) {
505         virtio_blk_submit_multireq(s->blk, mrb);
506     }
507     blk_aio_flush(s->blk, virtio_blk_flush_complete, req);
508 }
509 
510 static bool virtio_blk_sect_range_ok(VirtIOBlock *dev,
511                                      uint64_t sector, size_t size)
512 {
513     uint64_t nb_sectors = size >> BDRV_SECTOR_BITS;
514     uint64_t total_sectors;
515 
516     if (nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
517         return false;
518     }
519     if (sector & dev->sector_mask) {
520         return false;
521     }
522     if (size % dev->conf.conf.logical_block_size) {
523         return false;
524     }
525     blk_get_geometry(dev->blk, &total_sectors);
526     if (sector > total_sectors || nb_sectors > total_sectors - sector) {
527         return false;
528     }
529     return true;
530 }
531 
532 static uint8_t virtio_blk_handle_discard_write_zeroes(VirtIOBlockReq *req,
533     struct virtio_blk_discard_write_zeroes *dwz_hdr, bool is_write_zeroes)
534 {
535     VirtIOBlock *s = req->dev;
536     VirtIODevice *vdev = VIRTIO_DEVICE(s);
537     uint64_t sector;
538     uint32_t num_sectors, flags, max_sectors;
539     uint8_t err_status;
540     int bytes;
541 
542     sector = virtio_ldq_p(vdev, &dwz_hdr->sector);
543     num_sectors = virtio_ldl_p(vdev, &dwz_hdr->num_sectors);
544     flags = virtio_ldl_p(vdev, &dwz_hdr->flags);
545     max_sectors = is_write_zeroes ? s->conf.max_write_zeroes_sectors :
546                   s->conf.max_discard_sectors;
547 
548     /*
549      * max_sectors is at most BDRV_REQUEST_MAX_SECTORS, this check
550      * make us sure that "num_sectors << BDRV_SECTOR_BITS" can fit in
551      * the integer variable.
552      */
553     if (unlikely(num_sectors > max_sectors)) {
554         err_status = VIRTIO_BLK_S_IOERR;
555         goto err;
556     }
557 
558     bytes = num_sectors << BDRV_SECTOR_BITS;
559 
560     if (unlikely(!virtio_blk_sect_range_ok(s, sector, bytes))) {
561         err_status = VIRTIO_BLK_S_IOERR;
562         goto err;
563     }
564 
565     /*
566      * The device MUST set the status byte to VIRTIO_BLK_S_UNSUPP for discard
567      * and write zeroes commands if any unknown flag is set.
568      */
569     if (unlikely(flags & ~VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP)) {
570         err_status = VIRTIO_BLK_S_UNSUPP;
571         goto err;
572     }
573 
574     if (is_write_zeroes) { /* VIRTIO_BLK_T_WRITE_ZEROES */
575         int blk_aio_flags = 0;
576 
577         if (flags & VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP) {
578             blk_aio_flags |= BDRV_REQ_MAY_UNMAP;
579         }
580 
581         block_acct_start(blk_get_stats(s->blk), &req->acct, bytes,
582                          BLOCK_ACCT_WRITE);
583 
584         blk_aio_pwrite_zeroes(s->blk, sector << BDRV_SECTOR_BITS,
585                               bytes, blk_aio_flags,
586                               virtio_blk_discard_write_zeroes_complete, req);
587     } else { /* VIRTIO_BLK_T_DISCARD */
588         /*
589          * The device MUST set the status byte to VIRTIO_BLK_S_UNSUPP for
590          * discard commands if the unmap flag is set.
591          */
592         if (unlikely(flags & VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP)) {
593             err_status = VIRTIO_BLK_S_UNSUPP;
594             goto err;
595         }
596 
597         blk_aio_pdiscard(s->blk, sector << BDRV_SECTOR_BITS, bytes,
598                          virtio_blk_discard_write_zeroes_complete, req);
599     }
600 
601     return VIRTIO_BLK_S_OK;
602 
603 err:
604     if (is_write_zeroes) {
605         block_acct_invalid(blk_get_stats(s->blk), BLOCK_ACCT_WRITE);
606     }
607     return err_status;
608 }
609 
610 static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
611 {
612     uint32_t type;
613     struct iovec *in_iov = req->elem.in_sg;
614     struct iovec *out_iov = req->elem.out_sg;
615     unsigned in_num = req->elem.in_num;
616     unsigned out_num = req->elem.out_num;
617     VirtIOBlock *s = req->dev;
618     VirtIODevice *vdev = VIRTIO_DEVICE(s);
619 
620     if (req->elem.out_num < 1 || req->elem.in_num < 1) {
621         virtio_error(vdev, "virtio-blk missing headers");
622         return -1;
623     }
624 
625     if (unlikely(iov_to_buf(out_iov, out_num, 0, &req->out,
626                             sizeof(req->out)) != sizeof(req->out))) {
627         virtio_error(vdev, "virtio-blk request outhdr too short");
628         return -1;
629     }
630 
631     iov_discard_front(&out_iov, &out_num, sizeof(req->out));
632 
633     if (in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {
634         virtio_error(vdev, "virtio-blk request inhdr too short");
635         return -1;
636     }
637 
638     /* We always touch the last byte, so just see how big in_iov is.  */
639     req->in_len = iov_size(in_iov, in_num);
640     req->in = (void *)in_iov[in_num - 1].iov_base
641               + in_iov[in_num - 1].iov_len
642               - sizeof(struct virtio_blk_inhdr);
643     iov_discard_back(in_iov, &in_num, sizeof(struct virtio_blk_inhdr));
644 
645     type = virtio_ldl_p(vdev, &req->out.type);
646 
647     /* VIRTIO_BLK_T_OUT defines the command direction. VIRTIO_BLK_T_BARRIER
648      * is an optional flag. Although a guest should not send this flag if
649      * not negotiated we ignored it in the past. So keep ignoring it. */
650     switch (type & ~(VIRTIO_BLK_T_OUT | VIRTIO_BLK_T_BARRIER)) {
651     case VIRTIO_BLK_T_IN:
652     {
653         bool is_write = type & VIRTIO_BLK_T_OUT;
654         req->sector_num = virtio_ldq_p(vdev, &req->out.sector);
655 
656         if (is_write) {
657             qemu_iovec_init_external(&req->qiov, out_iov, out_num);
658             trace_virtio_blk_handle_write(vdev, req, req->sector_num,
659                                           req->qiov.size / BDRV_SECTOR_SIZE);
660         } else {
661             qemu_iovec_init_external(&req->qiov, in_iov, in_num);
662             trace_virtio_blk_handle_read(vdev, req, req->sector_num,
663                                          req->qiov.size / BDRV_SECTOR_SIZE);
664         }
665 
666         if (!virtio_blk_sect_range_ok(s, req->sector_num, req->qiov.size)) {
667             virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
668             block_acct_invalid(blk_get_stats(s->blk),
669                                is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
670             virtio_blk_free_request(req);
671             return 0;
672         }
673 
674         block_acct_start(blk_get_stats(s->blk), &req->acct, req->qiov.size,
675                          is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
676 
677         /* merge would exceed maximum number of requests or IO direction
678          * changes */
679         if (mrb->num_reqs > 0 && (mrb->num_reqs == VIRTIO_BLK_MAX_MERGE_REQS ||
680                                   is_write != mrb->is_write ||
681                                   !s->conf.request_merging)) {
682             virtio_blk_submit_multireq(s->blk, mrb);
683         }
684 
685         assert(mrb->num_reqs < VIRTIO_BLK_MAX_MERGE_REQS);
686         mrb->reqs[mrb->num_reqs++] = req;
687         mrb->is_write = is_write;
688         break;
689     }
690     case VIRTIO_BLK_T_FLUSH:
691         virtio_blk_handle_flush(req, mrb);
692         break;
693     case VIRTIO_BLK_T_SCSI_CMD:
694         virtio_blk_handle_scsi(req);
695         break;
696     case VIRTIO_BLK_T_GET_ID:
697     {
698         /*
699          * NB: per existing s/n string convention the string is
700          * terminated by '\0' only when shorter than buffer.
701          */
702         const char *serial = s->conf.serial ? s->conf.serial : "";
703         size_t size = MIN(strlen(serial) + 1,
704                           MIN(iov_size(in_iov, in_num),
705                               VIRTIO_BLK_ID_BYTES));
706         iov_from_buf(in_iov, in_num, 0, serial, size);
707         virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
708         virtio_blk_free_request(req);
709         break;
710     }
711     /*
712      * VIRTIO_BLK_T_DISCARD and VIRTIO_BLK_T_WRITE_ZEROES are defined with
713      * VIRTIO_BLK_T_OUT flag set. We masked this flag in the switch statement,
714      * so we must mask it for these requests, then we will check if it is set.
715      */
716     case VIRTIO_BLK_T_DISCARD & ~VIRTIO_BLK_T_OUT:
717     case VIRTIO_BLK_T_WRITE_ZEROES & ~VIRTIO_BLK_T_OUT:
718     {
719         struct virtio_blk_discard_write_zeroes dwz_hdr;
720         size_t out_len = iov_size(out_iov, out_num);
721         bool is_write_zeroes = (type & ~VIRTIO_BLK_T_BARRIER) ==
722                                VIRTIO_BLK_T_WRITE_ZEROES;
723         uint8_t err_status;
724 
725         /*
726          * Unsupported if VIRTIO_BLK_T_OUT is not set or the request contains
727          * more than one segment.
728          */
729         if (unlikely(!(type & VIRTIO_BLK_T_OUT) ||
730                      out_len > sizeof(dwz_hdr))) {
731             virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
732             virtio_blk_free_request(req);
733             return 0;
734         }
735 
736         if (unlikely(iov_to_buf(out_iov, out_num, 0, &dwz_hdr,
737                                 sizeof(dwz_hdr)) != sizeof(dwz_hdr))) {
738             virtio_error(vdev, "virtio-blk discard/write_zeroes header"
739                          " too short");
740             return -1;
741         }
742 
743         err_status = virtio_blk_handle_discard_write_zeroes(req, &dwz_hdr,
744                                                             is_write_zeroes);
745         if (err_status != VIRTIO_BLK_S_OK) {
746             virtio_blk_req_complete(req, err_status);
747             virtio_blk_free_request(req);
748         }
749 
750         break;
751     }
752     default:
753         virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
754         virtio_blk_free_request(req);
755     }
756     return 0;
757 }
758 
759 bool virtio_blk_handle_vq(VirtIOBlock *s, VirtQueue *vq)
760 {
761     VirtIOBlockReq *req;
762     MultiReqBuffer mrb = {};
763     bool progress = false;
764 
765     aio_context_acquire(blk_get_aio_context(s->blk));
766     blk_io_plug(s->blk);
767 
768     do {
769         virtio_queue_set_notification(vq, 0);
770 
771         while ((req = virtio_blk_get_request(s, vq))) {
772             progress = true;
773             if (virtio_blk_handle_request(req, &mrb)) {
774                 virtqueue_detach_element(req->vq, &req->elem, 0);
775                 virtio_blk_free_request(req);
776                 break;
777             }
778         }
779 
780         virtio_queue_set_notification(vq, 1);
781     } while (!virtio_queue_empty(vq));
782 
783     if (mrb.num_reqs) {
784         virtio_blk_submit_multireq(s->blk, &mrb);
785     }
786 
787     blk_io_unplug(s->blk);
788     aio_context_release(blk_get_aio_context(s->blk));
789     return progress;
790 }
791 
792 static void virtio_blk_handle_output_do(VirtIOBlock *s, VirtQueue *vq)
793 {
794     virtio_blk_handle_vq(s, vq);
795 }
796 
797 static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)
798 {
799     VirtIOBlock *s = (VirtIOBlock *)vdev;
800 
801     if (s->dataplane) {
802         /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start
803          * dataplane here instead of waiting for .set_status().
804          */
805         virtio_device_start_ioeventfd(vdev);
806         if (!s->dataplane_disabled) {
807             return;
808         }
809     }
810     virtio_blk_handle_output_do(s, vq);
811 }
812 
813 static void virtio_blk_dma_restart_bh(void *opaque)
814 {
815     VirtIOBlock *s = opaque;
816     VirtIOBlockReq *req = s->rq;
817     MultiReqBuffer mrb = {};
818 
819     qemu_bh_delete(s->bh);
820     s->bh = NULL;
821 
822     s->rq = NULL;
823 
824     aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
825     while (req) {
826         VirtIOBlockReq *next = req->next;
827         if (virtio_blk_handle_request(req, &mrb)) {
828             /* Device is now broken and won't do any processing until it gets
829              * reset. Already queued requests will be lost: let's purge them.
830              */
831             while (req) {
832                 next = req->next;
833                 virtqueue_detach_element(req->vq, &req->elem, 0);
834                 virtio_blk_free_request(req);
835                 req = next;
836             }
837             break;
838         }
839         req = next;
840     }
841 
842     if (mrb.num_reqs) {
843         virtio_blk_submit_multireq(s->blk, &mrb);
844     }
845     blk_dec_in_flight(s->conf.conf.blk);
846     aio_context_release(blk_get_aio_context(s->conf.conf.blk));
847 }
848 
849 static void virtio_blk_dma_restart_cb(void *opaque, int running,
850                                       RunState state)
851 {
852     VirtIOBlock *s = opaque;
853 
854     if (!running) {
855         return;
856     }
857 
858     if (!s->bh) {
859         /* FIXME The data plane is not started yet, so these requests are
860          * processed in the main thread. */
861         s->bh = aio_bh_new(blk_get_aio_context(s->conf.conf.blk),
862                            virtio_blk_dma_restart_bh, s);
863         blk_inc_in_flight(s->conf.conf.blk);
864         qemu_bh_schedule(s->bh);
865     }
866 }
867 
868 static void virtio_blk_reset(VirtIODevice *vdev)
869 {
870     VirtIOBlock *s = VIRTIO_BLK(vdev);
871     AioContext *ctx;
872     VirtIOBlockReq *req;
873 
874     ctx = blk_get_aio_context(s->blk);
875     aio_context_acquire(ctx);
876     blk_drain(s->blk);
877 
878     /* We drop queued requests after blk_drain() because blk_drain() itself can
879      * produce them. */
880     while (s->rq) {
881         req = s->rq;
882         s->rq = req->next;
883         virtqueue_detach_element(req->vq, &req->elem, 0);
884         virtio_blk_free_request(req);
885     }
886 
887     aio_context_release(ctx);
888 
889     assert(!s->dataplane_started);
890     blk_set_enable_write_cache(s->blk, s->original_wce);
891 }
892 
893 /* coalesce internal state, copy to pci i/o region 0
894  */
895 static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
896 {
897     VirtIOBlock *s = VIRTIO_BLK(vdev);
898     BlockConf *conf = &s->conf.conf;
899     struct virtio_blk_config blkcfg;
900     uint64_t capacity;
901     int64_t length;
902     int blk_size = conf->logical_block_size;
903 
904     blk_get_geometry(s->blk, &capacity);
905     memset(&blkcfg, 0, sizeof(blkcfg));
906     virtio_stq_p(vdev, &blkcfg.capacity, capacity);
907     virtio_stl_p(vdev, &blkcfg.seg_max, 128 - 2);
908     virtio_stw_p(vdev, &blkcfg.geometry.cylinders, conf->cyls);
909     virtio_stl_p(vdev, &blkcfg.blk_size, blk_size);
910     virtio_stw_p(vdev, &blkcfg.min_io_size, conf->min_io_size / blk_size);
911     virtio_stw_p(vdev, &blkcfg.opt_io_size, conf->opt_io_size / blk_size);
912     blkcfg.geometry.heads = conf->heads;
913     /*
914      * We must ensure that the block device capacity is a multiple of
915      * the logical block size. If that is not the case, let's use
916      * sector_mask to adopt the geometry to have a correct picture.
917      * For those devices where the capacity is ok for the given geometry
918      * we don't touch the sector value of the geometry, since some devices
919      * (like s390 dasd) need a specific value. Here the capacity is already
920      * cyls*heads*secs*blk_size and the sector value is not block size
921      * divided by 512 - instead it is the amount of blk_size blocks
922      * per track (cylinder).
923      */
924     length = blk_getlength(s->blk);
925     if (length > 0 && length / conf->heads / conf->secs % blk_size) {
926         blkcfg.geometry.sectors = conf->secs & ~s->sector_mask;
927     } else {
928         blkcfg.geometry.sectors = conf->secs;
929     }
930     blkcfg.size_max = 0;
931     blkcfg.physical_block_exp = get_physical_block_exp(conf);
932     blkcfg.alignment_offset = 0;
933     blkcfg.wce = blk_enable_write_cache(s->blk);
934     virtio_stw_p(vdev, &blkcfg.num_queues, s->conf.num_queues);
935     if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_DISCARD)) {
936         virtio_stl_p(vdev, &blkcfg.max_discard_sectors,
937                      s->conf.max_discard_sectors);
938         virtio_stl_p(vdev, &blkcfg.discard_sector_alignment,
939                      blk_size >> BDRV_SECTOR_BITS);
940         /*
941          * We support only one segment per request since multiple segments
942          * are not widely used and there are no userspace APIs that allow
943          * applications to submit multiple segments in a single call.
944          */
945         virtio_stl_p(vdev, &blkcfg.max_discard_seg, 1);
946     }
947     if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_WRITE_ZEROES)) {
948         virtio_stl_p(vdev, &blkcfg.max_write_zeroes_sectors,
949                      s->conf.max_write_zeroes_sectors);
950         blkcfg.write_zeroes_may_unmap = 1;
951         virtio_stl_p(vdev, &blkcfg.max_write_zeroes_seg, 1);
952     }
953     memcpy(config, &blkcfg, s->config_size);
954 }
955 
956 static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config)
957 {
958     VirtIOBlock *s = VIRTIO_BLK(vdev);
959     struct virtio_blk_config blkcfg;
960 
961     memcpy(&blkcfg, config, s->config_size);
962 
963     aio_context_acquire(blk_get_aio_context(s->blk));
964     blk_set_enable_write_cache(s->blk, blkcfg.wce != 0);
965     aio_context_release(blk_get_aio_context(s->blk));
966 }
967 
968 static uint64_t virtio_blk_get_features(VirtIODevice *vdev, uint64_t features,
969                                         Error **errp)
970 {
971     VirtIOBlock *s = VIRTIO_BLK(vdev);
972 
973     /* Firstly sync all virtio-blk possible supported features */
974     features |= s->host_features;
975 
976     virtio_add_feature(&features, VIRTIO_BLK_F_SEG_MAX);
977     virtio_add_feature(&features, VIRTIO_BLK_F_GEOMETRY);
978     virtio_add_feature(&features, VIRTIO_BLK_F_TOPOLOGY);
979     virtio_add_feature(&features, VIRTIO_BLK_F_BLK_SIZE);
980     if (virtio_has_feature(features, VIRTIO_F_VERSION_1)) {
981         if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_SCSI)) {
982             error_setg(errp, "Please set scsi=off for virtio-blk devices in order to use virtio 1.0");
983             return 0;
984         }
985     } else {
986         virtio_clear_feature(&features, VIRTIO_F_ANY_LAYOUT);
987         virtio_add_feature(&features, VIRTIO_BLK_F_SCSI);
988     }
989 
990     if (blk_enable_write_cache(s->blk)) {
991         virtio_add_feature(&features, VIRTIO_BLK_F_WCE);
992     }
993     if (blk_is_read_only(s->blk)) {
994         virtio_add_feature(&features, VIRTIO_BLK_F_RO);
995     }
996     if (s->conf.num_queues > 1) {
997         virtio_add_feature(&features, VIRTIO_BLK_F_MQ);
998     }
999 
1000     return features;
1001 }
1002 
1003 static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)
1004 {
1005     VirtIOBlock *s = VIRTIO_BLK(vdev);
1006 
1007     if (!(status & (VIRTIO_CONFIG_S_DRIVER | VIRTIO_CONFIG_S_DRIVER_OK))) {
1008         assert(!s->dataplane_started);
1009     }
1010 
1011     if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
1012         return;
1013     }
1014 
1015     /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send
1016      * cache flushes.  Thus, the "auto writethrough" behavior is never
1017      * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.
1018      * Leaving it enabled would break the following sequence:
1019      *
1020      *     Guest started with "-drive cache=writethrough"
1021      *     Guest sets status to 0
1022      *     Guest sets DRIVER bit in status field
1023      *     Guest reads host features (WCE=0, CONFIG_WCE=1)
1024      *     Guest writes guest features (WCE=0, CONFIG_WCE=1)
1025      *     Guest writes 1 to the WCE configuration field (writeback mode)
1026      *     Guest sets DRIVER_OK bit in status field
1027      *
1028      * s->blk would erroneously be placed in writethrough mode.
1029      */
1030     if (!virtio_vdev_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE)) {
1031         aio_context_acquire(blk_get_aio_context(s->blk));
1032         blk_set_enable_write_cache(s->blk,
1033                                    virtio_vdev_has_feature(vdev,
1034                                                            VIRTIO_BLK_F_WCE));
1035         aio_context_release(blk_get_aio_context(s->blk));
1036     }
1037 }
1038 
1039 static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f)
1040 {
1041     VirtIOBlock *s = VIRTIO_BLK(vdev);
1042     VirtIOBlockReq *req = s->rq;
1043 
1044     while (req) {
1045         qemu_put_sbyte(f, 1);
1046 
1047         if (s->conf.num_queues > 1) {
1048             qemu_put_be32(f, virtio_get_queue_index(req->vq));
1049         }
1050 
1051         qemu_put_virtqueue_element(f, &req->elem);
1052         req = req->next;
1053     }
1054     qemu_put_sbyte(f, 0);
1055 }
1056 
1057 static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f,
1058                                   int version_id)
1059 {
1060     VirtIOBlock *s = VIRTIO_BLK(vdev);
1061 
1062     while (qemu_get_sbyte(f)) {
1063         unsigned nvqs = s->conf.num_queues;
1064         unsigned vq_idx = 0;
1065         VirtIOBlockReq *req;
1066 
1067         if (nvqs > 1) {
1068             vq_idx = qemu_get_be32(f);
1069 
1070             if (vq_idx >= nvqs) {
1071                 error_report("Invalid virtqueue index in request list: %#x",
1072                              vq_idx);
1073                 return -EINVAL;
1074             }
1075         }
1076 
1077         req = qemu_get_virtqueue_element(vdev, f, sizeof(VirtIOBlockReq));
1078         virtio_blk_init_request(s, virtio_get_queue(vdev, vq_idx), req);
1079         req->next = s->rq;
1080         s->rq = req;
1081     }
1082 
1083     return 0;
1084 }
1085 
1086 static void virtio_blk_resize(void *opaque)
1087 {
1088     VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
1089 
1090     virtio_notify_config(vdev);
1091 }
1092 
1093 static const BlockDevOps virtio_block_ops = {
1094     .resize_cb = virtio_blk_resize,
1095 };
1096 
1097 static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
1098 {
1099     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1100     VirtIOBlock *s = VIRTIO_BLK(dev);
1101     VirtIOBlkConf *conf = &s->conf;
1102     Error *err = NULL;
1103     unsigned i;
1104 
1105     if (!conf->conf.blk) {
1106         error_setg(errp, "drive property not set");
1107         return;
1108     }
1109     if (!blk_is_inserted(conf->conf.blk)) {
1110         error_setg(errp, "Device needs media, but drive is empty");
1111         return;
1112     }
1113     if (!conf->num_queues) {
1114         error_setg(errp, "num-queues property must be larger than 0");
1115         return;
1116     }
1117     if (!is_power_of_2(conf->queue_size) ||
1118         conf->queue_size > VIRTQUEUE_MAX_SIZE) {
1119         error_setg(errp, "invalid queue-size property (%" PRIu16 "), "
1120                    "must be a power of 2 (max %d)",
1121                    conf->queue_size, VIRTQUEUE_MAX_SIZE);
1122         return;
1123     }
1124 
1125     if (!blkconf_apply_backend_options(&conf->conf,
1126                                        blk_is_read_only(conf->conf.blk), true,
1127                                        errp)) {
1128         return;
1129     }
1130     s->original_wce = blk_enable_write_cache(conf->conf.blk);
1131     if (!blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, errp)) {
1132         return;
1133     }
1134 
1135     blkconf_blocksizes(&conf->conf);
1136 
1137     if (conf->conf.logical_block_size >
1138         conf->conf.physical_block_size) {
1139         error_setg(errp,
1140                    "logical_block_size > physical_block_size not supported");
1141         return;
1142     }
1143 
1144     if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_DISCARD) &&
1145         (!conf->max_discard_sectors ||
1146          conf->max_discard_sectors > BDRV_REQUEST_MAX_SECTORS)) {
1147         error_setg(errp, "invalid max-discard-sectors property (%" PRIu32 ")"
1148                    ", must be between 1 and %d",
1149                    conf->max_discard_sectors, (int)BDRV_REQUEST_MAX_SECTORS);
1150         return;
1151     }
1152 
1153     if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_WRITE_ZEROES) &&
1154         (!conf->max_write_zeroes_sectors ||
1155          conf->max_write_zeroes_sectors > BDRV_REQUEST_MAX_SECTORS)) {
1156         error_setg(errp, "invalid max-write-zeroes-sectors property (%" PRIu32
1157                    "), must be between 1 and %d",
1158                    conf->max_write_zeroes_sectors,
1159                    (int)BDRV_REQUEST_MAX_SECTORS);
1160         return;
1161     }
1162 
1163     virtio_blk_set_config_size(s, s->host_features);
1164 
1165     virtio_init(vdev, "virtio-blk", VIRTIO_ID_BLOCK, s->config_size);
1166 
1167     s->blk = conf->conf.blk;
1168     s->rq = NULL;
1169     s->sector_mask = (s->conf.conf.logical_block_size / BDRV_SECTOR_SIZE) - 1;
1170 
1171     for (i = 0; i < conf->num_queues; i++) {
1172         virtio_add_queue(vdev, conf->queue_size, virtio_blk_handle_output);
1173     }
1174     virtio_blk_data_plane_create(vdev, conf, &s->dataplane, &err);
1175     if (err != NULL) {
1176         error_propagate(errp, err);
1177         virtio_cleanup(vdev);
1178         return;
1179     }
1180 
1181     s->change = qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);
1182     blk_set_dev_ops(s->blk, &virtio_block_ops, s);
1183     blk_set_guest_block_size(s->blk, s->conf.conf.logical_block_size);
1184 
1185     blk_iostatus_enable(s->blk);
1186 }
1187 
1188 static void virtio_blk_device_unrealize(DeviceState *dev, Error **errp)
1189 {
1190     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1191     VirtIOBlock *s = VIRTIO_BLK(dev);
1192 
1193     virtio_blk_data_plane_destroy(s->dataplane);
1194     s->dataplane = NULL;
1195     qemu_del_vm_change_state_handler(s->change);
1196     blockdev_mark_auto_del(s->blk);
1197     virtio_cleanup(vdev);
1198 }
1199 
1200 static void virtio_blk_instance_init(Object *obj)
1201 {
1202     VirtIOBlock *s = VIRTIO_BLK(obj);
1203 
1204     device_add_bootindex_property(obj, &s->conf.conf.bootindex,
1205                                   "bootindex", "/disk@0,0",
1206                                   DEVICE(obj), NULL);
1207 }
1208 
1209 static const VMStateDescription vmstate_virtio_blk = {
1210     .name = "virtio-blk",
1211     .minimum_version_id = 2,
1212     .version_id = 2,
1213     .fields = (VMStateField[]) {
1214         VMSTATE_VIRTIO_DEVICE,
1215         VMSTATE_END_OF_LIST()
1216     },
1217 };
1218 
1219 static Property virtio_blk_properties[] = {
1220     DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf),
1221     DEFINE_BLOCK_ERROR_PROPERTIES(VirtIOBlock, conf.conf),
1222     DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf),
1223     DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial),
1224     DEFINE_PROP_BIT64("config-wce", VirtIOBlock, host_features,
1225                       VIRTIO_BLK_F_CONFIG_WCE, true),
1226 #ifdef __linux__
1227     DEFINE_PROP_BIT64("scsi", VirtIOBlock, host_features,
1228                       VIRTIO_BLK_F_SCSI, false),
1229 #endif
1230     DEFINE_PROP_BIT("request-merging", VirtIOBlock, conf.request_merging, 0,
1231                     true),
1232     DEFINE_PROP_UINT16("num-queues", VirtIOBlock, conf.num_queues, 1),
1233     DEFINE_PROP_UINT16("queue-size", VirtIOBlock, conf.queue_size, 128),
1234     DEFINE_PROP_LINK("iothread", VirtIOBlock, conf.iothread, TYPE_IOTHREAD,
1235                      IOThread *),
1236     DEFINE_PROP_BIT64("discard", VirtIOBlock, host_features,
1237                       VIRTIO_BLK_F_DISCARD, true),
1238     DEFINE_PROP_BIT64("write-zeroes", VirtIOBlock, host_features,
1239                       VIRTIO_BLK_F_WRITE_ZEROES, true),
1240     DEFINE_PROP_UINT32("max-discard-sectors", VirtIOBlock,
1241                        conf.max_discard_sectors, BDRV_REQUEST_MAX_SECTORS),
1242     DEFINE_PROP_UINT32("max-write-zeroes-sectors", VirtIOBlock,
1243                        conf.max_write_zeroes_sectors, BDRV_REQUEST_MAX_SECTORS),
1244     DEFINE_PROP_END_OF_LIST(),
1245 };
1246 
1247 static void virtio_blk_class_init(ObjectClass *klass, void *data)
1248 {
1249     DeviceClass *dc = DEVICE_CLASS(klass);
1250     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1251 
1252     dc->props = virtio_blk_properties;
1253     dc->vmsd = &vmstate_virtio_blk;
1254     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1255     vdc->realize = virtio_blk_device_realize;
1256     vdc->unrealize = virtio_blk_device_unrealize;
1257     vdc->get_config = virtio_blk_update_config;
1258     vdc->set_config = virtio_blk_set_config;
1259     vdc->get_features = virtio_blk_get_features;
1260     vdc->set_status = virtio_blk_set_status;
1261     vdc->reset = virtio_blk_reset;
1262     vdc->save = virtio_blk_save_device;
1263     vdc->load = virtio_blk_load_device;
1264     vdc->start_ioeventfd = virtio_blk_data_plane_start;
1265     vdc->stop_ioeventfd = virtio_blk_data_plane_stop;
1266 }
1267 
1268 static const TypeInfo virtio_blk_info = {
1269     .name = TYPE_VIRTIO_BLK,
1270     .parent = TYPE_VIRTIO_DEVICE,
1271     .instance_size = sizeof(VirtIOBlock),
1272     .instance_init = virtio_blk_instance_init,
1273     .class_init = virtio_blk_class_init,
1274 };
1275 
1276 static void virtio_register_types(void)
1277 {
1278     type_register_static(&virtio_blk_info);
1279 }
1280 
1281 type_init(virtio_register_types)
1282