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
;
59 typedef struct BlockCopyTask
{
63 BlockCopyCallState
*call_state
;
67 QLIST_ENTRY(BlockCopyTask
) list
;
68 CoQueue wait_queue
; /* coroutines blocked on this task */
71 static int64_t task_end(BlockCopyTask
*task
)
73 return task
->offset
+ task
->bytes
;
76 typedef struct BlockCopyState
{
78 * BdrvChild objects are not owned or managed by block-copy. They are
79 * provided by block-copy user and user is responsible for appropriate
80 * permissions on these children.
84 BdrvDirtyBitmap
*copy_bitmap
;
85 int64_t in_flight_bytes
;
90 QLIST_HEAD(, BlockCopyTask
) tasks
; /* All tasks from all block-copy calls */
91 QLIST_HEAD(, BlockCopyCallState
) calls
;
93 BdrvRequestFlags write_flags
;
98 * Used by sync=top jobs, which first scan the source node for unallocated
99 * areas and clear them in the copy_bitmap. During this process, the bitmap
100 * is thus not fully initialized: It may still have bits set for areas that
101 * are unallocated and should actually not be copied.
103 * This is indicated by skip_unallocated.
105 * In this case, block_copy() will query the source’s allocation status,
106 * skip unallocated regions, clear them in the copy_bitmap, and invoke
107 * block_copy_reset_unallocated() every time it does.
109 bool skip_unallocated
;
111 ProgressMeter
*progress
;
112 /* progress_bytes_callback: called when some copying progress is done. */
113 ProgressBytesCallbackFunc progress_bytes_callback
;
114 void *progress_opaque
;
119 RateLimit rate_limit
;
122 static BlockCopyTask
*find_conflicting_task(BlockCopyState
*s
,
123 int64_t offset
, int64_t bytes
)
127 QLIST_FOREACH(t
, &s
->tasks
, list
) {
128 if (offset
+ bytes
> t
->offset
&& offset
< t
->offset
+ t
->bytes
) {
137 * If there are no intersecting tasks return false. Otherwise, wait for the
138 * first found intersecting tasks to finish and return true.
140 static bool coroutine_fn
block_copy_wait_one(BlockCopyState
*s
, int64_t offset
,
143 BlockCopyTask
*task
= find_conflicting_task(s
, offset
, bytes
);
149 qemu_co_queue_wait(&task
->wait_queue
, NULL
);
155 * Search for the first dirty area in offset/bytes range and create task at
156 * the beginning of it.
158 static BlockCopyTask
*block_copy_task_create(BlockCopyState
*s
,
159 BlockCopyCallState
*call_state
,
160 int64_t offset
, int64_t bytes
)
163 int64_t max_chunk
= MIN_NON_ZERO(s
->copy_size
, call_state
->max_chunk
);
165 if (!bdrv_dirty_bitmap_next_dirty_area(s
->copy_bitmap
,
166 offset
, offset
+ bytes
,
167 max_chunk
, &offset
, &bytes
))
172 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
173 bytes
= QEMU_ALIGN_UP(bytes
, s
->cluster_size
);
175 /* region is dirty, so no existent tasks possible in it */
176 assert(!find_conflicting_task(s
, offset
, bytes
));
178 bdrv_reset_dirty_bitmap(s
->copy_bitmap
, offset
, bytes
);
179 s
->in_flight_bytes
+= bytes
;
181 task
= g_new(BlockCopyTask
, 1);
182 *task
= (BlockCopyTask
) {
183 .task
.func
= block_copy_task_entry
,
185 .call_state
= call_state
,
189 qemu_co_queue_init(&task
->wait_queue
);
190 QLIST_INSERT_HEAD(&s
->tasks
, task
, list
);
196 * block_copy_task_shrink
198 * Drop the tail of the task to be handled later. Set dirty bits back and
199 * wake up all tasks waiting for us (may be some of them are not intersecting
202 static void coroutine_fn
block_copy_task_shrink(BlockCopyTask
*task
,
205 if (new_bytes
== task
->bytes
) {
209 assert(new_bytes
> 0 && new_bytes
< task
->bytes
);
211 task
->s
->in_flight_bytes
-= task
->bytes
- new_bytes
;
212 bdrv_set_dirty_bitmap(task
->s
->copy_bitmap
,
213 task
->offset
+ new_bytes
, task
->bytes
- new_bytes
);
215 task
->bytes
= new_bytes
;
216 qemu_co_queue_restart_all(&task
->wait_queue
);
219 static void coroutine_fn
block_copy_task_end(BlockCopyTask
*task
, int ret
)
221 task
->s
->in_flight_bytes
-= task
->bytes
;
223 bdrv_set_dirty_bitmap(task
->s
->copy_bitmap
, task
->offset
, task
->bytes
);
225 QLIST_REMOVE(task
, list
);
226 qemu_co_queue_restart_all(&task
->wait_queue
);
229 void block_copy_state_free(BlockCopyState
*s
)
235 bdrv_release_dirty_bitmap(s
->copy_bitmap
);
236 shres_destroy(s
->mem
);
240 static uint32_t block_copy_max_transfer(BdrvChild
*source
, BdrvChild
*target
)
242 return MIN_NON_ZERO(INT_MAX
,
243 MIN_NON_ZERO(source
->bs
->bl
.max_transfer
,
244 target
->bs
->bl
.max_transfer
));
247 BlockCopyState
*block_copy_state_new(BdrvChild
*source
, BdrvChild
*target
,
248 int64_t cluster_size
, bool use_copy_range
,
249 BdrvRequestFlags write_flags
, Error
**errp
)
252 BdrvDirtyBitmap
*copy_bitmap
;
254 copy_bitmap
= bdrv_create_dirty_bitmap(source
->bs
, cluster_size
, NULL
,
259 bdrv_disable_dirty_bitmap(copy_bitmap
);
261 s
= g_new(BlockCopyState
, 1);
262 *s
= (BlockCopyState
) {
265 .copy_bitmap
= copy_bitmap
,
266 .cluster_size
= cluster_size
,
267 .len
= bdrv_dirty_bitmap_size(copy_bitmap
),
268 .write_flags
= write_flags
,
269 .mem
= shres_create(BLOCK_COPY_MAX_MEM
),
272 if (block_copy_max_transfer(source
, target
) < cluster_size
) {
274 * copy_range does not respect max_transfer. We don't want to bother
275 * with requests smaller than block-copy cluster size, so fallback to
276 * buffered copying (read and write respect max_transfer on their
279 s
->use_copy_range
= false;
280 s
->copy_size
= cluster_size
;
281 } else if (write_flags
& BDRV_REQ_WRITE_COMPRESSED
) {
282 /* Compression supports only cluster-size writes and no copy-range. */
283 s
->use_copy_range
= false;
284 s
->copy_size
= cluster_size
;
287 * We enable copy-range, but keep small copy_size, until first
288 * successful copy_range (look at block_copy_do_copy).
290 s
->use_copy_range
= use_copy_range
;
291 s
->copy_size
= MAX(s
->cluster_size
, BLOCK_COPY_MAX_BUFFER
);
294 QLIST_INIT(&s
->tasks
);
295 QLIST_INIT(&s
->calls
);
300 void block_copy_set_progress_callback(
302 ProgressBytesCallbackFunc progress_bytes_callback
,
303 void *progress_opaque
)
305 s
->progress_bytes_callback
= progress_bytes_callback
;
306 s
->progress_opaque
= progress_opaque
;
309 void block_copy_set_progress_meter(BlockCopyState
*s
, ProgressMeter
*pm
)
315 * Takes ownership of @task
317 * If pool is NULL directly run the task, otherwise schedule it into the pool.
319 * Returns: task.func return code if pool is NULL
320 * otherwise -ECANCELED if pool status is bad
321 * otherwise 0 (successfully scheduled)
323 static coroutine_fn
int block_copy_task_run(AioTaskPool
*pool
,
327 int ret
= task
->task
.func(&task
->task
);
333 aio_task_pool_wait_slot(pool
);
334 if (aio_task_pool_status(pool
) < 0) {
335 co_put_to_shres(task
->s
->mem
, task
->bytes
);
336 block_copy_task_end(task
, -ECANCELED
);
341 aio_task_pool_start_task(pool
, &task
->task
);
349 * Do copy of cluster-aligned chunk. Requested region is allowed to exceed
350 * s->len only to cover last cluster when s->len is not aligned to clusters.
352 * No sync here: nor bitmap neighter intersecting requests handling, only copy.
354 * Returns 0 on success.
356 static int coroutine_fn
block_copy_do_copy(BlockCopyState
*s
,
357 int64_t offset
, int64_t bytes
,
358 bool zeroes
, bool *error_is_read
)
361 int64_t nbytes
= MIN(offset
+ bytes
, s
->len
) - offset
;
362 void *bounce_buffer
= NULL
;
364 assert(offset
>= 0 && bytes
> 0 && INT64_MAX
- offset
>= bytes
);
365 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
366 assert(QEMU_IS_ALIGNED(bytes
, s
->cluster_size
));
367 assert(offset
< s
->len
);
368 assert(offset
+ bytes
<= s
->len
||
369 offset
+ bytes
== QEMU_ALIGN_UP(s
->len
, s
->cluster_size
));
370 assert(nbytes
< INT_MAX
);
373 ret
= bdrv_co_pwrite_zeroes(s
->target
, offset
, nbytes
, s
->write_flags
&
374 ~BDRV_REQ_WRITE_COMPRESSED
);
376 trace_block_copy_write_zeroes_fail(s
, offset
, ret
);
377 *error_is_read
= false;
382 if (s
->use_copy_range
) {
383 ret
= bdrv_co_copy_range(s
->source
, offset
, s
->target
, offset
, nbytes
,
386 trace_block_copy_copy_range_fail(s
, offset
, ret
);
387 s
->use_copy_range
= false;
388 s
->copy_size
= MAX(s
->cluster_size
, BLOCK_COPY_MAX_BUFFER
);
389 /* Fallback to read+write with allocated buffer */
391 if (s
->use_copy_range
) {
393 * Successful copy-range. Now increase copy_size. copy_range
394 * does not respect max_transfer (it's a TODO), so we factor
397 * Note: we double-check s->use_copy_range for the case when
398 * parallel block-copy request unsets it during previous
399 * bdrv_co_copy_range call.
402 MIN(MAX(s
->cluster_size
, BLOCK_COPY_MAX_COPY_RANGE
),
403 QEMU_ALIGN_DOWN(block_copy_max_transfer(s
->source
,
412 * In case of failed copy_range request above, we may proceed with buffered
413 * request larger than BLOCK_COPY_MAX_BUFFER. Still, further requests will
414 * be properly limited, so don't care too much. Moreover the most likely
415 * case (copy_range is unsupported for the configuration, so the very first
416 * copy_range request fails) is handled by setting large copy_size only
417 * after first successful copy_range.
420 bounce_buffer
= qemu_blockalign(s
->source
->bs
, nbytes
);
422 ret
= bdrv_co_pread(s
->source
, offset
, nbytes
, bounce_buffer
, 0);
424 trace_block_copy_read_fail(s
, offset
, ret
);
425 *error_is_read
= true;
429 ret
= bdrv_co_pwrite(s
->target
, offset
, nbytes
, bounce_buffer
,
432 trace_block_copy_write_fail(s
, offset
, ret
);
433 *error_is_read
= false;
438 qemu_vfree(bounce_buffer
);
443 static coroutine_fn
int block_copy_task_entry(AioTask
*task
)
445 BlockCopyTask
*t
= container_of(task
, BlockCopyTask
, task
);
446 bool error_is_read
= false;
449 ret
= block_copy_do_copy(t
->s
, t
->offset
, t
->bytes
, t
->zeroes
,
451 if (ret
< 0 && !t
->call_state
->ret
) {
452 t
->call_state
->ret
= ret
;
453 t
->call_state
->error_is_read
= error_is_read
;
455 progress_work_done(t
->s
->progress
, t
->bytes
);
456 t
->s
->progress_bytes_callback(t
->bytes
, t
->s
->progress_opaque
);
458 co_put_to_shres(t
->s
->mem
, t
->bytes
);
459 block_copy_task_end(t
, ret
);
464 static int block_copy_block_status(BlockCopyState
*s
, int64_t offset
,
465 int64_t bytes
, int64_t *pnum
)
468 BlockDriverState
*base
;
471 if (s
->skip_unallocated
) {
472 base
= bdrv_backing_chain_next(s
->source
->bs
);
477 ret
= bdrv_block_status_above(s
->source
->bs
, base
, offset
, bytes
, &num
,
479 if (ret
< 0 || num
< s
->cluster_size
) {
481 * On error or if failed to obtain large enough chunk just fallback to
484 num
= s
->cluster_size
;
485 ret
= BDRV_BLOCK_ALLOCATED
| BDRV_BLOCK_DATA
;
486 } else if (offset
+ num
== s
->len
) {
487 num
= QEMU_ALIGN_UP(num
, s
->cluster_size
);
489 num
= QEMU_ALIGN_DOWN(num
, s
->cluster_size
);
497 * Check if the cluster starting at offset is allocated or not.
498 * return via pnum the number of contiguous clusters sharing this allocation.
500 static int block_copy_is_cluster_allocated(BlockCopyState
*s
, int64_t offset
,
503 BlockDriverState
*bs
= s
->source
->bs
;
504 int64_t count
, total_count
= 0;
505 int64_t bytes
= s
->len
- offset
;
508 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
511 ret
= bdrv_is_allocated(bs
, offset
, bytes
, &count
);
516 total_count
+= count
;
518 if (ret
|| count
== 0) {
520 * ret: partial segment(s) are considered allocated.
521 * otherwise: unallocated tail is treated as an entire segment.
523 *pnum
= DIV_ROUND_UP(total_count
, s
->cluster_size
);
527 /* Unallocated segment(s) with uncertain following segment(s) */
528 if (total_count
>= s
->cluster_size
) {
529 *pnum
= total_count
/ s
->cluster_size
;
539 * Reset bits in copy_bitmap starting at offset if they represent unallocated
540 * data in the image. May reset subsequent contiguous bits.
541 * @return 0 when the cluster at @offset was unallocated,
542 * 1 otherwise, and -ret on error.
544 int64_t block_copy_reset_unallocated(BlockCopyState
*s
,
545 int64_t offset
, int64_t *count
)
548 int64_t clusters
, bytes
;
550 ret
= block_copy_is_cluster_allocated(s
, offset
, &clusters
);
555 bytes
= clusters
* s
->cluster_size
;
558 bdrv_reset_dirty_bitmap(s
->copy_bitmap
, offset
, bytes
);
559 progress_set_remaining(s
->progress
,
560 bdrv_get_dirty_count(s
->copy_bitmap
) +
569 * block_copy_dirty_clusters
571 * Copy dirty clusters in @offset/@bytes range.
572 * Returns 1 if dirty clusters found and successfully copied, 0 if no dirty
573 * clusters found and -errno on failure.
575 static int coroutine_fn
576 block_copy_dirty_clusters(BlockCopyCallState
*call_state
)
578 BlockCopyState
*s
= call_state
->s
;
579 int64_t offset
= call_state
->offset
;
580 int64_t bytes
= call_state
->bytes
;
583 bool found_dirty
= false;
584 int64_t end
= offset
+ bytes
;
585 AioTaskPool
*aio
= NULL
;
588 * block_copy() user is responsible for keeping source and target in same
591 assert(bdrv_get_aio_context(s
->source
->bs
) ==
592 bdrv_get_aio_context(s
->target
->bs
));
594 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
595 assert(QEMU_IS_ALIGNED(bytes
, s
->cluster_size
));
597 while (bytes
&& aio_task_pool_status(aio
) == 0) {
599 int64_t status_bytes
;
601 task
= block_copy_task_create(s
, call_state
, offset
, bytes
);
603 /* No more dirty bits in the bitmap */
604 trace_block_copy_skip_range(s
, offset
, bytes
);
607 if (task
->offset
> offset
) {
608 trace_block_copy_skip_range(s
, offset
, task
->offset
- offset
);
613 ret
= block_copy_block_status(s
, task
->offset
, task
->bytes
,
615 assert(ret
>= 0); /* never fail */
616 if (status_bytes
< task
->bytes
) {
617 block_copy_task_shrink(task
, status_bytes
);
619 if (s
->skip_unallocated
&& !(ret
& BDRV_BLOCK_ALLOCATED
)) {
620 block_copy_task_end(task
, 0);
621 progress_set_remaining(s
->progress
,
622 bdrv_get_dirty_count(s
->copy_bitmap
) +
624 trace_block_copy_skip_range(s
, task
->offset
, task
->bytes
);
625 offset
= task_end(task
);
626 bytes
= end
- offset
;
630 task
->zeroes
= ret
& BDRV_BLOCK_ZERO
;
633 if (!call_state
->ignore_ratelimit
) {
634 uint64_t ns
= ratelimit_calculate_delay(&s
->rate_limit
, 0);
636 block_copy_task_end(task
, -EAGAIN
);
638 qemu_co_sleep_ns_wakeable(QEMU_CLOCK_REALTIME
, ns
,
639 &call_state
->sleep_state
);
644 ratelimit_calculate_delay(&s
->rate_limit
, task
->bytes
);
647 trace_block_copy_process(s
, task
->offset
);
649 co_get_from_shres(s
->mem
, task
->bytes
);
651 offset
= task_end(task
);
652 bytes
= end
- offset
;
655 aio
= aio_task_pool_new(call_state
->max_workers
);
658 ret
= block_copy_task_run(aio
, task
);
666 aio_task_pool_wait_all(aio
);
669 * We are not really interested in -ECANCELED returned from
670 * block_copy_task_run. If it fails, it means some task already failed
671 * for real reason, let's return first failure.
672 * Still, assert that we don't rewrite failure by success.
674 * Note: ret may be positive here because of block-status result.
676 assert(ret
>= 0 || aio_task_pool_status(aio
) < 0);
677 ret
= aio_task_pool_status(aio
);
679 aio_task_pool_free(aio
);
682 return ret
< 0 ? ret
: found_dirty
;
685 void block_copy_kick(BlockCopyCallState
*call_state
)
687 if (call_state
->sleep_state
) {
688 qemu_co_sleep_wake(call_state
->sleep_state
);
695 * Copy requested region, accordingly to dirty bitmap.
696 * Collaborate with parallel block_copy requests: if they succeed it will help
697 * us. If they fail, we will retry not-copied regions. So, if we return error,
698 * it means that some I/O operation failed in context of _this_ block_copy call,
699 * not some parallel operation.
701 static int coroutine_fn
block_copy_common(BlockCopyCallState
*call_state
)
705 QLIST_INSERT_HEAD(&call_state
->s
->calls
, call_state
, list
);
708 ret
= block_copy_dirty_clusters(call_state
);
711 ret
= block_copy_wait_one(call_state
->s
, call_state
->offset
,
716 * We retry in two cases:
717 * 1. Some progress done
718 * Something was copied, which means that there were yield points
719 * and some new dirty bits may have appeared (due to failed parallel
720 * block-copy requests).
721 * 2. We have waited for some intersecting block-copy request
722 * It may have failed and produced new dirty bits.
726 call_state
->finished
= true;
728 if (call_state
->cb
) {
729 call_state
->cb(call_state
->cb_opaque
);
732 QLIST_REMOVE(call_state
, list
);
737 int coroutine_fn
block_copy(BlockCopyState
*s
, int64_t start
, int64_t bytes
,
738 bool ignore_ratelimit
, bool *error_is_read
)
740 BlockCopyCallState call_state
= {
744 .ignore_ratelimit
= ignore_ratelimit
,
745 .max_workers
= BLOCK_COPY_MAX_WORKERS
,
748 int ret
= block_copy_common(&call_state
);
750 if (error_is_read
&& ret
< 0) {
751 *error_is_read
= call_state
.error_is_read
;
757 static void coroutine_fn
block_copy_async_co_entry(void *opaque
)
759 block_copy_common(opaque
);
762 BlockCopyCallState
*block_copy_async(BlockCopyState
*s
,
763 int64_t offset
, int64_t bytes
,
764 int max_workers
, int64_t max_chunk
,
765 BlockCopyAsyncCallbackFunc cb
,
768 BlockCopyCallState
*call_state
= g_new(BlockCopyCallState
, 1);
770 *call_state
= (BlockCopyCallState
) {
774 .max_workers
= max_workers
,
775 .max_chunk
= max_chunk
,
777 .cb_opaque
= cb_opaque
,
779 .co
= qemu_coroutine_create(block_copy_async_co_entry
, call_state
),
782 qemu_coroutine_enter(call_state
->co
);
787 void block_copy_call_free(BlockCopyCallState
*call_state
)
793 assert(call_state
->finished
);
797 bool block_copy_call_finished(BlockCopyCallState
*call_state
)
799 return call_state
->finished
;
802 bool block_copy_call_succeeded(BlockCopyCallState
*call_state
)
804 return call_state
->finished
&& call_state
->ret
== 0;
807 bool block_copy_call_failed(BlockCopyCallState
*call_state
)
809 return call_state
->finished
&& call_state
->ret
< 0;
812 int block_copy_call_status(BlockCopyCallState
*call_state
, bool *error_is_read
)
814 assert(call_state
->finished
);
816 *error_is_read
= call_state
->error_is_read
;
818 return call_state
->ret
;
821 BdrvDirtyBitmap
*block_copy_dirty_bitmap(BlockCopyState
*s
)
823 return s
->copy_bitmap
;
826 void block_copy_set_skip_unallocated(BlockCopyState
*s
, bool skip
)
828 s
->skip_unallocated
= skip
;
831 void block_copy_set_speed(BlockCopyState
*s
, uint64_t speed
)
835 ratelimit_set_speed(&s
->rate_limit
, speed
, BLOCK_COPY_SLICE_TIME
);
839 * Note: it's good to kick all call states from here, but it should be done
840 * only from a coroutine, to not crash if s->calls list changed while
841 * entering one call. So for now, the only user of this function kicks its
842 * only one call_state by hand.