xref: /openbmc/qemu/hw/block/virtio-blk.c (revision 87a45cfe)
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 #endif
205 
206     /*
207      * We require at least one output segment each for the virtio_blk_outhdr
208      * and the SCSI command block.
209      *
210      * We also at least require the virtio_blk_inhdr, the virtio_scsi_inhdr
211      * and the sense buffer pointer in the input segments.
212      */
213     if (elem->out_num < 2 || elem->in_num < 3) {
214         status = VIRTIO_BLK_S_IOERR;
215         goto fail;
216     }
217 
218     /*
219      * The scsi inhdr is placed in the second-to-last input segment, just
220      * before the regular inhdr.
221      */
222     scsi = (void *)elem->in_sg[elem->in_num - 2].iov_base;
223 
224     if (!blk->conf.scsi) {
225         status = VIRTIO_BLK_S_UNSUPP;
226         goto fail;
227     }
228 
229     /*
230      * No support for bidirection commands yet.
231      */
232     if (elem->out_num > 2 && elem->in_num > 3) {
233         status = VIRTIO_BLK_S_UNSUPP;
234         goto fail;
235     }
236 
237 #ifdef __linux__
238     ioctl_req = g_new0(VirtIOBlockIoctlReq, 1);
239     ioctl_req->req = req;
240     ioctl_req->hdr.interface_id = 'S';
241     ioctl_req->hdr.cmd_len = elem->out_sg[1].iov_len;
242     ioctl_req->hdr.cmdp = elem->out_sg[1].iov_base;
243     ioctl_req->hdr.dxfer_len = 0;
244 
245     if (elem->out_num > 2) {
246         /*
247          * If there are more than the minimally required 2 output segments
248          * there is write payload starting from the third iovec.
249          */
250         ioctl_req->hdr.dxfer_direction = SG_DXFER_TO_DEV;
251         ioctl_req->hdr.iovec_count = elem->out_num - 2;
252 
253         for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
254             ioctl_req->hdr.dxfer_len += elem->out_sg[i + 2].iov_len;
255         }
256 
257         ioctl_req->hdr.dxferp = elem->out_sg + 2;
258 
259     } else if (elem->in_num > 3) {
260         /*
261          * If we have more than 3 input segments the guest wants to actually
262          * read data.
263          */
264         ioctl_req->hdr.dxfer_direction = SG_DXFER_FROM_DEV;
265         ioctl_req->hdr.iovec_count = elem->in_num - 3;
266         for (i = 0; i < ioctl_req->hdr.iovec_count; i++) {
267             ioctl_req->hdr.dxfer_len += elem->in_sg[i].iov_len;
268         }
269 
270         ioctl_req->hdr.dxferp = elem->in_sg;
271     } else {
272         /*
273          * Some SCSI commands don't actually transfer any data.
274          */
275         ioctl_req->hdr.dxfer_direction = SG_DXFER_NONE;
276     }
277 
278     ioctl_req->hdr.sbp = elem->in_sg[elem->in_num - 3].iov_base;
279     ioctl_req->hdr.mx_sb_len = elem->in_sg[elem->in_num - 3].iov_len;
280 
281     blk_aio_ioctl(blk->blk, SG_IO, &ioctl_req->hdr,
282                   virtio_blk_ioctl_complete, ioctl_req);
283     return -EINPROGRESS;
284 #else
285     abort();
286 #endif
287 
288 fail:
289     /* Just put anything nonzero so that the ioctl fails in the guest.  */
290     if (scsi) {
291         virtio_stl_p(vdev, &scsi->errors, 255);
292     }
293     return status;
294 }
295 
296 static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
297 {
298     int status;
299 
300     status = virtio_blk_handle_scsi_req(req);
301     if (status != -EINPROGRESS) {
302         virtio_blk_req_complete(req, status);
303         virtio_blk_free_request(req);
304     }
305 }
306 
307 static inline void submit_requests(BlockBackend *blk, MultiReqBuffer *mrb,
308                                    int start, int num_reqs, int niov)
309 {
310     QEMUIOVector *qiov = &mrb->reqs[start]->qiov;
311     int64_t sector_num = mrb->reqs[start]->sector_num;
312     int nb_sectors = mrb->reqs[start]->qiov.size / BDRV_SECTOR_SIZE;
313     bool is_write = mrb->is_write;
314 
315     if (num_reqs > 1) {
316         int i;
317         struct iovec *tmp_iov = qiov->iov;
318         int tmp_niov = qiov->niov;
319 
320         /* mrb->reqs[start]->qiov was initialized from external so we can't
321          * modifiy it here. We need to initialize it locally and then add the
322          * external iovecs. */
323         qemu_iovec_init(qiov, niov);
324 
325         for (i = 0; i < tmp_niov; i++) {
326             qemu_iovec_add(qiov, tmp_iov[i].iov_base, tmp_iov[i].iov_len);
327         }
328 
329         for (i = start + 1; i < start + num_reqs; i++) {
330             qemu_iovec_concat(qiov, &mrb->reqs[i]->qiov, 0,
331                               mrb->reqs[i]->qiov.size);
332             mrb->reqs[i - 1]->mr_next = mrb->reqs[i];
333             nb_sectors += mrb->reqs[i]->qiov.size / BDRV_SECTOR_SIZE;
334         }
335         assert(nb_sectors == qiov->size / BDRV_SECTOR_SIZE);
336 
337         trace_virtio_blk_submit_multireq(mrb, start, num_reqs, sector_num,
338                                          nb_sectors, is_write);
339         block_acct_merge_done(blk_get_stats(blk),
340                               is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ,
341                               num_reqs - 1);
342     }
343 
344     if (is_write) {
345         blk_aio_writev(blk, sector_num, qiov, nb_sectors,
346                        virtio_blk_rw_complete, mrb->reqs[start]);
347     } else {
348         blk_aio_readv(blk, sector_num, qiov, nb_sectors,
349                       virtio_blk_rw_complete, mrb->reqs[start]);
350     }
351 }
352 
353 static int multireq_compare(const void *a, const void *b)
354 {
355     const VirtIOBlockReq *req1 = *(VirtIOBlockReq **)a,
356                          *req2 = *(VirtIOBlockReq **)b;
357 
358     /*
359      * Note that we can't simply subtract sector_num1 from sector_num2
360      * here as that could overflow the return value.
361      */
362     if (req1->sector_num > req2->sector_num) {
363         return 1;
364     } else if (req1->sector_num < req2->sector_num) {
365         return -1;
366     } else {
367         return 0;
368     }
369 }
370 
371 void virtio_blk_submit_multireq(BlockBackend *blk, MultiReqBuffer *mrb)
372 {
373     int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
374     int max_xfer_len = 0;
375     int64_t sector_num = 0;
376 
377     if (mrb->num_reqs == 1) {
378         submit_requests(blk, mrb, 0, 1, -1);
379         mrb->num_reqs = 0;
380         return;
381     }
382 
383     max_xfer_len = blk_get_max_transfer_length(mrb->reqs[0]->dev->blk);
384     max_xfer_len = MIN_NON_ZERO(max_xfer_len, BDRV_REQUEST_MAX_SECTORS);
385 
386     qsort(mrb->reqs, mrb->num_reqs, sizeof(*mrb->reqs),
387           &multireq_compare);
388 
389     for (i = 0; i < mrb->num_reqs; i++) {
390         VirtIOBlockReq *req = mrb->reqs[i];
391         if (num_reqs > 0) {
392             bool merge = true;
393 
394             /* merge would exceed maximum number of IOVs */
395             if (niov + req->qiov.niov > IOV_MAX) {
396                 merge = false;
397             }
398 
399             /* merge would exceed maximum transfer length of backend device */
400             if (req->qiov.size / BDRV_SECTOR_SIZE + nb_sectors > max_xfer_len) {
401                 merge = false;
402             }
403 
404             /* requests are not sequential */
405             if (sector_num + nb_sectors != req->sector_num) {
406                 merge = false;
407             }
408 
409             if (!merge) {
410                 submit_requests(blk, mrb, start, num_reqs, niov);
411                 num_reqs = 0;
412             }
413         }
414 
415         if (num_reqs == 0) {
416             sector_num = req->sector_num;
417             nb_sectors = niov = 0;
418             start = i;
419         }
420 
421         nb_sectors += req->qiov.size / BDRV_SECTOR_SIZE;
422         niov += req->qiov.niov;
423         num_reqs++;
424     }
425 
426     submit_requests(blk, mrb, start, num_reqs, niov);
427     mrb->num_reqs = 0;
428 }
429 
430 static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
431 {
432     block_acct_start(blk_get_stats(req->dev->blk), &req->acct, 0,
433                      BLOCK_ACCT_FLUSH);
434 
435     /*
436      * Make sure all outstanding writes are posted to the backing device.
437      */
438     if (mrb->is_write && mrb->num_reqs > 0) {
439         virtio_blk_submit_multireq(req->dev->blk, mrb);
440     }
441     blk_aio_flush(req->dev->blk, virtio_blk_flush_complete, req);
442 }
443 
444 static bool virtio_blk_sect_range_ok(VirtIOBlock *dev,
445                                      uint64_t sector, size_t size)
446 {
447     uint64_t nb_sectors = size >> BDRV_SECTOR_BITS;
448     uint64_t total_sectors;
449 
450     if (nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
451         return false;
452     }
453     if (sector & dev->sector_mask) {
454         return false;
455     }
456     if (size % dev->conf.conf.logical_block_size) {
457         return false;
458     }
459     blk_get_geometry(dev->blk, &total_sectors);
460     if (sector > total_sectors || nb_sectors > total_sectors - sector) {
461         return false;
462     }
463     return true;
464 }
465 
466 void virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
467 {
468     uint32_t type;
469     struct iovec *in_iov = req->elem.in_sg;
470     struct iovec *iov = req->elem.out_sg;
471     unsigned in_num = req->elem.in_num;
472     unsigned out_num = req->elem.out_num;
473 
474     if (req->elem.out_num < 1 || req->elem.in_num < 1) {
475         error_report("virtio-blk missing headers");
476         exit(1);
477     }
478 
479     if (unlikely(iov_to_buf(iov, out_num, 0, &req->out,
480                             sizeof(req->out)) != sizeof(req->out))) {
481         error_report("virtio-blk request outhdr too short");
482         exit(1);
483     }
484 
485     iov_discard_front(&iov, &out_num, sizeof(req->out));
486 
487     if (in_num < 1 ||
488         in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {
489         error_report("virtio-blk request inhdr too short");
490         exit(1);
491     }
492 
493     req->in = (void *)in_iov[in_num - 1].iov_base
494               + in_iov[in_num - 1].iov_len
495               - sizeof(struct virtio_blk_inhdr);
496     iov_discard_back(in_iov, &in_num, sizeof(struct virtio_blk_inhdr));
497 
498     type = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);
499 
500     /* VIRTIO_BLK_T_OUT defines the command direction. VIRTIO_BLK_T_BARRIER
501      * is an optional flag. Altough a guest should not send this flag if
502      * not negotiated we ignored it in the past. So keep ignoring it. */
503     switch (type & ~(VIRTIO_BLK_T_OUT | VIRTIO_BLK_T_BARRIER)) {
504     case VIRTIO_BLK_T_IN:
505     {
506         bool is_write = type & VIRTIO_BLK_T_OUT;
507         req->sector_num = virtio_ldq_p(VIRTIO_DEVICE(req->dev),
508                                        &req->out.sector);
509 
510         if (is_write) {
511             qemu_iovec_init_external(&req->qiov, iov, out_num);
512             trace_virtio_blk_handle_write(req, req->sector_num,
513                                           req->qiov.size / BDRV_SECTOR_SIZE);
514         } else {
515             qemu_iovec_init_external(&req->qiov, in_iov, in_num);
516             trace_virtio_blk_handle_read(req, req->sector_num,
517                                          req->qiov.size / BDRV_SECTOR_SIZE);
518         }
519 
520         if (!virtio_blk_sect_range_ok(req->dev, req->sector_num,
521                                       req->qiov.size)) {
522             virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
523             virtio_blk_free_request(req);
524             return;
525         }
526 
527         block_acct_start(blk_get_stats(req->dev->blk),
528                          &req->acct, req->qiov.size,
529                          is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
530 
531         /* merge would exceed maximum number of requests or IO direction
532          * changes */
533         if (mrb->num_reqs > 0 && (mrb->num_reqs == VIRTIO_BLK_MAX_MERGE_REQS ||
534                                   is_write != mrb->is_write ||
535                                   !req->dev->conf.request_merging)) {
536             virtio_blk_submit_multireq(req->dev->blk, mrb);
537         }
538 
539         assert(mrb->num_reqs < VIRTIO_BLK_MAX_MERGE_REQS);
540         mrb->reqs[mrb->num_reqs++] = req;
541         mrb->is_write = is_write;
542         break;
543     }
544     case VIRTIO_BLK_T_FLUSH:
545         virtio_blk_handle_flush(req, mrb);
546         break;
547     case VIRTIO_BLK_T_SCSI_CMD:
548         virtio_blk_handle_scsi(req);
549         break;
550     case VIRTIO_BLK_T_GET_ID:
551     {
552         VirtIOBlock *s = req->dev;
553 
554         /*
555          * NB: per existing s/n string convention the string is
556          * terminated by '\0' only when shorter than buffer.
557          */
558         const char *serial = s->conf.serial ? s->conf.serial : "";
559         size_t size = MIN(strlen(serial) + 1,
560                           MIN(iov_size(in_iov, in_num),
561                               VIRTIO_BLK_ID_BYTES));
562         iov_from_buf(in_iov, in_num, 0, serial, size);
563         virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
564         virtio_blk_free_request(req);
565         break;
566     }
567     default:
568         virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
569         virtio_blk_free_request(req);
570     }
571 }
572 
573 static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)
574 {
575     VirtIOBlock *s = VIRTIO_BLK(vdev);
576     VirtIOBlockReq *req;
577     MultiReqBuffer mrb = {};
578 
579     /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start
580      * dataplane here instead of waiting for .set_status().
581      */
582     if (s->dataplane) {
583         virtio_blk_data_plane_start(s->dataplane);
584         return;
585     }
586 
587     while ((req = virtio_blk_get_request(s))) {
588         virtio_blk_handle_request(req, &mrb);
589     }
590 
591     if (mrb.num_reqs) {
592         virtio_blk_submit_multireq(s->blk, &mrb);
593     }
594 
595     /*
596      * FIXME: Want to check for completions before returning to guest mode,
597      * so cached reads and writes are reported as quickly as possible. But
598      * that should be done in the generic block layer.
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.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.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.sectors = conf->secs & ~s->sector_mask;
688     } else {
689         blkcfg.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     features |= (1 << VIRTIO_BLK_F_SEG_MAX);
715     features |= (1 << VIRTIO_BLK_F_GEOMETRY);
716     features |= (1 << VIRTIO_BLK_F_TOPOLOGY);
717     features |= (1 << VIRTIO_BLK_F_BLK_SIZE);
718     features |= (1 << VIRTIO_BLK_F_SCSI);
719 
720     if (s->conf.config_wce) {
721         features |= (1 << VIRTIO_BLK_F_CONFIG_WCE);
722     }
723     if (blk_enable_write_cache(s->blk)) {
724         features |= (1 << VIRTIO_BLK_F_WCE);
725     }
726     if (blk_is_read_only(s->blk)) {
727         features |= 1 << 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     uint32_t features;
737 
738     if (s->dataplane && !(status & (VIRTIO_CONFIG_S_DRIVER |
739                                     VIRTIO_CONFIG_S_DRIVER_OK))) {
740         virtio_blk_data_plane_stop(s->dataplane);
741     }
742 
743     if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
744         return;
745     }
746 
747     features = vdev->guest_features;
748 
749     /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send
750      * cache flushes.  Thus, the "auto writethrough" behavior is never
751      * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.
752      * Leaving it enabled would break the following sequence:
753      *
754      *     Guest started with "-drive cache=writethrough"
755      *     Guest sets status to 0
756      *     Guest sets DRIVER bit in status field
757      *     Guest reads host features (WCE=0, CONFIG_WCE=1)
758      *     Guest writes guest features (WCE=0, CONFIG_WCE=1)
759      *     Guest writes 1 to the WCE configuration field (writeback mode)
760      *     Guest sets DRIVER_OK bit in status field
761      *
762      * s->blk would erroneously be placed in writethrough mode.
763      */
764     if (!(features & (1 << VIRTIO_BLK_F_CONFIG_WCE))) {
765         aio_context_acquire(blk_get_aio_context(s->blk));
766         blk_set_enable_write_cache(s->blk,
767                                    !!(features & (1 << VIRTIO_BLK_F_WCE)));
768         aio_context_release(blk_get_aio_context(s->blk));
769     }
770 }
771 
772 static void virtio_blk_save(QEMUFile *f, void *opaque)
773 {
774     VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
775 
776     virtio_save(vdev, f);
777 }
778 
779 static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f)
780 {
781     VirtIOBlock *s = VIRTIO_BLK(vdev);
782     VirtIOBlockReq *req = s->rq;
783 
784     while (req) {
785         qemu_put_sbyte(f, 1);
786         qemu_put_buffer(f, (unsigned char *)&req->elem,
787                         sizeof(VirtQueueElement));
788         req = req->next;
789     }
790     qemu_put_sbyte(f, 0);
791 }
792 
793 static int virtio_blk_load(QEMUFile *f, void *opaque, int version_id)
794 {
795     VirtIOBlock *s = opaque;
796     VirtIODevice *vdev = VIRTIO_DEVICE(s);
797 
798     if (version_id != 2)
799         return -EINVAL;
800 
801     return virtio_load(vdev, f, version_id);
802 }
803 
804 static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f,
805                                   int version_id)
806 {
807     VirtIOBlock *s = VIRTIO_BLK(vdev);
808 
809     while (qemu_get_sbyte(f)) {
810         VirtIOBlockReq *req = virtio_blk_alloc_request(s);
811         qemu_get_buffer(f, (unsigned char *)&req->elem,
812                         sizeof(VirtQueueElement));
813         req->next = s->rq;
814         s->rq = req;
815 
816         virtqueue_map_sg(req->elem.in_sg, req->elem.in_addr,
817             req->elem.in_num, 1);
818         virtqueue_map_sg(req->elem.out_sg, req->elem.out_addr,
819             req->elem.out_num, 0);
820     }
821 
822     return 0;
823 }
824 
825 static void virtio_blk_resize(void *opaque)
826 {
827     VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
828 
829     virtio_notify_config(vdev);
830 }
831 
832 static const BlockDevOps virtio_block_ops = {
833     .resize_cb = virtio_blk_resize,
834 };
835 
836 /* Disable dataplane thread during live migration since it does not
837  * update the dirty memory bitmap yet.
838  */
839 static void virtio_blk_migration_state_changed(Notifier *notifier, void *data)
840 {
841     VirtIOBlock *s = container_of(notifier, VirtIOBlock,
842                                   migration_state_notifier);
843     MigrationState *mig = data;
844     Error *err = NULL;
845 
846     if (migration_in_setup(mig)) {
847         if (!s->dataplane) {
848             return;
849         }
850         virtio_blk_data_plane_destroy(s->dataplane);
851         s->dataplane = NULL;
852     } else if (migration_has_finished(mig) ||
853                migration_has_failed(mig)) {
854         if (s->dataplane) {
855             return;
856         }
857         blk_drain_all(); /* complete in-flight non-dataplane requests */
858         virtio_blk_data_plane_create(VIRTIO_DEVICE(s), &s->conf,
859                                      &s->dataplane, &err);
860         if (err != NULL) {
861             error_report_err(err);
862         }
863     }
864 }
865 
866 static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
867 {
868     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
869     VirtIOBlock *s = VIRTIO_BLK(dev);
870     VirtIOBlkConf *conf = &s->conf;
871     Error *err = NULL;
872     static int virtio_blk_id;
873 
874     if (!conf->conf.blk) {
875         error_setg(errp, "drive property not set");
876         return;
877     }
878     if (!blk_is_inserted(conf->conf.blk)) {
879         error_setg(errp, "Device needs media, but drive is empty");
880         return;
881     }
882 
883     blkconf_serial(&conf->conf, &conf->serial);
884     s->original_wce = blk_enable_write_cache(conf->conf.blk);
885     blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, &err);
886     if (err) {
887         error_propagate(errp, err);
888         return;
889     }
890 
891     virtio_init(vdev, "virtio-blk", VIRTIO_ID_BLOCK,
892                 sizeof(struct virtio_blk_config));
893 
894     s->blk = conf->conf.blk;
895     s->rq = NULL;
896     s->sector_mask = (s->conf.conf.logical_block_size / BDRV_SECTOR_SIZE) - 1;
897 
898     s->vq = virtio_add_queue(vdev, 128, virtio_blk_handle_output);
899     s->complete_request = virtio_blk_complete_request;
900     virtio_blk_data_plane_create(vdev, conf, &s->dataplane, &err);
901     if (err != NULL) {
902         error_propagate(errp, err);
903         virtio_cleanup(vdev);
904         return;
905     }
906     s->migration_state_notifier.notify = virtio_blk_migration_state_changed;
907     add_migration_state_change_notifier(&s->migration_state_notifier);
908 
909     s->change = qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);
910     register_savevm(dev, "virtio-blk", virtio_blk_id++, 2,
911                     virtio_blk_save, virtio_blk_load, s);
912     blk_set_dev_ops(s->blk, &virtio_block_ops, s);
913     blk_set_guest_block_size(s->blk, s->conf.conf.logical_block_size);
914 
915     blk_iostatus_enable(s->blk);
916 }
917 
918 static void virtio_blk_device_unrealize(DeviceState *dev, Error **errp)
919 {
920     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
921     VirtIOBlock *s = VIRTIO_BLK(dev);
922 
923     remove_migration_state_change_notifier(&s->migration_state_notifier);
924     virtio_blk_data_plane_destroy(s->dataplane);
925     s->dataplane = NULL;
926     qemu_del_vm_change_state_handler(s->change);
927     unregister_savevm(dev, "virtio-blk", s);
928     blockdev_mark_auto_del(s->blk);
929     virtio_cleanup(vdev);
930 }
931 
932 static void virtio_blk_instance_init(Object *obj)
933 {
934     VirtIOBlock *s = VIRTIO_BLK(obj);
935 
936     object_property_add_link(obj, "iothread", TYPE_IOTHREAD,
937                              (Object **)&s->conf.iothread,
938                              qdev_prop_allow_set_link_before_realize,
939                              OBJ_PROP_LINK_UNREF_ON_RELEASE, NULL);
940     device_add_bootindex_property(obj, &s->conf.conf.bootindex,
941                                   "bootindex", "/disk@0,0",
942                                   DEVICE(obj), NULL);
943 }
944 
945 static Property virtio_blk_properties[] = {
946     DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf),
947     DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf),
948     DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial),
949     DEFINE_PROP_BIT("config-wce", VirtIOBlock, conf.config_wce, 0, true),
950 #ifdef __linux__
951     DEFINE_PROP_BIT("scsi", VirtIOBlock, conf.scsi, 0, true),
952 #endif
953     DEFINE_PROP_BIT("request-merging", VirtIOBlock, conf.request_merging, 0,
954                     true),
955     DEFINE_PROP_BIT("x-data-plane", VirtIOBlock, conf.data_plane, 0, false),
956     DEFINE_PROP_END_OF_LIST(),
957 };
958 
959 static void virtio_blk_class_init(ObjectClass *klass, void *data)
960 {
961     DeviceClass *dc = DEVICE_CLASS(klass);
962     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
963 
964     dc->props = virtio_blk_properties;
965     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
966     vdc->realize = virtio_blk_device_realize;
967     vdc->unrealize = virtio_blk_device_unrealize;
968     vdc->get_config = virtio_blk_update_config;
969     vdc->set_config = virtio_blk_set_config;
970     vdc->get_features = virtio_blk_get_features;
971     vdc->set_status = virtio_blk_set_status;
972     vdc->reset = virtio_blk_reset;
973     vdc->save = virtio_blk_save_device;
974     vdc->load = virtio_blk_load_device;
975 }
976 
977 static const TypeInfo virtio_device_info = {
978     .name = TYPE_VIRTIO_BLK,
979     .parent = TYPE_VIRTIO_DEVICE,
980     .instance_size = sizeof(VirtIOBlock),
981     .instance_init = virtio_blk_instance_init,
982     .class_init = virtio_blk_class_init,
983 };
984 
985 static void virtio_register_types(void)
986 {
987     type_register_static(&virtio_device_info);
988 }
989 
990 type_init(virtio_register_types)
991