]> git.proxmox.com Git - mirror_qemu.git/blob - block/io.c
block: Move throttling fields from BDS to BB
[mirror_qemu.git] / block / io.c
1 /*
2 * Block layer I/O functions
3 *
4 * Copyright (c) 2003 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24
25 #include "qemu/osdep.h"
26 #include "trace.h"
27 #include "sysemu/block-backend.h"
28 #include "block/blockjob.h"
29 #include "block/block_int.h"
30 #include "block/throttle-groups.h"
31 #include "qemu/cutils.h"
32 #include "qapi/error.h"
33 #include "qemu/error-report.h"
34
35 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
36
37 static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
38 int64_t sector_num,
39 QEMUIOVector *qiov,
40 int nb_sectors,
41 BdrvRequestFlags flags,
42 BlockCompletionFunc *cb,
43 void *opaque,
44 bool is_write);
45 static void coroutine_fn bdrv_co_do_rw(void *opaque);
46 static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
47 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags);
48
49 /* throttling disk I/O limits */
50 void bdrv_set_io_limits(BlockDriverState *bs,
51 ThrottleConfig *cfg)
52 {
53 throttle_group_config(bs, cfg);
54 }
55
56 void bdrv_no_throttling_begin(BlockDriverState *bs)
57 {
58 if (!bs->blk) {
59 return;
60 }
61
62 if (blk_get_public(bs->blk)->io_limits_disabled++ == 0) {
63 throttle_group_restart_blk(bs->blk);
64 }
65 }
66
67 void bdrv_no_throttling_end(BlockDriverState *bs)
68 {
69 BlockBackendPublic *blkp;
70
71 if (!bs->blk) {
72 return;
73 }
74
75 blkp = blk_get_public(bs->blk);
76 assert(blkp->io_limits_disabled);
77 --blkp->io_limits_disabled;
78 }
79
80 void bdrv_io_limits_disable(BlockDriverState *bs)
81 {
82 assert(blk_get_public(bs->blk)->throttle_state);
83 bdrv_no_throttling_begin(bs);
84 throttle_group_unregister_blk(bs->blk);
85 bdrv_no_throttling_end(bs);
86 }
87
88 /* should be called before bdrv_set_io_limits if a limit is set */
89 void bdrv_io_limits_enable(BlockDriverState *bs, const char *group)
90 {
91 BlockBackendPublic *blkp = blk_get_public(bs->blk);
92
93 assert(!blkp->throttle_state);
94 throttle_group_register_blk(bs->blk, group);
95 }
96
97 void bdrv_io_limits_update_group(BlockDriverState *bs, const char *group)
98 {
99 /* this bs is not part of any group */
100 if (!blk_get_public(bs->blk)->throttle_state) {
101 return;
102 }
103
104 /* this bs is a part of the same group than the one we want */
105 if (!g_strcmp0(throttle_group_get_name(bs->blk), group)) {
106 return;
107 }
108
109 /* need to change the group this bs belong to */
110 bdrv_io_limits_disable(bs);
111 bdrv_io_limits_enable(bs, group);
112 }
113
114 void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)
115 {
116 BlockDriver *drv = bs->drv;
117 Error *local_err = NULL;
118
119 memset(&bs->bl, 0, sizeof(bs->bl));
120
121 if (!drv) {
122 return;
123 }
124
125 /* Take some limits from the children as a default */
126 if (bs->file) {
127 bdrv_refresh_limits(bs->file->bs, &local_err);
128 if (local_err) {
129 error_propagate(errp, local_err);
130 return;
131 }
132 bs->bl.opt_transfer_length = bs->file->bs->bl.opt_transfer_length;
133 bs->bl.max_transfer_length = bs->file->bs->bl.max_transfer_length;
134 bs->bl.min_mem_alignment = bs->file->bs->bl.min_mem_alignment;
135 bs->bl.opt_mem_alignment = bs->file->bs->bl.opt_mem_alignment;
136 bs->bl.max_iov = bs->file->bs->bl.max_iov;
137 } else {
138 bs->bl.min_mem_alignment = 512;
139 bs->bl.opt_mem_alignment = getpagesize();
140
141 /* Safe default since most protocols use readv()/writev()/etc */
142 bs->bl.max_iov = IOV_MAX;
143 }
144
145 if (bs->backing) {
146 bdrv_refresh_limits(bs->backing->bs, &local_err);
147 if (local_err) {
148 error_propagate(errp, local_err);
149 return;
150 }
151 bs->bl.opt_transfer_length =
152 MAX(bs->bl.opt_transfer_length,
153 bs->backing->bs->bl.opt_transfer_length);
154 bs->bl.max_transfer_length =
155 MIN_NON_ZERO(bs->bl.max_transfer_length,
156 bs->backing->bs->bl.max_transfer_length);
157 bs->bl.opt_mem_alignment =
158 MAX(bs->bl.opt_mem_alignment,
159 bs->backing->bs->bl.opt_mem_alignment);
160 bs->bl.min_mem_alignment =
161 MAX(bs->bl.min_mem_alignment,
162 bs->backing->bs->bl.min_mem_alignment);
163 bs->bl.max_iov =
164 MIN(bs->bl.max_iov,
165 bs->backing->bs->bl.max_iov);
166 }
167
168 /* Then let the driver override it */
169 if (drv->bdrv_refresh_limits) {
170 drv->bdrv_refresh_limits(bs, errp);
171 }
172 }
173
174 /**
175 * The copy-on-read flag is actually a reference count so multiple users may
176 * use the feature without worrying about clobbering its previous state.
177 * Copy-on-read stays enabled until all users have called to disable it.
178 */
179 void bdrv_enable_copy_on_read(BlockDriverState *bs)
180 {
181 bs->copy_on_read++;
182 }
183
184 void bdrv_disable_copy_on_read(BlockDriverState *bs)
185 {
186 assert(bs->copy_on_read > 0);
187 bs->copy_on_read--;
188 }
189
190 /* Check if any requests are in-flight (including throttled requests) */
191 bool bdrv_requests_pending(BlockDriverState *bs)
192 {
193 BdrvChild *child;
194 BlockBackendPublic *blkp = bs->blk ? blk_get_public(bs->blk) : NULL;
195
196 if (!QLIST_EMPTY(&bs->tracked_requests)) {
197 return true;
198 }
199 if (blkp && !qemu_co_queue_empty(&blkp->throttled_reqs[0])) {
200 return true;
201 }
202 if (blkp && !qemu_co_queue_empty(&blkp->throttled_reqs[1])) {
203 return true;
204 }
205
206 QLIST_FOREACH(child, &bs->children, next) {
207 if (bdrv_requests_pending(child->bs)) {
208 return true;
209 }
210 }
211
212 return false;
213 }
214
215 static void bdrv_drain_recurse(BlockDriverState *bs)
216 {
217 BdrvChild *child;
218
219 if (bs->drv && bs->drv->bdrv_drain) {
220 bs->drv->bdrv_drain(bs);
221 }
222 QLIST_FOREACH(child, &bs->children, next) {
223 bdrv_drain_recurse(child->bs);
224 }
225 }
226
227 typedef struct {
228 Coroutine *co;
229 BlockDriverState *bs;
230 QEMUBH *bh;
231 bool done;
232 } BdrvCoDrainData;
233
234 static void bdrv_drain_poll(BlockDriverState *bs)
235 {
236 bool busy = true;
237
238 while (busy) {
239 /* Keep iterating */
240 busy = bdrv_requests_pending(bs);
241 busy |= aio_poll(bdrv_get_aio_context(bs), busy);
242 }
243 }
244
245 static void bdrv_co_drain_bh_cb(void *opaque)
246 {
247 BdrvCoDrainData *data = opaque;
248 Coroutine *co = data->co;
249
250 qemu_bh_delete(data->bh);
251 bdrv_drain_poll(data->bs);
252 data->done = true;
253 qemu_coroutine_enter(co, NULL);
254 }
255
256 static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs)
257 {
258 BdrvCoDrainData data;
259
260 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
261 * other coroutines run if they were queued from
262 * qemu_co_queue_run_restart(). */
263
264 assert(qemu_in_coroutine());
265 data = (BdrvCoDrainData) {
266 .co = qemu_coroutine_self(),
267 .bs = bs,
268 .done = false,
269 .bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_drain_bh_cb, &data),
270 };
271 qemu_bh_schedule(data.bh);
272
273 qemu_coroutine_yield();
274 /* If we are resumed from some other event (such as an aio completion or a
275 * timer callback), it is a bug in the caller that should be fixed. */
276 assert(data.done);
277 }
278
279 /*
280 * Wait for pending requests to complete on a single BlockDriverState subtree,
281 * and suspend block driver's internal I/O until next request arrives.
282 *
283 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
284 * AioContext.
285 *
286 * Only this BlockDriverState's AioContext is run, so in-flight requests must
287 * not depend on events in other AioContexts. In that case, use
288 * bdrv_drain_all() instead.
289 */
290 void coroutine_fn bdrv_co_drain(BlockDriverState *bs)
291 {
292 bdrv_no_throttling_begin(bs);
293 bdrv_io_unplugged_begin(bs);
294 bdrv_drain_recurse(bs);
295 bdrv_co_yield_to_drain(bs);
296 bdrv_io_unplugged_end(bs);
297 bdrv_no_throttling_end(bs);
298 }
299
300 void bdrv_drain(BlockDriverState *bs)
301 {
302 bdrv_no_throttling_begin(bs);
303 bdrv_io_unplugged_begin(bs);
304 bdrv_drain_recurse(bs);
305 if (qemu_in_coroutine()) {
306 bdrv_co_yield_to_drain(bs);
307 } else {
308 bdrv_drain_poll(bs);
309 }
310 bdrv_io_unplugged_end(bs);
311 bdrv_no_throttling_end(bs);
312 }
313
314 /*
315 * Wait for pending requests to complete across all BlockDriverStates
316 *
317 * This function does not flush data to disk, use bdrv_flush_all() for that
318 * after calling this function.
319 */
320 void bdrv_drain_all(void)
321 {
322 /* Always run first iteration so any pending completion BHs run */
323 bool busy = true;
324 BlockDriverState *bs = NULL;
325 GSList *aio_ctxs = NULL, *ctx;
326
327 while ((bs = bdrv_next(bs))) {
328 AioContext *aio_context = bdrv_get_aio_context(bs);
329
330 aio_context_acquire(aio_context);
331 if (bs->job) {
332 block_job_pause(bs->job);
333 }
334 bdrv_no_throttling_begin(bs);
335 bdrv_io_unplugged_begin(bs);
336 bdrv_drain_recurse(bs);
337 aio_context_release(aio_context);
338
339 if (!g_slist_find(aio_ctxs, aio_context)) {
340 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
341 }
342 }
343
344 /* Note that completion of an asynchronous I/O operation can trigger any
345 * number of other I/O operations on other devices---for example a
346 * coroutine can submit an I/O request to another device in response to
347 * request completion. Therefore we must keep looping until there was no
348 * more activity rather than simply draining each device independently.
349 */
350 while (busy) {
351 busy = false;
352
353 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
354 AioContext *aio_context = ctx->data;
355 bs = NULL;
356
357 aio_context_acquire(aio_context);
358 while ((bs = bdrv_next(bs))) {
359 if (aio_context == bdrv_get_aio_context(bs)) {
360 if (bdrv_requests_pending(bs)) {
361 busy = true;
362 aio_poll(aio_context, busy);
363 }
364 }
365 }
366 busy |= aio_poll(aio_context, false);
367 aio_context_release(aio_context);
368 }
369 }
370
371 bs = NULL;
372 while ((bs = bdrv_next(bs))) {
373 AioContext *aio_context = bdrv_get_aio_context(bs);
374
375 aio_context_acquire(aio_context);
376 bdrv_io_unplugged_end(bs);
377 bdrv_no_throttling_end(bs);
378 if (bs->job) {
379 block_job_resume(bs->job);
380 }
381 aio_context_release(aio_context);
382 }
383 g_slist_free(aio_ctxs);
384 }
385
386 /**
387 * Remove an active request from the tracked requests list
388 *
389 * This function should be called when a tracked request is completing.
390 */
391 static void tracked_request_end(BdrvTrackedRequest *req)
392 {
393 if (req->serialising) {
394 req->bs->serialising_in_flight--;
395 }
396
397 QLIST_REMOVE(req, list);
398 qemu_co_queue_restart_all(&req->wait_queue);
399 }
400
401 /**
402 * Add an active request to the tracked requests list
403 */
404 static void tracked_request_begin(BdrvTrackedRequest *req,
405 BlockDriverState *bs,
406 int64_t offset,
407 unsigned int bytes,
408 enum BdrvTrackedRequestType type)
409 {
410 *req = (BdrvTrackedRequest){
411 .bs = bs,
412 .offset = offset,
413 .bytes = bytes,
414 .type = type,
415 .co = qemu_coroutine_self(),
416 .serialising = false,
417 .overlap_offset = offset,
418 .overlap_bytes = bytes,
419 };
420
421 qemu_co_queue_init(&req->wait_queue);
422
423 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
424 }
425
426 static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
427 {
428 int64_t overlap_offset = req->offset & ~(align - 1);
429 unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
430 - overlap_offset;
431
432 if (!req->serialising) {
433 req->bs->serialising_in_flight++;
434 req->serialising = true;
435 }
436
437 req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
438 req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
439 }
440
441 /**
442 * Round a region to cluster boundaries
443 */
444 void bdrv_round_to_clusters(BlockDriverState *bs,
445 int64_t sector_num, int nb_sectors,
446 int64_t *cluster_sector_num,
447 int *cluster_nb_sectors)
448 {
449 BlockDriverInfo bdi;
450
451 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
452 *cluster_sector_num = sector_num;
453 *cluster_nb_sectors = nb_sectors;
454 } else {
455 int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
456 *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
457 *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
458 nb_sectors, c);
459 }
460 }
461
462 static int bdrv_get_cluster_size(BlockDriverState *bs)
463 {
464 BlockDriverInfo bdi;
465 int ret;
466
467 ret = bdrv_get_info(bs, &bdi);
468 if (ret < 0 || bdi.cluster_size == 0) {
469 return bs->request_alignment;
470 } else {
471 return bdi.cluster_size;
472 }
473 }
474
475 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
476 int64_t offset, unsigned int bytes)
477 {
478 /* aaaa bbbb */
479 if (offset >= req->overlap_offset + req->overlap_bytes) {
480 return false;
481 }
482 /* bbbb aaaa */
483 if (req->overlap_offset >= offset + bytes) {
484 return false;
485 }
486 return true;
487 }
488
489 static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
490 {
491 BlockDriverState *bs = self->bs;
492 BdrvTrackedRequest *req;
493 bool retry;
494 bool waited = false;
495
496 if (!bs->serialising_in_flight) {
497 return false;
498 }
499
500 do {
501 retry = false;
502 QLIST_FOREACH(req, &bs->tracked_requests, list) {
503 if (req == self || (!req->serialising && !self->serialising)) {
504 continue;
505 }
506 if (tracked_request_overlaps(req, self->overlap_offset,
507 self->overlap_bytes))
508 {
509 /* Hitting this means there was a reentrant request, for
510 * example, a block driver issuing nested requests. This must
511 * never happen since it means deadlock.
512 */
513 assert(qemu_coroutine_self() != req->co);
514
515 /* If the request is already (indirectly) waiting for us, or
516 * will wait for us as soon as it wakes up, then just go on
517 * (instead of producing a deadlock in the former case). */
518 if (!req->waiting_for) {
519 self->waiting_for = req;
520 qemu_co_queue_wait(&req->wait_queue);
521 self->waiting_for = NULL;
522 retry = true;
523 waited = true;
524 break;
525 }
526 }
527 }
528 } while (retry);
529
530 return waited;
531 }
532
533 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
534 size_t size)
535 {
536 if (size > BDRV_REQUEST_MAX_SECTORS << BDRV_SECTOR_BITS) {
537 return -EIO;
538 }
539
540 if (!bdrv_is_inserted(bs)) {
541 return -ENOMEDIUM;
542 }
543
544 if (offset < 0) {
545 return -EIO;
546 }
547
548 return 0;
549 }
550
551 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
552 int nb_sectors)
553 {
554 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
555 return -EIO;
556 }
557
558 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
559 nb_sectors * BDRV_SECTOR_SIZE);
560 }
561
562 typedef struct RwCo {
563 BlockDriverState *bs;
564 int64_t offset;
565 QEMUIOVector *qiov;
566 bool is_write;
567 int ret;
568 BdrvRequestFlags flags;
569 } RwCo;
570
571 static void coroutine_fn bdrv_rw_co_entry(void *opaque)
572 {
573 RwCo *rwco = opaque;
574
575 if (!rwco->is_write) {
576 rwco->ret = bdrv_co_preadv(rwco->bs, rwco->offset,
577 rwco->qiov->size, rwco->qiov,
578 rwco->flags);
579 } else {
580 rwco->ret = bdrv_co_pwritev(rwco->bs, rwco->offset,
581 rwco->qiov->size, rwco->qiov,
582 rwco->flags);
583 }
584 }
585
586 /*
587 * Process a vectored synchronous request using coroutines
588 */
589 static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,
590 QEMUIOVector *qiov, bool is_write,
591 BdrvRequestFlags flags)
592 {
593 Coroutine *co;
594 RwCo rwco = {
595 .bs = bs,
596 .offset = offset,
597 .qiov = qiov,
598 .is_write = is_write,
599 .ret = NOT_DONE,
600 .flags = flags,
601 };
602
603 if (qemu_in_coroutine()) {
604 /* Fast-path if already in coroutine context */
605 bdrv_rw_co_entry(&rwco);
606 } else {
607 AioContext *aio_context = bdrv_get_aio_context(bs);
608
609 co = qemu_coroutine_create(bdrv_rw_co_entry);
610 qemu_coroutine_enter(co, &rwco);
611 while (rwco.ret == NOT_DONE) {
612 aio_poll(aio_context, true);
613 }
614 }
615 return rwco.ret;
616 }
617
618 /*
619 * Process a synchronous request using coroutines
620 */
621 static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
622 int nb_sectors, bool is_write, BdrvRequestFlags flags)
623 {
624 QEMUIOVector qiov;
625 struct iovec iov = {
626 .iov_base = (void *)buf,
627 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
628 };
629
630 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
631 return -EINVAL;
632 }
633
634 qemu_iovec_init_external(&qiov, &iov, 1);
635 return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
636 &qiov, is_write, flags);
637 }
638
639 /* return < 0 if error. See bdrv_write() for the return codes */
640 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
641 uint8_t *buf, int nb_sectors)
642 {
643 return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
644 }
645
646 /* Return < 0 if error. Important errors are:
647 -EIO generic I/O error (may happen for all errors)
648 -ENOMEDIUM No media inserted.
649 -EINVAL Invalid sector number or nb_sectors
650 -EACCES Trying to write a read-only device
651 */
652 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
653 const uint8_t *buf, int nb_sectors)
654 {
655 return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
656 }
657
658 int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
659 int nb_sectors, BdrvRequestFlags flags)
660 {
661 return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
662 BDRV_REQ_ZERO_WRITE | flags);
663 }
664
665 /*
666 * Completely zero out a block device with the help of bdrv_write_zeroes.
667 * The operation is sped up by checking the block status and only writing
668 * zeroes to the device if they currently do not return zeroes. Optional
669 * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
670 * BDRV_REQ_FUA).
671 *
672 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
673 */
674 int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
675 {
676 int64_t target_sectors, ret, nb_sectors, sector_num = 0;
677 BlockDriverState *file;
678 int n;
679
680 target_sectors = bdrv_nb_sectors(bs);
681 if (target_sectors < 0) {
682 return target_sectors;
683 }
684
685 for (;;) {
686 nb_sectors = MIN(target_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
687 if (nb_sectors <= 0) {
688 return 0;
689 }
690 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n, &file);
691 if (ret < 0) {
692 error_report("error getting block status at sector %" PRId64 ": %s",
693 sector_num, strerror(-ret));
694 return ret;
695 }
696 if (ret & BDRV_BLOCK_ZERO) {
697 sector_num += n;
698 continue;
699 }
700 ret = bdrv_write_zeroes(bs, sector_num, n, flags);
701 if (ret < 0) {
702 error_report("error writing zeroes at sector %" PRId64 ": %s",
703 sector_num, strerror(-ret));
704 return ret;
705 }
706 sector_num += n;
707 }
708 }
709
710 int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes)
711 {
712 QEMUIOVector qiov;
713 struct iovec iov = {
714 .iov_base = (void *)buf,
715 .iov_len = bytes,
716 };
717 int ret;
718
719 if (bytes < 0) {
720 return -EINVAL;
721 }
722
723 qemu_iovec_init_external(&qiov, &iov, 1);
724 ret = bdrv_prwv_co(bs, offset, &qiov, false, 0);
725 if (ret < 0) {
726 return ret;
727 }
728
729 return bytes;
730 }
731
732 int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
733 {
734 int ret;
735
736 ret = bdrv_prwv_co(bs, offset, qiov, true, 0);
737 if (ret < 0) {
738 return ret;
739 }
740
741 return qiov->size;
742 }
743
744 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
745 const void *buf, int bytes)
746 {
747 QEMUIOVector qiov;
748 struct iovec iov = {
749 .iov_base = (void *) buf,
750 .iov_len = bytes,
751 };
752
753 if (bytes < 0) {
754 return -EINVAL;
755 }
756
757 qemu_iovec_init_external(&qiov, &iov, 1);
758 return bdrv_pwritev(bs, offset, &qiov);
759 }
760
761 /*
762 * Writes to the file and ensures that no writes are reordered across this
763 * request (acts as a barrier)
764 *
765 * Returns 0 on success, -errno in error cases.
766 */
767 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
768 const void *buf, int count)
769 {
770 int ret;
771
772 ret = bdrv_pwrite(bs, offset, buf, count);
773 if (ret < 0) {
774 return ret;
775 }
776
777 ret = bdrv_flush(bs);
778 if (ret < 0) {
779 return ret;
780 }
781
782 return 0;
783 }
784
785 typedef struct CoroutineIOCompletion {
786 Coroutine *coroutine;
787 int ret;
788 } CoroutineIOCompletion;
789
790 static void bdrv_co_io_em_complete(void *opaque, int ret)
791 {
792 CoroutineIOCompletion *co = opaque;
793
794 co->ret = ret;
795 qemu_coroutine_enter(co->coroutine, NULL);
796 }
797
798 static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
799 uint64_t offset, uint64_t bytes,
800 QEMUIOVector *qiov, int flags)
801 {
802 BlockDriver *drv = bs->drv;
803 int64_t sector_num;
804 unsigned int nb_sectors;
805
806 if (drv->bdrv_co_preadv) {
807 return drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
808 }
809
810 sector_num = offset >> BDRV_SECTOR_BITS;
811 nb_sectors = bytes >> BDRV_SECTOR_BITS;
812
813 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
814 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
815 assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
816
817 if (drv->bdrv_co_readv) {
818 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
819 } else {
820 BlockAIOCB *acb;
821 CoroutineIOCompletion co = {
822 .coroutine = qemu_coroutine_self(),
823 };
824
825 acb = bs->drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
826 bdrv_co_io_em_complete, &co);
827 if (acb == NULL) {
828 return -EIO;
829 } else {
830 qemu_coroutine_yield();
831 return co.ret;
832 }
833 }
834 }
835
836 static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,
837 uint64_t offset, uint64_t bytes,
838 QEMUIOVector *qiov, int flags)
839 {
840 BlockDriver *drv = bs->drv;
841 int64_t sector_num;
842 unsigned int nb_sectors;
843 int ret;
844
845 if (drv->bdrv_co_pwritev) {
846 ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov, flags);
847 goto emulate_flags;
848 }
849
850 sector_num = offset >> BDRV_SECTOR_BITS;
851 nb_sectors = bytes >> BDRV_SECTOR_BITS;
852
853 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
854 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
855 assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
856
857 if (drv->bdrv_co_writev_flags) {
858 ret = drv->bdrv_co_writev_flags(bs, sector_num, nb_sectors, qiov,
859 flags & bs->supported_write_flags);
860 flags &= ~bs->supported_write_flags;
861 } else if (drv->bdrv_co_writev) {
862 assert(!bs->supported_write_flags);
863 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
864 } else {
865 BlockAIOCB *acb;
866 CoroutineIOCompletion co = {
867 .coroutine = qemu_coroutine_self(),
868 };
869
870 acb = bs->drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
871 bdrv_co_io_em_complete, &co);
872 if (acb == NULL) {
873 ret = -EIO;
874 } else {
875 qemu_coroutine_yield();
876 ret = co.ret;
877 }
878 }
879
880 emulate_flags:
881 if (ret == 0 && (flags & BDRV_REQ_FUA)) {
882 ret = bdrv_co_flush(bs);
883 }
884
885 return ret;
886 }
887
888 static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
889 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
890 {
891 /* Perform I/O through a temporary buffer so that users who scribble over
892 * their read buffer while the operation is in progress do not end up
893 * modifying the image file. This is critical for zero-copy guest I/O
894 * where anything might happen inside guest memory.
895 */
896 void *bounce_buffer;
897
898 BlockDriver *drv = bs->drv;
899 struct iovec iov;
900 QEMUIOVector bounce_qiov;
901 int64_t cluster_sector_num;
902 int cluster_nb_sectors;
903 size_t skip_bytes;
904 int ret;
905
906 /* Cover entire cluster so no additional backing file I/O is required when
907 * allocating cluster in the image file.
908 */
909 bdrv_round_to_clusters(bs, sector_num, nb_sectors,
910 &cluster_sector_num, &cluster_nb_sectors);
911
912 trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
913 cluster_sector_num, cluster_nb_sectors);
914
915 iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
916 iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len);
917 if (bounce_buffer == NULL) {
918 ret = -ENOMEM;
919 goto err;
920 }
921
922 qemu_iovec_init_external(&bounce_qiov, &iov, 1);
923
924 ret = bdrv_driver_preadv(bs, cluster_sector_num * BDRV_SECTOR_SIZE,
925 cluster_nb_sectors * BDRV_SECTOR_SIZE,
926 &bounce_qiov, 0);
927 if (ret < 0) {
928 goto err;
929 }
930
931 if (drv->bdrv_co_write_zeroes &&
932 buffer_is_zero(bounce_buffer, iov.iov_len)) {
933 ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
934 cluster_nb_sectors, 0);
935 } else {
936 /* This does not change the data on the disk, it is not necessary
937 * to flush even in cache=writethrough mode.
938 */
939 ret = bdrv_driver_pwritev(bs, cluster_sector_num * BDRV_SECTOR_SIZE,
940 cluster_nb_sectors * BDRV_SECTOR_SIZE,
941 &bounce_qiov, 0);
942 }
943
944 if (ret < 0) {
945 /* It might be okay to ignore write errors for guest requests. If this
946 * is a deliberate copy-on-read then we don't want to ignore the error.
947 * Simply report it in all cases.
948 */
949 goto err;
950 }
951
952 skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
953 qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
954 nb_sectors * BDRV_SECTOR_SIZE);
955
956 err:
957 qemu_vfree(bounce_buffer);
958 return ret;
959 }
960
961 /*
962 * Forwards an already correctly aligned request to the BlockDriver. This
963 * handles copy on read and zeroing after EOF; any other features must be
964 * implemented by the caller.
965 */
966 static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
967 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
968 int64_t align, QEMUIOVector *qiov, int flags)
969 {
970 int ret;
971
972 int64_t sector_num = offset >> BDRV_SECTOR_BITS;
973 unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
974
975 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
976 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
977 assert(!qiov || bytes == qiov->size);
978 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
979
980 /* Handle Copy on Read and associated serialisation */
981 if (flags & BDRV_REQ_COPY_ON_READ) {
982 /* If we touch the same cluster it counts as an overlap. This
983 * guarantees that allocating writes will be serialized and not race
984 * with each other for the same cluster. For example, in copy-on-read
985 * it ensures that the CoR read and write operations are atomic and
986 * guest writes cannot interleave between them. */
987 mark_request_serialising(req, bdrv_get_cluster_size(bs));
988 }
989
990 if (!(flags & BDRV_REQ_NO_SERIALISING)) {
991 wait_serialising_requests(req);
992 }
993
994 if (flags & BDRV_REQ_COPY_ON_READ) {
995 int pnum;
996
997 ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
998 if (ret < 0) {
999 goto out;
1000 }
1001
1002 if (!ret || pnum != nb_sectors) {
1003 ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
1004 goto out;
1005 }
1006 }
1007
1008 /* Forward the request to the BlockDriver */
1009 if (!bs->zero_beyond_eof) {
1010 ret = bdrv_driver_preadv(bs, offset, bytes, qiov, 0);
1011 } else {
1012 /* Read zeros after EOF */
1013 int64_t total_sectors, max_nb_sectors;
1014
1015 total_sectors = bdrv_nb_sectors(bs);
1016 if (total_sectors < 0) {
1017 ret = total_sectors;
1018 goto out;
1019 }
1020
1021 max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num),
1022 align >> BDRV_SECTOR_BITS);
1023 if (nb_sectors < max_nb_sectors) {
1024 ret = bdrv_driver_preadv(bs, offset, bytes, qiov, 0);
1025 } else if (max_nb_sectors > 0) {
1026 QEMUIOVector local_qiov;
1027
1028 qemu_iovec_init(&local_qiov, qiov->niov);
1029 qemu_iovec_concat(&local_qiov, qiov, 0,
1030 max_nb_sectors * BDRV_SECTOR_SIZE);
1031
1032 ret = bdrv_driver_preadv(bs, offset,
1033 max_nb_sectors * BDRV_SECTOR_SIZE,
1034 &local_qiov, 0);
1035
1036 qemu_iovec_destroy(&local_qiov);
1037 } else {
1038 ret = 0;
1039 }
1040
1041 /* Reading beyond end of file is supposed to produce zeroes */
1042 if (ret == 0 && total_sectors < sector_num + nb_sectors) {
1043 uint64_t offset = MAX(0, total_sectors - sector_num);
1044 uint64_t bytes = (sector_num + nb_sectors - offset) *
1045 BDRV_SECTOR_SIZE;
1046 qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
1047 }
1048 }
1049
1050 out:
1051 return ret;
1052 }
1053
1054 /*
1055 * Handle a read request in coroutine context
1056 */
1057 int coroutine_fn bdrv_co_preadv(BlockDriverState *bs,
1058 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1059 BdrvRequestFlags flags)
1060 {
1061 BlockDriver *drv = bs->drv;
1062 BdrvTrackedRequest req;
1063
1064 /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
1065 uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
1066 uint8_t *head_buf = NULL;
1067 uint8_t *tail_buf = NULL;
1068 QEMUIOVector local_qiov;
1069 bool use_local_qiov = false;
1070 int ret;
1071
1072 if (!drv) {
1073 return -ENOMEDIUM;
1074 }
1075
1076 ret = bdrv_check_byte_request(bs, offset, bytes);
1077 if (ret < 0) {
1078 return ret;
1079 }
1080
1081 /* Don't do copy-on-read if we read data before write operation */
1082 if (bs->copy_on_read && !(flags & BDRV_REQ_NO_SERIALISING)) {
1083 flags |= BDRV_REQ_COPY_ON_READ;
1084 }
1085
1086 /* throttling disk I/O */
1087 if (bs->blk && blk_get_public(bs->blk)->throttle_state) {
1088 throttle_group_co_io_limits_intercept(bs, bytes, false);
1089 }
1090
1091 /* Align read if necessary by padding qiov */
1092 if (offset & (align - 1)) {
1093 head_buf = qemu_blockalign(bs, align);
1094 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1095 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1096 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1097 use_local_qiov = true;
1098
1099 bytes += offset & (align - 1);
1100 offset = offset & ~(align - 1);
1101 }
1102
1103 if ((offset + bytes) & (align - 1)) {
1104 if (!use_local_qiov) {
1105 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1106 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1107 use_local_qiov = true;
1108 }
1109 tail_buf = qemu_blockalign(bs, align);
1110 qemu_iovec_add(&local_qiov, tail_buf,
1111 align - ((offset + bytes) & (align - 1)));
1112
1113 bytes = ROUND_UP(bytes, align);
1114 }
1115
1116 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
1117 ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
1118 use_local_qiov ? &local_qiov : qiov,
1119 flags);
1120 tracked_request_end(&req);
1121
1122 if (use_local_qiov) {
1123 qemu_iovec_destroy(&local_qiov);
1124 qemu_vfree(head_buf);
1125 qemu_vfree(tail_buf);
1126 }
1127
1128 return ret;
1129 }
1130
1131 static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
1132 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1133 BdrvRequestFlags flags)
1134 {
1135 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1136 return -EINVAL;
1137 }
1138
1139 return bdrv_co_preadv(bs, sector_num << BDRV_SECTOR_BITS,
1140 nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
1141 }
1142
1143 int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1144 int nb_sectors, QEMUIOVector *qiov)
1145 {
1146 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1147
1148 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
1149 }
1150
1151 int coroutine_fn bdrv_co_readv_no_serialising(BlockDriverState *bs,
1152 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
1153 {
1154 trace_bdrv_co_readv_no_serialising(bs, sector_num, nb_sectors);
1155
1156 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
1157 BDRV_REQ_NO_SERIALISING);
1158 }
1159
1160 int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
1161 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
1162 {
1163 trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
1164
1165 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
1166 BDRV_REQ_COPY_ON_READ);
1167 }
1168
1169 #define MAX_WRITE_ZEROES_BOUNCE_BUFFER 32768
1170
1171 static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
1172 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1173 {
1174 BlockDriver *drv = bs->drv;
1175 QEMUIOVector qiov;
1176 struct iovec iov = {0};
1177 int ret = 0;
1178 bool need_flush = false;
1179
1180 int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_write_zeroes,
1181 BDRV_REQUEST_MAX_SECTORS);
1182
1183 while (nb_sectors > 0 && !ret) {
1184 int num = nb_sectors;
1185
1186 /* Align request. Block drivers can expect the "bulk" of the request
1187 * to be aligned.
1188 */
1189 if (bs->bl.write_zeroes_alignment
1190 && num > bs->bl.write_zeroes_alignment) {
1191 if (sector_num % bs->bl.write_zeroes_alignment != 0) {
1192 /* Make a small request up to the first aligned sector. */
1193 num = bs->bl.write_zeroes_alignment;
1194 num -= sector_num % bs->bl.write_zeroes_alignment;
1195 } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
1196 /* Shorten the request to the last aligned sector. num cannot
1197 * underflow because num > bs->bl.write_zeroes_alignment.
1198 */
1199 num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
1200 }
1201 }
1202
1203 /* limit request size */
1204 if (num > max_write_zeroes) {
1205 num = max_write_zeroes;
1206 }
1207
1208 ret = -ENOTSUP;
1209 /* First try the efficient write zeroes operation */
1210 if (drv->bdrv_co_write_zeroes) {
1211 ret = drv->bdrv_co_write_zeroes(bs, sector_num, num,
1212 flags & bs->supported_zero_flags);
1213 if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1214 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1215 need_flush = true;
1216 }
1217 } else {
1218 assert(!bs->supported_zero_flags);
1219 }
1220
1221 if (ret == -ENOTSUP) {
1222 /* Fall back to bounce buffer if write zeroes is unsupported */
1223 int max_xfer_len = MIN_NON_ZERO(bs->bl.max_transfer_length,
1224 MAX_WRITE_ZEROES_BOUNCE_BUFFER);
1225 BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1226
1227 if ((flags & BDRV_REQ_FUA) &&
1228 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1229 /* No need for bdrv_driver_pwrite() to do a fallback
1230 * flush on each chunk; use just one at the end */
1231 write_flags &= ~BDRV_REQ_FUA;
1232 need_flush = true;
1233 }
1234 num = MIN(num, max_xfer_len);
1235 iov.iov_len = num * BDRV_SECTOR_SIZE;
1236 if (iov.iov_base == NULL) {
1237 iov.iov_base = qemu_try_blockalign(bs, num * BDRV_SECTOR_SIZE);
1238 if (iov.iov_base == NULL) {
1239 ret = -ENOMEM;
1240 goto fail;
1241 }
1242 memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
1243 }
1244 qemu_iovec_init_external(&qiov, &iov, 1);
1245
1246 ret = bdrv_driver_pwritev(bs, sector_num * BDRV_SECTOR_SIZE,
1247 num * BDRV_SECTOR_SIZE, &qiov,
1248 write_flags);
1249
1250 /* Keep bounce buffer around if it is big enough for all
1251 * all future requests.
1252 */
1253 if (num < max_xfer_len) {
1254 qemu_vfree(iov.iov_base);
1255 iov.iov_base = NULL;
1256 }
1257 }
1258
1259 sector_num += num;
1260 nb_sectors -= num;
1261 }
1262
1263 fail:
1264 if (ret == 0 && need_flush) {
1265 ret = bdrv_co_flush(bs);
1266 }
1267 qemu_vfree(iov.iov_base);
1268 return ret;
1269 }
1270
1271 /*
1272 * Forwards an already correctly aligned write request to the BlockDriver.
1273 */
1274 static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
1275 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1276 QEMUIOVector *qiov, int flags)
1277 {
1278 BlockDriver *drv = bs->drv;
1279 bool waited;
1280 int ret;
1281
1282 int64_t sector_num = offset >> BDRV_SECTOR_BITS;
1283 unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
1284
1285 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1286 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1287 assert(!qiov || bytes == qiov->size);
1288 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1289
1290 waited = wait_serialising_requests(req);
1291 assert(!waited || !req->serialising);
1292 assert(req->overlap_offset <= offset);
1293 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
1294
1295 ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
1296
1297 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
1298 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_write_zeroes &&
1299 qemu_iovec_is_zero(qiov)) {
1300 flags |= BDRV_REQ_ZERO_WRITE;
1301 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
1302 flags |= BDRV_REQ_MAY_UNMAP;
1303 }
1304 }
1305
1306 if (ret < 0) {
1307 /* Do nothing, write notifier decided to fail this request */
1308 } else if (flags & BDRV_REQ_ZERO_WRITE) {
1309 bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
1310 ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
1311 } else {
1312 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1313 ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, flags);
1314 }
1315 bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
1316
1317 bdrv_set_dirty(bs, sector_num, nb_sectors);
1318
1319 if (bs->wr_highest_offset < offset + bytes) {
1320 bs->wr_highest_offset = offset + bytes;
1321 }
1322
1323 if (ret >= 0) {
1324 bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
1325 }
1326
1327 return ret;
1328 }
1329
1330 static int coroutine_fn bdrv_co_do_zero_pwritev(BlockDriverState *bs,
1331 int64_t offset,
1332 unsigned int bytes,
1333 BdrvRequestFlags flags,
1334 BdrvTrackedRequest *req)
1335 {
1336 uint8_t *buf = NULL;
1337 QEMUIOVector local_qiov;
1338 struct iovec iov;
1339 uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
1340 unsigned int head_padding_bytes, tail_padding_bytes;
1341 int ret = 0;
1342
1343 head_padding_bytes = offset & (align - 1);
1344 tail_padding_bytes = align - ((offset + bytes) & (align - 1));
1345
1346
1347 assert(flags & BDRV_REQ_ZERO_WRITE);
1348 if (head_padding_bytes || tail_padding_bytes) {
1349 buf = qemu_blockalign(bs, align);
1350 iov = (struct iovec) {
1351 .iov_base = buf,
1352 .iov_len = align,
1353 };
1354 qemu_iovec_init_external(&local_qiov, &iov, 1);
1355 }
1356 if (head_padding_bytes) {
1357 uint64_t zero_bytes = MIN(bytes, align - head_padding_bytes);
1358
1359 /* RMW the unaligned part before head. */
1360 mark_request_serialising(req, align);
1361 wait_serialising_requests(req);
1362 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1363 ret = bdrv_aligned_preadv(bs, req, offset & ~(align - 1), align,
1364 align, &local_qiov, 0);
1365 if (ret < 0) {
1366 goto fail;
1367 }
1368 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1369
1370 memset(buf + head_padding_bytes, 0, zero_bytes);
1371 ret = bdrv_aligned_pwritev(bs, req, offset & ~(align - 1), align,
1372 &local_qiov,
1373 flags & ~BDRV_REQ_ZERO_WRITE);
1374 if (ret < 0) {
1375 goto fail;
1376 }
1377 offset += zero_bytes;
1378 bytes -= zero_bytes;
1379 }
1380
1381 assert(!bytes || (offset & (align - 1)) == 0);
1382 if (bytes >= align) {
1383 /* Write the aligned part in the middle. */
1384 uint64_t aligned_bytes = bytes & ~(align - 1);
1385 ret = bdrv_aligned_pwritev(bs, req, offset, aligned_bytes,
1386 NULL, flags);
1387 if (ret < 0) {
1388 goto fail;
1389 }
1390 bytes -= aligned_bytes;
1391 offset += aligned_bytes;
1392 }
1393
1394 assert(!bytes || (offset & (align - 1)) == 0);
1395 if (bytes) {
1396 assert(align == tail_padding_bytes + bytes);
1397 /* RMW the unaligned part after tail. */
1398 mark_request_serialising(req, align);
1399 wait_serialising_requests(req);
1400 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1401 ret = bdrv_aligned_preadv(bs, req, offset, align,
1402 align, &local_qiov, 0);
1403 if (ret < 0) {
1404 goto fail;
1405 }
1406 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1407
1408 memset(buf, 0, bytes);
1409 ret = bdrv_aligned_pwritev(bs, req, offset, align,
1410 &local_qiov, flags & ~BDRV_REQ_ZERO_WRITE);
1411 }
1412 fail:
1413 qemu_vfree(buf);
1414 return ret;
1415
1416 }
1417
1418 /*
1419 * Handle a write request in coroutine context
1420 */
1421 int coroutine_fn bdrv_co_pwritev(BlockDriverState *bs,
1422 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1423 BdrvRequestFlags flags)
1424 {
1425 BdrvTrackedRequest req;
1426 /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
1427 uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
1428 uint8_t *head_buf = NULL;
1429 uint8_t *tail_buf = NULL;
1430 QEMUIOVector local_qiov;
1431 bool use_local_qiov = false;
1432 int ret;
1433
1434 if (!bs->drv) {
1435 return -ENOMEDIUM;
1436 }
1437 if (bs->read_only) {
1438 return -EPERM;
1439 }
1440 assert(!(bs->open_flags & BDRV_O_INACTIVE));
1441
1442 ret = bdrv_check_byte_request(bs, offset, bytes);
1443 if (ret < 0) {
1444 return ret;
1445 }
1446
1447 /* throttling disk I/O */
1448 if (bs->blk && blk_get_public(bs->blk)->throttle_state) {
1449 throttle_group_co_io_limits_intercept(bs, bytes, true);
1450 }
1451
1452 /*
1453 * Align write if necessary by performing a read-modify-write cycle.
1454 * Pad qiov with the read parts and be sure to have a tracked request not
1455 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1456 */
1457 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
1458
1459 if (!qiov) {
1460 ret = bdrv_co_do_zero_pwritev(bs, offset, bytes, flags, &req);
1461 goto out;
1462 }
1463
1464 if (offset & (align - 1)) {
1465 QEMUIOVector head_qiov;
1466 struct iovec head_iov;
1467
1468 mark_request_serialising(&req, align);
1469 wait_serialising_requests(&req);
1470
1471 head_buf = qemu_blockalign(bs, align);
1472 head_iov = (struct iovec) {
1473 .iov_base = head_buf,
1474 .iov_len = align,
1475 };
1476 qemu_iovec_init_external(&head_qiov, &head_iov, 1);
1477
1478 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1479 ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
1480 align, &head_qiov, 0);
1481 if (ret < 0) {
1482 goto fail;
1483 }
1484 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1485
1486 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1487 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1488 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1489 use_local_qiov = true;
1490
1491 bytes += offset & (align - 1);
1492 offset = offset & ~(align - 1);
1493 }
1494
1495 if ((offset + bytes) & (align - 1)) {
1496 QEMUIOVector tail_qiov;
1497 struct iovec tail_iov;
1498 size_t tail_bytes;
1499 bool waited;
1500
1501 mark_request_serialising(&req, align);
1502 waited = wait_serialising_requests(&req);
1503 assert(!waited || !use_local_qiov);
1504
1505 tail_buf = qemu_blockalign(bs, align);
1506 tail_iov = (struct iovec) {
1507 .iov_base = tail_buf,
1508 .iov_len = align,
1509 };
1510 qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
1511
1512 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1513 ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
1514 align, &tail_qiov, 0);
1515 if (ret < 0) {
1516 goto fail;
1517 }
1518 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1519
1520 if (!use_local_qiov) {
1521 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1522 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1523 use_local_qiov = true;
1524 }
1525
1526 tail_bytes = (offset + bytes) & (align - 1);
1527 qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
1528
1529 bytes = ROUND_UP(bytes, align);
1530 }
1531
1532 ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,
1533 use_local_qiov ? &local_qiov : qiov,
1534 flags);
1535
1536 fail:
1537
1538 if (use_local_qiov) {
1539 qemu_iovec_destroy(&local_qiov);
1540 }
1541 qemu_vfree(head_buf);
1542 qemu_vfree(tail_buf);
1543 out:
1544 tracked_request_end(&req);
1545 return ret;
1546 }
1547
1548 static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
1549 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1550 BdrvRequestFlags flags)
1551 {
1552 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1553 return -EINVAL;
1554 }
1555
1556 return bdrv_co_pwritev(bs, sector_num << BDRV_SECTOR_BITS,
1557 nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
1558 }
1559
1560 int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1561 int nb_sectors, QEMUIOVector *qiov)
1562 {
1563 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1564
1565 return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
1566 }
1567
1568 int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
1569 int64_t sector_num, int nb_sectors,
1570 BdrvRequestFlags flags)
1571 {
1572 trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
1573
1574 if (!(bs->open_flags & BDRV_O_UNMAP)) {
1575 flags &= ~BDRV_REQ_MAY_UNMAP;
1576 }
1577
1578 return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
1579 BDRV_REQ_ZERO_WRITE | flags);
1580 }
1581
1582 typedef struct BdrvCoGetBlockStatusData {
1583 BlockDriverState *bs;
1584 BlockDriverState *base;
1585 BlockDriverState **file;
1586 int64_t sector_num;
1587 int nb_sectors;
1588 int *pnum;
1589 int64_t ret;
1590 bool done;
1591 } BdrvCoGetBlockStatusData;
1592
1593 /*
1594 * Returns the allocation status of the specified sectors.
1595 * Drivers not implementing the functionality are assumed to not support
1596 * backing files, hence all their sectors are reported as allocated.
1597 *
1598 * If 'sector_num' is beyond the end of the disk image the return value is 0
1599 * and 'pnum' is set to 0.
1600 *
1601 * 'pnum' is set to the number of sectors (including and immediately following
1602 * the specified sector) that are known to be in the same
1603 * allocated/unallocated state.
1604 *
1605 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1606 * beyond the end of the disk image it will be clamped.
1607 *
1608 * If returned value is positive and BDRV_BLOCK_OFFSET_VALID bit is set, 'file'
1609 * points to the BDS which the sector range is allocated in.
1610 */
1611 static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
1612 int64_t sector_num,
1613 int nb_sectors, int *pnum,
1614 BlockDriverState **file)
1615 {
1616 int64_t total_sectors;
1617 int64_t n;
1618 int64_t ret, ret2;
1619
1620 total_sectors = bdrv_nb_sectors(bs);
1621 if (total_sectors < 0) {
1622 return total_sectors;
1623 }
1624
1625 if (sector_num >= total_sectors) {
1626 *pnum = 0;
1627 return 0;
1628 }
1629
1630 n = total_sectors - sector_num;
1631 if (n < nb_sectors) {
1632 nb_sectors = n;
1633 }
1634
1635 if (!bs->drv->bdrv_co_get_block_status) {
1636 *pnum = nb_sectors;
1637 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
1638 if (bs->drv->protocol_name) {
1639 ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
1640 }
1641 return ret;
1642 }
1643
1644 *file = NULL;
1645 ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum,
1646 file);
1647 if (ret < 0) {
1648 *pnum = 0;
1649 return ret;
1650 }
1651
1652 if (ret & BDRV_BLOCK_RAW) {
1653 assert(ret & BDRV_BLOCK_OFFSET_VALID);
1654 return bdrv_get_block_status(bs->file->bs, ret >> BDRV_SECTOR_BITS,
1655 *pnum, pnum, file);
1656 }
1657
1658 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
1659 ret |= BDRV_BLOCK_ALLOCATED;
1660 } else {
1661 if (bdrv_unallocated_blocks_are_zero(bs)) {
1662 ret |= BDRV_BLOCK_ZERO;
1663 } else if (bs->backing) {
1664 BlockDriverState *bs2 = bs->backing->bs;
1665 int64_t nb_sectors2 = bdrv_nb_sectors(bs2);
1666 if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) {
1667 ret |= BDRV_BLOCK_ZERO;
1668 }
1669 }
1670 }
1671
1672 if (*file && *file != bs &&
1673 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
1674 (ret & BDRV_BLOCK_OFFSET_VALID)) {
1675 BlockDriverState *file2;
1676 int file_pnum;
1677
1678 ret2 = bdrv_co_get_block_status(*file, ret >> BDRV_SECTOR_BITS,
1679 *pnum, &file_pnum, &file2);
1680 if (ret2 >= 0) {
1681 /* Ignore errors. This is just providing extra information, it
1682 * is useful but not necessary.
1683 */
1684 if (!file_pnum) {
1685 /* !file_pnum indicates an offset at or beyond the EOF; it is
1686 * perfectly valid for the format block driver to point to such
1687 * offsets, so catch it and mark everything as zero */
1688 ret |= BDRV_BLOCK_ZERO;
1689 } else {
1690 /* Limit request to the range reported by the protocol driver */
1691 *pnum = file_pnum;
1692 ret |= (ret2 & BDRV_BLOCK_ZERO);
1693 }
1694 }
1695 }
1696
1697 return ret;
1698 }
1699
1700 static int64_t coroutine_fn bdrv_co_get_block_status_above(BlockDriverState *bs,
1701 BlockDriverState *base,
1702 int64_t sector_num,
1703 int nb_sectors,
1704 int *pnum,
1705 BlockDriverState **file)
1706 {
1707 BlockDriverState *p;
1708 int64_t ret = 0;
1709
1710 assert(bs != base);
1711 for (p = bs; p != base; p = backing_bs(p)) {
1712 ret = bdrv_co_get_block_status(p, sector_num, nb_sectors, pnum, file);
1713 if (ret < 0 || ret & BDRV_BLOCK_ALLOCATED) {
1714 break;
1715 }
1716 /* [sector_num, pnum] unallocated on this layer, which could be only
1717 * the first part of [sector_num, nb_sectors]. */
1718 nb_sectors = MIN(nb_sectors, *pnum);
1719 }
1720 return ret;
1721 }
1722
1723 /* Coroutine wrapper for bdrv_get_block_status_above() */
1724 static void coroutine_fn bdrv_get_block_status_above_co_entry(void *opaque)
1725 {
1726 BdrvCoGetBlockStatusData *data = opaque;
1727
1728 data->ret = bdrv_co_get_block_status_above(data->bs, data->base,
1729 data->sector_num,
1730 data->nb_sectors,
1731 data->pnum,
1732 data->file);
1733 data->done = true;
1734 }
1735
1736 /*
1737 * Synchronous wrapper around bdrv_co_get_block_status_above().
1738 *
1739 * See bdrv_co_get_block_status_above() for details.
1740 */
1741 int64_t bdrv_get_block_status_above(BlockDriverState *bs,
1742 BlockDriverState *base,
1743 int64_t sector_num,
1744 int nb_sectors, int *pnum,
1745 BlockDriverState **file)
1746 {
1747 Coroutine *co;
1748 BdrvCoGetBlockStatusData data = {
1749 .bs = bs,
1750 .base = base,
1751 .file = file,
1752 .sector_num = sector_num,
1753 .nb_sectors = nb_sectors,
1754 .pnum = pnum,
1755 .done = false,
1756 };
1757
1758 if (qemu_in_coroutine()) {
1759 /* Fast-path if already in coroutine context */
1760 bdrv_get_block_status_above_co_entry(&data);
1761 } else {
1762 AioContext *aio_context = bdrv_get_aio_context(bs);
1763
1764 co = qemu_coroutine_create(bdrv_get_block_status_above_co_entry);
1765 qemu_coroutine_enter(co, &data);
1766 while (!data.done) {
1767 aio_poll(aio_context, true);
1768 }
1769 }
1770 return data.ret;
1771 }
1772
1773 int64_t bdrv_get_block_status(BlockDriverState *bs,
1774 int64_t sector_num,
1775 int nb_sectors, int *pnum,
1776 BlockDriverState **file)
1777 {
1778 return bdrv_get_block_status_above(bs, backing_bs(bs),
1779 sector_num, nb_sectors, pnum, file);
1780 }
1781
1782 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
1783 int nb_sectors, int *pnum)
1784 {
1785 BlockDriverState *file;
1786 int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum,
1787 &file);
1788 if (ret < 0) {
1789 return ret;
1790 }
1791 return !!(ret & BDRV_BLOCK_ALLOCATED);
1792 }
1793
1794 /*
1795 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
1796 *
1797 * Return true if the given sector is allocated in any image between
1798 * BASE and TOP (inclusive). BASE can be NULL to check if the given
1799 * sector is allocated in any image of the chain. Return false otherwise.
1800 *
1801 * 'pnum' is set to the number of sectors (including and immediately following
1802 * the specified sector) that are known to be in the same
1803 * allocated/unallocated state.
1804 *
1805 */
1806 int bdrv_is_allocated_above(BlockDriverState *top,
1807 BlockDriverState *base,
1808 int64_t sector_num,
1809 int nb_sectors, int *pnum)
1810 {
1811 BlockDriverState *intermediate;
1812 int ret, n = nb_sectors;
1813
1814 intermediate = top;
1815 while (intermediate && intermediate != base) {
1816 int pnum_inter;
1817 ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
1818 &pnum_inter);
1819 if (ret < 0) {
1820 return ret;
1821 } else if (ret) {
1822 *pnum = pnum_inter;
1823 return 1;
1824 }
1825
1826 /*
1827 * [sector_num, nb_sectors] is unallocated on top but intermediate
1828 * might have
1829 *
1830 * [sector_num+x, nr_sectors] allocated.
1831 */
1832 if (n > pnum_inter &&
1833 (intermediate == top ||
1834 sector_num + pnum_inter < intermediate->total_sectors)) {
1835 n = pnum_inter;
1836 }
1837
1838 intermediate = backing_bs(intermediate);
1839 }
1840
1841 *pnum = n;
1842 return 0;
1843 }
1844
1845 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1846 const uint8_t *buf, int nb_sectors)
1847 {
1848 BlockDriver *drv = bs->drv;
1849 int ret;
1850
1851 if (!drv) {
1852 return -ENOMEDIUM;
1853 }
1854 if (!drv->bdrv_write_compressed) {
1855 return -ENOTSUP;
1856 }
1857 ret = bdrv_check_request(bs, sector_num, nb_sectors);
1858 if (ret < 0) {
1859 return ret;
1860 }
1861
1862 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
1863
1864 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1865 }
1866
1867 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1868 int64_t pos, int size)
1869 {
1870 QEMUIOVector qiov;
1871 struct iovec iov = {
1872 .iov_base = (void *) buf,
1873 .iov_len = size,
1874 };
1875
1876 qemu_iovec_init_external(&qiov, &iov, 1);
1877 return bdrv_writev_vmstate(bs, &qiov, pos);
1878 }
1879
1880 int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
1881 {
1882 BlockDriver *drv = bs->drv;
1883
1884 if (!drv) {
1885 return -ENOMEDIUM;
1886 } else if (drv->bdrv_save_vmstate) {
1887 return drv->bdrv_save_vmstate(bs, qiov, pos);
1888 } else if (bs->file) {
1889 return bdrv_writev_vmstate(bs->file->bs, qiov, pos);
1890 }
1891
1892 return -ENOTSUP;
1893 }
1894
1895 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1896 int64_t pos, int size)
1897 {
1898 BlockDriver *drv = bs->drv;
1899 if (!drv)
1900 return -ENOMEDIUM;
1901 if (drv->bdrv_load_vmstate)
1902 return drv->bdrv_load_vmstate(bs, buf, pos, size);
1903 if (bs->file)
1904 return bdrv_load_vmstate(bs->file->bs, buf, pos, size);
1905 return -ENOTSUP;
1906 }
1907
1908 /**************************************************************/
1909 /* async I/Os */
1910
1911 BlockAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1912 QEMUIOVector *qiov, int nb_sectors,
1913 BlockCompletionFunc *cb, void *opaque)
1914 {
1915 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
1916
1917 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
1918 cb, opaque, false);
1919 }
1920
1921 BlockAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1922 QEMUIOVector *qiov, int nb_sectors,
1923 BlockCompletionFunc *cb, void *opaque)
1924 {
1925 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
1926
1927 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
1928 cb, opaque, true);
1929 }
1930
1931 BlockAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
1932 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
1933 BlockCompletionFunc *cb, void *opaque)
1934 {
1935 trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
1936
1937 return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
1938 BDRV_REQ_ZERO_WRITE | flags,
1939 cb, opaque, true);
1940 }
1941
1942
1943 typedef struct MultiwriteCB {
1944 int error;
1945 int num_requests;
1946 int num_callbacks;
1947 struct {
1948 BlockCompletionFunc *cb;
1949 void *opaque;
1950 QEMUIOVector *free_qiov;
1951 } callbacks[];
1952 } MultiwriteCB;
1953
1954 static void multiwrite_user_cb(MultiwriteCB *mcb)
1955 {
1956 int i;
1957
1958 for (i = 0; i < mcb->num_callbacks; i++) {
1959 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1960 if (mcb->callbacks[i].free_qiov) {
1961 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
1962 }
1963 g_free(mcb->callbacks[i].free_qiov);
1964 }
1965 }
1966
1967 static void multiwrite_cb(void *opaque, int ret)
1968 {
1969 MultiwriteCB *mcb = opaque;
1970
1971 trace_multiwrite_cb(mcb, ret);
1972
1973 if (ret < 0 && !mcb->error) {
1974 mcb->error = ret;
1975 }
1976
1977 mcb->num_requests--;
1978 if (mcb->num_requests == 0) {
1979 multiwrite_user_cb(mcb);
1980 g_free(mcb);
1981 }
1982 }
1983
1984 static int multiwrite_req_compare(const void *a, const void *b)
1985 {
1986 const BlockRequest *req1 = a, *req2 = b;
1987
1988 /*
1989 * Note that we can't simply subtract req2->sector from req1->sector
1990 * here as that could overflow the return value.
1991 */
1992 if (req1->sector > req2->sector) {
1993 return 1;
1994 } else if (req1->sector < req2->sector) {
1995 return -1;
1996 } else {
1997 return 0;
1998 }
1999 }
2000
2001 /*
2002 * Takes a bunch of requests and tries to merge them. Returns the number of
2003 * requests that remain after merging.
2004 */
2005 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2006 int num_reqs, MultiwriteCB *mcb)
2007 {
2008 int i, outidx;
2009
2010 // Sort requests by start sector
2011 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2012
2013 // Check if adjacent requests touch the same clusters. If so, combine them,
2014 // filling up gaps with zero sectors.
2015 outidx = 0;
2016 for (i = 1; i < num_reqs; i++) {
2017 int merge = 0;
2018 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2019
2020 // Handle exactly sequential writes and overlapping writes.
2021 if (reqs[i].sector <= oldreq_last) {
2022 merge = 1;
2023 }
2024
2025 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 >
2026 bs->bl.max_iov) {
2027 merge = 0;
2028 }
2029
2030 if (bs->bl.max_transfer_length && reqs[outidx].nb_sectors +
2031 reqs[i].nb_sectors > bs->bl.max_transfer_length) {
2032 merge = 0;
2033 }
2034
2035 if (merge) {
2036 size_t size;
2037 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
2038 qemu_iovec_init(qiov,
2039 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2040
2041 // Add the first request to the merged one. If the requests are
2042 // overlapping, drop the last sectors of the first request.
2043 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2044 qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
2045
2046 // We should need to add any zeros between the two requests
2047 assert (reqs[i].sector <= oldreq_last);
2048
2049 // Add the second request
2050 qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
2051
2052 // Add tail of first request, if necessary
2053 if (qiov->size < reqs[outidx].qiov->size) {
2054 qemu_iovec_concat(qiov, reqs[outidx].qiov, qiov->size,
2055 reqs[outidx].qiov->size - qiov->size);
2056 }
2057
2058 reqs[outidx].nb_sectors = qiov->size >> 9;
2059 reqs[outidx].qiov = qiov;
2060
2061 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2062 } else {
2063 outidx++;
2064 reqs[outidx].sector = reqs[i].sector;
2065 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2066 reqs[outidx].qiov = reqs[i].qiov;
2067 }
2068 }
2069
2070 if (bs->blk) {
2071 block_acct_merge_done(blk_get_stats(bs->blk), BLOCK_ACCT_WRITE,
2072 num_reqs - outidx - 1);
2073 }
2074
2075 return outidx + 1;
2076 }
2077
2078 /*
2079 * Submit multiple AIO write requests at once.
2080 *
2081 * On success, the function returns 0 and all requests in the reqs array have
2082 * been submitted. In error case this function returns -1, and any of the
2083 * requests may or may not be submitted yet. In particular, this means that the
2084 * callback will be called for some of the requests, for others it won't. The
2085 * caller must check the error field of the BlockRequest to wait for the right
2086 * callbacks (if error != 0, no callback will be called).
2087 *
2088 * The implementation may modify the contents of the reqs array, e.g. to merge
2089 * requests. However, the fields opaque and error are left unmodified as they
2090 * are used to signal failure for a single request to the caller.
2091 */
2092 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2093 {
2094 MultiwriteCB *mcb;
2095 int i;
2096
2097 /* don't submit writes if we don't have a medium */
2098 if (bs->drv == NULL) {
2099 for (i = 0; i < num_reqs; i++) {
2100 reqs[i].error = -ENOMEDIUM;
2101 }
2102 return -1;
2103 }
2104
2105 if (num_reqs == 0) {
2106 return 0;
2107 }
2108
2109 // Create MultiwriteCB structure
2110 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
2111 mcb->num_requests = 0;
2112 mcb->num_callbacks = num_reqs;
2113
2114 for (i = 0; i < num_reqs; i++) {
2115 mcb->callbacks[i].cb = reqs[i].cb;
2116 mcb->callbacks[i].opaque = reqs[i].opaque;
2117 }
2118
2119 // Check for mergable requests
2120 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2121
2122 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2123
2124 /* Run the aio requests. */
2125 mcb->num_requests = num_reqs;
2126 for (i = 0; i < num_reqs; i++) {
2127 bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
2128 reqs[i].nb_sectors, reqs[i].flags,
2129 multiwrite_cb, mcb,
2130 true);
2131 }
2132
2133 return 0;
2134 }
2135
2136 void bdrv_aio_cancel(BlockAIOCB *acb)
2137 {
2138 qemu_aio_ref(acb);
2139 bdrv_aio_cancel_async(acb);
2140 while (acb->refcnt > 1) {
2141 if (acb->aiocb_info->get_aio_context) {
2142 aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2143 } else if (acb->bs) {
2144 aio_poll(bdrv_get_aio_context(acb->bs), true);
2145 } else {
2146 abort();
2147 }
2148 }
2149 qemu_aio_unref(acb);
2150 }
2151
2152 /* Async version of aio cancel. The caller is not blocked if the acb implements
2153 * cancel_async, otherwise we do nothing and let the request normally complete.
2154 * In either case the completion callback must be called. */
2155 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2156 {
2157 if (acb->aiocb_info->cancel_async) {
2158 acb->aiocb_info->cancel_async(acb);
2159 }
2160 }
2161
2162 /**************************************************************/
2163 /* async block device emulation */
2164
2165 typedef struct BlockAIOCBCoroutine {
2166 BlockAIOCB common;
2167 BlockRequest req;
2168 bool is_write;
2169 bool need_bh;
2170 bool *done;
2171 QEMUBH* bh;
2172 } BlockAIOCBCoroutine;
2173
2174 static const AIOCBInfo bdrv_em_co_aiocb_info = {
2175 .aiocb_size = sizeof(BlockAIOCBCoroutine),
2176 };
2177
2178 static void bdrv_co_complete(BlockAIOCBCoroutine *acb)
2179 {
2180 if (!acb->need_bh) {
2181 acb->common.cb(acb->common.opaque, acb->req.error);
2182 qemu_aio_unref(acb);
2183 }
2184 }
2185
2186 static void bdrv_co_em_bh(void *opaque)
2187 {
2188 BlockAIOCBCoroutine *acb = opaque;
2189
2190 assert(!acb->need_bh);
2191 qemu_bh_delete(acb->bh);
2192 bdrv_co_complete(acb);
2193 }
2194
2195 static void bdrv_co_maybe_schedule_bh(BlockAIOCBCoroutine *acb)
2196 {
2197 acb->need_bh = false;
2198 if (acb->req.error != -EINPROGRESS) {
2199 BlockDriverState *bs = acb->common.bs;
2200
2201 acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
2202 qemu_bh_schedule(acb->bh);
2203 }
2204 }
2205
2206 /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
2207 static void coroutine_fn bdrv_co_do_rw(void *opaque)
2208 {
2209 BlockAIOCBCoroutine *acb = opaque;
2210 BlockDriverState *bs = acb->common.bs;
2211
2212 if (!acb->is_write) {
2213 acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
2214 acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
2215 } else {
2216 acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
2217 acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
2218 }
2219
2220 bdrv_co_complete(acb);
2221 }
2222
2223 static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2224 int64_t sector_num,
2225 QEMUIOVector *qiov,
2226 int nb_sectors,
2227 BdrvRequestFlags flags,
2228 BlockCompletionFunc *cb,
2229 void *opaque,
2230 bool is_write)
2231 {
2232 Coroutine *co;
2233 BlockAIOCBCoroutine *acb;
2234
2235 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2236 acb->need_bh = true;
2237 acb->req.error = -EINPROGRESS;
2238 acb->req.sector = sector_num;
2239 acb->req.nb_sectors = nb_sectors;
2240 acb->req.qiov = qiov;
2241 acb->req.flags = flags;
2242 acb->is_write = is_write;
2243
2244 co = qemu_coroutine_create(bdrv_co_do_rw);
2245 qemu_coroutine_enter(co, acb);
2246
2247 bdrv_co_maybe_schedule_bh(acb);
2248 return &acb->common;
2249 }
2250
2251 static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
2252 {
2253 BlockAIOCBCoroutine *acb = opaque;
2254 BlockDriverState *bs = acb->common.bs;
2255
2256 acb->req.error = bdrv_co_flush(bs);
2257 bdrv_co_complete(acb);
2258 }
2259
2260 BlockAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2261 BlockCompletionFunc *cb, void *opaque)
2262 {
2263 trace_bdrv_aio_flush(bs, opaque);
2264
2265 Coroutine *co;
2266 BlockAIOCBCoroutine *acb;
2267
2268 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2269 acb->need_bh = true;
2270 acb->req.error = -EINPROGRESS;
2271
2272 co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
2273 qemu_coroutine_enter(co, acb);
2274
2275 bdrv_co_maybe_schedule_bh(acb);
2276 return &acb->common;
2277 }
2278
2279 static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
2280 {
2281 BlockAIOCBCoroutine *acb = opaque;
2282 BlockDriverState *bs = acb->common.bs;
2283
2284 acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
2285 bdrv_co_complete(acb);
2286 }
2287
2288 BlockAIOCB *bdrv_aio_discard(BlockDriverState *bs,
2289 int64_t sector_num, int nb_sectors,
2290 BlockCompletionFunc *cb, void *opaque)
2291 {
2292 Coroutine *co;
2293 BlockAIOCBCoroutine *acb;
2294
2295 trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
2296
2297 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2298 acb->need_bh = true;
2299 acb->req.error = -EINPROGRESS;
2300 acb->req.sector = sector_num;
2301 acb->req.nb_sectors = nb_sectors;
2302 co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
2303 qemu_coroutine_enter(co, acb);
2304
2305 bdrv_co_maybe_schedule_bh(acb);
2306 return &acb->common;
2307 }
2308
2309 void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
2310 BlockCompletionFunc *cb, void *opaque)
2311 {
2312 BlockAIOCB *acb;
2313
2314 acb = g_malloc(aiocb_info->aiocb_size);
2315 acb->aiocb_info = aiocb_info;
2316 acb->bs = bs;
2317 acb->cb = cb;
2318 acb->opaque = opaque;
2319 acb->refcnt = 1;
2320 return acb;
2321 }
2322
2323 void qemu_aio_ref(void *p)
2324 {
2325 BlockAIOCB *acb = p;
2326 acb->refcnt++;
2327 }
2328
2329 void qemu_aio_unref(void *p)
2330 {
2331 BlockAIOCB *acb = p;
2332 assert(acb->refcnt > 0);
2333 if (--acb->refcnt == 0) {
2334 g_free(acb);
2335 }
2336 }
2337
2338 /**************************************************************/
2339 /* Coroutine block device emulation */
2340
2341 static void coroutine_fn bdrv_flush_co_entry(void *opaque)
2342 {
2343 RwCo *rwco = opaque;
2344
2345 rwco->ret = bdrv_co_flush(rwco->bs);
2346 }
2347
2348 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2349 {
2350 int ret;
2351 BdrvTrackedRequest req;
2352
2353 if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
2354 bdrv_is_sg(bs)) {
2355 return 0;
2356 }
2357
2358 tracked_request_begin(&req, bs, 0, 0, BDRV_TRACKED_FLUSH);
2359
2360 /* Write back all layers by calling one driver function */
2361 if (bs->drv->bdrv_co_flush) {
2362 ret = bs->drv->bdrv_co_flush(bs);
2363 goto out;
2364 }
2365
2366 /* Write back cached data to the OS even with cache=unsafe */
2367 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
2368 if (bs->drv->bdrv_co_flush_to_os) {
2369 ret = bs->drv->bdrv_co_flush_to_os(bs);
2370 if (ret < 0) {
2371 goto out;
2372 }
2373 }
2374
2375 /* But don't actually force it to the disk with cache=unsafe */
2376 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2377 goto flush_parent;
2378 }
2379
2380 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
2381 if (bs->drv->bdrv_co_flush_to_disk) {
2382 ret = bs->drv->bdrv_co_flush_to_disk(bs);
2383 } else if (bs->drv->bdrv_aio_flush) {
2384 BlockAIOCB *acb;
2385 CoroutineIOCompletion co = {
2386 .coroutine = qemu_coroutine_self(),
2387 };
2388
2389 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2390 if (acb == NULL) {
2391 ret = -EIO;
2392 } else {
2393 qemu_coroutine_yield();
2394 ret = co.ret;
2395 }
2396 } else {
2397 /*
2398 * Some block drivers always operate in either writethrough or unsafe
2399 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2400 * know how the server works (because the behaviour is hardcoded or
2401 * depends on server-side configuration), so we can't ensure that
2402 * everything is safe on disk. Returning an error doesn't work because
2403 * that would break guests even if the server operates in writethrough
2404 * mode.
2405 *
2406 * Let's hope the user knows what he's doing.
2407 */
2408 ret = 0;
2409 }
2410 if (ret < 0) {
2411 goto out;
2412 }
2413
2414 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2415 * in the case of cache=unsafe, so there are no useless flushes.
2416 */
2417 flush_parent:
2418 ret = bs->file ? bdrv_co_flush(bs->file->bs) : 0;
2419 out:
2420 tracked_request_end(&req);
2421 return ret;
2422 }
2423
2424 int bdrv_flush(BlockDriverState *bs)
2425 {
2426 Coroutine *co;
2427 RwCo rwco = {
2428 .bs = bs,
2429 .ret = NOT_DONE,
2430 };
2431
2432 if (qemu_in_coroutine()) {
2433 /* Fast-path if already in coroutine context */
2434 bdrv_flush_co_entry(&rwco);
2435 } else {
2436 AioContext *aio_context = bdrv_get_aio_context(bs);
2437
2438 co = qemu_coroutine_create(bdrv_flush_co_entry);
2439 qemu_coroutine_enter(co, &rwco);
2440 while (rwco.ret == NOT_DONE) {
2441 aio_poll(aio_context, true);
2442 }
2443 }
2444
2445 return rwco.ret;
2446 }
2447
2448 typedef struct DiscardCo {
2449 BlockDriverState *bs;
2450 int64_t sector_num;
2451 int nb_sectors;
2452 int ret;
2453 } DiscardCo;
2454 static void coroutine_fn bdrv_discard_co_entry(void *opaque)
2455 {
2456 DiscardCo *rwco = opaque;
2457
2458 rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
2459 }
2460
2461 int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
2462 int nb_sectors)
2463 {
2464 BdrvTrackedRequest req;
2465 int max_discard, ret;
2466
2467 if (!bs->drv) {
2468 return -ENOMEDIUM;
2469 }
2470
2471 ret = bdrv_check_request(bs, sector_num, nb_sectors);
2472 if (ret < 0) {
2473 return ret;
2474 } else if (bs->read_only) {
2475 return -EPERM;
2476 }
2477 assert(!(bs->open_flags & BDRV_O_INACTIVE));
2478
2479 /* Do nothing if disabled. */
2480 if (!(bs->open_flags & BDRV_O_UNMAP)) {
2481 return 0;
2482 }
2483
2484 if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
2485 return 0;
2486 }
2487
2488 tracked_request_begin(&req, bs, sector_num, nb_sectors,
2489 BDRV_TRACKED_DISCARD);
2490 bdrv_set_dirty(bs, sector_num, nb_sectors);
2491
2492 max_discard = MIN_NON_ZERO(bs->bl.max_discard, BDRV_REQUEST_MAX_SECTORS);
2493 while (nb_sectors > 0) {
2494 int ret;
2495 int num = nb_sectors;
2496
2497 /* align request */
2498 if (bs->bl.discard_alignment &&
2499 num >= bs->bl.discard_alignment &&
2500 sector_num % bs->bl.discard_alignment) {
2501 if (num > bs->bl.discard_alignment) {
2502 num = bs->bl.discard_alignment;
2503 }
2504 num -= sector_num % bs->bl.discard_alignment;
2505 }
2506
2507 /* limit request size */
2508 if (num > max_discard) {
2509 num = max_discard;
2510 }
2511
2512 if (bs->drv->bdrv_co_discard) {
2513 ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
2514 } else {
2515 BlockAIOCB *acb;
2516 CoroutineIOCompletion co = {
2517 .coroutine = qemu_coroutine_self(),
2518 };
2519
2520 acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
2521 bdrv_co_io_em_complete, &co);
2522 if (acb == NULL) {
2523 ret = -EIO;
2524 goto out;
2525 } else {
2526 qemu_coroutine_yield();
2527 ret = co.ret;
2528 }
2529 }
2530 if (ret && ret != -ENOTSUP) {
2531 goto out;
2532 }
2533
2534 sector_num += num;
2535 nb_sectors -= num;
2536 }
2537 ret = 0;
2538 out:
2539 tracked_request_end(&req);
2540 return ret;
2541 }
2542
2543 int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
2544 {
2545 Coroutine *co;
2546 DiscardCo rwco = {
2547 .bs = bs,
2548 .sector_num = sector_num,
2549 .nb_sectors = nb_sectors,
2550 .ret = NOT_DONE,
2551 };
2552
2553 if (qemu_in_coroutine()) {
2554 /* Fast-path if already in coroutine context */
2555 bdrv_discard_co_entry(&rwco);
2556 } else {
2557 AioContext *aio_context = bdrv_get_aio_context(bs);
2558
2559 co = qemu_coroutine_create(bdrv_discard_co_entry);
2560 qemu_coroutine_enter(co, &rwco);
2561 while (rwco.ret == NOT_DONE) {
2562 aio_poll(aio_context, true);
2563 }
2564 }
2565
2566 return rwco.ret;
2567 }
2568
2569 typedef struct {
2570 CoroutineIOCompletion *co;
2571 QEMUBH *bh;
2572 } BdrvIoctlCompletionData;
2573
2574 static void bdrv_ioctl_bh_cb(void *opaque)
2575 {
2576 BdrvIoctlCompletionData *data = opaque;
2577
2578 bdrv_co_io_em_complete(data->co, -ENOTSUP);
2579 qemu_bh_delete(data->bh);
2580 }
2581
2582 static int bdrv_co_do_ioctl(BlockDriverState *bs, int req, void *buf)
2583 {
2584 BlockDriver *drv = bs->drv;
2585 BdrvTrackedRequest tracked_req;
2586 CoroutineIOCompletion co = {
2587 .coroutine = qemu_coroutine_self(),
2588 };
2589 BlockAIOCB *acb;
2590
2591 tracked_request_begin(&tracked_req, bs, 0, 0, BDRV_TRACKED_IOCTL);
2592 if (!drv || !drv->bdrv_aio_ioctl) {
2593 co.ret = -ENOTSUP;
2594 goto out;
2595 }
2596
2597 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
2598 if (!acb) {
2599 BdrvIoctlCompletionData *data = g_new(BdrvIoctlCompletionData, 1);
2600 data->bh = aio_bh_new(bdrv_get_aio_context(bs),
2601 bdrv_ioctl_bh_cb, data);
2602 data->co = &co;
2603 qemu_bh_schedule(data->bh);
2604 }
2605 qemu_coroutine_yield();
2606 out:
2607 tracked_request_end(&tracked_req);
2608 return co.ret;
2609 }
2610
2611 typedef struct {
2612 BlockDriverState *bs;
2613 int req;
2614 void *buf;
2615 int ret;
2616 } BdrvIoctlCoData;
2617
2618 static void coroutine_fn bdrv_co_ioctl_entry(void *opaque)
2619 {
2620 BdrvIoctlCoData *data = opaque;
2621 data->ret = bdrv_co_do_ioctl(data->bs, data->req, data->buf);
2622 }
2623
2624 /* needed for generic scsi interface */
2625 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2626 {
2627 BdrvIoctlCoData data = {
2628 .bs = bs,
2629 .req = req,
2630 .buf = buf,
2631 .ret = -EINPROGRESS,
2632 };
2633
2634 if (qemu_in_coroutine()) {
2635 /* Fast-path if already in coroutine context */
2636 bdrv_co_ioctl_entry(&data);
2637 } else {
2638 Coroutine *co = qemu_coroutine_create(bdrv_co_ioctl_entry);
2639
2640 qemu_coroutine_enter(co, &data);
2641 while (data.ret == -EINPROGRESS) {
2642 aio_poll(bdrv_get_aio_context(bs), true);
2643 }
2644 }
2645 return data.ret;
2646 }
2647
2648 static void coroutine_fn bdrv_co_aio_ioctl_entry(void *opaque)
2649 {
2650 BlockAIOCBCoroutine *acb = opaque;
2651 acb->req.error = bdrv_co_do_ioctl(acb->common.bs,
2652 acb->req.req, acb->req.buf);
2653 bdrv_co_complete(acb);
2654 }
2655
2656 BlockAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2657 unsigned long int req, void *buf,
2658 BlockCompletionFunc *cb, void *opaque)
2659 {
2660 BlockAIOCBCoroutine *acb = qemu_aio_get(&bdrv_em_co_aiocb_info,
2661 bs, cb, opaque);
2662 Coroutine *co;
2663
2664 acb->need_bh = true;
2665 acb->req.error = -EINPROGRESS;
2666 acb->req.req = req;
2667 acb->req.buf = buf;
2668 co = qemu_coroutine_create(bdrv_co_aio_ioctl_entry);
2669 qemu_coroutine_enter(co, acb);
2670
2671 bdrv_co_maybe_schedule_bh(acb);
2672 return &acb->common;
2673 }
2674
2675 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2676 {
2677 return qemu_memalign(bdrv_opt_mem_align(bs), size);
2678 }
2679
2680 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
2681 {
2682 return memset(qemu_blockalign(bs, size), 0, size);
2683 }
2684
2685 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
2686 {
2687 size_t align = bdrv_opt_mem_align(bs);
2688
2689 /* Ensure that NULL is never returned on success */
2690 assert(align > 0);
2691 if (size == 0) {
2692 size = align;
2693 }
2694
2695 return qemu_try_memalign(align, size);
2696 }
2697
2698 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
2699 {
2700 void *mem = qemu_try_blockalign(bs, size);
2701
2702 if (mem) {
2703 memset(mem, 0, size);
2704 }
2705
2706 return mem;
2707 }
2708
2709 /*
2710 * Check if all memory in this vector is sector aligned.
2711 */
2712 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2713 {
2714 int i;
2715 size_t alignment = bdrv_min_mem_align(bs);
2716
2717 for (i = 0; i < qiov->niov; i++) {
2718 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2719 return false;
2720 }
2721 if (qiov->iov[i].iov_len % alignment) {
2722 return false;
2723 }
2724 }
2725
2726 return true;
2727 }
2728
2729 void bdrv_add_before_write_notifier(BlockDriverState *bs,
2730 NotifierWithReturn *notifier)
2731 {
2732 notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
2733 }
2734
2735 void bdrv_io_plug(BlockDriverState *bs)
2736 {
2737 BdrvChild *child;
2738
2739 QLIST_FOREACH(child, &bs->children, next) {
2740 bdrv_io_plug(child->bs);
2741 }
2742
2743 if (bs->io_plugged++ == 0 && bs->io_plug_disabled == 0) {
2744 BlockDriver *drv = bs->drv;
2745 if (drv && drv->bdrv_io_plug) {
2746 drv->bdrv_io_plug(bs);
2747 }
2748 }
2749 }
2750
2751 void bdrv_io_unplug(BlockDriverState *bs)
2752 {
2753 BdrvChild *child;
2754
2755 assert(bs->io_plugged);
2756 if (--bs->io_plugged == 0 && bs->io_plug_disabled == 0) {
2757 BlockDriver *drv = bs->drv;
2758 if (drv && drv->bdrv_io_unplug) {
2759 drv->bdrv_io_unplug(bs);
2760 }
2761 }
2762
2763 QLIST_FOREACH(child, &bs->children, next) {
2764 bdrv_io_unplug(child->bs);
2765 }
2766 }
2767
2768 void bdrv_io_unplugged_begin(BlockDriverState *bs)
2769 {
2770 BdrvChild *child;
2771
2772 if (bs->io_plug_disabled++ == 0 && bs->io_plugged > 0) {
2773 BlockDriver *drv = bs->drv;
2774 if (drv && drv->bdrv_io_unplug) {
2775 drv->bdrv_io_unplug(bs);
2776 }
2777 }
2778
2779 QLIST_FOREACH(child, &bs->children, next) {
2780 bdrv_io_unplugged_begin(child->bs);
2781 }
2782 }
2783
2784 void bdrv_io_unplugged_end(BlockDriverState *bs)
2785 {
2786 BdrvChild *child;
2787
2788 assert(bs->io_plug_disabled);
2789 QLIST_FOREACH(child, &bs->children, next) {
2790 bdrv_io_unplugged_end(child->bs);
2791 }
2792
2793 if (--bs->io_plug_disabled == 0 && bs->io_plugged > 0) {
2794 BlockDriver *drv = bs->drv;
2795 if (drv && drv->bdrv_io_plug) {
2796 drv->bdrv_io_plug(bs);
2797 }
2798 }
2799 }
2800
2801 void bdrv_drained_begin(BlockDriverState *bs)
2802 {
2803 if (!bs->quiesce_counter++) {
2804 aio_disable_external(bdrv_get_aio_context(bs));
2805 }
2806 bdrv_drain(bs);
2807 }
2808
2809 void bdrv_drained_end(BlockDriverState *bs)
2810 {
2811 assert(bs->quiesce_counter > 0);
2812 if (--bs->quiesce_counter > 0) {
2813 return;
2814 }
2815 aio_enable_external(bdrv_get_aio_context(bs));
2816 }