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