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