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