xref: /openbmc/qemu/hw/block/virtio-blk.c (revision e7ae771f)
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-common.h"
15 #include "qemu/iov.h"
16 #include "qemu/error-report.h"
17 #include "trace.h"
18 #include "hw/block/block.h"
19 #include "sysemu/block-backend.h"
20 #include "sysemu/blockdev.h"
21 #include "hw/virtio/virtio-blk.h"
22 #include "dataplane/virtio-blk.h"
23 #include "migration/migration.h"
24 #include "block/scsi.h"
25 #ifdef __linux__
26 # include <scsi/sg.h>
27 #endif
28 #include "hw/virtio/virtio-bus.h"
29 #include "hw/virtio/virtio-access.h"
30 
31 VirtIOBlockReq *virtio_blk_alloc_request(VirtIOBlock *s)
32 {
33     VirtIOBlockReq *req = g_slice_new(VirtIOBlockReq);
34     req->dev = s;
35     req->qiov.size = 0;
36     req->next = NULL;
37     req->mr_next = NULL;
38     return req;
39 }
40 
41 void virtio_blk_free_request(VirtIOBlockReq *req)
42 {
43     if (req) {
44         g_slice_free(VirtIOBlockReq, req);
45     }
46 }
47 
48 static void virtio_blk_complete_request(VirtIOBlockReq *req,
49                                         unsigned char status)
50 {
51     VirtIOBlock *s = req->dev;
52     VirtIODevice *vdev = VIRTIO_DEVICE(s);
53 
54     trace_virtio_blk_req_complete(req, status);
55 
56     stb_p(&req->in->status, status);
57     virtqueue_push(s->vq, &req->elem, req->qiov.size + sizeof(*req->in));
58     virtio_notify(vdev, s->vq);
59 }
60 
61 static void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
62 {
63     req->dev->complete_request(req, status);
64 }
65 
66 static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
67     bool is_read)
68 {
69     BlockErrorAction action = blk_get_error_action(req->dev->blk,
70                                                    is_read, error);
71     VirtIOBlock *s = req->dev;
72 
73     if (action == BLOCK_ERROR_ACTION_STOP) {
74         req->next = s->rq;
75         s->rq = req;
76     } else if (action == BLOCK_ERROR_ACTION_REPORT) {
77         virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
78         block_acct_done(blk_get_stats(s->blk), &req->acct);
79         virtio_blk_free_request(req);
80     }
81 
82     blk_error_action(s->blk, action, is_read, error);
83     return action != BLOCK_ERROR_ACTION_IGNORE;
84 }
85 
86 static void virtio_blk_rw_complete(void *opaque, int ret)
87 {
88     VirtIOBlockReq *next = opaque;
89 
90     while (next) {
91         VirtIOBlockReq *req = next;
92         next = req->mr_next;
93         trace_virtio_blk_rw_complete(req, ret);
94 
95         if (req->qiov.nalloc != -1) {
96             /* If nalloc is != 1 req->qiov is a local copy of the original
97              * external iovec. It was allocated in submit_merged_requests
98              * to be able to merge requests. */
99             qemu_iovec_destroy(&req->qiov);
100         }
101 
102         if (ret) {
103             int p = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);
104             bool is_read = !(p & VIRTIO_BLK_T_OUT);
105             if (virtio_blk_handle_rw_error(req, -ret, is_read)) {
106                 continue;
107             }
108         }
109 
110         virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
111         block_acct_done(blk_get_stats(req->dev->blk), &req->acct);
112         virtio_blk_free_request(req);
113     }
114 }
115 
116 static void virtio_blk_flush_complete(void *opaque, int ret)
117 {
118     VirtIOBlockReq *req = opaque;
119 
120     if (ret) {
121         if (virtio_blk_handle_rw_error(req, -ret, 0)) {
122             return;
123         }
124     }
125 
126     virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
127     block_acct_done(blk_get_stats(req->dev->blk), &req->acct);
128     virtio_blk_free_request(req);
129 }
130 
131 #ifdef __linux__
132 
133 typedef struct {
134     VirtIOBlockReq *req;
135     struct sg_io_hdr hdr;
136 } VirtIOBlockIoctlReq;
137 
138 static void virtio_blk_ioctl_complete(void *opaque, int status)
139 {
140     VirtIOBlockIoctlReq *ioctl_req = opaque;
141     VirtIOBlockReq *req = ioctl_req->req;
142     VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
143     struct virtio_scsi_inhdr *scsi;
144     struct sg_io_hdr *hdr;
145 
146     scsi = (void *)req->elem.in_sg[req->elem.in_num - 2].iov_base;
147 
148     if (status) {
149         status = VIRTIO_BLK_S_UNSUPP;
150         virtio_stl_p(vdev, &scsi->errors, 255);
151         goto out;
152     }
153 
154     hdr = &ioctl_req->hdr;
155     /*
156      * From SCSI-Generic-HOWTO: "Some lower level drivers (e.g. ide-scsi)
157      * clear the masked_status field [hence status gets cleared too, see
158      * block/scsi_ioctl.c] even when a CHECK_CONDITION or COMMAND_TERMINATED
159      * status has occurred.  However they do set DRIVER_SENSE in driver_status
160      * field. Also a (sb_len_wr > 0) indicates there is a sense buffer.
161      */
162     if (hdr->status == 0 && hdr->sb_len_wr > 0) {
163         hdr->status = CHECK_CONDITION;
164     }
165 
166     virtio_stl_p(vdev, &scsi->errors,
167                  hdr->status | (hdr->msg_status << 8) |
168                  (hdr->host_status << 16) | (hdr->driver_status << 24));
169     virtio_stl_p(vdev, &scsi->residual, hdr->resid);
170     virtio_stl_p(vdev, &scsi->sense_len, hdr->sb_len_wr);
171     virtio_stl_p(vdev, &scsi->data_len, hdr->dxfer_len);
172 
173 out:
174     virtio_blk_req_complete(req, status);
175     virtio_blk_free_request(req);
176     g_free(ioctl_req);
177 }
178 
179 #endif
180 
181 static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s)
182 {
183     VirtIOBlockReq *req = virtio_blk_alloc_request(s);
184 
185     if (!virtqueue_pop(s->vq, &req->elem)) {
186         virtio_blk_free_request(req);
187         return NULL;
188     }
189 
190     return req;
191 }
192 
193 static int virtio_blk_handle_scsi_req(VirtIOBlockReq *req)
194 {
195     int status = VIRTIO_BLK_S_OK;
196     struct virtio_scsi_inhdr *scsi = NULL;
197     VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
198     VirtQueueElement *elem = &req->elem;
199     VirtIOBlock *blk = req->dev;
200 
201 #ifdef __linux__
202     int i;
203     VirtIOBlockIoctlReq *ioctl_req;
204     BlockAIOCB *acb;
205 #endif
206 
207     /*
208      * We require at least one output segment each for the virtio_blk_outhdr
209      * and the SCSI command block.
210      *
211      * We also at least require the virtio_blk_inhdr, the virtio_scsi_inhdr
212      * and the sense buffer pointer in the input segments.
213      */
214     if (elem->out_num < 2 || elem->in_num < 3) {
215         status = VIRTIO_BLK_S_IOERR;
216         goto fail;
217     }
218 
219     /*
220      * The scsi inhdr is placed in the second-to-last input segment, just
221      * before the regular inhdr.
222      */
223     scsi = (void *)elem->in_sg[elem->in_num - 2].iov_base;
224 
225     if (!blk->conf.scsi) {
226         status = VIRTIO_BLK_S_UNSUPP;
227         goto fail;
228     }
229 
230     /*
231      * No support for bidirection commands yet.
232      */
233     if (elem->out_num > 2 && elem->in_num > 3) {
234         status = VIRTIO_BLK_S_UNSUPP;
235         goto fail;
236     }
237 
238 #ifdef __linux__
239     ioctl_req = g_new0(VirtIOBlockIoctlReq, 1);
240     ioctl_req->req = req;
241     ioctl_req->hdr.interface_id = 'S';
242     ioctl_req->hdr.cmd_len = elem->out_sg[1].iov_len;
243     ioctl_req->hdr.cmdp = elem->out_sg[1].iov_base;
244     ioctl_req->hdr.dxfer_len = 0;
245 
246     if (elem->out_num > 2) {
247         /*
248          * If there are more than the minimally required 2 output segments
249          * there is write payload starting from the third iovec.
250          */
251         ioctl_req->hdr.dxfer_direction = SG_DXFER_TO_DEV;
252         ioctl_req->hdr.iovec_count = elem->out_num - 2;
253 
254         for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
255             ioctl_req->hdr.dxfer_len += elem->out_sg[i + 2].iov_len;
256         }
257 
258         ioctl_req->hdr.dxferp = elem->out_sg + 2;
259 
260     } else if (elem->in_num > 3) {
261         /*
262          * If we have more than 3 input segments the guest wants to actually
263          * read data.
264          */
265         ioctl_req->hdr.dxfer_direction = SG_DXFER_FROM_DEV;
266         ioctl_req->hdr.iovec_count = elem->in_num - 3;
267         for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
268             ioctl_req->hdr.dxfer_len += elem->in_sg[i].iov_len;
269         }
270 
271         ioctl_req->hdr.dxferp = elem->in_sg;
272     } else {
273         /*
274          * Some SCSI commands don't actually transfer any data.
275          */
276         ioctl_req->hdr.dxfer_direction = SG_DXFER_NONE;
277     }
278 
279     ioctl_req->hdr.sbp = elem->in_sg[elem->in_num - 3].iov_base;
280     ioctl_req->hdr.mx_sb_len = elem->in_sg[elem->in_num - 3].iov_len;
281 
282     acb = blk_aio_ioctl(blk->blk, SG_IO, &ioctl_req->hdr,
283                         virtio_blk_ioctl_complete, ioctl_req);
284     if (!acb) {
285         g_free(ioctl_req);
286         status = VIRTIO_BLK_S_UNSUPP;
287         goto fail;
288     }
289     return -EINPROGRESS;
290 #else
291     abort();
292 #endif
293 
294 fail:
295     /* Just put anything nonzero so that the ioctl fails in the guest.  */
296     if (scsi) {
297         virtio_stl_p(vdev, &scsi->errors, 255);
298     }
299     return status;
300 }
301 
302 static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
303 {
304     int status;
305 
306     status = virtio_blk_handle_scsi_req(req);
307     if (status != -EINPROGRESS) {
308         virtio_blk_req_complete(req, status);
309         virtio_blk_free_request(req);
310     }
311 }
312 
313 static inline void submit_requests(BlockBackend *blk, MultiReqBuffer *mrb,
314                                    int start, int num_reqs, int niov)
315 {
316     QEMUIOVector *qiov = &mrb->reqs[start]->qiov;
317     int64_t sector_num = mrb->reqs[start]->sector_num;
318     int nb_sectors = mrb->reqs[start]->qiov.size / BDRV_SECTOR_SIZE;
319     bool is_write = mrb->is_write;
320 
321     if (num_reqs > 1) {
322         int i;
323         struct iovec *tmp_iov = qiov->iov;
324         int tmp_niov = qiov->niov;
325 
326         /* mrb->reqs[start]->qiov was initialized from external so we can't
327          * modifiy it here. We need to initialize it locally and then add the
328          * external iovecs. */
329         qemu_iovec_init(qiov, niov);
330 
331         for (i = 0; i < tmp_niov; i++) {
332             qemu_iovec_add(qiov, tmp_iov[i].iov_base, tmp_iov[i].iov_len);
333         }
334 
335         for (i = start + 1; i < start + num_reqs; i++) {
336             qemu_iovec_concat(qiov, &mrb->reqs[i]->qiov, 0,
337                               mrb->reqs[i]->qiov.size);
338             mrb->reqs[i - 1]->mr_next = mrb->reqs[i];
339             nb_sectors += mrb->reqs[i]->qiov.size / BDRV_SECTOR_SIZE;
340         }
341         assert(nb_sectors == qiov->size / BDRV_SECTOR_SIZE);
342 
343         trace_virtio_blk_submit_multireq(mrb, start, num_reqs, sector_num,
344                                          nb_sectors, is_write);
345         block_acct_merge_done(blk_get_stats(blk),
346                               is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ,
347                               num_reqs - 1);
348     }
349 
350     if (is_write) {
351         blk_aio_writev(blk, sector_num, qiov, nb_sectors,
352                        virtio_blk_rw_complete, mrb->reqs[start]);
353     } else {
354         blk_aio_readv(blk, sector_num, qiov, nb_sectors,
355                       virtio_blk_rw_complete, mrb->reqs[start]);
356     }
357 }
358 
359 static int multireq_compare(const void *a, const void *b)
360 {
361     const VirtIOBlockReq *req1 = *(VirtIOBlockReq **)a,
362                          *req2 = *(VirtIOBlockReq **)b;
363 
364     /*
365      * Note that we can't simply subtract sector_num1 from sector_num2
366      * here as that could overflow the return value.
367      */
368     if (req1->sector_num > req2->sector_num) {
369         return 1;
370     } else if (req1->sector_num < req2->sector_num) {
371         return -1;
372     } else {
373         return 0;
374     }
375 }
376 
377 void virtio_blk_submit_multireq(BlockBackend *blk, MultiReqBuffer *mrb)
378 {
379     int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
380     int max_xfer_len = 0;
381     int64_t sector_num = 0;
382 
383     if (mrb->num_reqs == 1) {
384         submit_requests(blk, mrb, 0, 1, -1);
385         mrb->num_reqs = 0;
386         return;
387     }
388 
389     max_xfer_len = blk_get_max_transfer_length(mrb->reqs[0]->dev->blk);
390     max_xfer_len = MIN_NON_ZERO(max_xfer_len, BDRV_REQUEST_MAX_SECTORS);
391 
392     qsort(mrb->reqs, mrb->num_reqs, sizeof(*mrb->reqs),
393           &multireq_compare);
394 
395     for (i = 0; i < mrb->num_reqs; i++) {
396         VirtIOBlockReq *req = mrb->reqs[i];
397         if (num_reqs > 0) {
398             bool merge = true;
399 
400             /* merge would exceed maximum number of IOVs */
401             if (niov + req->qiov.niov > IOV_MAX) {
402                 merge = false;
403             }
404 
405             /* merge would exceed maximum transfer length of backend device */
406             if (req->qiov.size / BDRV_SECTOR_SIZE + nb_sectors > max_xfer_len) {
407                 merge = false;
408             }
409 
410             /* requests are not sequential */
411             if (sector_num + nb_sectors != req->sector_num) {
412                 merge = false;
413             }
414 
415             if (!merge) {
416                 submit_requests(blk, mrb, start, num_reqs, niov);
417                 num_reqs = 0;
418             }
419         }
420 
421         if (num_reqs == 0) {
422             sector_num = req->sector_num;
423             nb_sectors = niov = 0;
424             start = i;
425         }
426 
427         nb_sectors += req->qiov.size / BDRV_SECTOR_SIZE;
428         niov += req->qiov.niov;
429         num_reqs++;
430     }
431 
432     submit_requests(blk, mrb, start, num_reqs, niov);
433     mrb->num_reqs = 0;
434 }
435 
436 static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
437 {
438     block_acct_start(blk_get_stats(req->dev->blk), &req->acct, 0,
439                      BLOCK_ACCT_FLUSH);
440 
441     /*
442      * Make sure all outstanding writes are posted to the backing device.
443      */
444     if (mrb->is_write && mrb->num_reqs > 0) {
445         virtio_blk_submit_multireq(req->dev->blk, mrb);
446     }
447     blk_aio_flush(req->dev->blk, virtio_blk_flush_complete, req);
448 }
449 
450 static bool virtio_blk_sect_range_ok(VirtIOBlock *dev,
451                                      uint64_t sector, size_t size)
452 {
453     uint64_t nb_sectors = size >> BDRV_SECTOR_BITS;
454     uint64_t total_sectors;
455 
456     if (nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
457         return false;
458     }
459     if (sector & dev->sector_mask) {
460         return false;
461     }
462     if (size % dev->conf.conf.logical_block_size) {
463         return false;
464     }
465     blk_get_geometry(dev->blk, &total_sectors);
466     if (sector > total_sectors || nb_sectors > total_sectors - sector) {
467         return false;
468     }
469     return true;
470 }
471 
472 void virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
473 {
474     uint32_t type;
475     struct iovec *in_iov = req->elem.in_sg;
476     struct iovec *iov = req->elem.out_sg;
477     unsigned in_num = req->elem.in_num;
478     unsigned out_num = req->elem.out_num;
479 
480     if (req->elem.out_num < 1 || req->elem.in_num < 1) {
481         error_report("virtio-blk missing headers");
482         exit(1);
483     }
484 
485     if (unlikely(iov_to_buf(iov, out_num, 0, &req->out,
486                             sizeof(req->out)) != sizeof(req->out))) {
487         error_report("virtio-blk request outhdr too short");
488         exit(1);
489     }
490 
491     iov_discard_front(&iov, &out_num, sizeof(req->out));
492 
493     if (in_num < 1 ||
494         in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {
495         error_report("virtio-blk request inhdr too short");
496         exit(1);
497     }
498 
499     req->in = (void *)in_iov[in_num - 1].iov_base
500               + in_iov[in_num - 1].iov_len
501               - sizeof(struct virtio_blk_inhdr);
502     iov_discard_back(in_iov, &in_num, sizeof(struct virtio_blk_inhdr));
503 
504     type = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);
505 
506     /* VIRTIO_BLK_T_OUT defines the command direction. VIRTIO_BLK_T_BARRIER
507      * is an optional flag. Altough a guest should not send this flag if
508      * not negotiated we ignored it in the past. So keep ignoring it. */
509     switch (type & ~(VIRTIO_BLK_T_OUT | VIRTIO_BLK_T_BARRIER)) {
510     case VIRTIO_BLK_T_IN:
511     {
512         bool is_write = type & VIRTIO_BLK_T_OUT;
513         req->sector_num = virtio_ldq_p(VIRTIO_DEVICE(req->dev),
514                                        &req->out.sector);
515 
516         if (is_write) {
517             qemu_iovec_init_external(&req->qiov, iov, out_num);
518             trace_virtio_blk_handle_write(req, req->sector_num,
519                                           req->qiov.size / BDRV_SECTOR_SIZE);
520         } else {
521             qemu_iovec_init_external(&req->qiov, in_iov, in_num);
522             trace_virtio_blk_handle_read(req, req->sector_num,
523                                          req->qiov.size / BDRV_SECTOR_SIZE);
524         }
525 
526         if (!virtio_blk_sect_range_ok(req->dev, req->sector_num,
527                                       req->qiov.size)) {
528             virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
529             virtio_blk_free_request(req);
530             return;
531         }
532 
533         block_acct_start(blk_get_stats(req->dev->blk),
534                          &req->acct, req->qiov.size,
535                          is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
536 
537         /* merge would exceed maximum number of requests or IO direction
538          * changes */
539         if (mrb->num_reqs > 0 && (mrb->num_reqs == VIRTIO_BLK_MAX_MERGE_REQS ||
540                                   is_write != mrb->is_write ||
541                                   !req->dev->conf.request_merging)) {
542             virtio_blk_submit_multireq(req->dev->blk, mrb);
543         }
544 
545         assert(mrb->num_reqs < VIRTIO_BLK_MAX_MERGE_REQS);
546         mrb->reqs[mrb->num_reqs++] = req;
547         mrb->is_write = is_write;
548         break;
549     }
550     case VIRTIO_BLK_T_FLUSH:
551         virtio_blk_handle_flush(req, mrb);
552         break;
553     case VIRTIO_BLK_T_SCSI_CMD:
554         virtio_blk_handle_scsi(req);
555         break;
556     case VIRTIO_BLK_T_GET_ID:
557     {
558         VirtIOBlock *s = req->dev;
559 
560         /*
561          * NB: per existing s/n string convention the string is
562          * terminated by '\0' only when shorter than buffer.
563          */
564         const char *serial = s->conf.serial ? s->conf.serial : "";
565         size_t size = MIN(strlen(serial) + 1,
566                           MIN(iov_size(in_iov, in_num),
567                               VIRTIO_BLK_ID_BYTES));
568         iov_from_buf(in_iov, in_num, 0, serial, size);
569         virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
570         virtio_blk_free_request(req);
571         break;
572     }
573     default:
574         virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
575         virtio_blk_free_request(req);
576     }
577 }
578 
579 static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)
580 {
581     VirtIOBlock *s = VIRTIO_BLK(vdev);
582     VirtIOBlockReq *req;
583     MultiReqBuffer mrb = {};
584 
585     /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start
586      * dataplane here instead of waiting for .set_status().
587      */
588     if (s->dataplane) {
589         virtio_blk_data_plane_start(s->dataplane);
590         return;
591     }
592 
593     while ((req = virtio_blk_get_request(s))) {
594         virtio_blk_handle_request(req, &mrb);
595     }
596 
597     if (mrb.num_reqs) {
598         virtio_blk_submit_multireq(s->blk, &mrb);
599     }
600 }
601 
602 static void virtio_blk_dma_restart_bh(void *opaque)
603 {
604     VirtIOBlock *s = opaque;
605     VirtIOBlockReq *req = s->rq;
606     MultiReqBuffer mrb = {};
607 
608     qemu_bh_delete(s->bh);
609     s->bh = NULL;
610 
611     s->rq = NULL;
612 
613     while (req) {
614         VirtIOBlockReq *next = req->next;
615         virtio_blk_handle_request(req, &mrb);
616         req = next;
617     }
618 
619     if (mrb.num_reqs) {
620         virtio_blk_submit_multireq(s->blk, &mrb);
621     }
622 }
623 
624 static void virtio_blk_dma_restart_cb(void *opaque, int running,
625                                       RunState state)
626 {
627     VirtIOBlock *s = opaque;
628 
629     if (!running) {
630         return;
631     }
632 
633     if (!s->bh) {
634         s->bh = aio_bh_new(blk_get_aio_context(s->conf.conf.blk),
635                            virtio_blk_dma_restart_bh, s);
636         qemu_bh_schedule(s->bh);
637     }
638 }
639 
640 static void virtio_blk_reset(VirtIODevice *vdev)
641 {
642     VirtIOBlock *s = VIRTIO_BLK(vdev);
643 
644     if (s->dataplane) {
645         virtio_blk_data_plane_stop(s->dataplane);
646     }
647 
648     /*
649      * This should cancel pending requests, but can't do nicely until there
650      * are per-device request lists.
651      */
652     blk_drain_all();
653     blk_set_enable_write_cache(s->blk, s->original_wce);
654 }
655 
656 /* coalesce internal state, copy to pci i/o region 0
657  */
658 static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
659 {
660     VirtIOBlock *s = VIRTIO_BLK(vdev);
661     BlockConf *conf = &s->conf.conf;
662     struct virtio_blk_config blkcfg;
663     uint64_t capacity;
664     int blk_size = conf->logical_block_size;
665 
666     blk_get_geometry(s->blk, &capacity);
667     memset(&blkcfg, 0, sizeof(blkcfg));
668     virtio_stq_p(vdev, &blkcfg.capacity, capacity);
669     virtio_stl_p(vdev, &blkcfg.seg_max, 128 - 2);
670     virtio_stw_p(vdev, &blkcfg.geometry.cylinders, conf->cyls);
671     virtio_stl_p(vdev, &blkcfg.blk_size, blk_size);
672     virtio_stw_p(vdev, &blkcfg.min_io_size, conf->min_io_size / blk_size);
673     virtio_stw_p(vdev, &blkcfg.opt_io_size, conf->opt_io_size / blk_size);
674     blkcfg.geometry.heads = conf->heads;
675     /*
676      * We must ensure that the block device capacity is a multiple of
677      * the logical block size. If that is not the case, let's use
678      * sector_mask to adopt the geometry to have a correct picture.
679      * For those devices where the capacity is ok for the given geometry
680      * we don't touch the sector value of the geometry, since some devices
681      * (like s390 dasd) need a specific value. Here the capacity is already
682      * cyls*heads*secs*blk_size and the sector value is not block size
683      * divided by 512 - instead it is the amount of blk_size blocks
684      * per track (cylinder).
685      */
686     if (blk_getlength(s->blk) /  conf->heads / conf->secs % blk_size) {
687         blkcfg.geometry.sectors = conf->secs & ~s->sector_mask;
688     } else {
689         blkcfg.geometry.sectors = conf->secs;
690     }
691     blkcfg.size_max = 0;
692     blkcfg.physical_block_exp = get_physical_block_exp(conf);
693     blkcfg.alignment_offset = 0;
694     blkcfg.wce = blk_enable_write_cache(s->blk);
695     memcpy(config, &blkcfg, sizeof(struct virtio_blk_config));
696 }
697 
698 static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config)
699 {
700     VirtIOBlock *s = VIRTIO_BLK(vdev);
701     struct virtio_blk_config blkcfg;
702 
703     memcpy(&blkcfg, config, sizeof(blkcfg));
704 
705     aio_context_acquire(blk_get_aio_context(s->blk));
706     blk_set_enable_write_cache(s->blk, blkcfg.wce != 0);
707     aio_context_release(blk_get_aio_context(s->blk));
708 }
709 
710 static uint32_t virtio_blk_get_features(VirtIODevice *vdev, uint32_t features)
711 {
712     VirtIOBlock *s = VIRTIO_BLK(vdev);
713 
714     virtio_add_feature(&features, VIRTIO_BLK_F_SEG_MAX);
715     virtio_add_feature(&features, VIRTIO_BLK_F_GEOMETRY);
716     virtio_add_feature(&features, VIRTIO_BLK_F_TOPOLOGY);
717     virtio_add_feature(&features, VIRTIO_BLK_F_BLK_SIZE);
718     virtio_add_feature(&features, VIRTIO_BLK_F_SCSI);
719 
720     if (s->conf.config_wce) {
721         virtio_add_feature(&features, VIRTIO_BLK_F_CONFIG_WCE);
722     }
723     if (blk_enable_write_cache(s->blk)) {
724         virtio_add_feature(&features, VIRTIO_BLK_F_WCE);
725     }
726     if (blk_is_read_only(s->blk)) {
727         virtio_add_feature(&features, VIRTIO_BLK_F_RO);
728     }
729 
730     return features;
731 }
732 
733 static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)
734 {
735     VirtIOBlock *s = VIRTIO_BLK(vdev);
736 
737     if (s->dataplane && !(status & (VIRTIO_CONFIG_S_DRIVER |
738                                     VIRTIO_CONFIG_S_DRIVER_OK))) {
739         virtio_blk_data_plane_stop(s->dataplane);
740     }
741 
742     if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
743         return;
744     }
745 
746     /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send
747      * cache flushes.  Thus, the "auto writethrough" behavior is never
748      * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.
749      * Leaving it enabled would break the following sequence:
750      *
751      *     Guest started with "-drive cache=writethrough"
752      *     Guest sets status to 0
753      *     Guest sets DRIVER bit in status field
754      *     Guest reads host features (WCE=0, CONFIG_WCE=1)
755      *     Guest writes guest features (WCE=0, CONFIG_WCE=1)
756      *     Guest writes 1 to the WCE configuration field (writeback mode)
757      *     Guest sets DRIVER_OK bit in status field
758      *
759      * s->blk would erroneously be placed in writethrough mode.
760      */
761     if (!virtio_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE)) {
762         aio_context_acquire(blk_get_aio_context(s->blk));
763         blk_set_enable_write_cache(s->blk,
764                                    virtio_has_feature(vdev, VIRTIO_BLK_F_WCE));
765         aio_context_release(blk_get_aio_context(s->blk));
766     }
767 }
768 
769 static void virtio_blk_save(QEMUFile *f, void *opaque)
770 {
771     VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
772 
773     virtio_save(vdev, f);
774 }
775 
776 static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f)
777 {
778     VirtIOBlock *s = VIRTIO_BLK(vdev);
779     VirtIOBlockReq *req = s->rq;
780 
781     while (req) {
782         qemu_put_sbyte(f, 1);
783         qemu_put_buffer(f, (unsigned char *)&req->elem,
784                         sizeof(VirtQueueElement));
785         req = req->next;
786     }
787     qemu_put_sbyte(f, 0);
788 }
789 
790 static int virtio_blk_load(QEMUFile *f, void *opaque, int version_id)
791 {
792     VirtIOBlock *s = opaque;
793     VirtIODevice *vdev = VIRTIO_DEVICE(s);
794 
795     if (version_id != 2)
796         return -EINVAL;
797 
798     return virtio_load(vdev, f, version_id);
799 }
800 
801 static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f,
802                                   int version_id)
803 {
804     VirtIOBlock *s = VIRTIO_BLK(vdev);
805 
806     while (qemu_get_sbyte(f)) {
807         VirtIOBlockReq *req = virtio_blk_alloc_request(s);
808         qemu_get_buffer(f, (unsigned char *)&req->elem,
809                         sizeof(VirtQueueElement));
810         req->next = s->rq;
811         s->rq = req;
812 
813         virtqueue_map_sg(req->elem.in_sg, req->elem.in_addr,
814             req->elem.in_num, 1);
815         virtqueue_map_sg(req->elem.out_sg, req->elem.out_addr,
816             req->elem.out_num, 0);
817     }
818 
819     return 0;
820 }
821 
822 static void virtio_blk_resize(void *opaque)
823 {
824     VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
825 
826     virtio_notify_config(vdev);
827 }
828 
829 static const BlockDevOps virtio_block_ops = {
830     .resize_cb = virtio_blk_resize,
831 };
832 
833 /* Disable dataplane thread during live migration since it does not
834  * update the dirty memory bitmap yet.
835  */
836 static void virtio_blk_migration_state_changed(Notifier *notifier, void *data)
837 {
838     VirtIOBlock *s = container_of(notifier, VirtIOBlock,
839                                   migration_state_notifier);
840     MigrationState *mig = data;
841     Error *err = NULL;
842 
843     if (migration_in_setup(mig)) {
844         if (!s->dataplane) {
845             return;
846         }
847         virtio_blk_data_plane_destroy(s->dataplane);
848         s->dataplane = NULL;
849     } else if (migration_has_finished(mig) ||
850                migration_has_failed(mig)) {
851         if (s->dataplane) {
852             return;
853         }
854         blk_drain_all(); /* complete in-flight non-dataplane requests */
855         virtio_blk_data_plane_create(VIRTIO_DEVICE(s), &s->conf,
856                                      &s->dataplane, &err);
857         if (err != NULL) {
858             error_report_err(err);
859         }
860     }
861 }
862 
863 static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
864 {
865     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
866     VirtIOBlock *s = VIRTIO_BLK(dev);
867     VirtIOBlkConf *conf = &s->conf;
868     Error *err = NULL;
869     static int virtio_blk_id;
870 
871     if (!conf->conf.blk) {
872         error_setg(errp, "drive property not set");
873         return;
874     }
875     if (!blk_is_inserted(conf->conf.blk)) {
876         error_setg(errp, "Device needs media, but drive is empty");
877         return;
878     }
879 
880     blkconf_serial(&conf->conf, &conf->serial);
881     s->original_wce = blk_enable_write_cache(conf->conf.blk);
882     blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, &err);
883     if (err) {
884         error_propagate(errp, err);
885         return;
886     }
887     blkconf_blocksizes(&conf->conf);
888 
889     virtio_init(vdev, "virtio-blk", VIRTIO_ID_BLOCK,
890                 sizeof(struct virtio_blk_config));
891 
892     s->blk = conf->conf.blk;
893     s->rq = NULL;
894     s->sector_mask = (s->conf.conf.logical_block_size / BDRV_SECTOR_SIZE) - 1;
895 
896     s->vq = virtio_add_queue(vdev, 128, virtio_blk_handle_output);
897     s->complete_request = virtio_blk_complete_request;
898     virtio_blk_data_plane_create(vdev, conf, &s->dataplane, &err);
899     if (err != NULL) {
900         error_propagate(errp, err);
901         virtio_cleanup(vdev);
902         return;
903     }
904     s->migration_state_notifier.notify = virtio_blk_migration_state_changed;
905     add_migration_state_change_notifier(&s->migration_state_notifier);
906 
907     s->change = qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);
908     register_savevm(dev, "virtio-blk", virtio_blk_id++, 2,
909                     virtio_blk_save, virtio_blk_load, s);
910     blk_set_dev_ops(s->blk, &virtio_block_ops, s);
911     blk_set_guest_block_size(s->blk, s->conf.conf.logical_block_size);
912 
913     blk_iostatus_enable(s->blk);
914 }
915 
916 static void virtio_blk_device_unrealize(DeviceState *dev, Error **errp)
917 {
918     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
919     VirtIOBlock *s = VIRTIO_BLK(dev);
920 
921     remove_migration_state_change_notifier(&s->migration_state_notifier);
922     virtio_blk_data_plane_destroy(s->dataplane);
923     s->dataplane = NULL;
924     qemu_del_vm_change_state_handler(s->change);
925     unregister_savevm(dev, "virtio-blk", s);
926     blockdev_mark_auto_del(s->blk);
927     virtio_cleanup(vdev);
928 }
929 
930 static void virtio_blk_instance_init(Object *obj)
931 {
932     VirtIOBlock *s = VIRTIO_BLK(obj);
933 
934     object_property_add_link(obj, "iothread", TYPE_IOTHREAD,
935                              (Object **)&s->conf.iothread,
936                              qdev_prop_allow_set_link_before_realize,
937                              OBJ_PROP_LINK_UNREF_ON_RELEASE, NULL);
938     device_add_bootindex_property(obj, &s->conf.conf.bootindex,
939                                   "bootindex", "/disk@0,0",
940                                   DEVICE(obj), NULL);
941 }
942 
943 static Property virtio_blk_properties[] = {
944     DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf),
945     DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf),
946     DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial),
947     DEFINE_PROP_BIT("config-wce", VirtIOBlock, conf.config_wce, 0, true),
948 #ifdef __linux__
949     DEFINE_PROP_BIT("scsi", VirtIOBlock, conf.scsi, 0, true),
950 #endif
951     DEFINE_PROP_BIT("request-merging", VirtIOBlock, conf.request_merging, 0,
952                     true),
953     DEFINE_PROP_BIT("x-data-plane", VirtIOBlock, conf.data_plane, 0, false),
954     DEFINE_PROP_END_OF_LIST(),
955 };
956 
957 static void virtio_blk_class_init(ObjectClass *klass, void *data)
958 {
959     DeviceClass *dc = DEVICE_CLASS(klass);
960     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
961 
962     dc->props = virtio_blk_properties;
963     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
964     vdc->realize = virtio_blk_device_realize;
965     vdc->unrealize = virtio_blk_device_unrealize;
966     vdc->get_config = virtio_blk_update_config;
967     vdc->set_config = virtio_blk_set_config;
968     vdc->get_features = virtio_blk_get_features;
969     vdc->set_status = virtio_blk_set_status;
970     vdc->reset = virtio_blk_reset;
971     vdc->save = virtio_blk_save_device;
972     vdc->load = virtio_blk_load_device;
973 }
974 
975 static const TypeInfo virtio_device_info = {
976     .name = TYPE_VIRTIO_BLK,
977     .parent = TYPE_VIRTIO_DEVICE,
978     .instance_size = sizeof(VirtIOBlock),
979     .instance_init = virtio_blk_instance_init,
980     .class_init = virtio_blk_class_init,
981 };
982 
983 static void virtio_register_types(void)
984 {
985     type_register_static(&virtio_device_info);
986 }
987 
988 type_init(virtio_register_types)
989