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