xref: /openbmc/qemu/hw/block/virtio-blk.c (revision 744c72a8)
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 bool 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     bool progress = false;
776 
777     aio_context_acquire(blk_get_aio_context(s->blk));
778     blk_io_plug(s->blk);
779 
780     do {
781         if (suppress_notifications) {
782             virtio_queue_set_notification(vq, 0);
783         }
784 
785         while ((req = virtio_blk_get_request(s, vq))) {
786             progress = true;
787             if (virtio_blk_handle_request(req, &mrb)) {
788                 virtqueue_detach_element(req->vq, &req->elem, 0);
789                 virtio_blk_free_request(req);
790                 break;
791             }
792         }
793 
794         if (suppress_notifications) {
795             virtio_queue_set_notification(vq, 1);
796         }
797     } while (!virtio_queue_empty(vq));
798 
799     if (mrb.num_reqs) {
800         virtio_blk_submit_multireq(s->blk, &mrb);
801     }
802 
803     blk_io_unplug(s->blk);
804     aio_context_release(blk_get_aio_context(s->blk));
805     return progress;
806 }
807 
808 static void virtio_blk_handle_output_do(VirtIOBlock *s, VirtQueue *vq)
809 {
810     virtio_blk_handle_vq(s, vq);
811 }
812 
813 static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)
814 {
815     VirtIOBlock *s = (VirtIOBlock *)vdev;
816 
817     if (s->dataplane) {
818         /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start
819          * dataplane here instead of waiting for .set_status().
820          */
821         virtio_device_start_ioeventfd(vdev);
822         if (!s->dataplane_disabled) {
823             return;
824         }
825     }
826     virtio_blk_handle_output_do(s, vq);
827 }
828 
829 void virtio_blk_process_queued_requests(VirtIOBlock *s, bool is_bh)
830 {
831     VirtIOBlockReq *req = s->rq;
832     MultiReqBuffer mrb = {};
833 
834     s->rq = NULL;
835 
836     aio_context_acquire(blk_get_aio_context(s->conf.conf.blk));
837     while (req) {
838         VirtIOBlockReq *next = req->next;
839         if (virtio_blk_handle_request(req, &mrb)) {
840             /* Device is now broken and won't do any processing until it gets
841              * reset. Already queued requests will be lost: let's purge them.
842              */
843             while (req) {
844                 next = req->next;
845                 virtqueue_detach_element(req->vq, &req->elem, 0);
846                 virtio_blk_free_request(req);
847                 req = next;
848             }
849             break;
850         }
851         req = next;
852     }
853 
854     if (mrb.num_reqs) {
855         virtio_blk_submit_multireq(s->blk, &mrb);
856     }
857     if (is_bh) {
858         blk_dec_in_flight(s->conf.conf.blk);
859     }
860     aio_context_release(blk_get_aio_context(s->conf.conf.blk));
861 }
862 
863 static void virtio_blk_dma_restart_bh(void *opaque)
864 {
865     VirtIOBlock *s = opaque;
866 
867     qemu_bh_delete(s->bh);
868     s->bh = NULL;
869 
870     virtio_blk_process_queued_requests(s, true);
871 }
872 
873 static void virtio_blk_dma_restart_cb(void *opaque, bool running,
874                                       RunState state)
875 {
876     VirtIOBlock *s = opaque;
877     BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s)));
878     VirtioBusState *bus = VIRTIO_BUS(qbus);
879 
880     if (!running) {
881         return;
882     }
883 
884     /*
885      * If ioeventfd is enabled, don't schedule the BH here as queued
886      * requests will be processed while starting the data plane.
887      */
888     if (!s->bh && !virtio_bus_ioeventfd_enabled(bus)) {
889         s->bh = aio_bh_new(blk_get_aio_context(s->conf.conf.blk),
890                            virtio_blk_dma_restart_bh, s);
891         blk_inc_in_flight(s->conf.conf.blk);
892         qemu_bh_schedule(s->bh);
893     }
894 }
895 
896 static void virtio_blk_reset(VirtIODevice *vdev)
897 {
898     VirtIOBlock *s = VIRTIO_BLK(vdev);
899     AioContext *ctx;
900     VirtIOBlockReq *req;
901 
902     ctx = blk_get_aio_context(s->blk);
903     aio_context_acquire(ctx);
904     blk_drain(s->blk);
905 
906     /* We drop queued requests after blk_drain() because blk_drain() itself can
907      * produce them. */
908     while (s->rq) {
909         req = s->rq;
910         s->rq = req->next;
911         virtqueue_detach_element(req->vq, &req->elem, 0);
912         virtio_blk_free_request(req);
913     }
914 
915     aio_context_release(ctx);
916 
917     assert(!s->dataplane_started);
918     blk_set_enable_write_cache(s->blk, s->original_wce);
919 }
920 
921 /* coalesce internal state, copy to pci i/o region 0
922  */
923 static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
924 {
925     VirtIOBlock *s = VIRTIO_BLK(vdev);
926     BlockConf *conf = &s->conf.conf;
927     struct virtio_blk_config blkcfg;
928     uint64_t capacity;
929     int64_t length;
930     int blk_size = conf->logical_block_size;
931 
932     blk_get_geometry(s->blk, &capacity);
933     memset(&blkcfg, 0, sizeof(blkcfg));
934     virtio_stq_p(vdev, &blkcfg.capacity, capacity);
935     virtio_stl_p(vdev, &blkcfg.seg_max,
936                  s->conf.seg_max_adjust ? s->conf.queue_size - 2 : 128 - 2);
937     virtio_stw_p(vdev, &blkcfg.geometry.cylinders, conf->cyls);
938     virtio_stl_p(vdev, &blkcfg.blk_size, blk_size);
939     virtio_stw_p(vdev, &blkcfg.min_io_size, conf->min_io_size / blk_size);
940     virtio_stl_p(vdev, &blkcfg.opt_io_size, conf->opt_io_size / blk_size);
941     blkcfg.geometry.heads = conf->heads;
942     /*
943      * We must ensure that the block device capacity is a multiple of
944      * the logical block size. If that is not the case, let's use
945      * sector_mask to adopt the geometry to have a correct picture.
946      * For those devices where the capacity is ok for the given geometry
947      * we don't touch the sector value of the geometry, since some devices
948      * (like s390 dasd) need a specific value. Here the capacity is already
949      * cyls*heads*secs*blk_size and the sector value is not block size
950      * divided by 512 - instead it is the amount of blk_size blocks
951      * per track (cylinder).
952      */
953     length = blk_getlength(s->blk);
954     if (length > 0 && length / conf->heads / conf->secs % blk_size) {
955         blkcfg.geometry.sectors = conf->secs & ~s->sector_mask;
956     } else {
957         blkcfg.geometry.sectors = conf->secs;
958     }
959     blkcfg.size_max = 0;
960     blkcfg.physical_block_exp = get_physical_block_exp(conf);
961     blkcfg.alignment_offset = 0;
962     blkcfg.wce = blk_enable_write_cache(s->blk);
963     virtio_stw_p(vdev, &blkcfg.num_queues, s->conf.num_queues);
964     if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_DISCARD)) {
965         uint32_t discard_granularity = conf->discard_granularity;
966         if (discard_granularity == -1 || !s->conf.report_discard_granularity) {
967             discard_granularity = blk_size;
968         }
969         virtio_stl_p(vdev, &blkcfg.max_discard_sectors,
970                      s->conf.max_discard_sectors);
971         virtio_stl_p(vdev, &blkcfg.discard_sector_alignment,
972                      discard_granularity >> BDRV_SECTOR_BITS);
973         /*
974          * We support only one segment per request since multiple segments
975          * are not widely used and there are no userspace APIs that allow
976          * applications to submit multiple segments in a single call.
977          */
978         virtio_stl_p(vdev, &blkcfg.max_discard_seg, 1);
979     }
980     if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_WRITE_ZEROES)) {
981         virtio_stl_p(vdev, &blkcfg.max_write_zeroes_sectors,
982                      s->conf.max_write_zeroes_sectors);
983         blkcfg.write_zeroes_may_unmap = 1;
984         virtio_stl_p(vdev, &blkcfg.max_write_zeroes_seg, 1);
985     }
986     memcpy(config, &blkcfg, s->config_size);
987 }
988 
989 static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config)
990 {
991     VirtIOBlock *s = VIRTIO_BLK(vdev);
992     struct virtio_blk_config blkcfg;
993 
994     memcpy(&blkcfg, config, s->config_size);
995 
996     aio_context_acquire(blk_get_aio_context(s->blk));
997     blk_set_enable_write_cache(s->blk, blkcfg.wce != 0);
998     aio_context_release(blk_get_aio_context(s->blk));
999 }
1000 
1001 static uint64_t virtio_blk_get_features(VirtIODevice *vdev, uint64_t features,
1002                                         Error **errp)
1003 {
1004     VirtIOBlock *s = VIRTIO_BLK(vdev);
1005 
1006     /* Firstly sync all virtio-blk possible supported features */
1007     features |= s->host_features;
1008 
1009     virtio_add_feature(&features, VIRTIO_BLK_F_SEG_MAX);
1010     virtio_add_feature(&features, VIRTIO_BLK_F_GEOMETRY);
1011     virtio_add_feature(&features, VIRTIO_BLK_F_TOPOLOGY);
1012     virtio_add_feature(&features, VIRTIO_BLK_F_BLK_SIZE);
1013     if (virtio_has_feature(features, VIRTIO_F_VERSION_1)) {
1014         if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_SCSI)) {
1015             error_setg(errp, "Please set scsi=off for virtio-blk devices in order to use virtio 1.0");
1016             return 0;
1017         }
1018     } else {
1019         virtio_clear_feature(&features, VIRTIO_F_ANY_LAYOUT);
1020         virtio_add_feature(&features, VIRTIO_BLK_F_SCSI);
1021     }
1022 
1023     if (blk_enable_write_cache(s->blk) ||
1024         (s->conf.x_enable_wce_if_config_wce &&
1025          virtio_has_feature(features, VIRTIO_BLK_F_CONFIG_WCE))) {
1026         virtio_add_feature(&features, VIRTIO_BLK_F_WCE);
1027     }
1028     if (!blk_is_writable(s->blk)) {
1029         virtio_add_feature(&features, VIRTIO_BLK_F_RO);
1030     }
1031     if (s->conf.num_queues > 1) {
1032         virtio_add_feature(&features, VIRTIO_BLK_F_MQ);
1033     }
1034 
1035     return features;
1036 }
1037 
1038 static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)
1039 {
1040     VirtIOBlock *s = VIRTIO_BLK(vdev);
1041 
1042     if (!(status & (VIRTIO_CONFIG_S_DRIVER | VIRTIO_CONFIG_S_DRIVER_OK))) {
1043         assert(!s->dataplane_started);
1044     }
1045 
1046     if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
1047         return;
1048     }
1049 
1050     /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send
1051      * cache flushes.  Thus, the "auto writethrough" behavior is never
1052      * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.
1053      * Leaving it enabled would break the following sequence:
1054      *
1055      *     Guest started with "-drive cache=writethrough"
1056      *     Guest sets status to 0
1057      *     Guest sets DRIVER bit in status field
1058      *     Guest reads host features (WCE=0, CONFIG_WCE=1)
1059      *     Guest writes guest features (WCE=0, CONFIG_WCE=1)
1060      *     Guest writes 1 to the WCE configuration field (writeback mode)
1061      *     Guest sets DRIVER_OK bit in status field
1062      *
1063      * s->blk would erroneously be placed in writethrough mode.
1064      */
1065     if (!virtio_vdev_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE)) {
1066         aio_context_acquire(blk_get_aio_context(s->blk));
1067         blk_set_enable_write_cache(s->blk,
1068                                    virtio_vdev_has_feature(vdev,
1069                                                            VIRTIO_BLK_F_WCE));
1070         aio_context_release(blk_get_aio_context(s->blk));
1071     }
1072 }
1073 
1074 static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f)
1075 {
1076     VirtIOBlock *s = VIRTIO_BLK(vdev);
1077     VirtIOBlockReq *req = s->rq;
1078 
1079     while (req) {
1080         qemu_put_sbyte(f, 1);
1081 
1082         if (s->conf.num_queues > 1) {
1083             qemu_put_be32(f, virtio_get_queue_index(req->vq));
1084         }
1085 
1086         qemu_put_virtqueue_element(vdev, f, &req->elem);
1087         req = req->next;
1088     }
1089     qemu_put_sbyte(f, 0);
1090 }
1091 
1092 static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f,
1093                                   int version_id)
1094 {
1095     VirtIOBlock *s = VIRTIO_BLK(vdev);
1096 
1097     while (qemu_get_sbyte(f)) {
1098         unsigned nvqs = s->conf.num_queues;
1099         unsigned vq_idx = 0;
1100         VirtIOBlockReq *req;
1101 
1102         if (nvqs > 1) {
1103             vq_idx = qemu_get_be32(f);
1104 
1105             if (vq_idx >= nvqs) {
1106                 error_report("Invalid virtqueue index in request list: %#x",
1107                              vq_idx);
1108                 return -EINVAL;
1109             }
1110         }
1111 
1112         req = qemu_get_virtqueue_element(vdev, f, sizeof(VirtIOBlockReq));
1113         virtio_blk_init_request(s, virtio_get_queue(vdev, vq_idx), req);
1114         req->next = s->rq;
1115         s->rq = req;
1116     }
1117 
1118     return 0;
1119 }
1120 
1121 static void virtio_resize_cb(void *opaque)
1122 {
1123     VirtIODevice *vdev = opaque;
1124 
1125     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1126     virtio_notify_config(vdev);
1127 }
1128 
1129 static void virtio_blk_resize(void *opaque)
1130 {
1131     VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
1132 
1133     /*
1134      * virtio_notify_config() needs to acquire the global mutex,
1135      * so it can't be called from an iothread. Instead, schedule
1136      * it to be run in the main context BH.
1137      */
1138     aio_bh_schedule_oneshot(qemu_get_aio_context(), virtio_resize_cb, vdev);
1139 }
1140 
1141 static const BlockDevOps virtio_block_ops = {
1142     .resize_cb = virtio_blk_resize,
1143 };
1144 
1145 static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
1146 {
1147     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1148     VirtIOBlock *s = VIRTIO_BLK(dev);
1149     VirtIOBlkConf *conf = &s->conf;
1150     Error *err = NULL;
1151     unsigned i;
1152 
1153     if (!conf->conf.blk) {
1154         error_setg(errp, "drive property not set");
1155         return;
1156     }
1157     if (!blk_is_inserted(conf->conf.blk)) {
1158         error_setg(errp, "Device needs media, but drive is empty");
1159         return;
1160     }
1161     if (conf->num_queues == VIRTIO_BLK_AUTO_NUM_QUEUES) {
1162         conf->num_queues = 1;
1163     }
1164     if (!conf->num_queues) {
1165         error_setg(errp, "num-queues property must be larger than 0");
1166         return;
1167     }
1168     if (conf->queue_size <= 2) {
1169         error_setg(errp, "invalid queue-size property (%" PRIu16 "), "
1170                    "must be > 2", conf->queue_size);
1171         return;
1172     }
1173     if (!is_power_of_2(conf->queue_size) ||
1174         conf->queue_size > VIRTQUEUE_MAX_SIZE) {
1175         error_setg(errp, "invalid queue-size property (%" PRIu16 "), "
1176                    "must be a power of 2 (max %d)",
1177                    conf->queue_size, VIRTQUEUE_MAX_SIZE);
1178         return;
1179     }
1180 
1181     if (!blkconf_apply_backend_options(&conf->conf,
1182                                        !blk_supports_write_perm(conf->conf.blk),
1183                                        true, errp)) {
1184         return;
1185     }
1186     s->original_wce = blk_enable_write_cache(conf->conf.blk);
1187     if (!blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, errp)) {
1188         return;
1189     }
1190 
1191     if (!blkconf_blocksizes(&conf->conf, errp)) {
1192         return;
1193     }
1194 
1195     if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_DISCARD) &&
1196         (!conf->max_discard_sectors ||
1197          conf->max_discard_sectors > BDRV_REQUEST_MAX_SECTORS)) {
1198         error_setg(errp, "invalid max-discard-sectors property (%" PRIu32 ")"
1199                    ", must be between 1 and %d",
1200                    conf->max_discard_sectors, (int)BDRV_REQUEST_MAX_SECTORS);
1201         return;
1202     }
1203 
1204     if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_WRITE_ZEROES) &&
1205         (!conf->max_write_zeroes_sectors ||
1206          conf->max_write_zeroes_sectors > BDRV_REQUEST_MAX_SECTORS)) {
1207         error_setg(errp, "invalid max-write-zeroes-sectors property (%" PRIu32
1208                    "), must be between 1 and %d",
1209                    conf->max_write_zeroes_sectors,
1210                    (int)BDRV_REQUEST_MAX_SECTORS);
1211         return;
1212     }
1213 
1214     virtio_blk_set_config_size(s, s->host_features);
1215 
1216     virtio_init(vdev, "virtio-blk", VIRTIO_ID_BLOCK, s->config_size);
1217 
1218     s->blk = conf->conf.blk;
1219     s->rq = NULL;
1220     s->sector_mask = (s->conf.conf.logical_block_size / BDRV_SECTOR_SIZE) - 1;
1221 
1222     for (i = 0; i < conf->num_queues; i++) {
1223         virtio_add_queue(vdev, conf->queue_size, virtio_blk_handle_output);
1224     }
1225     virtio_blk_data_plane_create(vdev, conf, &s->dataplane, &err);
1226     if (err != NULL) {
1227         error_propagate(errp, err);
1228         for (i = 0; i < conf->num_queues; i++) {
1229             virtio_del_queue(vdev, i);
1230         }
1231         virtio_cleanup(vdev);
1232         return;
1233     }
1234 
1235     s->change = qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);
1236     blk_set_dev_ops(s->blk, &virtio_block_ops, s);
1237     blk_set_guest_block_size(s->blk, s->conf.conf.logical_block_size);
1238 
1239     blk_iostatus_enable(s->blk);
1240 
1241     add_boot_device_lchs(dev, "/disk@0,0",
1242                          conf->conf.lcyls,
1243                          conf->conf.lheads,
1244                          conf->conf.lsecs);
1245 }
1246 
1247 static void virtio_blk_device_unrealize(DeviceState *dev)
1248 {
1249     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1250     VirtIOBlock *s = VIRTIO_BLK(dev);
1251     VirtIOBlkConf *conf = &s->conf;
1252     unsigned i;
1253 
1254     blk_drain(s->blk);
1255     del_boot_device_lchs(dev, "/disk@0,0");
1256     virtio_blk_data_plane_destroy(s->dataplane);
1257     s->dataplane = NULL;
1258     for (i = 0; i < conf->num_queues; i++) {
1259         virtio_del_queue(vdev, i);
1260     }
1261     qemu_del_vm_change_state_handler(s->change);
1262     blockdev_mark_auto_del(s->blk);
1263     virtio_cleanup(vdev);
1264 }
1265 
1266 static void virtio_blk_instance_init(Object *obj)
1267 {
1268     VirtIOBlock *s = VIRTIO_BLK(obj);
1269 
1270     device_add_bootindex_property(obj, &s->conf.conf.bootindex,
1271                                   "bootindex", "/disk@0,0",
1272                                   DEVICE(obj));
1273 }
1274 
1275 static const VMStateDescription vmstate_virtio_blk = {
1276     .name = "virtio-blk",
1277     .minimum_version_id = 2,
1278     .version_id = 2,
1279     .fields = (VMStateField[]) {
1280         VMSTATE_VIRTIO_DEVICE,
1281         VMSTATE_END_OF_LIST()
1282     },
1283 };
1284 
1285 static Property virtio_blk_properties[] = {
1286     DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf),
1287     DEFINE_BLOCK_ERROR_PROPERTIES(VirtIOBlock, conf.conf),
1288     DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf),
1289     DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial),
1290     DEFINE_PROP_BIT64("config-wce", VirtIOBlock, host_features,
1291                       VIRTIO_BLK_F_CONFIG_WCE, true),
1292 #ifdef __linux__
1293     DEFINE_PROP_BIT64("scsi", VirtIOBlock, host_features,
1294                       VIRTIO_BLK_F_SCSI, false),
1295 #endif
1296     DEFINE_PROP_BIT("request-merging", VirtIOBlock, conf.request_merging, 0,
1297                     true),
1298     DEFINE_PROP_UINT16("num-queues", VirtIOBlock, conf.num_queues,
1299                        VIRTIO_BLK_AUTO_NUM_QUEUES),
1300     DEFINE_PROP_UINT16("queue-size", VirtIOBlock, conf.queue_size, 256),
1301     DEFINE_PROP_BOOL("seg-max-adjust", VirtIOBlock, conf.seg_max_adjust, true),
1302     DEFINE_PROP_LINK("iothread", VirtIOBlock, conf.iothread, TYPE_IOTHREAD,
1303                      IOThread *),
1304     DEFINE_PROP_BIT64("discard", VirtIOBlock, host_features,
1305                       VIRTIO_BLK_F_DISCARD, true),
1306     DEFINE_PROP_BOOL("report-discard-granularity", VirtIOBlock,
1307                      conf.report_discard_granularity, true),
1308     DEFINE_PROP_BIT64("write-zeroes", VirtIOBlock, host_features,
1309                       VIRTIO_BLK_F_WRITE_ZEROES, true),
1310     DEFINE_PROP_UINT32("max-discard-sectors", VirtIOBlock,
1311                        conf.max_discard_sectors, BDRV_REQUEST_MAX_SECTORS),
1312     DEFINE_PROP_UINT32("max-write-zeroes-sectors", VirtIOBlock,
1313                        conf.max_write_zeroes_sectors, BDRV_REQUEST_MAX_SECTORS),
1314     DEFINE_PROP_BOOL("x-enable-wce-if-config-wce", VirtIOBlock,
1315                      conf.x_enable_wce_if_config_wce, true),
1316     DEFINE_PROP_END_OF_LIST(),
1317 };
1318 
1319 static void virtio_blk_class_init(ObjectClass *klass, void *data)
1320 {
1321     DeviceClass *dc = DEVICE_CLASS(klass);
1322     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1323 
1324     device_class_set_props(dc, virtio_blk_properties);
1325     dc->vmsd = &vmstate_virtio_blk;
1326     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1327     vdc->realize = virtio_blk_device_realize;
1328     vdc->unrealize = virtio_blk_device_unrealize;
1329     vdc->get_config = virtio_blk_update_config;
1330     vdc->set_config = virtio_blk_set_config;
1331     vdc->get_features = virtio_blk_get_features;
1332     vdc->set_status = virtio_blk_set_status;
1333     vdc->reset = virtio_blk_reset;
1334     vdc->save = virtio_blk_save_device;
1335     vdc->load = virtio_blk_load_device;
1336     vdc->start_ioeventfd = virtio_blk_data_plane_start;
1337     vdc->stop_ioeventfd = virtio_blk_data_plane_stop;
1338 }
1339 
1340 static const TypeInfo virtio_blk_info = {
1341     .name = TYPE_VIRTIO_BLK,
1342     .parent = TYPE_VIRTIO_DEVICE,
1343     .instance_size = sizeof(VirtIOBlock),
1344     .instance_init = virtio_blk_instance_init,
1345     .class_init = virtio_blk_class_init,
1346 };
1347 
1348 static void virtio_register_types(void)
1349 {
1350     type_register_static(&virtio_blk_info);
1351 }
1352 
1353 type_init(virtio_register_types)
1354