4 * Copyright (c) 2003-2008 Fabrice Bellard
5 * Copyright (c) 2011-2015 Red Hat Inc
8 * Juan Quintela <quintela@redhat.com>
10 * Permission is hereby granted, free of charge, to any person obtaining a copy
11 * of this software and associated documentation files (the "Software"), to deal
12 * in the Software without restriction, including without limitation the rights
13 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 * copies of the Software, and to permit persons to whom the Software is
15 * furnished to do so, subject to the following conditions:
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 #include "qemu/bitops.h"
31 #include "qemu/bitmap.h"
32 #include "qemu/timer.h"
33 #include "qemu/main-loop.h"
34 #include "migration/migration.h"
35 #include "exec/address-spaces.h"
36 #include "migration/page_cache.h"
37 #include "qemu/error-report.h"
39 #include "exec/ram_addr.h"
40 #include "qemu/rcu_queue.h"
42 #ifdef DEBUG_MIGRATION_RAM
43 #define DPRINTF(fmt, ...) \
44 do { fprintf(stdout, "migration_ram: " fmt, ## __VA_ARGS__); } while (0)
46 #define DPRINTF(fmt, ...) \
50 static bool mig_throttle_on
;
51 static int dirty_rate_high_cnt
;
52 static void check_guest_throttling(void);
54 static uint64_t bitmap_sync_count
;
56 /***********************************************************/
57 /* ram save/restore */
59 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
60 #define RAM_SAVE_FLAG_COMPRESS 0x02
61 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
62 #define RAM_SAVE_FLAG_PAGE 0x08
63 #define RAM_SAVE_FLAG_EOS 0x10
64 #define RAM_SAVE_FLAG_CONTINUE 0x20
65 #define RAM_SAVE_FLAG_XBZRLE 0x40
66 /* 0x80 is reserved in migration.h start with 0x100 next */
67 #define RAM_SAVE_FLAG_COMPRESS_PAGE 0x100
69 static const uint8_t ZERO_TARGET_PAGE
[TARGET_PAGE_SIZE
];
71 static inline bool is_zero_range(uint8_t *p
, uint64_t size
)
73 return buffer_find_nonzero_offset(p
, size
) == size
;
76 /* struct contains XBZRLE cache and a static page
77 used by the compression */
79 /* buffer used for XBZRLE encoding */
81 /* buffer for storing page content */
83 /* Cache for XBZRLE, Protected by lock. */
88 /* buffer used for XBZRLE decoding */
89 static uint8_t *xbzrle_decoded_buf
;
91 static void XBZRLE_cache_lock(void)
93 if (migrate_use_xbzrle())
94 qemu_mutex_lock(&XBZRLE
.lock
);
97 static void XBZRLE_cache_unlock(void)
99 if (migrate_use_xbzrle())
100 qemu_mutex_unlock(&XBZRLE
.lock
);
104 * called from qmp_migrate_set_cache_size in main thread, possibly while
105 * a migration is in progress.
106 * A running migration maybe using the cache and might finish during this
107 * call, hence changes to the cache are protected by XBZRLE.lock().
109 int64_t xbzrle_cache_resize(int64_t new_size
)
111 PageCache
*new_cache
;
114 if (new_size
< TARGET_PAGE_SIZE
) {
120 if (XBZRLE
.cache
!= NULL
) {
121 if (pow2floor(new_size
) == migrate_xbzrle_cache_size()) {
124 new_cache
= cache_init(new_size
/ TARGET_PAGE_SIZE
,
127 error_report("Error creating cache");
132 cache_fini(XBZRLE
.cache
);
133 XBZRLE
.cache
= new_cache
;
137 ret
= pow2floor(new_size
);
139 XBZRLE_cache_unlock();
143 /* accounting for migration statistics */
144 typedef struct AccountingInfo
{
146 uint64_t skipped_pages
;
149 uint64_t xbzrle_bytes
;
150 uint64_t xbzrle_pages
;
151 uint64_t xbzrle_cache_miss
;
152 double xbzrle_cache_miss_rate
;
153 uint64_t xbzrle_overflows
;
156 static AccountingInfo acct_info
;
158 static void acct_clear(void)
160 memset(&acct_info
, 0, sizeof(acct_info
));
163 uint64_t dup_mig_bytes_transferred(void)
165 return acct_info
.dup_pages
* TARGET_PAGE_SIZE
;
168 uint64_t dup_mig_pages_transferred(void)
170 return acct_info
.dup_pages
;
173 uint64_t skipped_mig_bytes_transferred(void)
175 return acct_info
.skipped_pages
* TARGET_PAGE_SIZE
;
178 uint64_t skipped_mig_pages_transferred(void)
180 return acct_info
.skipped_pages
;
183 uint64_t norm_mig_bytes_transferred(void)
185 return acct_info
.norm_pages
* TARGET_PAGE_SIZE
;
188 uint64_t norm_mig_pages_transferred(void)
190 return acct_info
.norm_pages
;
193 uint64_t xbzrle_mig_bytes_transferred(void)
195 return acct_info
.xbzrle_bytes
;
198 uint64_t xbzrle_mig_pages_transferred(void)
200 return acct_info
.xbzrle_pages
;
203 uint64_t xbzrle_mig_pages_cache_miss(void)
205 return acct_info
.xbzrle_cache_miss
;
208 double xbzrle_mig_cache_miss_rate(void)
210 return acct_info
.xbzrle_cache_miss_rate
;
213 uint64_t xbzrle_mig_pages_overflow(void)
215 return acct_info
.xbzrle_overflows
;
218 /* This is the last block that we have visited serching for dirty pages
220 static RAMBlock
*last_seen_block
;
221 /* This is the last block from where we have sent data */
222 static RAMBlock
*last_sent_block
;
223 static ram_addr_t last_offset
;
224 static unsigned long *migration_bitmap
;
225 static uint64_t migration_dirty_pages
;
226 static uint32_t last_version
;
227 static bool ram_bulk_stage
;
229 struct CompressParam
{
238 typedef struct CompressParam CompressParam
;
240 struct DecompressParam
{
248 typedef struct DecompressParam DecompressParam
;
250 static CompressParam
*comp_param
;
251 static QemuThread
*compress_threads
;
252 /* comp_done_cond is used to wake up the migration thread when
253 * one of the compression threads has finished the compression.
254 * comp_done_lock is used to co-work with comp_done_cond.
256 static QemuMutex
*comp_done_lock
;
257 static QemuCond
*comp_done_cond
;
258 /* The empty QEMUFileOps will be used by file in CompressParam */
259 static const QEMUFileOps empty_ops
= { };
261 static bool compression_switch
;
262 static bool quit_comp_thread
;
263 static bool quit_decomp_thread
;
264 static DecompressParam
*decomp_param
;
265 static QemuThread
*decompress_threads
;
266 static uint8_t *compressed_data_buf
;
268 static int do_compress_ram_page(CompressParam
*param
);
270 static void *do_data_compress(void *opaque
)
272 CompressParam
*param
= opaque
;
274 while (!quit_comp_thread
) {
275 qemu_mutex_lock(¶m
->mutex
);
276 /* Re-check the quit_comp_thread in case of
277 * terminate_compression_threads is called just before
278 * qemu_mutex_lock(¶m->mutex) and after
279 * while(!quit_comp_thread), re-check it here can make
280 * sure the compression thread terminate as expected.
282 while (!param
->start
&& !quit_comp_thread
) {
283 qemu_cond_wait(¶m
->cond
, ¶m
->mutex
);
285 if (!quit_comp_thread
) {
286 do_compress_ram_page(param
);
288 param
->start
= false;
289 qemu_mutex_unlock(¶m
->mutex
);
291 qemu_mutex_lock(comp_done_lock
);
293 qemu_cond_signal(comp_done_cond
);
294 qemu_mutex_unlock(comp_done_lock
);
300 static inline void terminate_compression_threads(void)
302 int idx
, thread_count
;
304 thread_count
= migrate_compress_threads();
305 quit_comp_thread
= true;
306 for (idx
= 0; idx
< thread_count
; idx
++) {
307 qemu_mutex_lock(&comp_param
[idx
].mutex
);
308 qemu_cond_signal(&comp_param
[idx
].cond
);
309 qemu_mutex_unlock(&comp_param
[idx
].mutex
);
313 void migrate_compress_threads_join(void)
317 if (!migrate_use_compression()) {
320 terminate_compression_threads();
321 thread_count
= migrate_compress_threads();
322 for (i
= 0; i
< thread_count
; i
++) {
323 qemu_thread_join(compress_threads
+ i
);
324 qemu_fclose(comp_param
[i
].file
);
325 qemu_mutex_destroy(&comp_param
[i
].mutex
);
326 qemu_cond_destroy(&comp_param
[i
].cond
);
328 qemu_mutex_destroy(comp_done_lock
);
329 qemu_cond_destroy(comp_done_cond
);
330 g_free(compress_threads
);
332 g_free(comp_done_cond
);
333 g_free(comp_done_lock
);
334 compress_threads
= NULL
;
336 comp_done_cond
= NULL
;
337 comp_done_lock
= NULL
;
340 void migrate_compress_threads_create(void)
344 if (!migrate_use_compression()) {
347 quit_comp_thread
= false;
348 compression_switch
= true;
349 thread_count
= migrate_compress_threads();
350 compress_threads
= g_new0(QemuThread
, thread_count
);
351 comp_param
= g_new0(CompressParam
, thread_count
);
352 comp_done_cond
= g_new0(QemuCond
, 1);
353 comp_done_lock
= g_new0(QemuMutex
, 1);
354 qemu_cond_init(comp_done_cond
);
355 qemu_mutex_init(comp_done_lock
);
356 for (i
= 0; i
< thread_count
; i
++) {
357 /* com_param[i].file is just used as a dummy buffer to save data, set
360 comp_param
[i
].file
= qemu_fopen_ops(NULL
, &empty_ops
);
361 comp_param
[i
].done
= true;
362 qemu_mutex_init(&comp_param
[i
].mutex
);
363 qemu_cond_init(&comp_param
[i
].cond
);
364 qemu_thread_create(compress_threads
+ i
, "compress",
365 do_data_compress
, comp_param
+ i
,
366 QEMU_THREAD_JOINABLE
);
371 * save_page_header: Write page header to wire
373 * If this is the 1st block, it also writes the block identification
375 * Returns: Number of bytes written
377 * @f: QEMUFile where to send the data
378 * @block: block that contains the page we want to send
379 * @offset: offset inside the block for the page
380 * in the lower bits, it contains flags
382 static size_t save_page_header(QEMUFile
*f
, RAMBlock
*block
, ram_addr_t offset
)
386 qemu_put_be64(f
, offset
);
389 if (!(offset
& RAM_SAVE_FLAG_CONTINUE
)) {
390 qemu_put_byte(f
, strlen(block
->idstr
));
391 qemu_put_buffer(f
, (uint8_t *)block
->idstr
,
392 strlen(block
->idstr
));
393 size
+= 1 + strlen(block
->idstr
);
398 /* Update the xbzrle cache to reflect a page that's been sent as all 0.
399 * The important thing is that a stale (not-yet-0'd) page be replaced
401 * As a bonus, if the page wasn't in the cache it gets added so that
402 * when a small write is made into the 0'd page it gets XBZRLE sent
404 static void xbzrle_cache_zero_page(ram_addr_t current_addr
)
406 if (ram_bulk_stage
|| !migrate_use_xbzrle()) {
410 /* We don't care if this fails to allocate a new cache page
411 * as long as it updated an old one */
412 cache_insert(XBZRLE
.cache
, current_addr
, ZERO_TARGET_PAGE
,
416 #define ENCODING_FLAG_XBZRLE 0x1
419 * save_xbzrle_page: compress and send current page
421 * Returns: 1 means that we wrote the page
422 * 0 means that page is identical to the one already sent
423 * -1 means that xbzrle would be longer than normal
425 * @f: QEMUFile where to send the data
428 * @block: block that contains the page we want to send
429 * @offset: offset inside the block for the page
430 * @last_stage: if we are at the completion stage
431 * @bytes_transferred: increase it with the number of transferred bytes
433 static int save_xbzrle_page(QEMUFile
*f
, uint8_t **current_data
,
434 ram_addr_t current_addr
, RAMBlock
*block
,
435 ram_addr_t offset
, bool last_stage
,
436 uint64_t *bytes_transferred
)
438 int encoded_len
= 0, bytes_xbzrle
;
439 uint8_t *prev_cached_page
;
441 if (!cache_is_cached(XBZRLE
.cache
, current_addr
, bitmap_sync_count
)) {
442 acct_info
.xbzrle_cache_miss
++;
444 if (cache_insert(XBZRLE
.cache
, current_addr
, *current_data
,
445 bitmap_sync_count
) == -1) {
448 /* update *current_data when the page has been
449 inserted into cache */
450 *current_data
= get_cached_data(XBZRLE
.cache
, current_addr
);
456 prev_cached_page
= get_cached_data(XBZRLE
.cache
, current_addr
);
458 /* save current buffer into memory */
459 memcpy(XBZRLE
.current_buf
, *current_data
, TARGET_PAGE_SIZE
);
461 /* XBZRLE encoding (if there is no overflow) */
462 encoded_len
= xbzrle_encode_buffer(prev_cached_page
, XBZRLE
.current_buf
,
463 TARGET_PAGE_SIZE
, XBZRLE
.encoded_buf
,
465 if (encoded_len
== 0) {
466 DPRINTF("Skipping unmodified page\n");
468 } else if (encoded_len
== -1) {
469 DPRINTF("Overflow\n");
470 acct_info
.xbzrle_overflows
++;
471 /* update data in the cache */
473 memcpy(prev_cached_page
, *current_data
, TARGET_PAGE_SIZE
);
474 *current_data
= prev_cached_page
;
479 /* we need to update the data in the cache, in order to get the same data */
481 memcpy(prev_cached_page
, XBZRLE
.current_buf
, TARGET_PAGE_SIZE
);
484 /* Send XBZRLE based compressed page */
485 bytes_xbzrle
= save_page_header(f
, block
, offset
| RAM_SAVE_FLAG_XBZRLE
);
486 qemu_put_byte(f
, ENCODING_FLAG_XBZRLE
);
487 qemu_put_be16(f
, encoded_len
);
488 qemu_put_buffer(f
, XBZRLE
.encoded_buf
, encoded_len
);
489 bytes_xbzrle
+= encoded_len
+ 1 + 2;
490 acct_info
.xbzrle_pages
++;
491 acct_info
.xbzrle_bytes
+= bytes_xbzrle
;
492 *bytes_transferred
+= bytes_xbzrle
;
498 ram_addr_t
migration_bitmap_find_and_reset_dirty(MemoryRegion
*mr
,
501 unsigned long base
= mr
->ram_addr
>> TARGET_PAGE_BITS
;
502 unsigned long nr
= base
+ (start
>> TARGET_PAGE_BITS
);
503 uint64_t mr_size
= TARGET_PAGE_ALIGN(memory_region_size(mr
));
504 unsigned long size
= base
+ (mr_size
>> TARGET_PAGE_BITS
);
508 if (ram_bulk_stage
&& nr
> base
) {
511 next
= find_next_bit(migration_bitmap
, size
, nr
);
515 clear_bit(next
, migration_bitmap
);
516 migration_dirty_pages
--;
518 return (next
- base
) << TARGET_PAGE_BITS
;
521 static void migration_bitmap_sync_range(ram_addr_t start
, ram_addr_t length
)
523 migration_dirty_pages
+=
524 cpu_physical_memory_sync_dirty_bitmap(migration_bitmap
, start
, length
);
528 /* Fix me: there are too many global variables used in migration process. */
529 static int64_t start_time
;
530 static int64_t bytes_xfer_prev
;
531 static int64_t num_dirty_pages_period
;
532 static uint64_t xbzrle_cache_miss_prev
;
533 static uint64_t iterations_prev
;
535 static void migration_bitmap_sync_init(void)
539 num_dirty_pages_period
= 0;
540 xbzrle_cache_miss_prev
= 0;
544 /* Called with iothread lock held, to protect ram_list.dirty_memory[] */
545 static void migration_bitmap_sync(void)
548 uint64_t num_dirty_pages_init
= migration_dirty_pages
;
549 MigrationState
*s
= migrate_get_current();
551 int64_t bytes_xfer_now
;
555 if (!bytes_xfer_prev
) {
556 bytes_xfer_prev
= ram_bytes_transferred();
560 start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
563 trace_migration_bitmap_sync_start();
564 address_space_sync_dirty_bitmap(&address_space_memory
);
567 QLIST_FOREACH_RCU(block
, &ram_list
.blocks
, next
) {
568 migration_bitmap_sync_range(block
->mr
->ram_addr
, block
->used_length
);
572 trace_migration_bitmap_sync_end(migration_dirty_pages
573 - num_dirty_pages_init
);
574 num_dirty_pages_period
+= migration_dirty_pages
- num_dirty_pages_init
;
575 end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
577 /* more than 1 second = 1000 millisecons */
578 if (end_time
> start_time
+ 1000) {
579 if (migrate_auto_converge()) {
580 /* The following detection logic can be refined later. For now:
581 Check to see if the dirtied bytes is 50% more than the approx.
582 amount of bytes that just got transferred since the last time we
583 were in this routine. If that happens >N times (for now N==4)
584 we turn on the throttle down logic */
585 bytes_xfer_now
= ram_bytes_transferred();
586 if (s
->dirty_pages_rate
&&
587 (num_dirty_pages_period
* TARGET_PAGE_SIZE
>
588 (bytes_xfer_now
- bytes_xfer_prev
)/2) &&
589 (dirty_rate_high_cnt
++ > 4)) {
590 trace_migration_throttle();
591 mig_throttle_on
= true;
592 dirty_rate_high_cnt
= 0;
594 bytes_xfer_prev
= bytes_xfer_now
;
596 mig_throttle_on
= false;
598 if (migrate_use_xbzrle()) {
599 if (iterations_prev
!= acct_info
.iterations
) {
600 acct_info
.xbzrle_cache_miss_rate
=
601 (double)(acct_info
.xbzrle_cache_miss
-
602 xbzrle_cache_miss_prev
) /
603 (acct_info
.iterations
- iterations_prev
);
605 iterations_prev
= acct_info
.iterations
;
606 xbzrle_cache_miss_prev
= acct_info
.xbzrle_cache_miss
;
608 s
->dirty_pages_rate
= num_dirty_pages_period
* 1000
609 / (end_time
- start_time
);
610 s
->dirty_bytes_rate
= s
->dirty_pages_rate
* TARGET_PAGE_SIZE
;
611 start_time
= end_time
;
612 num_dirty_pages_period
= 0;
614 s
->dirty_sync_count
= bitmap_sync_count
;
618 * save_zero_page: Send the zero page to the stream
620 * Returns: Number of pages written.
622 * @f: QEMUFile where to send the data
623 * @block: block that contains the page we want to send
624 * @offset: offset inside the block for the page
625 * @p: pointer to the page
626 * @bytes_transferred: increase it with the number of transferred bytes
628 static int save_zero_page(QEMUFile
*f
, RAMBlock
*block
, ram_addr_t offset
,
629 uint8_t *p
, uint64_t *bytes_transferred
)
633 if (is_zero_range(p
, TARGET_PAGE_SIZE
)) {
634 acct_info
.dup_pages
++;
635 *bytes_transferred
+= save_page_header(f
, block
,
636 offset
| RAM_SAVE_FLAG_COMPRESS
);
638 *bytes_transferred
+= 1;
646 * ram_save_page: Send the given page to the stream
648 * Returns: Number of pages written.
650 * @f: QEMUFile where to send the data
651 * @block: block that contains the page we want to send
652 * @offset: offset inside the block for the page
653 * @last_stage: if we are at the completion stage
654 * @bytes_transferred: increase it with the number of transferred bytes
656 static int ram_save_page(QEMUFile
*f
, RAMBlock
* block
, ram_addr_t offset
,
657 bool last_stage
, uint64_t *bytes_transferred
)
661 ram_addr_t current_addr
;
662 MemoryRegion
*mr
= block
->mr
;
665 bool send_async
= true;
667 p
= memory_region_get_ram_ptr(mr
) + offset
;
669 /* In doubt sent page as normal */
671 ret
= ram_control_save_page(f
, block
->offset
,
672 offset
, TARGET_PAGE_SIZE
, &bytes_xmit
);
674 *bytes_transferred
+= bytes_xmit
;
680 current_addr
= block
->offset
+ offset
;
682 if (block
== last_sent_block
) {
683 offset
|= RAM_SAVE_FLAG_CONTINUE
;
685 if (ret
!= RAM_SAVE_CONTROL_NOT_SUPP
) {
686 if (ret
!= RAM_SAVE_CONTROL_DELAYED
) {
687 if (bytes_xmit
> 0) {
688 acct_info
.norm_pages
++;
689 } else if (bytes_xmit
== 0) {
690 acct_info
.dup_pages
++;
694 pages
= save_zero_page(f
, block
, offset
, p
, bytes_transferred
);
696 /* Must let xbzrle know, otherwise a previous (now 0'd) cached
697 * page would be stale
699 xbzrle_cache_zero_page(current_addr
);
700 } else if (!ram_bulk_stage
&& migrate_use_xbzrle()) {
701 pages
= save_xbzrle_page(f
, &p
, current_addr
, block
,
702 offset
, last_stage
, bytes_transferred
);
704 /* Can't send this cached data async, since the cache page
705 * might get updated before it gets to the wire
712 /* XBZRLE overflow or normal page */
714 *bytes_transferred
+= save_page_header(f
, block
,
715 offset
| RAM_SAVE_FLAG_PAGE
);
717 qemu_put_buffer_async(f
, p
, TARGET_PAGE_SIZE
);
719 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
721 *bytes_transferred
+= TARGET_PAGE_SIZE
;
723 acct_info
.norm_pages
++;
726 XBZRLE_cache_unlock();
731 static int do_compress_ram_page(CompressParam
*param
)
733 int bytes_sent
, blen
;
735 RAMBlock
*block
= param
->block
;
736 ram_addr_t offset
= param
->offset
;
738 p
= memory_region_get_ram_ptr(block
->mr
) + (offset
& TARGET_PAGE_MASK
);
740 bytes_sent
= save_page_header(param
->file
, block
, offset
|
741 RAM_SAVE_FLAG_COMPRESS_PAGE
);
742 blen
= qemu_put_compression_data(param
->file
, p
, TARGET_PAGE_SIZE
,
743 migrate_compress_level());
749 static inline void start_compression(CompressParam
*param
)
752 qemu_mutex_lock(¶m
->mutex
);
754 qemu_cond_signal(¶m
->cond
);
755 qemu_mutex_unlock(¶m
->mutex
);
758 static inline void start_decompression(DecompressParam
*param
)
760 qemu_mutex_lock(¶m
->mutex
);
762 qemu_cond_signal(¶m
->cond
);
763 qemu_mutex_unlock(¶m
->mutex
);
766 static uint64_t bytes_transferred
;
768 static void flush_compressed_data(QEMUFile
*f
)
770 int idx
, len
, thread_count
;
772 if (!migrate_use_compression()) {
775 thread_count
= migrate_compress_threads();
776 for (idx
= 0; idx
< thread_count
; idx
++) {
777 if (!comp_param
[idx
].done
) {
778 qemu_mutex_lock(comp_done_lock
);
779 while (!comp_param
[idx
].done
&& !quit_comp_thread
) {
780 qemu_cond_wait(comp_done_cond
, comp_done_lock
);
782 qemu_mutex_unlock(comp_done_lock
);
784 if (!quit_comp_thread
) {
785 len
= qemu_put_qemu_file(f
, comp_param
[idx
].file
);
786 bytes_transferred
+= len
;
791 static inline void set_compress_params(CompressParam
*param
, RAMBlock
*block
,
794 param
->block
= block
;
795 param
->offset
= offset
;
798 static int compress_page_with_multi_thread(QEMUFile
*f
, RAMBlock
*block
,
800 uint64_t *bytes_transferred
)
802 int idx
, thread_count
, bytes_xmit
= -1, pages
= -1;
804 thread_count
= migrate_compress_threads();
805 qemu_mutex_lock(comp_done_lock
);
807 for (idx
= 0; idx
< thread_count
; idx
++) {
808 if (comp_param
[idx
].done
) {
809 bytes_xmit
= qemu_put_qemu_file(f
, comp_param
[idx
].file
);
810 set_compress_params(&comp_param
[idx
], block
, offset
);
811 start_compression(&comp_param
[idx
]);
813 acct_info
.norm_pages
++;
814 *bytes_transferred
+= bytes_xmit
;
821 qemu_cond_wait(comp_done_cond
, comp_done_lock
);
824 qemu_mutex_unlock(comp_done_lock
);
830 * ram_save_compressed_page: compress the given page and send it to the stream
832 * Returns: Number of pages written.
834 * @f: QEMUFile where to send the data
835 * @block: block that contains the page we want to send
836 * @offset: offset inside the block for the page
837 * @last_stage: if we are at the completion stage
838 * @bytes_transferred: increase it with the number of transferred bytes
840 static int ram_save_compressed_page(QEMUFile
*f
, RAMBlock
*block
,
841 ram_addr_t offset
, bool last_stage
,
842 uint64_t *bytes_transferred
)
846 MemoryRegion
*mr
= block
->mr
;
850 p
= memory_region_get_ram_ptr(mr
) + offset
;
853 ret
= ram_control_save_page(f
, block
->offset
,
854 offset
, TARGET_PAGE_SIZE
, &bytes_xmit
);
856 *bytes_transferred
+= bytes_xmit
;
859 if (block
== last_sent_block
) {
860 offset
|= RAM_SAVE_FLAG_CONTINUE
;
862 if (ret
!= RAM_SAVE_CONTROL_NOT_SUPP
) {
863 if (ret
!= RAM_SAVE_CONTROL_DELAYED
) {
864 if (bytes_xmit
> 0) {
865 acct_info
.norm_pages
++;
866 } else if (bytes_xmit
== 0) {
867 acct_info
.dup_pages
++;
871 /* When starting the process of a new block, the first page of
872 * the block should be sent out before other pages in the same
873 * block, and all the pages in last block should have been sent
874 * out, keeping this order is important, because the 'cont' flag
875 * is used to avoid resending the block name.
877 if (block
!= last_sent_block
) {
878 flush_compressed_data(f
);
879 pages
= save_zero_page(f
, block
, offset
, p
, bytes_transferred
);
881 set_compress_params(&comp_param
[0], block
, offset
);
882 /* Use the qemu thread to compress the data to make sure the
883 * first page is sent out before other pages
885 bytes_xmit
= do_compress_ram_page(&comp_param
[0]);
886 acct_info
.norm_pages
++;
887 qemu_put_qemu_file(f
, comp_param
[0].file
);
888 *bytes_transferred
+= bytes_xmit
;
892 pages
= save_zero_page(f
, block
, offset
, p
, bytes_transferred
);
894 pages
= compress_page_with_multi_thread(f
, block
, offset
,
904 * ram_find_and_save_block: Finds a dirty page and sends it to f
906 * Called within an RCU critical section.
908 * Returns: The number of pages written
909 * 0 means no dirty pages
911 * @f: QEMUFile where to send the data
912 * @last_stage: if we are at the completion stage
913 * @bytes_transferred: increase it with the number of transferred bytes
916 static int ram_find_and_save_block(QEMUFile
*f
, bool last_stage
,
917 uint64_t *bytes_transferred
)
919 RAMBlock
*block
= last_seen_block
;
920 ram_addr_t offset
= last_offset
;
921 bool complete_round
= false;
926 block
= QLIST_FIRST_RCU(&ram_list
.blocks
);
930 offset
= migration_bitmap_find_and_reset_dirty(mr
, offset
);
931 if (complete_round
&& block
== last_seen_block
&&
932 offset
>= last_offset
) {
935 if (offset
>= block
->used_length
) {
937 block
= QLIST_NEXT_RCU(block
, next
);
939 block
= QLIST_FIRST_RCU(&ram_list
.blocks
);
940 complete_round
= true;
941 ram_bulk_stage
= false;
942 if (migrate_use_xbzrle()) {
943 /* If xbzrle is on, stop using the data compression at this
944 * point. In theory, xbzrle can do better than compression.
946 flush_compressed_data(f
);
947 compression_switch
= false;
951 if (compression_switch
&& migrate_use_compression()) {
952 pages
= ram_save_compressed_page(f
, block
, offset
, last_stage
,
955 pages
= ram_save_page(f
, block
, offset
, last_stage
,
959 /* if page is unmodified, continue to the next */
961 last_sent_block
= block
;
967 last_seen_block
= block
;
968 last_offset
= offset
;
973 void acct_update_position(QEMUFile
*f
, size_t size
, bool zero
)
975 uint64_t pages
= size
/ TARGET_PAGE_SIZE
;
977 acct_info
.dup_pages
+= pages
;
979 acct_info
.norm_pages
+= pages
;
980 bytes_transferred
+= size
;
981 qemu_update_position(f
, size
);
985 static ram_addr_t
ram_save_remaining(void)
987 return migration_dirty_pages
;
990 uint64_t ram_bytes_remaining(void)
992 return ram_save_remaining() * TARGET_PAGE_SIZE
;
995 uint64_t ram_bytes_transferred(void)
997 return bytes_transferred
;
1000 uint64_t ram_bytes_total(void)
1006 QLIST_FOREACH_RCU(block
, &ram_list
.blocks
, next
)
1007 total
+= block
->used_length
;
1012 void free_xbzrle_decoded_buf(void)
1014 g_free(xbzrle_decoded_buf
);
1015 xbzrle_decoded_buf
= NULL
;
1018 static void migration_end(void)
1020 if (migration_bitmap
) {
1021 memory_global_dirty_log_stop();
1022 g_free(migration_bitmap
);
1023 migration_bitmap
= NULL
;
1026 XBZRLE_cache_lock();
1028 cache_fini(XBZRLE
.cache
);
1029 g_free(XBZRLE
.encoded_buf
);
1030 g_free(XBZRLE
.current_buf
);
1031 XBZRLE
.cache
= NULL
;
1032 XBZRLE
.encoded_buf
= NULL
;
1033 XBZRLE
.current_buf
= NULL
;
1035 XBZRLE_cache_unlock();
1038 static void ram_migration_cancel(void *opaque
)
1043 static void reset_ram_globals(void)
1045 last_seen_block
= NULL
;
1046 last_sent_block
= NULL
;
1048 last_version
= ram_list
.version
;
1049 ram_bulk_stage
= true;
1052 #define MAX_WAIT 50 /* ms, half buffered_file limit */
1055 /* Each of ram_save_setup, ram_save_iterate and ram_save_complete has
1056 * long-running RCU critical section. When rcu-reclaims in the code
1057 * start to become numerous it will be necessary to reduce the
1058 * granularity of these critical sections.
1061 static int ram_save_setup(QEMUFile
*f
, void *opaque
)
1064 int64_t ram_bitmap_pages
; /* Size of bitmap in pages, including gaps */
1066 mig_throttle_on
= false;
1067 dirty_rate_high_cnt
= 0;
1068 bitmap_sync_count
= 0;
1069 migration_bitmap_sync_init();
1071 if (migrate_use_xbzrle()) {
1072 XBZRLE_cache_lock();
1073 XBZRLE
.cache
= cache_init(migrate_xbzrle_cache_size() /
1076 if (!XBZRLE
.cache
) {
1077 XBZRLE_cache_unlock();
1078 error_report("Error creating cache");
1081 XBZRLE_cache_unlock();
1083 /* We prefer not to abort if there is no memory */
1084 XBZRLE
.encoded_buf
= g_try_malloc0(TARGET_PAGE_SIZE
);
1085 if (!XBZRLE
.encoded_buf
) {
1086 error_report("Error allocating encoded_buf");
1090 XBZRLE
.current_buf
= g_try_malloc(TARGET_PAGE_SIZE
);
1091 if (!XBZRLE
.current_buf
) {
1092 error_report("Error allocating current_buf");
1093 g_free(XBZRLE
.encoded_buf
);
1094 XBZRLE
.encoded_buf
= NULL
;
1101 /* iothread lock needed for ram_list.dirty_memory[] */
1102 qemu_mutex_lock_iothread();
1103 qemu_mutex_lock_ramlist();
1105 bytes_transferred
= 0;
1106 reset_ram_globals();
1108 ram_bitmap_pages
= last_ram_offset() >> TARGET_PAGE_BITS
;
1109 migration_bitmap
= bitmap_new(ram_bitmap_pages
);
1110 bitmap_set(migration_bitmap
, 0, ram_bitmap_pages
);
1113 * Count the total number of pages used by ram blocks not including any
1114 * gaps due to alignment or unplugs.
1116 migration_dirty_pages
= ram_bytes_total() >> TARGET_PAGE_BITS
;
1118 memory_global_dirty_log_start();
1119 migration_bitmap_sync();
1120 qemu_mutex_unlock_ramlist();
1121 qemu_mutex_unlock_iothread();
1123 qemu_put_be64(f
, ram_bytes_total() | RAM_SAVE_FLAG_MEM_SIZE
);
1125 QLIST_FOREACH_RCU(block
, &ram_list
.blocks
, next
) {
1126 qemu_put_byte(f
, strlen(block
->idstr
));
1127 qemu_put_buffer(f
, (uint8_t *)block
->idstr
, strlen(block
->idstr
));
1128 qemu_put_be64(f
, block
->used_length
);
1133 ram_control_before_iterate(f
, RAM_CONTROL_SETUP
);
1134 ram_control_after_iterate(f
, RAM_CONTROL_SETUP
);
1136 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
1141 static int ram_save_iterate(QEMUFile
*f
, void *opaque
)
1149 if (ram_list
.version
!= last_version
) {
1150 reset_ram_globals();
1153 /* Read version before ram_list.blocks */
1156 ram_control_before_iterate(f
, RAM_CONTROL_ROUND
);
1158 t0
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
1160 while ((ret
= qemu_file_rate_limit(f
)) == 0) {
1163 pages
= ram_find_and_save_block(f
, false, &bytes_transferred
);
1164 /* no more pages to sent */
1168 pages_sent
+= pages
;
1169 acct_info
.iterations
++;
1170 check_guest_throttling();
1171 /* we want to check in the 1st loop, just in case it was the 1st time
1172 and we had to sync the dirty bitmap.
1173 qemu_get_clock_ns() is a bit expensive, so we only check each some
1176 if ((i
& 63) == 0) {
1177 uint64_t t1
= (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) - t0
) / 1000000;
1178 if (t1
> MAX_WAIT
) {
1179 DPRINTF("big wait: %" PRIu64
" milliseconds, %d iterations\n",
1186 flush_compressed_data(f
);
1190 * Must occur before EOS (or any QEMUFile operation)
1191 * because of RDMA protocol.
1193 ram_control_after_iterate(f
, RAM_CONTROL_ROUND
);
1195 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
1196 bytes_transferred
+= 8;
1198 ret
= qemu_file_get_error(f
);
1206 /* Called with iothread lock */
1207 static int ram_save_complete(QEMUFile
*f
, void *opaque
)
1211 migration_bitmap_sync();
1213 ram_control_before_iterate(f
, RAM_CONTROL_FINISH
);
1215 /* try transferring iterative blocks of memory */
1217 /* flush all remaining blocks regardless of rate limiting */
1221 pages
= ram_find_and_save_block(f
, true, &bytes_transferred
);
1222 /* no more blocks to sent */
1228 flush_compressed_data(f
);
1229 ram_control_after_iterate(f
, RAM_CONTROL_FINISH
);
1233 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
1238 static uint64_t ram_save_pending(QEMUFile
*f
, void *opaque
, uint64_t max_size
)
1240 uint64_t remaining_size
;
1242 remaining_size
= ram_save_remaining() * TARGET_PAGE_SIZE
;
1244 if (remaining_size
< max_size
) {
1245 qemu_mutex_lock_iothread();
1247 migration_bitmap_sync();
1249 qemu_mutex_unlock_iothread();
1250 remaining_size
= ram_save_remaining() * TARGET_PAGE_SIZE
;
1252 return remaining_size
;
1255 static int load_xbzrle(QEMUFile
*f
, ram_addr_t addr
, void *host
)
1257 unsigned int xh_len
;
1260 if (!xbzrle_decoded_buf
) {
1261 xbzrle_decoded_buf
= g_malloc(TARGET_PAGE_SIZE
);
1264 /* extract RLE header */
1265 xh_flags
= qemu_get_byte(f
);
1266 xh_len
= qemu_get_be16(f
);
1268 if (xh_flags
!= ENCODING_FLAG_XBZRLE
) {
1269 error_report("Failed to load XBZRLE page - wrong compression!");
1273 if (xh_len
> TARGET_PAGE_SIZE
) {
1274 error_report("Failed to load XBZRLE page - len overflow!");
1277 /* load data and decode */
1278 qemu_get_buffer(f
, xbzrle_decoded_buf
, xh_len
);
1281 if (xbzrle_decode_buffer(xbzrle_decoded_buf
, xh_len
, host
,
1282 TARGET_PAGE_SIZE
) == -1) {
1283 error_report("Failed to load XBZRLE page - decode error!");
1290 /* Must be called from within a rcu critical section.
1291 * Returns a pointer from within the RCU-protected ram_list.
1293 static inline void *host_from_stream_offset(QEMUFile
*f
,
1297 static RAMBlock
*block
= NULL
;
1301 if (flags
& RAM_SAVE_FLAG_CONTINUE
) {
1302 if (!block
|| block
->max_length
<= offset
) {
1303 error_report("Ack, bad migration stream!");
1307 return memory_region_get_ram_ptr(block
->mr
) + offset
;
1310 len
= qemu_get_byte(f
);
1311 qemu_get_buffer(f
, (uint8_t *)id
, len
);
1314 QLIST_FOREACH_RCU(block
, &ram_list
.blocks
, next
) {
1315 if (!strncmp(id
, block
->idstr
, sizeof(id
)) &&
1316 block
->max_length
> offset
) {
1317 return memory_region_get_ram_ptr(block
->mr
) + offset
;
1321 error_report("Can't find block %s!", id
);
1326 * If a page (or a whole RDMA chunk) has been
1327 * determined to be zero, then zap it.
1329 void ram_handle_compressed(void *host
, uint8_t ch
, uint64_t size
)
1331 if (ch
!= 0 || !is_zero_range(host
, size
)) {
1332 memset(host
, ch
, size
);
1336 static void *do_data_decompress(void *opaque
)
1338 DecompressParam
*param
= opaque
;
1339 unsigned long pagesize
;
1341 while (!quit_decomp_thread
) {
1342 qemu_mutex_lock(¶m
->mutex
);
1343 while (!param
->start
&& !quit_decomp_thread
) {
1344 qemu_cond_wait(¶m
->cond
, ¶m
->mutex
);
1345 pagesize
= TARGET_PAGE_SIZE
;
1346 if (!quit_decomp_thread
) {
1347 /* uncompress() will return failed in some case, especially
1348 * when the page is dirted when doing the compression, it's
1349 * not a problem because the dirty page will be retransferred
1350 * and uncompress() won't break the data in other pages.
1352 uncompress((Bytef
*)param
->des
, &pagesize
,
1353 (const Bytef
*)param
->compbuf
, param
->len
);
1355 param
->start
= false;
1357 qemu_mutex_unlock(¶m
->mutex
);
1363 void migrate_decompress_threads_create(void)
1365 int i
, thread_count
;
1367 thread_count
= migrate_decompress_threads();
1368 decompress_threads
= g_new0(QemuThread
, thread_count
);
1369 decomp_param
= g_new0(DecompressParam
, thread_count
);
1370 compressed_data_buf
= g_malloc0(compressBound(TARGET_PAGE_SIZE
));
1371 quit_decomp_thread
= false;
1372 for (i
= 0; i
< thread_count
; i
++) {
1373 qemu_mutex_init(&decomp_param
[i
].mutex
);
1374 qemu_cond_init(&decomp_param
[i
].cond
);
1375 decomp_param
[i
].compbuf
= g_malloc0(compressBound(TARGET_PAGE_SIZE
));
1376 qemu_thread_create(decompress_threads
+ i
, "decompress",
1377 do_data_decompress
, decomp_param
+ i
,
1378 QEMU_THREAD_JOINABLE
);
1382 void migrate_decompress_threads_join(void)
1384 int i
, thread_count
;
1386 quit_decomp_thread
= true;
1387 thread_count
= migrate_decompress_threads();
1388 for (i
= 0; i
< thread_count
; i
++) {
1389 qemu_mutex_lock(&decomp_param
[i
].mutex
);
1390 qemu_cond_signal(&decomp_param
[i
].cond
);
1391 qemu_mutex_unlock(&decomp_param
[i
].mutex
);
1393 for (i
= 0; i
< thread_count
; i
++) {
1394 qemu_thread_join(decompress_threads
+ i
);
1395 qemu_mutex_destroy(&decomp_param
[i
].mutex
);
1396 qemu_cond_destroy(&decomp_param
[i
].cond
);
1397 g_free(decomp_param
[i
].compbuf
);
1399 g_free(decompress_threads
);
1400 g_free(decomp_param
);
1401 g_free(compressed_data_buf
);
1402 decompress_threads
= NULL
;
1403 decomp_param
= NULL
;
1404 compressed_data_buf
= NULL
;
1407 static void decompress_data_with_multi_threads(uint8_t *compbuf
,
1408 void *host
, int len
)
1410 int idx
, thread_count
;
1412 thread_count
= migrate_decompress_threads();
1414 for (idx
= 0; idx
< thread_count
; idx
++) {
1415 if (!decomp_param
[idx
].start
) {
1416 memcpy(decomp_param
[idx
].compbuf
, compbuf
, len
);
1417 decomp_param
[idx
].des
= host
;
1418 decomp_param
[idx
].len
= len
;
1419 start_decompression(&decomp_param
[idx
]);
1423 if (idx
< thread_count
) {
1429 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
1431 int flags
= 0, ret
= 0;
1432 static uint64_t seq_iter
;
1437 if (version_id
!= 4) {
1441 /* This RCU critical section can be very long running.
1442 * When RCU reclaims in the code start to become numerous,
1443 * it will be necessary to reduce the granularity of this
1447 while (!ret
&& !(flags
& RAM_SAVE_FLAG_EOS
)) {
1448 ram_addr_t addr
, total_ram_bytes
;
1452 addr
= qemu_get_be64(f
);
1453 flags
= addr
& ~TARGET_PAGE_MASK
;
1454 addr
&= TARGET_PAGE_MASK
;
1456 switch (flags
& ~RAM_SAVE_FLAG_CONTINUE
) {
1457 case RAM_SAVE_FLAG_MEM_SIZE
:
1458 /* Synchronize RAM block list */
1459 total_ram_bytes
= addr
;
1460 while (!ret
&& total_ram_bytes
) {
1465 len
= qemu_get_byte(f
);
1466 qemu_get_buffer(f
, (uint8_t *)id
, len
);
1468 length
= qemu_get_be64(f
);
1470 QLIST_FOREACH_RCU(block
, &ram_list
.blocks
, next
) {
1471 if (!strncmp(id
, block
->idstr
, sizeof(id
))) {
1472 if (length
!= block
->used_length
) {
1473 Error
*local_err
= NULL
;
1475 ret
= qemu_ram_resize(block
->offset
, length
, &local_err
);
1477 error_report_err(local_err
);
1485 error_report("Unknown ramblock \"%s\", cannot "
1486 "accept migration", id
);
1490 total_ram_bytes
-= length
;
1493 case RAM_SAVE_FLAG_COMPRESS
:
1494 host
= host_from_stream_offset(f
, addr
, flags
);
1496 error_report("Illegal RAM offset " RAM_ADDR_FMT
, addr
);
1500 ch
= qemu_get_byte(f
);
1501 ram_handle_compressed(host
, ch
, TARGET_PAGE_SIZE
);
1503 case RAM_SAVE_FLAG_PAGE
:
1504 host
= host_from_stream_offset(f
, addr
, flags
);
1506 error_report("Illegal RAM offset " RAM_ADDR_FMT
, addr
);
1510 qemu_get_buffer(f
, host
, TARGET_PAGE_SIZE
);
1512 case RAM_SAVE_FLAG_COMPRESS_PAGE
:
1513 host
= host_from_stream_offset(f
, addr
, flags
);
1515 error_report("Invalid RAM offset " RAM_ADDR_FMT
, addr
);
1520 len
= qemu_get_be32(f
);
1521 if (len
< 0 || len
> compressBound(TARGET_PAGE_SIZE
)) {
1522 error_report("Invalid compressed data length: %d", len
);
1526 qemu_get_buffer(f
, compressed_data_buf
, len
);
1527 decompress_data_with_multi_threads(compressed_data_buf
, host
, len
);
1529 case RAM_SAVE_FLAG_XBZRLE
:
1530 host
= host_from_stream_offset(f
, addr
, flags
);
1532 error_report("Illegal RAM offset " RAM_ADDR_FMT
, addr
);
1536 if (load_xbzrle(f
, addr
, host
) < 0) {
1537 error_report("Failed to decompress XBZRLE page at "
1538 RAM_ADDR_FMT
, addr
);
1543 case RAM_SAVE_FLAG_EOS
:
1547 if (flags
& RAM_SAVE_FLAG_HOOK
) {
1548 ram_control_load_hook(f
, flags
);
1550 error_report("Unknown combination of migration flags: %#x",
1556 ret
= qemu_file_get_error(f
);
1561 DPRINTF("Completed load of VM with exit code %d seq iteration "
1562 "%" PRIu64
"\n", ret
, seq_iter
);
1566 static SaveVMHandlers savevm_ram_handlers
= {
1567 .save_live_setup
= ram_save_setup
,
1568 .save_live_iterate
= ram_save_iterate
,
1569 .save_live_complete
= ram_save_complete
,
1570 .save_live_pending
= ram_save_pending
,
1571 .load_state
= ram_load
,
1572 .cancel
= ram_migration_cancel
,
1575 void ram_mig_init(void)
1577 qemu_mutex_init(&XBZRLE
.lock
);
1578 register_savevm_live(NULL
, "ram", 0, 4, &savevm_ram_handlers
, NULL
);
1580 /* Stub function that's gets run on the vcpu when its brought out of the
1581 VM to run inside qemu via async_run_on_cpu()*/
1583 static void mig_sleep_cpu(void *opq
)
1585 qemu_mutex_unlock_iothread();
1587 qemu_mutex_lock_iothread();
1590 /* To reduce the dirty rate explicitly disallow the VCPUs from spending
1591 much time in the VM. The migration thread will try to catchup.
1592 Workload will experience a performance drop.
1594 static void mig_throttle_guest_down(void)
1598 qemu_mutex_lock_iothread();
1600 async_run_on_cpu(cpu
, mig_sleep_cpu
, NULL
);
1602 qemu_mutex_unlock_iothread();
1605 static void check_guest_throttling(void)
1610 if (!mig_throttle_on
) {
1615 t0
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
1619 t1
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
1621 /* If it has been more than 40 ms since the last time the guest
1622 * was throttled then do it again.
1624 if (40 < (t1
-t0
)/1000000) {
1625 mig_throttle_guest_down();