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