4 * Copyright (C) 2013 Proxmox Server Solutions
5 * Copyright (c) 2019 Virtuozzo International GmbH.
8 * Dietmar Maurer (dietmar@proxmox.com)
9 * Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
11 * This work is licensed under the terms of the GNU GPL, version 2 or later.
12 * See the COPYING file in the top-level directory.
15 #include "qemu/osdep.h"
18 #include "qapi/error.h"
19 #include "block/block-copy.h"
20 #include "sysemu/block-backend.h"
21 #include "qemu/units.h"
22 #include "qemu/coroutine.h"
23 #include "block/aio_task.h"
25 #define BLOCK_COPY_MAX_COPY_RANGE (16 * MiB)
26 #define BLOCK_COPY_MAX_BUFFER (1 * MiB)
27 #define BLOCK_COPY_MAX_MEM (128 * MiB)
28 #define BLOCK_COPY_MAX_WORKERS 64
29 #define BLOCK_COPY_SLICE_TIME 100000000ULL /* ns */
31 static coroutine_fn
int block_copy_task_entry(AioTask
*task
);
33 typedef struct BlockCopyCallState
{
34 /* IN parameters. Initialized in block_copy_async() and never changed. */
40 bool ignore_ratelimit
;
41 BlockCopyAsyncCallbackFunc cb
;
44 /* Coroutine where async block-copy is running */
47 /* To reference all call states from BlockCopyState */
48 QLIST_ENTRY(BlockCopyCallState
) list
;
53 QemuCoSleepState
*sleep_state
;
60 typedef struct BlockCopyTask
{
64 BlockCopyCallState
*call_state
;
68 QLIST_ENTRY(BlockCopyTask
) list
;
69 CoQueue wait_queue
; /* coroutines blocked on this task */
72 static int64_t task_end(BlockCopyTask
*task
)
74 return task
->offset
+ task
->bytes
;
77 typedef struct BlockCopyState
{
79 * BdrvChild objects are not owned or managed by block-copy. They are
80 * provided by block-copy user and user is responsible for appropriate
81 * permissions on these children.
85 BdrvDirtyBitmap
*copy_bitmap
;
86 int64_t in_flight_bytes
;
91 QLIST_HEAD(, BlockCopyTask
) tasks
; /* All tasks from all block-copy calls */
92 QLIST_HEAD(, BlockCopyCallState
) calls
;
94 BdrvRequestFlags write_flags
;
99 * Used by sync=top jobs, which first scan the source node for unallocated
100 * areas and clear them in the copy_bitmap. During this process, the bitmap
101 * is thus not fully initialized: It may still have bits set for areas that
102 * are unallocated and should actually not be copied.
104 * This is indicated by skip_unallocated.
106 * In this case, block_copy() will query the source’s allocation status,
107 * skip unallocated regions, clear them in the copy_bitmap, and invoke
108 * block_copy_reset_unallocated() every time it does.
110 bool skip_unallocated
;
112 ProgressMeter
*progress
;
113 /* progress_bytes_callback: called when some copying progress is done. */
114 ProgressBytesCallbackFunc progress_bytes_callback
;
115 void *progress_opaque
;
120 RateLimit rate_limit
;
123 static BlockCopyTask
*find_conflicting_task(BlockCopyState
*s
,
124 int64_t offset
, int64_t bytes
)
128 QLIST_FOREACH(t
, &s
->tasks
, list
) {
129 if (offset
+ bytes
> t
->offset
&& offset
< t
->offset
+ t
->bytes
) {
138 * If there are no intersecting tasks return false. Otherwise, wait for the
139 * first found intersecting tasks to finish and return true.
141 static bool coroutine_fn
block_copy_wait_one(BlockCopyState
*s
, int64_t offset
,
144 BlockCopyTask
*task
= find_conflicting_task(s
, offset
, bytes
);
150 qemu_co_queue_wait(&task
->wait_queue
, NULL
);
156 * Search for the first dirty area in offset/bytes range and create task at
157 * the beginning of it.
159 static BlockCopyTask
*block_copy_task_create(BlockCopyState
*s
,
160 BlockCopyCallState
*call_state
,
161 int64_t offset
, int64_t bytes
)
164 int64_t max_chunk
= MIN_NON_ZERO(s
->copy_size
, call_state
->max_chunk
);
166 if (!bdrv_dirty_bitmap_next_dirty_area(s
->copy_bitmap
,
167 offset
, offset
+ bytes
,
168 max_chunk
, &offset
, &bytes
))
173 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
174 bytes
= QEMU_ALIGN_UP(bytes
, s
->cluster_size
);
176 /* region is dirty, so no existent tasks possible in it */
177 assert(!find_conflicting_task(s
, offset
, bytes
));
179 bdrv_reset_dirty_bitmap(s
->copy_bitmap
, offset
, bytes
);
180 s
->in_flight_bytes
+= bytes
;
182 task
= g_new(BlockCopyTask
, 1);
183 *task
= (BlockCopyTask
) {
184 .task
.func
= block_copy_task_entry
,
186 .call_state
= call_state
,
190 qemu_co_queue_init(&task
->wait_queue
);
191 QLIST_INSERT_HEAD(&s
->tasks
, task
, list
);
197 * block_copy_task_shrink
199 * Drop the tail of the task to be handled later. Set dirty bits back and
200 * wake up all tasks waiting for us (may be some of them are not intersecting
203 static void coroutine_fn
block_copy_task_shrink(BlockCopyTask
*task
,
206 if (new_bytes
== task
->bytes
) {
210 assert(new_bytes
> 0 && new_bytes
< task
->bytes
);
212 task
->s
->in_flight_bytes
-= task
->bytes
- new_bytes
;
213 bdrv_set_dirty_bitmap(task
->s
->copy_bitmap
,
214 task
->offset
+ new_bytes
, task
->bytes
- new_bytes
);
216 task
->bytes
= new_bytes
;
217 qemu_co_queue_restart_all(&task
->wait_queue
);
220 static void coroutine_fn
block_copy_task_end(BlockCopyTask
*task
, int ret
)
222 task
->s
->in_flight_bytes
-= task
->bytes
;
224 bdrv_set_dirty_bitmap(task
->s
->copy_bitmap
, task
->offset
, task
->bytes
);
226 QLIST_REMOVE(task
, list
);
227 qemu_co_queue_restart_all(&task
->wait_queue
);
230 void block_copy_state_free(BlockCopyState
*s
)
236 bdrv_release_dirty_bitmap(s
->copy_bitmap
);
237 shres_destroy(s
->mem
);
241 static uint32_t block_copy_max_transfer(BdrvChild
*source
, BdrvChild
*target
)
243 return MIN_NON_ZERO(INT_MAX
,
244 MIN_NON_ZERO(source
->bs
->bl
.max_transfer
,
245 target
->bs
->bl
.max_transfer
));
248 BlockCopyState
*block_copy_state_new(BdrvChild
*source
, BdrvChild
*target
,
249 int64_t cluster_size
, bool use_copy_range
,
250 BdrvRequestFlags write_flags
, Error
**errp
)
253 BdrvDirtyBitmap
*copy_bitmap
;
255 copy_bitmap
= bdrv_create_dirty_bitmap(source
->bs
, cluster_size
, NULL
,
260 bdrv_disable_dirty_bitmap(copy_bitmap
);
262 s
= g_new(BlockCopyState
, 1);
263 *s
= (BlockCopyState
) {
266 .copy_bitmap
= copy_bitmap
,
267 .cluster_size
= cluster_size
,
268 .len
= bdrv_dirty_bitmap_size(copy_bitmap
),
269 .write_flags
= write_flags
,
270 .mem
= shres_create(BLOCK_COPY_MAX_MEM
),
273 if (block_copy_max_transfer(source
, target
) < cluster_size
) {
275 * copy_range does not respect max_transfer. We don't want to bother
276 * with requests smaller than block-copy cluster size, so fallback to
277 * buffered copying (read and write respect max_transfer on their
280 s
->use_copy_range
= false;
281 s
->copy_size
= cluster_size
;
282 } else if (write_flags
& BDRV_REQ_WRITE_COMPRESSED
) {
283 /* Compression supports only cluster-size writes and no copy-range. */
284 s
->use_copy_range
= false;
285 s
->copy_size
= cluster_size
;
288 * We enable copy-range, but keep small copy_size, until first
289 * successful copy_range (look at block_copy_do_copy).
291 s
->use_copy_range
= use_copy_range
;
292 s
->copy_size
= MAX(s
->cluster_size
, BLOCK_COPY_MAX_BUFFER
);
295 QLIST_INIT(&s
->tasks
);
296 QLIST_INIT(&s
->calls
);
301 void block_copy_set_progress_callback(
303 ProgressBytesCallbackFunc progress_bytes_callback
,
304 void *progress_opaque
)
306 s
->progress_bytes_callback
= progress_bytes_callback
;
307 s
->progress_opaque
= progress_opaque
;
310 void block_copy_set_progress_meter(BlockCopyState
*s
, ProgressMeter
*pm
)
316 * Takes ownership of @task
318 * If pool is NULL directly run the task, otherwise schedule it into the pool.
320 * Returns: task.func return code if pool is NULL
321 * otherwise -ECANCELED if pool status is bad
322 * otherwise 0 (successfully scheduled)
324 static coroutine_fn
int block_copy_task_run(AioTaskPool
*pool
,
328 int ret
= task
->task
.func(&task
->task
);
334 aio_task_pool_wait_slot(pool
);
335 if (aio_task_pool_status(pool
) < 0) {
336 co_put_to_shres(task
->s
->mem
, task
->bytes
);
337 block_copy_task_end(task
, -ECANCELED
);
342 aio_task_pool_start_task(pool
, &task
->task
);
350 * Do copy of cluster-aligned chunk. Requested region is allowed to exceed
351 * s->len only to cover last cluster when s->len is not aligned to clusters.
353 * No sync here: nor bitmap neighter intersecting requests handling, only copy.
355 * Returns 0 on success.
357 static int coroutine_fn
block_copy_do_copy(BlockCopyState
*s
,
358 int64_t offset
, int64_t bytes
,
359 bool zeroes
, bool *error_is_read
)
362 int64_t nbytes
= MIN(offset
+ bytes
, s
->len
) - offset
;
363 void *bounce_buffer
= NULL
;
365 assert(offset
>= 0 && bytes
> 0 && INT64_MAX
- offset
>= bytes
);
366 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
367 assert(QEMU_IS_ALIGNED(bytes
, s
->cluster_size
));
368 assert(offset
< s
->len
);
369 assert(offset
+ bytes
<= s
->len
||
370 offset
+ bytes
== QEMU_ALIGN_UP(s
->len
, s
->cluster_size
));
371 assert(nbytes
< INT_MAX
);
374 ret
= bdrv_co_pwrite_zeroes(s
->target
, offset
, nbytes
, s
->write_flags
&
375 ~BDRV_REQ_WRITE_COMPRESSED
);
377 trace_block_copy_write_zeroes_fail(s
, offset
, ret
);
378 *error_is_read
= false;
383 if (s
->use_copy_range
) {
384 ret
= bdrv_co_copy_range(s
->source
, offset
, s
->target
, offset
, nbytes
,
387 trace_block_copy_copy_range_fail(s
, offset
, ret
);
388 s
->use_copy_range
= false;
389 s
->copy_size
= MAX(s
->cluster_size
, BLOCK_COPY_MAX_BUFFER
);
390 /* Fallback to read+write with allocated buffer */
392 if (s
->use_copy_range
) {
394 * Successful copy-range. Now increase copy_size. copy_range
395 * does not respect max_transfer (it's a TODO), so we factor
398 * Note: we double-check s->use_copy_range for the case when
399 * parallel block-copy request unsets it during previous
400 * bdrv_co_copy_range call.
403 MIN(MAX(s
->cluster_size
, BLOCK_COPY_MAX_COPY_RANGE
),
404 QEMU_ALIGN_DOWN(block_copy_max_transfer(s
->source
,
413 * In case of failed copy_range request above, we may proceed with buffered
414 * request larger than BLOCK_COPY_MAX_BUFFER. Still, further requests will
415 * be properly limited, so don't care too much. Moreover the most likely
416 * case (copy_range is unsupported for the configuration, so the very first
417 * copy_range request fails) is handled by setting large copy_size only
418 * after first successful copy_range.
421 bounce_buffer
= qemu_blockalign(s
->source
->bs
, nbytes
);
423 ret
= bdrv_co_pread(s
->source
, offset
, nbytes
, bounce_buffer
, 0);
425 trace_block_copy_read_fail(s
, offset
, ret
);
426 *error_is_read
= true;
430 ret
= bdrv_co_pwrite(s
->target
, offset
, nbytes
, bounce_buffer
,
433 trace_block_copy_write_fail(s
, offset
, ret
);
434 *error_is_read
= false;
439 qemu_vfree(bounce_buffer
);
444 static coroutine_fn
int block_copy_task_entry(AioTask
*task
)
446 BlockCopyTask
*t
= container_of(task
, BlockCopyTask
, task
);
447 bool error_is_read
= false;
450 ret
= block_copy_do_copy(t
->s
, t
->offset
, t
->bytes
, t
->zeroes
,
452 if (ret
< 0 && !t
->call_state
->ret
) {
453 t
->call_state
->ret
= ret
;
454 t
->call_state
->error_is_read
= error_is_read
;
456 progress_work_done(t
->s
->progress
, t
->bytes
);
457 t
->s
->progress_bytes_callback(t
->bytes
, t
->s
->progress_opaque
);
459 co_put_to_shres(t
->s
->mem
, t
->bytes
);
460 block_copy_task_end(t
, ret
);
465 static int block_copy_block_status(BlockCopyState
*s
, int64_t offset
,
466 int64_t bytes
, int64_t *pnum
)
469 BlockDriverState
*base
;
472 if (s
->skip_unallocated
) {
473 base
= bdrv_backing_chain_next(s
->source
->bs
);
478 ret
= bdrv_block_status_above(s
->source
->bs
, base
, offset
, bytes
, &num
,
480 if (ret
< 0 || num
< s
->cluster_size
) {
482 * On error or if failed to obtain large enough chunk just fallback to
485 num
= s
->cluster_size
;
486 ret
= BDRV_BLOCK_ALLOCATED
| BDRV_BLOCK_DATA
;
487 } else if (offset
+ num
== s
->len
) {
488 num
= QEMU_ALIGN_UP(num
, s
->cluster_size
);
490 num
= QEMU_ALIGN_DOWN(num
, s
->cluster_size
);
498 * Check if the cluster starting at offset is allocated or not.
499 * return via pnum the number of contiguous clusters sharing this allocation.
501 static int block_copy_is_cluster_allocated(BlockCopyState
*s
, int64_t offset
,
504 BlockDriverState
*bs
= s
->source
->bs
;
505 int64_t count
, total_count
= 0;
506 int64_t bytes
= s
->len
- offset
;
509 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
512 ret
= bdrv_is_allocated(bs
, offset
, bytes
, &count
);
517 total_count
+= count
;
519 if (ret
|| count
== 0) {
521 * ret: partial segment(s) are considered allocated.
522 * otherwise: unallocated tail is treated as an entire segment.
524 *pnum
= DIV_ROUND_UP(total_count
, s
->cluster_size
);
528 /* Unallocated segment(s) with uncertain following segment(s) */
529 if (total_count
>= s
->cluster_size
) {
530 *pnum
= total_count
/ s
->cluster_size
;
540 * Reset bits in copy_bitmap starting at offset if they represent unallocated
541 * data in the image. May reset subsequent contiguous bits.
542 * @return 0 when the cluster at @offset was unallocated,
543 * 1 otherwise, and -ret on error.
545 int64_t block_copy_reset_unallocated(BlockCopyState
*s
,
546 int64_t offset
, int64_t *count
)
549 int64_t clusters
, bytes
;
551 ret
= block_copy_is_cluster_allocated(s
, offset
, &clusters
);
556 bytes
= clusters
* s
->cluster_size
;
559 bdrv_reset_dirty_bitmap(s
->copy_bitmap
, offset
, bytes
);
560 progress_set_remaining(s
->progress
,
561 bdrv_get_dirty_count(s
->copy_bitmap
) +
570 * block_copy_dirty_clusters
572 * Copy dirty clusters in @offset/@bytes range.
573 * Returns 1 if dirty clusters found and successfully copied, 0 if no dirty
574 * clusters found and -errno on failure.
576 static int coroutine_fn
577 block_copy_dirty_clusters(BlockCopyCallState
*call_state
)
579 BlockCopyState
*s
= call_state
->s
;
580 int64_t offset
= call_state
->offset
;
581 int64_t bytes
= call_state
->bytes
;
584 bool found_dirty
= false;
585 int64_t end
= offset
+ bytes
;
586 AioTaskPool
*aio
= NULL
;
589 * block_copy() user is responsible for keeping source and target in same
592 assert(bdrv_get_aio_context(s
->source
->bs
) ==
593 bdrv_get_aio_context(s
->target
->bs
));
595 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
596 assert(QEMU_IS_ALIGNED(bytes
, s
->cluster_size
));
598 while (bytes
&& aio_task_pool_status(aio
) == 0 && !call_state
->cancelled
) {
600 int64_t status_bytes
;
602 task
= block_copy_task_create(s
, call_state
, offset
, bytes
);
604 /* No more dirty bits in the bitmap */
605 trace_block_copy_skip_range(s
, offset
, bytes
);
608 if (task
->offset
> offset
) {
609 trace_block_copy_skip_range(s
, offset
, task
->offset
- offset
);
614 ret
= block_copy_block_status(s
, task
->offset
, task
->bytes
,
616 assert(ret
>= 0); /* never fail */
617 if (status_bytes
< task
->bytes
) {
618 block_copy_task_shrink(task
, status_bytes
);
620 if (s
->skip_unallocated
&& !(ret
& BDRV_BLOCK_ALLOCATED
)) {
621 block_copy_task_end(task
, 0);
622 progress_set_remaining(s
->progress
,
623 bdrv_get_dirty_count(s
->copy_bitmap
) +
625 trace_block_copy_skip_range(s
, task
->offset
, task
->bytes
);
626 offset
= task_end(task
);
627 bytes
= end
- offset
;
631 task
->zeroes
= ret
& BDRV_BLOCK_ZERO
;
634 if (!call_state
->ignore_ratelimit
) {
635 uint64_t ns
= ratelimit_calculate_delay(&s
->rate_limit
, 0);
637 block_copy_task_end(task
, -EAGAIN
);
639 qemu_co_sleep_ns_wakeable(QEMU_CLOCK_REALTIME
, ns
,
640 &call_state
->sleep_state
);
645 ratelimit_calculate_delay(&s
->rate_limit
, task
->bytes
);
648 trace_block_copy_process(s
, task
->offset
);
650 co_get_from_shres(s
->mem
, task
->bytes
);
652 offset
= task_end(task
);
653 bytes
= end
- offset
;
656 aio
= aio_task_pool_new(call_state
->max_workers
);
659 ret
= block_copy_task_run(aio
, task
);
667 aio_task_pool_wait_all(aio
);
670 * We are not really interested in -ECANCELED returned from
671 * block_copy_task_run. If it fails, it means some task already failed
672 * for real reason, let's return first failure.
673 * Still, assert that we don't rewrite failure by success.
675 * Note: ret may be positive here because of block-status result.
677 assert(ret
>= 0 || aio_task_pool_status(aio
) < 0);
678 ret
= aio_task_pool_status(aio
);
680 aio_task_pool_free(aio
);
683 return ret
< 0 ? ret
: found_dirty
;
686 void block_copy_kick(BlockCopyCallState
*call_state
)
688 if (call_state
->sleep_state
) {
689 qemu_co_sleep_wake(call_state
->sleep_state
);
696 * Copy requested region, accordingly to dirty bitmap.
697 * Collaborate with parallel block_copy requests: if they succeed it will help
698 * us. If they fail, we will retry not-copied regions. So, if we return error,
699 * it means that some I/O operation failed in context of _this_ block_copy call,
700 * not some parallel operation.
702 static int coroutine_fn
block_copy_common(BlockCopyCallState
*call_state
)
706 QLIST_INSERT_HEAD(&call_state
->s
->calls
, call_state
, list
);
709 ret
= block_copy_dirty_clusters(call_state
);
711 if (ret
== 0 && !call_state
->cancelled
) {
712 ret
= block_copy_wait_one(call_state
->s
, call_state
->offset
,
717 * We retry in two cases:
718 * 1. Some progress done
719 * Something was copied, which means that there were yield points
720 * and some new dirty bits may have appeared (due to failed parallel
721 * block-copy requests).
722 * 2. We have waited for some intersecting block-copy request
723 * It may have failed and produced new dirty bits.
725 } while (ret
> 0 && !call_state
->cancelled
);
727 call_state
->finished
= true;
729 if (call_state
->cb
) {
730 call_state
->cb(call_state
->cb_opaque
);
733 QLIST_REMOVE(call_state
, list
);
738 int coroutine_fn
block_copy(BlockCopyState
*s
, int64_t start
, int64_t bytes
,
739 bool ignore_ratelimit
, bool *error_is_read
)
741 BlockCopyCallState call_state
= {
745 .ignore_ratelimit
= ignore_ratelimit
,
746 .max_workers
= BLOCK_COPY_MAX_WORKERS
,
749 int ret
= block_copy_common(&call_state
);
751 if (error_is_read
&& ret
< 0) {
752 *error_is_read
= call_state
.error_is_read
;
758 static void coroutine_fn
block_copy_async_co_entry(void *opaque
)
760 block_copy_common(opaque
);
763 BlockCopyCallState
*block_copy_async(BlockCopyState
*s
,
764 int64_t offset
, int64_t bytes
,
765 int max_workers
, int64_t max_chunk
,
766 BlockCopyAsyncCallbackFunc cb
,
769 BlockCopyCallState
*call_state
= g_new(BlockCopyCallState
, 1);
771 *call_state
= (BlockCopyCallState
) {
775 .max_workers
= max_workers
,
776 .max_chunk
= max_chunk
,
778 .cb_opaque
= cb_opaque
,
780 .co
= qemu_coroutine_create(block_copy_async_co_entry
, call_state
),
783 qemu_coroutine_enter(call_state
->co
);
788 void block_copy_call_free(BlockCopyCallState
*call_state
)
794 assert(call_state
->finished
);
798 bool block_copy_call_finished(BlockCopyCallState
*call_state
)
800 return call_state
->finished
;
803 bool block_copy_call_succeeded(BlockCopyCallState
*call_state
)
805 return call_state
->finished
&& !call_state
->cancelled
&&
806 call_state
->ret
== 0;
809 bool block_copy_call_failed(BlockCopyCallState
*call_state
)
811 return call_state
->finished
&& !call_state
->cancelled
&&
815 bool block_copy_call_cancelled(BlockCopyCallState
*call_state
)
817 return call_state
->cancelled
;
820 int block_copy_call_status(BlockCopyCallState
*call_state
, bool *error_is_read
)
822 assert(call_state
->finished
);
824 *error_is_read
= call_state
->error_is_read
;
826 return call_state
->ret
;
829 void block_copy_call_cancel(BlockCopyCallState
*call_state
)
831 call_state
->cancelled
= true;
832 block_copy_kick(call_state
);
835 BdrvDirtyBitmap
*block_copy_dirty_bitmap(BlockCopyState
*s
)
837 return s
->copy_bitmap
;
840 void block_copy_set_skip_unallocated(BlockCopyState
*s
, bool skip
)
842 s
->skip_unallocated
= skip
;
845 void block_copy_set_speed(BlockCopyState
*s
, uint64_t speed
)
849 ratelimit_set_speed(&s
->rate_limit
, speed
, BLOCK_COPY_SLICE_TIME
);
853 * Note: it's good to kick all call states from here, but it should be done
854 * only from a coroutine, to not crash if s->calls list changed while
855 * entering one call. So for now, the only user of this function kicks its
856 * only one call_state by hand.