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