master
c 1,961 lines 63.1 KB
Raw
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 "qemu/defer-call.h"
16 #include "qapi/error.h"
17 #include "qemu/iov.h"
18 #include "qemu/module.h"
19 #include "qemu/error-report.h"
20 #include "qemu/main-loop.h"
21 #include "block/block_int.h"
22 #include "trace.h"
23 #include "hw/block/block.h"
24 #include "hw/core/qdev-properties.h"
25 #include "system/blockdev.h"
26 #include "system/block-ram-registrar.h"
27 #include "system/system.h"
28 #include "system/runstate.h"
29 #include "hw/virtio/virtio-blk.h"
30 #include "scsi/constants.h"
31 #ifdef __linux__
32 # include <scsi/sg.h>
33 #endif
34 #include "hw/virtio/virtio-bus.h"
35 #include "migration/qemu-file-types.h"
36 #include "hw/virtio/iothread-vq-mapping.h"
37 #include "hw/virtio/virtio-access.h"
38 #include "hw/virtio/virtio-blk-common.h"
39 #include "qemu/coroutine.h"
40
41 /* Internal buffer size limit for zone report */
42 #define VIRTIO_BLK_MAX_ZONES_PER_BATCH 4096
43
44 static void virtio_blk_ioeventfd_attach(VirtIOBlock *s);
45
46 static void virtio_blk_init_request(VirtIOBlock *s, VirtQueue *vq,
47 VirtIOBlockReq *req)
48 {
49 req->dev = s;
50 req->vq = vq;
51 req->qiov.size = 0;
52 req->in_len = 0;
53 req->next = NULL;
54 req->mr_next = NULL;
55 }
56
57 void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
58 {
59 VirtIOBlock *s = req->dev;
60 VirtIODevice *vdev = VIRTIO_DEVICE(s);
61
62 trace_virtio_blk_req_complete(vdev, req, status);
63
64 stb_p(&req->in->status, status);
65 iov_discard_undo(&req->inhdr_undo);
66 iov_discard_undo(&req->outhdr_undo);
67 virtqueue_push(req->vq, &req->elem, req->in_len);
68 virtio_notify(vdev, req->vq);
69 }
70
71 static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
72 bool is_read, bool acct_failed)
73 {
74 VirtIOBlock *s = req->dev;
75 BlockErrorAction action = blk_get_error_action(s->blk, is_read, error);
76
77 if (action == BLOCK_ERROR_ACTION_STOP) {
78 /* Break the link as the next request is going to be parsed from the
79 * ring again. Otherwise we may end up doing a double completion! */
80 req->mr_next = NULL;
81
82 WITH_QEMU_LOCK_GUARD(&s->rq_lock) {
83 req->next = s->rq;
84 s->rq = req;
85 }
86 } else if (action == BLOCK_ERROR_ACTION_REPORT) {
87 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
88 if (acct_failed) {
89 block_acct_failed(blk_get_stats(s->blk), &req->acct);
90 }
91 g_free(req);
92 }
93
94 blk_error_action(s->blk, action, is_read, error);
95 return action != BLOCK_ERROR_ACTION_IGNORE;
96 }
97
98 static void virtio_blk_rw_complete(void *opaque, int ret)
99 {
100 VirtIOBlockReq *next = opaque;
101 VirtIOBlock *s = next->dev;
102 VirtIODevice *vdev = VIRTIO_DEVICE(s);
103
104 while (next) {
105 VirtIOBlockReq *req = next;
106 next = req->mr_next;
107 trace_virtio_blk_rw_complete(vdev, req, ret);
108
109 if (req->qiov.nalloc != -1) {
110 /* If nalloc is != -1 req->qiov is a local copy of the original
111 * external iovec. It was allocated in submit_requests to be
112 * able to merge requests. */
113 qemu_iovec_destroy(&req->qiov);
114 }
115
116 if (ret) {
117 int p = virtio_ldl_p(VIRTIO_DEVICE(s), &req->out.type);
118 bool is_read = !(p & VIRTIO_BLK_T_OUT);
119 /* Note that memory may be dirtied on read failure. If the
120 * virtio request is not completed here, as is the case for
121 * BLOCK_ERROR_ACTION_STOP, the memory may not be copied
122 * correctly during live migration. While this is ugly,
123 * it is acceptable because the device is free to write to
124 * the memory until the request is completed (which will
125 * happen on the other side of the migration).
126 */
127 if (virtio_blk_handle_rw_error(req, -ret, is_read, true)) {
128 continue;
129 }
130 }
131
132 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
133 block_acct_done(blk_get_stats(s->blk), &req->acct);
134 g_free(req);
135 }
136 }
137
138 static void virtio_blk_flush_complete(void *opaque, int ret)
139 {
140 VirtIOBlockReq *req = opaque;
141 VirtIOBlock *s = req->dev;
142
143 if (ret && virtio_blk_handle_rw_error(req, -ret, 0, true)) {
144 return;
145 }
146
147 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
148 block_acct_done(blk_get_stats(s->blk), &req->acct);
149 g_free(req);
150 }
151
152 static void virtio_blk_discard_write_zeroes_complete(void *opaque, int ret)
153 {
154 VirtIOBlockReq *req = opaque;
155 VirtIOBlock *s = req->dev;
156 bool is_write_zeroes = (virtio_ldl_p(VIRTIO_DEVICE(s), &req->out.type) &
157 ~VIRTIO_BLK_T_BARRIER) == VIRTIO_BLK_T_WRITE_ZEROES;
158
159 if (ret && virtio_blk_handle_rw_error(req, -ret, false, is_write_zeroes)) {
160 return;
161 }
162
163 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
164 if (is_write_zeroes) {
165 block_acct_done(blk_get_stats(s->blk), &req->acct);
166 }
167 g_free(req);
168 }
169
170 static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s, VirtQueue *vq)
171 {
172 VirtIOBlockReq *req = virtqueue_pop(vq, sizeof(VirtIOBlockReq));
173
174 if (req) {
175 virtio_blk_init_request(s, vq, req);
176 }
177 return req;
178 }
179
180 static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
181 {
182 int status;
183 struct virtio_scsi_inhdr *scsi;
184 VirtIOBlock *blk = req->dev;
185 VirtIODevice *vdev = VIRTIO_DEVICE(blk);
186 VirtQueueElement *elem = &req->elem;
187
188 /*
189 * We require at least one output segment each for the virtio_blk_outhdr
190 * and the SCSI command block.
191 *
192 * We also at least require the virtio_blk_inhdr, the virtio_scsi_inhdr
193 * and the sense buffer pointer in the input segments.
194 */
195 if (elem->out_num < 2 || elem->in_num < 3) {
196 status = VIRTIO_BLK_S_IOERR;
197 goto fail;
198 }
199
200 /*
201 * The scsi inhdr is placed in the second-to-last input segment, just
202 * before the regular inhdr. VIRTIO implementations normally do not rely on
203 * the precise message framing, but legacy implementations did and so we do
204 * too for the legacy virtio-blk SCSI request type.
205 *
206 * Just put anything nonzero so that the ioctl fails in the guest.
207 */
208 if (elem->in_sg[elem->in_num - 2].iov_len != sizeof(*scsi)) {
209 status = VIRTIO_BLK_S_IOERR;
210 goto fail;
211 }
212 scsi = (void *)elem->in_sg[elem->in_num - 2].iov_base;
213 virtio_stl_p(vdev, &scsi->errors, 255);
214 status = VIRTIO_BLK_S_UNSUPP;
215
216 fail:
217 virtio_blk_req_complete(req, status);
218 g_free(req);
219 }
220
221 static inline void submit_requests(VirtIOBlock *s, MultiReqBuffer *mrb,
222 int start, int num_reqs, int niov)
223 {
224 BlockBackend *blk = s->blk;
225 QEMUIOVector *qiov = &mrb->reqs[start]->qiov;
226 int64_t sector_num = mrb->reqs[start]->sector_num;
227 bool is_write = mrb->is_write;
228 BdrvRequestFlags flags = 0;
229
230 if (num_reqs > 1) {
231 int i;
232 struct iovec *tmp_iov = qiov->iov;
233 int tmp_niov = qiov->niov;
234
235 /* mrb->reqs[start]->qiov was initialized from external so we can't
236 * modify it here. We need to initialize it locally and then add the
237 * external iovecs. */
238 qemu_iovec_init(qiov, niov);
239
240 for (i = 0; i < tmp_niov; i++) {
241 qemu_iovec_add(qiov, tmp_iov[i].iov_base, tmp_iov[i].iov_len);
242 }
243
244 for (i = start + 1; i < start + num_reqs; i++) {
245 qemu_iovec_concat(qiov, &mrb->reqs[i]->qiov, 0,
246 mrb->reqs[i]->qiov.size);
247 mrb->reqs[i - 1]->mr_next = mrb->reqs[i];
248 }
249
250 trace_virtio_blk_submit_multireq(VIRTIO_DEVICE(mrb->reqs[start]->dev),
251 mrb, start, num_reqs,
252 sector_num << BDRV_SECTOR_BITS,
253 qiov->size, is_write);
254 block_acct_merge_done(blk_get_stats(blk),
255 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ,
256 num_reqs - 1);
257 }
258
259 if (blk_ram_registrar_ok(&s->blk_ram_registrar)) {
260 flags |= BDRV_REQ_REGISTERED_BUF;
261 }
262
263 if (is_write) {
264 blk_aio_pwritev(blk, sector_num << BDRV_SECTOR_BITS, qiov,
265 flags, virtio_blk_rw_complete,
266 mrb->reqs[start]);
267 } else {
268 blk_aio_preadv(blk, sector_num << BDRV_SECTOR_BITS, qiov,
269 flags, virtio_blk_rw_complete,
270 mrb->reqs[start]);
271 }
272 }
273
274 static int multireq_compare(const void *a, const void *b)
275 {
276 const VirtIOBlockReq *req1 = *(VirtIOBlockReq **)a,
277 *req2 = *(VirtIOBlockReq **)b;
278
279 /*
280 * Note that we can't simply subtract sector_num1 from sector_num2
281 * here as that could overflow the return value.
282 */
283 if (req1->sector_num > req2->sector_num) {
284 return 1;
285 } else if (req1->sector_num < req2->sector_num) {
286 return -1;
287 } else {
288 return 0;
289 }
290 }
291
292 static void virtio_blk_submit_multireq(VirtIOBlock *s, MultiReqBuffer *mrb)
293 {
294 int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
295 uint32_t max_transfer;
296 int64_t sector_num = 0;
297
298 if (mrb->num_reqs == 1) {
299 submit_requests(s, mrb, 0, 1, -1);
300 mrb->num_reqs = 0;
301 return;
302 }
303
304 max_transfer = blk_get_max_transfer(mrb->reqs[0]->dev->blk);
305
306 qsort(mrb->reqs, mrb->num_reqs, sizeof(*mrb->reqs),
307 &multireq_compare);
308
309 for (i = 0; i < mrb->num_reqs; i++) {
310 VirtIOBlockReq *req = mrb->reqs[i];
311 if (num_reqs > 0) {
312 /*
313 * NOTE: We cannot merge the requests in below situations:
314 * 1. requests are not sequential
315 * 2. merge would exceed maximum number of IOVs
316 * 3. merge would exceed maximum transfer length of backend device
317 */
318 if (sector_num + nb_sectors != req->sector_num ||
319 niov > blk_get_max_iov(s->blk) - req->qiov.niov ||
320 req->qiov.size > max_transfer ||
321 nb_sectors > (max_transfer -
322 req->qiov.size) / BDRV_SECTOR_SIZE) {
323 submit_requests(s, mrb, start, num_reqs, niov);
324 num_reqs = 0;
325 }
326 }
327
328 if (num_reqs == 0) {
329 sector_num = req->sector_num;
330 nb_sectors = niov = 0;
331 start = i;
332 }
333
334 nb_sectors += req->qiov.size / BDRV_SECTOR_SIZE;
335 niov += req->qiov.niov;
336 num_reqs++;
337 }
338
339 submit_requests(s, mrb, start, num_reqs, niov);
340 mrb->num_reqs = 0;
341 }
342
343 static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
344 {
345 VirtIOBlock *s = req->dev;
346
347 block_acct_start(blk_get_stats(s->blk), &req->acct, 0,
348 BLOCK_ACCT_FLUSH);
349
350 /*
351 * Make sure all outstanding writes are posted to the backing device.
352 */
353 if (mrb->is_write && mrb->num_reqs > 0) {
354 virtio_blk_submit_multireq(s, mrb);
355 }
356 blk_aio_flush(s->blk, virtio_blk_flush_complete, req);
357 }
358
359 static bool virtio_blk_sect_range_ok(VirtIOBlock *dev,
360 uint64_t sector, size_t size)
361 {
362 uint64_t nb_sectors = size >> BDRV_SECTOR_BITS;
363 uint64_t total_sectors;
364
365 if (nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
366 return false;
367 }
368 if (sector & dev->sector_mask) {
369 return false;
370 }
371 if (size % dev->conf.conf.logical_block_size) {
372 return false;
373 }
374 blk_get_geometry(dev->blk, &total_sectors);
375 if (sector > total_sectors || nb_sectors > total_sectors - sector) {
376 return false;
377 }
378 return true;
379 }
380
381 static uint8_t virtio_blk_handle_discard_write_zeroes(VirtIOBlockReq *req,
382 struct virtio_blk_discard_write_zeroes *dwz_hdr, bool is_write_zeroes)
383 {
384 VirtIOBlock *s = req->dev;
385 VirtIODevice *vdev = VIRTIO_DEVICE(s);
386 uint64_t sector;
387 uint32_t num_sectors, flags, max_sectors;
388 uint8_t err_status;
389 int bytes;
390
391 sector = virtio_ldq_p(vdev, &dwz_hdr->sector);
392 num_sectors = virtio_ldl_p(vdev, &dwz_hdr->num_sectors);
393 flags = virtio_ldl_p(vdev, &dwz_hdr->flags);
394 max_sectors = is_write_zeroes ? s->conf.max_write_zeroes_sectors :
395 s->conf.max_discard_sectors;
396
397 /*
398 * max_sectors is at most BDRV_REQUEST_MAX_SECTORS, this check
399 * make us sure that "num_sectors << BDRV_SECTOR_BITS" can fit in
400 * the integer variable.
401 */
402 if (unlikely(num_sectors > max_sectors)) {
403 err_status = VIRTIO_BLK_S_IOERR;
404 goto err;
405 }
406
407 bytes = num_sectors << BDRV_SECTOR_BITS;
408
409 if (unlikely(!virtio_blk_sect_range_ok(s, sector, bytes))) {
410 err_status = VIRTIO_BLK_S_IOERR;
411 goto err;
412 }
413
414 /*
415 * The device MUST set the status byte to VIRTIO_BLK_S_UNSUPP for discard
416 * and write zeroes commands if any unknown flag is set.
417 */
418 if (unlikely(flags & ~VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP)) {
419 err_status = VIRTIO_BLK_S_UNSUPP;
420 goto err;
421 }
422
423 if (is_write_zeroes) { /* VIRTIO_BLK_T_WRITE_ZEROES */
424 int blk_aio_flags = 0;
425
426 if (flags & VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP) {
427 blk_aio_flags |= BDRV_REQ_MAY_UNMAP;
428 }
429
430 block_acct_start(blk_get_stats(s->blk), &req->acct, bytes,
431 BLOCK_ACCT_WRITE);
432
433 blk_aio_pwrite_zeroes(s->blk, sector << BDRV_SECTOR_BITS,
434 bytes, blk_aio_flags,
435 virtio_blk_discard_write_zeroes_complete, req);
436 } else { /* VIRTIO_BLK_T_DISCARD */
437 /*
438 * The device MUST set the status byte to VIRTIO_BLK_S_UNSUPP for
439 * discard commands if the unmap flag is set.
440 */
441 if (unlikely(flags & VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP)) {
442 err_status = VIRTIO_BLK_S_UNSUPP;
443 goto err;
444 }
445
446 blk_aio_pdiscard(s->blk, sector << BDRV_SECTOR_BITS, bytes,
447 virtio_blk_discard_write_zeroes_complete, req);
448 }
449
450 return VIRTIO_BLK_S_OK;
451
452 err:
453 if (is_write_zeroes) {
454 block_acct_invalid(blk_get_stats(s->blk), BLOCK_ACCT_WRITE);
455 }
456 return err_status;
457 }
458
459 typedef struct {
460 unsigned int total_nr_zones; /* max zones to fill in this request */
461 unsigned int nr_zones_done; /* how many zones have been filled in */
462 int64_t iov_offset; /* current byte position in in_iov[] */
463 int64_t offset; /* current zone report disk offset */
464 unsigned int nr_zones; /* for zone report calls */
465 unsigned int zones_per_batch; /* size of zone report buffer */
466 BlockZoneDescriptor *zones; /* zone report buffer */
467 } ZoneReportData;
468
469 typedef struct ZoneCmdData {
470 VirtIOBlockReq *req;
471 struct iovec *in_iov;
472 unsigned in_num;
473 union {
474 ZoneReportData zone_report_data;
475 struct {
476 int64_t offset;
477 } zone_append_data;
478 };
479 } ZoneCmdData;
480
481 /*
482 * check zoned_request: error checking before issuing requests. If all checks
483 * passed, return true.
484 * append: true if only zone append requests issued.
485 */
486 static bool check_zoned_request(VirtIOBlock *s, int64_t offset, int64_t len,
487 bool append, uint8_t *status) {
488 BlockDriverState *bs = blk_bs(s->blk);
489 int index;
490
491 if (!virtio_has_feature(s->host_features, VIRTIO_BLK_F_ZONED)) {
492 *status = VIRTIO_BLK_S_UNSUPP;
493 return false;
494 }
495
496 if (offset < 0 || len < 0 || len > (bs->total_sectors << BDRV_SECTOR_BITS)
497 || offset > (bs->total_sectors << BDRV_SECTOR_BITS) - len) {
498 *status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
499 return false;
500 }
501
502 if (append) {
503 if (bs->bl.write_granularity) {
504 if ((offset % bs->bl.write_granularity) != 0) {
505 *status = VIRTIO_BLK_S_ZONE_UNALIGNED_WP;
506 return false;
507 }
508 }
509
510 index = offset / bs->bl.zone_size;
511 if (BDRV_ZT_IS_CONV(bs->wps->wp[index])) {
512 *status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
513 return false;
514 }
515
516 if (len / 512 > bs->bl.max_append_sectors) {
517 if (bs->bl.max_append_sectors == 0) {
518 *status = VIRTIO_BLK_S_UNSUPP;
519 } else {
520 *status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
521 }
522 return false;
523 }
524 }
525 return true;
526 }
527
528 static void virtio_blk_zone_report_complete(void *opaque, int ret)
529 {
530 ZoneCmdData *data = opaque;
531 ZoneReportData *zrd = &data->zone_report_data;
532 VirtIOBlockReq *req = data->req;
533 VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
534 struct iovec *in_iov = data->in_iov;
535 unsigned in_num = data->in_num;
536 int64_t n;
537 unsigned nz = zrd->nr_zones;
538 int8_t err_status = VIRTIO_BLK_S_OK;
539 struct virtio_blk_zone_report zrp_hdr = {};
540
541 trace_virtio_blk_zone_report_complete(vdev, req, nz, ret);
542 if (ret) {
543 err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
544 goto out;
545 }
546
547 for (unsigned j = 0; j < nz; j++) {
548 struct virtio_blk_zone_descriptor desc =
549 (struct virtio_blk_zone_descriptor) {
550 .z_start = cpu_to_le64(zrd->zones[j].start
551 >> BDRV_SECTOR_BITS),
552 .z_cap = cpu_to_le64(zrd->zones[j].cap
553 >> BDRV_SECTOR_BITS),
554 .z_wp = cpu_to_le64(zrd->zones[j].wp
555 >> BDRV_SECTOR_BITS),
556 };
557
558 switch (zrd->zones[j].type) {
559 case BLK_ZT_CONV:
560 desc.z_type = VIRTIO_BLK_ZT_CONV;
561 break;
562 case BLK_ZT_SWR:
563 desc.z_type = VIRTIO_BLK_ZT_SWR;
564 break;
565 case BLK_ZT_SWP:
566 desc.z_type = VIRTIO_BLK_ZT_SWP;
567 break;
568 default:
569 g_assert_not_reached();
570 }
571
572 switch (zrd->zones[j].state) {
573 case BLK_ZS_RDONLY:
574 desc.z_state = VIRTIO_BLK_ZS_RDONLY;
575 break;
576 case BLK_ZS_OFFLINE:
577 desc.z_state = VIRTIO_BLK_ZS_OFFLINE;
578 break;
579 case BLK_ZS_EMPTY:
580 desc.z_state = VIRTIO_BLK_ZS_EMPTY;
581 break;
582 case BLK_ZS_CLOSED:
583 desc.z_state = VIRTIO_BLK_ZS_CLOSED;
584 break;
585 case BLK_ZS_FULL:
586 desc.z_state = VIRTIO_BLK_ZS_FULL;
587 break;
588 case BLK_ZS_EOPEN:
589 desc.z_state = VIRTIO_BLK_ZS_EOPEN;
590 break;
591 case BLK_ZS_IOPEN:
592 desc.z_state = VIRTIO_BLK_ZS_IOPEN;
593 break;
594 case BLK_ZS_NOT_WP:
595 desc.z_state = VIRTIO_BLK_ZS_NOT_WP;
596 break;
597 default:
598 g_assert_not_reached();
599 }
600
601 /* TODO: it takes O(n^2) time complexity. Optimizations required. */
602 n = iov_from_buf(in_iov, in_num, zrd->iov_offset, &desc, sizeof(desc));
603 if (n != sizeof(desc)) {
604 virtio_error(vdev, "Driver provided input buffer "
605 "for descriptors that is too small!");
606 err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
607 goto out;
608 }
609
610 zrd->iov_offset += sizeof(desc);
611 }
612
613 if (nz > 0) {
614 BlockZoneDescriptor *zone = &zrd->zones[nz - 1];
615 zrd->offset = zone->start + zone->length;
616 }
617
618 zrd->nr_zones_done += nz;
619
620 /* Call zone report again if the end hasn't been reached yet */
621 if (nz == zrd->zones_per_batch &&
622 zrd->nr_zones_done < zrd->total_nr_zones) {
623 zrd->nr_zones = MIN(zrd->zones_per_batch,
624 zrd->total_nr_zones - zrd->nr_zones_done);
625 blk_aio_zone_report(req->dev->blk, zrd->offset, &zrd->nr_zones,
626 zrd->zones, virtio_blk_zone_report_complete, data);
627 return;
628 }
629
630 /* Fill in header now that all zones have been reported */
631 zrp_hdr.nr_zones = cpu_to_le64(zrd->nr_zones_done);
632 n = iov_from_buf(in_iov, in_num, 0, &zrp_hdr, sizeof(zrp_hdr));
633 if (n != sizeof(zrp_hdr)) {
634 virtio_error(vdev, "Driver provided input buffer that is too small!");
635 err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
636 goto out;
637 }
638
639 out:
640 virtio_blk_req_complete(req, err_status);
641 g_free(req);
642 g_free(zrd->zones);
643 g_free(data);
644 }
645
646 static void virtio_blk_handle_zone_report(VirtIOBlockReq *req,
647 struct iovec *in_iov,
648 unsigned in_num)
649 {
650 VirtIOBlock *s = req->dev;
651 VirtIODevice *vdev = VIRTIO_DEVICE(s);
652 unsigned int nr_zones;
653 ZoneCmdData *data;
654 ZoneReportData *zrd;
655 int64_t offset;
656 uint8_t err_status;
657
658 if (req->in_len < sizeof(struct virtio_blk_inhdr) +
659 sizeof(struct virtio_blk_zone_report) +
660 sizeof(struct virtio_blk_zone_descriptor)) {
661 virtio_error(vdev, "in buffer too small for zone report");
662 err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
663 goto out;
664 }
665
666 /* start byte offset of the zone report */
667 offset = virtio_ldq_p(vdev, &req->out.sector) << BDRV_SECTOR_BITS;
668 if (!check_zoned_request(s, offset, 0, false, &err_status)) {
669 goto out;
670 }
671 nr_zones = (req->in_len - sizeof(struct virtio_blk_inhdr) -
672 sizeof(struct virtio_blk_zone_report)) /
673 sizeof(struct virtio_blk_zone_descriptor);
674 trace_virtio_blk_handle_zone_report(vdev, req,
675 offset >> BDRV_SECTOR_BITS, nr_zones);
676
677 data = g_malloc(sizeof(ZoneCmdData));
678 data->req = req;
679 data->in_iov = in_iov;
680 data->in_num = in_num;
681
682 zrd = &data->zone_report_data;
683 zrd->total_nr_zones = nr_zones;
684 zrd->nr_zones_done = 0;
685 zrd->iov_offset = sizeof(struct virtio_blk_zone_report);
686 zrd->offset = offset;
687 zrd->zones_per_batch = MIN(nr_zones, VIRTIO_BLK_MAX_ZONES_PER_BATCH);
688 zrd->zones = g_malloc(zrd->zones_per_batch * sizeof(BlockZoneDescriptor));
689
690 zrd->nr_zones = zrd->zones_per_batch;
691 blk_aio_zone_report(s->blk, offset, &zrd->nr_zones, zrd->zones,
692 virtio_blk_zone_report_complete, data);
693 return;
694 out:
695 virtio_blk_req_complete(req, err_status);
696 g_free(req);
697 }
698
699 static void virtio_blk_zone_mgmt_complete(void *opaque, int ret)
700 {
701 VirtIOBlockReq *req = opaque;
702 VirtIOBlock *s = req->dev;
703 VirtIODevice *vdev = VIRTIO_DEVICE(s);
704 int8_t err_status = VIRTIO_BLK_S_OK;
705 trace_virtio_blk_zone_mgmt_complete(vdev, req,ret);
706
707 if (ret) {
708 err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
709 }
710
711 virtio_blk_req_complete(req, err_status);
712 g_free(req);
713 }
714
715 static int virtio_blk_handle_zone_mgmt(VirtIOBlockReq *req, BlockZoneOp op)
716 {
717 VirtIOBlock *s = req->dev;
718 VirtIODevice *vdev = VIRTIO_DEVICE(s);
719 BlockDriverState *bs = blk_bs(s->blk);
720 int64_t offset = virtio_ldq_p(vdev, &req->out.sector) << BDRV_SECTOR_BITS;
721 uint64_t len;
722 uint64_t capacity = bs->total_sectors << BDRV_SECTOR_BITS;
723 uint8_t err_status = VIRTIO_BLK_S_OK;
724
725 uint32_t type = virtio_ldl_p(vdev, &req->out.type);
726 if (type == VIRTIO_BLK_T_ZONE_RESET_ALL) {
727 /* Entire drive capacity */
728 offset = 0;
729 len = capacity;
730 trace_virtio_blk_handle_zone_reset_all(vdev, req, 0,
731 bs->total_sectors);
732 } else {
733 if (bs->bl.zone_size > capacity - offset) {
734 /* The zoned device allows the last smaller zone. */
735 len = capacity - bs->bl.zone_size * (bs->bl.nr_zones - 1ull);
736 } else {
737 len = bs->bl.zone_size;
738 }
739 trace_virtio_blk_handle_zone_mgmt(vdev, req, op,
740 offset >> BDRV_SECTOR_BITS,
741 len >> BDRV_SECTOR_BITS);
742 }
743
744 if (!check_zoned_request(s, offset, len, false, &err_status)) {
745 goto out;
746 }
747
748 blk_aio_zone_mgmt(s->blk, op, offset, len,
749 virtio_blk_zone_mgmt_complete, req);
750
751 return 0;
752 out:
753 virtio_blk_req_complete(req, err_status);
754 g_free(req);
755 return err_status;
756 }
757
758 static void virtio_blk_zone_append_complete(void *opaque, int ret)
759 {
760 ZoneCmdData *data = opaque;
761 VirtIOBlockReq *req = data->req;
762 VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
763 int64_t append_sector, n;
764 uint8_t err_status = VIRTIO_BLK_S_OK;
765
766 if (ret) {
767 err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
768 goto out;
769 }
770
771 virtio_stq_p(vdev, &append_sector,
772 data->zone_append_data.offset >> BDRV_SECTOR_BITS);
773 n = iov_from_buf(data->in_iov, data->in_num, 0, &append_sector,
774 sizeof(append_sector));
775 if (n != sizeof(append_sector)) {
776 virtio_error(vdev, "Driver provided input buffer less than size of "
777 "append_sector");
778 err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
779 goto out;
780 }
781 trace_virtio_blk_zone_append_complete(vdev, req, append_sector, ret);
782
783 out:
784 virtio_blk_req_complete(req, err_status);
785 g_free(req);
786 g_free(data);
787 }
788
789 static int virtio_blk_handle_zone_append(VirtIOBlockReq *req,
790 struct iovec *out_iov,
791 struct iovec *in_iov,
792 uint64_t out_num,
793 unsigned in_num) {
794 VirtIOBlock *s = req->dev;
795 VirtIODevice *vdev = VIRTIO_DEVICE(s);
796 uint8_t err_status = VIRTIO_BLK_S_OK;
797
798 int64_t offset = virtio_ldq_p(vdev, &req->out.sector) << BDRV_SECTOR_BITS;
799 int64_t len = iov_size(out_iov, out_num);
800 ZoneCmdData *data;
801
802 trace_virtio_blk_handle_zone_append(vdev, req, offset >> BDRV_SECTOR_BITS);
803 if (!check_zoned_request(s, offset, len, true, &err_status)) {
804 goto out;
805 }
806
807 data = g_malloc(sizeof(ZoneCmdData));
808 data->req = req;
809 data->in_iov = in_iov;
810 data->in_num = in_num;
811 data->zone_append_data.offset = offset;
812 qemu_iovec_init_external(&req->qiov, out_iov, out_num);
813
814 block_acct_start(blk_get_stats(s->blk), &req->acct, len,
815 BLOCK_ACCT_ZONE_APPEND);
816
817 blk_aio_zone_append(s->blk, &data->zone_append_data.offset, &req->qiov, 0,
818 virtio_blk_zone_append_complete, data);
819 return 0;
820
821 out:
822 virtio_blk_req_complete(req, err_status);
823 g_free(req);
824 return err_status;
825 }
826
827 static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
828 {
829 uint32_t type;
830 struct iovec *in_iov = req->elem.in_sg;
831 struct iovec *out_iov = req->elem.out_sg;
832 unsigned in_num = req->elem.in_num;
833 unsigned out_num = req->elem.out_num;
834 VirtIOBlock *s = req->dev;
835 VirtIODevice *vdev = VIRTIO_DEVICE(s);
836
837 if (req->elem.out_num < 1 || req->elem.in_num < 1) {
838 virtio_error(vdev, "virtio-blk missing headers");
839 return -1;
840 }
841
842 if (unlikely(iov_to_buf(out_iov, out_num, 0, &req->out,
843 sizeof(req->out)) != sizeof(req->out))) {
844 virtio_error(vdev, "virtio-blk request outhdr too short");
845 return -1;
846 }
847
848 iov_discard_front_undoable(&out_iov, &out_num, sizeof(req->out),
849 &req->outhdr_undo);
850
851 if (in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {
852 virtio_error(vdev, "virtio-blk request inhdr too short");
853 iov_discard_undo(&req->outhdr_undo);
854 return -1;
855 }
856
857 /* We always touch the last byte, so just see how big in_iov is. */
858 req->in_len = iov_size(in_iov, in_num);
859 req->in = (void *)in_iov[in_num - 1].iov_base
860 + in_iov[in_num - 1].iov_len
861 - sizeof(struct virtio_blk_inhdr);
862 iov_discard_back_undoable(in_iov, &in_num, sizeof(struct virtio_blk_inhdr),
863 &req->inhdr_undo);
864
865 type = virtio_ldl_p(vdev, &req->out.type);
866
867 /* VIRTIO_BLK_T_OUT defines the command direction. VIRTIO_BLK_T_BARRIER
868 * is an optional flag. Although a guest should not send this flag if
869 * not negotiated we ignored it in the past. So keep ignoring it. */
870 switch (type & ~(VIRTIO_BLK_T_OUT | VIRTIO_BLK_T_BARRIER)) {
871 case VIRTIO_BLK_T_IN:
872 {
873 bool is_write = type & VIRTIO_BLK_T_OUT;
874 req->sector_num = virtio_ldq_p(vdev, &req->out.sector);
875
876 if (is_write) {
877 qemu_iovec_init_external(&req->qiov, out_iov, out_num);
878 trace_virtio_blk_handle_write(vdev, req, req->sector_num,
879 req->qiov.size / BDRV_SECTOR_SIZE);
880 } else {
881 qemu_iovec_init_external(&req->qiov, in_iov, in_num);
882 trace_virtio_blk_handle_read(vdev, req, req->sector_num,
883 req->qiov.size / BDRV_SECTOR_SIZE);
884 }
885
886 if (!virtio_blk_sect_range_ok(s, req->sector_num, req->qiov.size)) {
887 virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
888 block_acct_invalid(blk_get_stats(s->blk),
889 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
890 g_free(req);
891 return 0;
892 }
893
894 block_acct_start(blk_get_stats(s->blk), &req->acct, req->qiov.size,
895 is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
896
897 /* merge would exceed maximum number of requests or IO direction
898 * changes */
899 if (mrb->num_reqs > 0 && (mrb->num_reqs == VIRTIO_BLK_MAX_MERGE_REQS ||
900 is_write != mrb->is_write ||
901 !s->conf.request_merging)) {
902 virtio_blk_submit_multireq(s, mrb);
903 }
904
905 assert(mrb->num_reqs < VIRTIO_BLK_MAX_MERGE_REQS);
906 mrb->reqs[mrb->num_reqs++] = req;
907 mrb->is_write = is_write;
908 break;
909 }
910 case VIRTIO_BLK_T_FLUSH:
911 virtio_blk_handle_flush(req, mrb);
912 break;
913 case VIRTIO_BLK_T_ZONE_REPORT:
914 virtio_blk_handle_zone_report(req, in_iov, in_num);
915 break;
916 case VIRTIO_BLK_T_ZONE_OPEN:
917 virtio_blk_handle_zone_mgmt(req, BLK_ZO_OPEN);
918 break;
919 case VIRTIO_BLK_T_ZONE_CLOSE:
920 virtio_blk_handle_zone_mgmt(req, BLK_ZO_CLOSE);
921 break;
922 case VIRTIO_BLK_T_ZONE_FINISH:
923 virtio_blk_handle_zone_mgmt(req, BLK_ZO_FINISH);
924 break;
925 case VIRTIO_BLK_T_ZONE_RESET:
926 virtio_blk_handle_zone_mgmt(req, BLK_ZO_RESET);
927 break;
928 case VIRTIO_BLK_T_ZONE_RESET_ALL:
929 virtio_blk_handle_zone_mgmt(req, BLK_ZO_RESET);
930 break;
931 case VIRTIO_BLK_T_SCSI_CMD:
932 virtio_blk_handle_scsi(req);
933 break;
934 case VIRTIO_BLK_T_GET_ID:
935 {
936 /*
937 * NB: per existing s/n string convention the string is
938 * terminated by '\0' only when shorter than buffer.
939 */
940 const char *serial = s->conf.serial ? s->conf.serial : "";
941 size_t size = MIN(strlen(serial) + 1,
942 MIN(iov_size(in_iov, in_num),
943 VIRTIO_BLK_ID_BYTES));
944 iov_from_buf(in_iov, in_num, 0, serial, size);
945 virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
946 g_free(req);
947 break;
948 }
949 case VIRTIO_BLK_T_ZONE_APPEND & ~VIRTIO_BLK_T_OUT:
950 /*
951 * Passing out_iov/out_num and in_iov/in_num is not safe
952 * to access req->elem.out_sg directly because it may be
953 * modified by virtio_blk_handle_request().
954 */
955 virtio_blk_handle_zone_append(req, out_iov, in_iov, out_num, in_num);
956 break;
957 /*
958 * VIRTIO_BLK_T_DISCARD and VIRTIO_BLK_T_WRITE_ZEROES are defined with
959 * VIRTIO_BLK_T_OUT flag set. We masked this flag in the switch statement,
960 * so we must mask it for these requests, then we will check if it is set.
961 */
962 case VIRTIO_BLK_T_DISCARD & ~VIRTIO_BLK_T_OUT:
963 case VIRTIO_BLK_T_WRITE_ZEROES & ~VIRTIO_BLK_T_OUT:
964 {
965 struct virtio_blk_discard_write_zeroes dwz_hdr;
966 size_t out_len = iov_size(out_iov, out_num);
967 bool is_write_zeroes = (type & ~VIRTIO_BLK_T_BARRIER) ==
968 VIRTIO_BLK_T_WRITE_ZEROES;
969 uint8_t err_status;
970
971 /*
972 * Unsupported if VIRTIO_BLK_T_OUT is not set or the request contains
973 * more than one segment.
974 */
975 if (unlikely(!(type & VIRTIO_BLK_T_OUT) ||
976 out_len > sizeof(dwz_hdr))) {
977 virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
978 g_free(req);
979 return 0;
980 }
981
982 if (unlikely(iov_to_buf(out_iov, out_num, 0, &dwz_hdr,
983 sizeof(dwz_hdr)) != sizeof(dwz_hdr))) {
984 iov_discard_undo(&req->inhdr_undo);
985 iov_discard_undo(&req->outhdr_undo);
986 virtio_error(vdev, "virtio-blk discard/write_zeroes header"
987 " too short");
988 return -1;
989 }
990
991 err_status = virtio_blk_handle_discard_write_zeroes(req, &dwz_hdr,
992 is_write_zeroes);
993 if (err_status != VIRTIO_BLK_S_OK) {
994 virtio_blk_req_complete(req, err_status);
995 g_free(req);
996 }
997
998 break;
999 }
1000 default:
1001 {
1002 /*
1003 * Give subclasses a chance to handle unknown requests. This way the
1004 * class lookup is not in the hot path.
1005 */
1006 VirtIOBlkClass *vbk = VIRTIO_BLK_GET_CLASS(s);
1007 if (!vbk->handle_unknown_request ||
1008 !vbk->handle_unknown_request(req, mrb, type)) {
1009 virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
1010 g_free(req);
1011 }
1012 }
1013 }
1014 return 0;
1015 }
1016
1017 void virtio_blk_handle_vq(VirtIOBlock *s, VirtQueue *vq)
1018 {
1019 VirtIOBlockReq *req;
1020 MultiReqBuffer mrb = {};
1021 bool suppress_notifications = virtio_queue_get_notification(vq);
1022
1023 defer_call_begin();
1024
1025 do {
1026 if (suppress_notifications) {
1027 virtio_queue_set_notification(vq, 0);
1028 }
1029
1030 while ((req = virtio_blk_get_request(s, vq))) {
1031 if (virtio_blk_handle_request(req, &mrb)) {
1032 virtqueue_detach_element(req->vq, &req->elem, 0);
1033 g_free(req);
1034 break;
1035 }
1036 }
1037
1038 if (suppress_notifications) {
1039 virtio_queue_set_notification(vq, 1);
1040 }
1041 } while (!virtio_queue_empty(vq));
1042
1043 if (mrb.num_reqs) {
1044 virtio_blk_submit_multireq(s, &mrb);
1045 }
1046
1047 defer_call_end();
1048 }
1049
1050 static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)
1051 {
1052 VirtIOBlock *s = (VirtIOBlock *)vdev;
1053
1054 if (!s->ioeventfd_disabled && !s->ioeventfd_started) {
1055 /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start
1056 * ioeventfd here instead of waiting for .set_status().
1057 */
1058 virtio_device_start_ioeventfd(vdev);
1059 if (!s->ioeventfd_disabled) {
1060 return;
1061 }
1062 }
1063
1064 virtio_blk_handle_vq(s, vq);
1065 }
1066
1067 static void virtio_blk_dma_restart_bh(void *opaque)
1068 {
1069 VirtIOBlockReq *req = opaque;
1070 VirtIOBlock *s = req->dev; /* we're called with at least one request */
1071
1072 MultiReqBuffer mrb = {};
1073
1074 while (req) {
1075 VirtIOBlockReq *next = req->next;
1076 if (virtio_blk_handle_request(req, &mrb)) {
1077 /* Device is now broken and won't do any processing until it gets
1078 * reset. Already queued requests will be lost: let's purge them.
1079 */
1080 while (req) {
1081 next = req->next;
1082 virtqueue_detach_element(req->vq, &req->elem, 0);
1083 g_free(req);
1084 req = next;
1085 }
1086 break;
1087 }
1088 req = next;
1089 }
1090
1091 if (mrb.num_reqs) {
1092 virtio_blk_submit_multireq(s, &mrb);
1093 }
1094
1095 /* Paired with inc in virtio_blk_dma_restart_cb() */
1096 blk_dec_in_flight(s->conf.conf.blk);
1097 }
1098
1099 static void virtio_blk_dma_restart_cb(void *opaque, bool running,
1100 RunState state)
1101 {
1102 VirtIOBlock *s = opaque;
1103 uint16_t num_queues = s->conf.num_queues;
1104 g_autofree VirtIOBlockReq **vq_rq = NULL;
1105 VirtIOBlockReq *rq = NULL;
1106
1107 if (!running) {
1108 return;
1109 }
1110
1111 /* Split the device-wide s->rq request list into per-vq request lists */
1112 vq_rq = g_new0(VirtIOBlockReq *, num_queues);
1113
1114 WITH_QEMU_LOCK_GUARD(&s->rq_lock) {
1115 rq = s->rq;
1116 s->rq = NULL;
1117 }
1118
1119 while (rq) {
1120 VirtIOBlockReq *next = rq->next;
1121 uint16_t idx = virtio_get_queue_index(rq->vq);
1122
1123 /* Only num_queues vqs were created so vq_rq[idx] is within bounds */
1124 assert(idx < num_queues);
1125 rq->next = vq_rq[idx];
1126 vq_rq[idx] = rq;
1127 rq = next;
1128 }
1129
1130 /* Schedule a BH to submit the requests in each vq's AioContext */
1131 for (uint16_t i = 0; i < num_queues; i++) {
1132 if (!vq_rq[i]) {
1133 continue;
1134 }
1135
1136 /* Paired with dec in virtio_blk_dma_restart_bh() */
1137 blk_inc_in_flight(s->conf.conf.blk);
1138
1139 aio_bh_schedule_oneshot(s->vq_aio_context[i],
1140 virtio_blk_dma_restart_bh,
1141 vq_rq[i]);
1142 }
1143 }
1144
1145 static void virtio_blk_reset(VirtIODevice *vdev)
1146 {
1147 VirtIOBlock *s = VIRTIO_BLK(vdev);
1148 VirtIOBlockReq *req;
1149
1150 /* Dataplane has stopped... */
1151 assert(!s->ioeventfd_started);
1152
1153 /* ...but requests may still be in flight. */
1154 blk_drain(s->blk);
1155
1156 /* We drop queued requests after blk_drain() because blk_drain() itself can
1157 * produce them. */
1158 WITH_QEMU_LOCK_GUARD(&s->rq_lock) {
1159 while (s->rq) {
1160 req = s->rq;
1161 s->rq = req->next;
1162
1163 /* No other threads can access req->vq here */
1164 virtqueue_detach_element(req->vq, &req->elem, 0);
1165
1166 g_free(req);
1167 }
1168 }
1169
1170 blk_set_enable_write_cache(s->blk, s->original_wce);
1171 }
1172
1173 /* coalesce internal state, copy to pci i/o region 0
1174 */
1175 static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
1176 {
1177 VirtIOBlock *s = VIRTIO_BLK(vdev);
1178 BlockConf *conf = &s->conf.conf;
1179 BlockDriverState *bs = blk_bs(s->blk);
1180 struct virtio_blk_config blkcfg;
1181 uint64_t capacity;
1182 int64_t length;
1183 int blk_size = conf->logical_block_size;
1184
1185 blk_get_geometry(s->blk, &capacity);
1186 memset(&blkcfg, 0, sizeof(blkcfg));
1187 virtio_stq_p(vdev, &blkcfg.capacity, capacity);
1188 virtio_stl_p(vdev, &blkcfg.seg_max,
1189 s->conf.seg_max_adjust ? s->conf.queue_size - 2 : 128 - 2);
1190 virtio_stw_p(vdev, &blkcfg.geometry.cylinders, conf->cyls);
1191 virtio_stl_p(vdev, &blkcfg.blk_size, blk_size);
1192 virtio_stw_p(vdev, &blkcfg.min_io_size, conf->min_io_size / blk_size);
1193 virtio_stl_p(vdev, &blkcfg.opt_io_size, conf->opt_io_size / blk_size);
1194 blkcfg.geometry.heads = conf->heads;
1195 /*
1196 * We must ensure that the block device capacity is a multiple of
1197 * the logical block size. If that is not the case, let's use
1198 * sector_mask to adopt the geometry to have a correct picture.
1199 * For those devices where the capacity is ok for the given geometry
1200 * we don't touch the sector value of the geometry, since some devices
1201 * (like s390 dasd) need a specific value. Here the capacity is already
1202 * cyls*heads*secs*blk_size and the sector value is not block size
1203 * divided by 512 - instead it is the amount of blk_size blocks
1204 * per track (cylinder).
1205 */
1206 length = blk_getlength(s->blk);
1207 if (length > 0 && length / conf->heads / conf->secs % blk_size) {
1208 blkcfg.geometry.sectors = conf->secs & ~s->sector_mask;
1209 } else {
1210 blkcfg.geometry.sectors = conf->secs;
1211 }
1212 blkcfg.size_max = 0;
1213 blkcfg.physical_block_exp = get_physical_block_exp(conf);
1214 blkcfg.alignment_offset = 0;
1215 blkcfg.wce = blk_enable_write_cache(s->blk);
1216 virtio_stw_p(vdev, &blkcfg.num_queues, s->conf.num_queues);
1217 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_DISCARD)) {
1218 uint32_t discard_granularity = conf->discard_granularity;
1219 if (discard_granularity == -1 || !s->conf.report_discard_granularity) {
1220 discard_granularity = blk_size;
1221 }
1222 virtio_stl_p(vdev, &blkcfg.max_discard_sectors,
1223 s->conf.max_discard_sectors);
1224 virtio_stl_p(vdev, &blkcfg.discard_sector_alignment,
1225 discard_granularity >> BDRV_SECTOR_BITS);
1226 /*
1227 * We support only one segment per request since multiple segments
1228 * are not widely used and there are no userspace APIs that allow
1229 * applications to submit multiple segments in a single call.
1230 */
1231 virtio_stl_p(vdev, &blkcfg.max_discard_seg, 1);
1232 }
1233 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_WRITE_ZEROES)) {
1234 virtio_stl_p(vdev, &blkcfg.max_write_zeroes_sectors,
1235 s->conf.max_write_zeroes_sectors);
1236 blkcfg.write_zeroes_may_unmap = 1;
1237 virtio_stl_p(vdev, &blkcfg.max_write_zeroes_seg, 1);
1238 }
1239 if (bs->bl.zoned != BLK_Z_NONE) {
1240 switch (bs->bl.zoned) {
1241 case BLK_Z_HM:
1242 blkcfg.zoned.model = VIRTIO_BLK_Z_HM;
1243 break;
1244 case BLK_Z_HA:
1245 blkcfg.zoned.model = VIRTIO_BLK_Z_HA;
1246 break;
1247 default:
1248 g_assert_not_reached();
1249 }
1250
1251 virtio_stl_p(vdev, &blkcfg.zoned.zone_sectors,
1252 bs->bl.zone_size / 512);
1253 virtio_stl_p(vdev, &blkcfg.zoned.max_active_zones,
1254 bs->bl.max_active_zones);
1255 virtio_stl_p(vdev, &blkcfg.zoned.max_open_zones,
1256 bs->bl.max_open_zones);
1257 virtio_stl_p(vdev, &blkcfg.zoned.write_granularity, blk_size);
1258 virtio_stl_p(vdev, &blkcfg.zoned.max_append_sectors,
1259 bs->bl.max_append_sectors);
1260 } else {
1261 blkcfg.zoned.model = VIRTIO_BLK_Z_NONE;
1262 }
1263 memcpy(config, &blkcfg, s->config_size);
1264 }
1265
1266 static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config)
1267 {
1268 VirtIOBlock *s = VIRTIO_BLK(vdev);
1269 struct virtio_blk_config blkcfg;
1270
1271 memcpy(&blkcfg, config, s->config_size);
1272
1273 blk_set_enable_write_cache(s->blk, blkcfg.wce != 0);
1274 }
1275
1276 static uint64_t virtio_blk_get_features(VirtIODevice *vdev, uint64_t features,
1277 Error **errp)
1278 {
1279 VirtIOBlock *s = VIRTIO_BLK(vdev);
1280
1281 /* Firstly sync all virtio-blk possible supported features */
1282 features |= s->host_features;
1283
1284 virtio_add_feature(&features, VIRTIO_BLK_F_SEG_MAX);
1285 virtio_add_feature(&features, VIRTIO_BLK_F_GEOMETRY);
1286 virtio_add_feature(&features, VIRTIO_BLK_F_TOPOLOGY);
1287 virtio_add_feature(&features, VIRTIO_BLK_F_BLK_SIZE);
1288 if (!virtio_has_feature(features, VIRTIO_F_VERSION_1)) {
1289 virtio_clear_feature(&features, VIRTIO_F_ANY_LAYOUT);
1290 /* Added for historical reasons, removing it could break migration. */
1291 virtio_add_feature(&features, VIRTIO_BLK_F_SCSI);
1292 }
1293
1294 if (blk_enable_write_cache(s->blk) ||
1295 (s->conf.x_enable_wce_if_config_wce &&
1296 virtio_has_feature(features, VIRTIO_BLK_F_CONFIG_WCE))) {
1297 virtio_add_feature(&features, VIRTIO_BLK_F_WCE);
1298 }
1299 if (!blk_is_writable(s->blk)) {
1300 virtio_add_feature(&features, VIRTIO_BLK_F_RO);
1301 }
1302 if (s->conf.num_queues > 1) {
1303 virtio_add_feature(&features, VIRTIO_BLK_F_MQ);
1304 }
1305
1306 return features;
1307 }
1308
1309 static int virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)
1310 {
1311 VirtIOBlock *s = VIRTIO_BLK(vdev);
1312
1313 if (!(status & (VIRTIO_CONFIG_S_DRIVER | VIRTIO_CONFIG_S_DRIVER_OK))) {
1314 assert(!s->ioeventfd_started);
1315 }
1316
1317 if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
1318 return 0;
1319 }
1320
1321 /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send
1322 * cache flushes. Thus, the "auto writethrough" behavior is never
1323 * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.
1324 * Leaving it enabled would break the following sequence:
1325 *
1326 * Guest started with "-drive cache=writethrough"
1327 * Guest sets status to 0
1328 * Guest sets DRIVER bit in status field
1329 * Guest reads host features (WCE=0, CONFIG_WCE=1)
1330 * Guest writes guest features (WCE=0, CONFIG_WCE=1)
1331 * Guest writes 1 to the WCE configuration field (writeback mode)
1332 * Guest sets DRIVER_OK bit in status field
1333 *
1334 * s->blk would erroneously be placed in writethrough mode.
1335 */
1336 if (!virtio_vdev_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE)) {
1337 blk_set_enable_write_cache(s->blk,
1338 virtio_vdev_has_feature(vdev,
1339 VIRTIO_BLK_F_WCE));
1340 }
1341 return 0;
1342 }
1343
1344 static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f)
1345 {
1346 VirtIOBlock *s = VIRTIO_BLK(vdev);
1347
1348 WITH_QEMU_LOCK_GUARD(&s->rq_lock) {
1349 VirtIOBlockReq *req = s->rq;
1350
1351 while (req) {
1352 qemu_put_sbyte(f, 1);
1353
1354 if (s->conf.num_queues > 1) {
1355 qemu_put_be32(f, virtio_get_queue_index(req->vq));
1356 }
1357
1358 qemu_put_virtqueue_element(vdev, f, &req->elem);
1359 req = req->next;
1360 }
1361 }
1362
1363 qemu_put_sbyte(f, 0);
1364 }
1365
1366 static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f,
1367 int version_id)
1368 {
1369 VirtIOBlock *s = VIRTIO_BLK(vdev);
1370
1371 while (qemu_get_sbyte(f)) {
1372 unsigned nvqs = s->conf.num_queues;
1373 unsigned vq_idx = 0;
1374 VirtIOBlockReq *req;
1375
1376 if (nvqs > 1) {
1377 vq_idx = qemu_get_be32(f);
1378
1379 if (vq_idx >= nvqs) {
1380 error_report("Invalid virtqueue index in request list: %#x",
1381 vq_idx);
1382 return -EINVAL;
1383 }
1384 }
1385
1386 req = qemu_get_virtqueue_element(vdev, f, sizeof(VirtIOBlockReq));
1387 virtio_blk_init_request(s, virtio_get_queue(vdev, vq_idx), req);
1388
1389 WITH_QEMU_LOCK_GUARD(&s->rq_lock) {
1390 req->next = s->rq;
1391 s->rq = req;
1392 }
1393 }
1394
1395 return 0;
1396 }
1397
1398 static void virtio_resize_cb(void *opaque)
1399 {
1400 VirtIODevice *vdev = opaque;
1401
1402 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1403 virtio_notify_config(vdev);
1404 }
1405
1406 static void virtio_blk_resize(void *opaque)
1407 {
1408 VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
1409
1410 /*
1411 * virtio_notify_config() needs to acquire the BQL,
1412 * so it can't be called from an iothread. Instead, schedule
1413 * it to be run in the main context BH.
1414 */
1415 aio_bh_schedule_oneshot(qemu_get_aio_context(), virtio_resize_cb, vdev);
1416 }
1417
1418 static void virtio_blk_ioeventfd_detach(VirtIOBlock *s)
1419 {
1420 VirtIODevice *vdev = VIRTIO_DEVICE(s);
1421
1422 for (uint16_t i = 0; i < s->conf.num_queues; i++) {
1423 VirtQueue *vq = virtio_get_queue(vdev, i);
1424 virtio_queue_aio_detach_host_notifier(vq, s->vq_aio_context[i]);
1425 }
1426 }
1427
1428 static void virtio_blk_ioeventfd_attach(VirtIOBlock *s)
1429 {
1430 VirtIODevice *vdev = VIRTIO_DEVICE(s);
1431
1432 for (uint16_t i = 0; i < s->conf.num_queues; i++) {
1433 VirtQueue *vq = virtio_get_queue(vdev, i);
1434 virtio_queue_aio_attach_host_notifier(vq, s->vq_aio_context[i]);
1435 }
1436 }
1437
1438 /* Suspend virtqueue ioeventfd processing during drain */
1439 static void virtio_blk_drained_begin(void *opaque)
1440 {
1441 VirtIOBlock *s = opaque;
1442
1443 if (s->ioeventfd_started) {
1444 virtio_blk_ioeventfd_detach(s);
1445 }
1446 }
1447
1448 /* Resume virtqueue ioeventfd processing after drain */
1449 static void virtio_blk_drained_end(void *opaque)
1450 {
1451 VirtIOBlock *s = opaque;
1452
1453 if (s->ioeventfd_started) {
1454 virtio_blk_ioeventfd_attach(s);
1455 }
1456 }
1457
1458 static const BlockDevOps virtio_block_ops = {
1459 .resize_cb = virtio_blk_resize,
1460 .drained_begin = virtio_blk_drained_begin,
1461 .drained_end = virtio_blk_drained_end,
1462 };
1463
1464 /* Context: BQL held */
1465 static bool virtio_blk_vq_aio_context_init(VirtIOBlock *s, Error **errp)
1466 {
1467 ERRP_GUARD();
1468 VirtIODevice *vdev = VIRTIO_DEVICE(s);
1469 VirtIOBlkConf *conf = &s->conf;
1470 BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1471 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1472
1473 if (conf->iothread && conf->iothread_vq_mapping_list) {
1474 error_setg(errp,
1475 "iothread and iothread-vq-mapping properties cannot be set "
1476 "at the same time");
1477 return false;
1478 }
1479
1480 if (conf->iothread || conf->iothread_vq_mapping_list) {
1481 if (!k->set_guest_notifiers || !k->ioeventfd_assign) {
1482 error_setg(errp,
1483 "device is incompatible with iothread "
1484 "(transport does not support notifiers)");
1485 return false;
1486 }
1487 if (!virtio_device_ioeventfd_enabled(vdev)) {
1488 error_setg(errp, "ioeventfd is required for iothread");
1489 return false;
1490 }
1491 }
1492
1493 s->vq_aio_context = g_new(AioContext *, conf->num_queues);
1494
1495 if (conf->iothread_vq_mapping_list) {
1496 if (!iothread_vq_mapping_apply(conf->iothread_vq_mapping_list,
1497 s->vq_aio_context,
1498 conf->num_queues,
1499 errp)) {
1500 g_free(s->vq_aio_context);
1501 s->vq_aio_context = NULL;
1502 return false;
1503 }
1504 } else if (conf->iothread) {
1505 AioContext *ctx = iothread_get_aio_context(conf->iothread);
1506 for (unsigned i = 0; i < conf->num_queues; i++) {
1507 s->vq_aio_context[i] = ctx;
1508 }
1509
1510 /* Released in virtio_blk_vq_aio_context_cleanup() */
1511 object_ref(OBJECT(conf->iothread));
1512 } else {
1513 AioContext *ctx = qemu_get_aio_context();
1514 for (unsigned i = 0; i < conf->num_queues; i++) {
1515 s->vq_aio_context[i] = ctx;
1516 }
1517 }
1518
1519 return true;
1520 }
1521
1522 /* Context: BQL held */
1523 static void virtio_blk_vq_aio_context_cleanup(VirtIOBlock *s)
1524 {
1525 VirtIOBlkConf *conf = &s->conf;
1526
1527 assert(!s->ioeventfd_started);
1528
1529 if (conf->iothread_vq_mapping_list) {
1530 iothread_vq_mapping_cleanup(conf->iothread_vq_mapping_list);
1531 }
1532
1533 if (conf->iothread) {
1534 object_unref(OBJECT(conf->iothread));
1535 }
1536
1537 g_free(s->vq_aio_context);
1538 s->vq_aio_context = NULL;
1539 }
1540
1541 /* Context: BQL held */
1542 static int virtio_blk_start_ioeventfd(VirtIODevice *vdev)
1543 {
1544 VirtIOBlock *s = VIRTIO_BLK(vdev);
1545 BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s)));
1546 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1547 unsigned i;
1548 unsigned nvqs = s->conf.num_queues;
1549 Error *local_err = NULL;
1550 int r;
1551
1552 if (s->ioeventfd_started || s->ioeventfd_starting) {
1553 return 0;
1554 }
1555
1556 s->ioeventfd_starting = true;
1557
1558 /* Set up guest notifier (irq) */
1559 r = k->set_guest_notifiers(qbus->parent, nvqs, true);
1560 if (r != 0) {
1561 error_report("virtio-blk failed to set guest notifier (%d), "
1562 "ensure -accel kvm is set.", r);
1563 goto fail_guest_notifiers;
1564 }
1565
1566 /*
1567 * Batch all the host notifiers in a single transaction to avoid
1568 * quadratic time complexity in address_space_update_ioeventfds().
1569 */
1570 memory_region_transaction_begin();
1571
1572 /* Set up virtqueue notify */
1573 for (i = 0; i < nvqs; i++) {
1574 r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), i, true);
1575 if (r != 0) {
1576 int j = i;
1577
1578 fprintf(stderr, "virtio-blk failed to set host notifier (%d)\n", r);
1579 while (i--) {
1580 virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), i, false);
1581 }
1582
1583 /*
1584 * The transaction expects the ioeventfds to be open when it
1585 * commits. Do it now, before the cleanup loop.
1586 */
1587 memory_region_transaction_commit();
1588
1589 while (j--) {
1590 virtio_bus_cleanup_host_notifier(VIRTIO_BUS(qbus), j);
1591 }
1592 goto fail_host_notifiers;
1593 }
1594 }
1595
1596 memory_region_transaction_commit();
1597
1598 /*
1599 * Try to change the AioContext so that block jobs and other operations can
1600 * co-locate their activity in the same AioContext. If it fails, nevermind.
1601 */
1602 assert(nvqs > 0); /* enforced during ->realize() */
1603 r = blk_set_aio_context(s->conf.conf.blk, s->vq_aio_context[0],
1604 &local_err);
1605 if (r < 0) {
1606 warn_report_err(local_err);
1607 }
1608
1609 /*
1610 * These fields must be visible to the IOThread when it processes the
1611 * virtqueue, otherwise it will think ioeventfd has not started yet.
1612 *
1613 * Make sure ->ioeventfd_started is false when blk_set_aio_context() is
1614 * called above so that draining does not cause the host notifier to be
1615 * detached/attached prematurely.
1616 */
1617 s->ioeventfd_starting = false;
1618 s->ioeventfd_started = true;
1619 smp_wmb(); /* paired with aio_notify_accept() on the read side */
1620
1621 /*
1622 * Get this show started by hooking up our callbacks. If drained now,
1623 * virtio_blk_drained_end() will do this later.
1624 * Attaching the notifier also kicks the virtqueues, processing any requests
1625 * they may already have.
1626 */
1627 if (!blk_in_drain(s->conf.conf.blk)) {
1628 virtio_blk_ioeventfd_attach(s);
1629 }
1630 return 0;
1631
1632 fail_host_notifiers:
1633 k->set_guest_notifiers(qbus->parent, nvqs, false);
1634 fail_guest_notifiers:
1635 s->ioeventfd_disabled = true;
1636 s->ioeventfd_starting = false;
1637 return -ENOSYS;
1638 }
1639
1640 /* Stop notifications for new requests from guest.
1641 *
1642 * Context: BH in IOThread
1643 */
1644 static void virtio_blk_ioeventfd_stop_vq_bh(void *opaque)
1645 {
1646 VirtQueue *vq = opaque;
1647 EventNotifier *host_notifier = virtio_queue_get_host_notifier(vq);
1648
1649 virtio_queue_aio_detach_host_notifier(vq, qemu_get_current_aio_context());
1650
1651 /*
1652 * Test and clear notifier after disabling event, in case poll callback
1653 * didn't have time to run.
1654 */
1655 virtio_queue_host_notifier_read(host_notifier);
1656 }
1657
1658 /* Context: BQL held */
1659 static void virtio_blk_stop_ioeventfd(VirtIODevice *vdev)
1660 {
1661 VirtIOBlock *s = VIRTIO_BLK(vdev);
1662 BusState *qbus = qdev_get_parent_bus(DEVICE(s));
1663 VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1664 unsigned i;
1665 unsigned nvqs = s->conf.num_queues;
1666
1667 if (!s->ioeventfd_started || s->ioeventfd_stopping) {
1668 return;
1669 }
1670
1671 /* Better luck next time. */
1672 if (s->ioeventfd_disabled) {
1673 s->ioeventfd_disabled = false;
1674 s->ioeventfd_started = false;
1675 return;
1676 }
1677 s->ioeventfd_stopping = true;
1678
1679 if (!blk_in_drain(s->conf.conf.blk)) {
1680 for (i = 0; i < nvqs; i++) {
1681 VirtQueue *vq = virtio_get_queue(vdev, i);
1682 AioContext *ctx = s->vq_aio_context[i];
1683
1684 aio_wait_bh_oneshot(ctx, virtio_blk_ioeventfd_stop_vq_bh, vq);
1685 }
1686 }
1687
1688 /*
1689 * Batch all the host notifiers in a single transaction to avoid
1690 * quadratic time complexity in address_space_update_ioeventfds().
1691 */
1692 memory_region_transaction_begin();
1693
1694 for (i = 0; i < nvqs; i++) {
1695 virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), i, false);
1696 }
1697
1698 /*
1699 * The transaction expects the ioeventfds to be open when it
1700 * commits. Do it now, before the cleanup loop.
1701 */
1702 memory_region_transaction_commit();
1703
1704 for (i = 0; i < nvqs; i++) {
1705 virtio_bus_cleanup_host_notifier(VIRTIO_BUS(qbus), i);
1706 }
1707
1708 /*
1709 * Set ->ioeventfd_started to false before draining so that host notifiers
1710 * are not detached/attached anymore.
1711 */
1712 s->ioeventfd_started = false;
1713
1714 /* Wait for virtio_blk_dma_restart_bh() and in flight I/O to complete */
1715 blk_drain(s->conf.conf.blk);
1716
1717 /*
1718 * Try to switch bs back to the QEMU main loop. If other users keep the
1719 * BlockBackend in the iothread, that's ok
1720 */
1721 blk_set_aio_context(s->conf.conf.blk, qemu_get_aio_context(), NULL);
1722
1723 /* Clean up guest notifier (irq) */
1724 k->set_guest_notifiers(qbus->parent, nvqs, false);
1725
1726 s->ioeventfd_stopping = false;
1727 }
1728
1729 static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
1730 {
1731 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1732 VirtIOBlock *s = VIRTIO_BLK(dev);
1733 VirtIOBlkConf *conf = &s->conf;
1734 BlockDriverState *bs;
1735 Error *err = NULL;
1736 unsigned i;
1737
1738 if (!conf->conf.blk) {
1739 error_setg(errp, "drive property not set");
1740 return;
1741 }
1742 if (!blk_is_inserted(conf->conf.blk)) {
1743 error_setg(errp, "Device needs media, but drive is empty");
1744 return;
1745 }
1746 if (conf->num_queues == VIRTIO_BLK_AUTO_NUM_QUEUES) {
1747 conf->num_queues = 1;
1748 }
1749 if (!conf->num_queues) {
1750 error_setg(errp, "num-queues property must be larger than 0");
1751 return;
1752 }
1753 if (conf->queue_size <= 2) {
1754 error_setg(errp, "invalid queue-size property (%" PRIu16 "), "
1755 "must be > 2", conf->queue_size);
1756 return;
1757 }
1758 if (!is_power_of_2(conf->queue_size) ||
1759 conf->queue_size > VIRTQUEUE_MAX_SIZE) {
1760 error_setg(errp, "invalid queue-size property (%" PRIu16 "), "
1761 "must be a power of 2 (max %d)",
1762 conf->queue_size, VIRTQUEUE_MAX_SIZE);
1763 return;
1764 }
1765
1766 if (!blkconf_apply_backend_options(&conf->conf,
1767 !blk_supports_write_perm(conf->conf.blk),
1768 true, errp)) {
1769 return;
1770 }
1771 s->original_wce = blk_enable_write_cache(conf->conf.blk);
1772 if (!blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, errp)) {
1773 return;
1774 }
1775
1776 if (!blkconf_blocksizes(&conf->conf, errp)) {
1777 return;
1778 }
1779
1780 bs = blk_bs(conf->conf.blk);
1781 if (bs->bl.zoned != BLK_Z_NONE) {
1782 virtio_add_feature(&s->host_features, VIRTIO_BLK_F_ZONED);
1783 if (bs->bl.zoned == BLK_Z_HM) {
1784 virtio_clear_feature(&s->host_features, VIRTIO_BLK_F_DISCARD);
1785 }
1786 }
1787
1788 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_DISCARD) &&
1789 (!conf->max_discard_sectors ||
1790 conf->max_discard_sectors > BDRV_REQUEST_MAX_SECTORS)) {
1791 error_setg(errp, "invalid max-discard-sectors property (%" PRIu32 ")"
1792 ", must be between 1 and %d",
1793 conf->max_discard_sectors, (int)BDRV_REQUEST_MAX_SECTORS);
1794 return;
1795 }
1796
1797 if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_WRITE_ZEROES) &&
1798 (!conf->max_write_zeroes_sectors ||
1799 conf->max_write_zeroes_sectors > BDRV_REQUEST_MAX_SECTORS)) {
1800 error_setg(errp, "invalid max-write-zeroes-sectors property (%" PRIu32
1801 "), must be between 1 and %d",
1802 conf->max_write_zeroes_sectors,
1803 (int)BDRV_REQUEST_MAX_SECTORS);
1804 return;
1805 }
1806
1807 s->config_size = virtio_get_config_size(&virtio_blk_cfg_size_params,
1808 s->host_features);
1809 virtio_init(vdev, VIRTIO_ID_BLOCK, s->config_size);
1810
1811 qemu_mutex_init(&s->rq_lock);
1812
1813 s->blk = conf->conf.blk;
1814 s->rq = NULL;
1815 s->sector_mask = (s->conf.conf.logical_block_size / BDRV_SECTOR_SIZE) - 1;
1816
1817 for (i = 0; i < conf->num_queues; i++) {
1818 virtio_add_queue(vdev, conf->queue_size, virtio_blk_handle_output);
1819 }
1820 qemu_coroutine_inc_pool_size(conf->num_queues * conf->queue_size / 2);
1821
1822 /* Don't start ioeventfd if transport does not support notifiers. */
1823 if (!virtio_device_ioeventfd_enabled(vdev)) {
1824 s->ioeventfd_disabled = true;
1825 }
1826
1827 virtio_blk_vq_aio_context_init(s, &err);
1828 if (err != NULL) {
1829 error_propagate(errp, err);
1830 for (i = 0; i < conf->num_queues; i++) {
1831 virtio_del_queue(vdev, i);
1832 }
1833 virtio_cleanup(vdev);
1834 return;
1835 }
1836
1837 /*
1838 * This must be after virtio_init() so virtio_blk_dma_restart_cb() gets
1839 * called after ->start_ioeventfd() has already set blk's AioContext.
1840 */
1841 s->change =
1842 qdev_add_vm_change_state_handler(dev, virtio_blk_dma_restart_cb, NULL, s);
1843
1844 blk_ram_registrar_init(&s->blk_ram_registrar, s->blk);
1845 blk_set_dev_ops(s->blk, &virtio_block_ops, s);
1846
1847 blk_iostatus_enable(s->blk);
1848
1849 add_boot_device_lchs(dev, "/disk@0,0",
1850 conf->conf.lcyls,
1851 conf->conf.lheads,
1852 conf->conf.lsecs);
1853 }
1854
1855 static void virtio_blk_device_unrealize(DeviceState *dev)
1856 {
1857 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1858 VirtIOBlock *s = VIRTIO_BLK(dev);
1859 VirtIOBlkConf *conf = &s->conf;
1860 unsigned i;
1861
1862 blk_drain(s->blk);
1863 del_boot_device_lchs(dev, "/disk@0,0");
1864 virtio_blk_vq_aio_context_cleanup(s);
1865 for (i = 0; i < conf->num_queues; i++) {
1866 virtio_del_queue(vdev, i);
1867 }
1868 qemu_coroutine_dec_pool_size(conf->num_queues * conf->queue_size / 2);
1869 qemu_mutex_destroy(&s->rq_lock);
1870 blk_ram_registrar_destroy(&s->blk_ram_registrar);
1871 qemu_del_vm_change_state_handler(s->change);
1872 blockdev_mark_auto_del(s->blk);
1873 virtio_cleanup(vdev);
1874 }
1875
1876 static void virtio_blk_instance_init(Object *obj)
1877 {
1878 VirtIOBlock *s = VIRTIO_BLK(obj);
1879
1880 device_add_bootindex_property(obj, &s->conf.conf.bootindex,
1881 "bootindex", "/disk@0,0",
1882 DEVICE(obj));
1883 }
1884
1885 static const VMStateDescription vmstate_virtio_blk = {
1886 .name = "virtio-blk",
1887 .minimum_version_id = 2,
1888 .version_id = 2,
1889 .fields = (const VMStateField[]) {
1890 VMSTATE_VIRTIO_DEVICE,
1891 VMSTATE_END_OF_LIST()
1892 },
1893 };
1894
1895 static const Property virtio_blk_properties[] = {
1896 DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf),
1897 DEFINE_BLOCK_ERROR_PROPERTIES(VirtIOBlock, conf.conf),
1898 DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf),
1899 DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial),
1900 DEFINE_PROP_BIT64("config-wce", VirtIOBlock, host_features,
1901 VIRTIO_BLK_F_CONFIG_WCE, true),
1902 DEFINE_PROP_BIT("request-merging", VirtIOBlock, conf.request_merging, 0,
1903 true),
1904 DEFINE_PROP_UINT16("num-queues", VirtIOBlock, conf.num_queues,
1905 VIRTIO_BLK_AUTO_NUM_QUEUES),
1906 DEFINE_PROP_UINT16("queue-size", VirtIOBlock, conf.queue_size, 256),
1907 DEFINE_PROP_BOOL("seg-max-adjust", VirtIOBlock, conf.seg_max_adjust, true),
1908 DEFINE_PROP_LINK("iothread", VirtIOBlock, conf.iothread, TYPE_IOTHREAD,
1909 IOThread *),
1910 DEFINE_PROP_IOTHREAD_VQ_MAPPING_LIST("iothread-vq-mapping", VirtIOBlock,
1911 conf.iothread_vq_mapping_list),
1912 DEFINE_PROP_BIT64("discard", VirtIOBlock, host_features,
1913 VIRTIO_BLK_F_DISCARD, true),
1914 DEFINE_PROP_BOOL("report-discard-granularity", VirtIOBlock,
1915 conf.report_discard_granularity, true),
1916 DEFINE_PROP_BIT64("write-zeroes", VirtIOBlock, host_features,
1917 VIRTIO_BLK_F_WRITE_ZEROES, true),
1918 DEFINE_PROP_UINT32("max-discard-sectors", VirtIOBlock,
1919 conf.max_discard_sectors, BDRV_REQUEST_MAX_SECTORS),
1920 DEFINE_PROP_UINT32("max-write-zeroes-sectors", VirtIOBlock,
1921 conf.max_write_zeroes_sectors, BDRV_REQUEST_MAX_SECTORS),
1922 DEFINE_PROP_BOOL("x-enable-wce-if-config-wce", VirtIOBlock,
1923 conf.x_enable_wce_if_config_wce, true),
1924 };
1925
1926 static void virtio_blk_class_init(ObjectClass *klass, const void *data)
1927 {
1928 DeviceClass *dc = DEVICE_CLASS(klass);
1929 VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1930
1931 device_class_set_props(dc, virtio_blk_properties);
1932 dc->vmsd = &vmstate_virtio_blk;
1933 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1934 vdc->realize = virtio_blk_device_realize;
1935 vdc->unrealize = virtio_blk_device_unrealize;
1936 vdc->get_config = virtio_blk_update_config;
1937 vdc->set_config = virtio_blk_set_config;
1938 vdc->get_features = virtio_blk_get_features;
1939 vdc->set_status = virtio_blk_set_status;
1940 vdc->reset = virtio_blk_reset;
1941 vdc->save = virtio_blk_save_device;
1942 vdc->load = virtio_blk_load_device;
1943 vdc->start_ioeventfd = virtio_blk_start_ioeventfd;
1944 vdc->stop_ioeventfd = virtio_blk_stop_ioeventfd;
1945 }
1946
1947 static const TypeInfo virtio_blk_info = {
1948 .name = TYPE_VIRTIO_BLK,
1949 .parent = TYPE_VIRTIO_DEVICE,
1950 .instance_size = sizeof(VirtIOBlock),
1951 .instance_init = virtio_blk_instance_init,
1952 .class_init = virtio_blk_class_init,
1953 .class_size = sizeof(VirtIOBlkClass),
1954 };
1955
1956 static void virtio_register_types(void)
1957 {
1958 type_register_static(&virtio_blk_info);
1959 }
1960
1961 type_init(virtio_register_types)