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