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 QemuMutex migration_bitmap_mutex;
226 static uint64_t migration_dirty_pages;
227 static uint32_t last_version;
228 static bool ram_bulk_stage;
230 struct CompressParam {
239 typedef struct CompressParam CompressParam;
241 struct DecompressParam {
249 typedef struct DecompressParam DecompressParam;
251 static CompressParam *comp_param;
252 static QemuThread *compress_threads;
253 /* comp_done_cond is used to wake up the migration thread when
254 * one of the compression threads has finished the compression.
255 * comp_done_lock is used to co-work with comp_done_cond.
257 static QemuMutex *comp_done_lock;
258 static QemuCond *comp_done_cond;
259 /* The empty QEMUFileOps will be used by file in CompressParam */
260 static const QEMUFileOps empty_ops = { };
262 static bool compression_switch;
263 static bool quit_comp_thread;
264 static bool quit_decomp_thread;
265 static DecompressParam *decomp_param;
266 static QemuThread *decompress_threads;
267 static uint8_t *compressed_data_buf;
269 static int do_compress_ram_page(CompressParam *param);
271 static void *do_data_compress(void *opaque)
273 CompressParam *param = opaque;
275 while (!quit_comp_thread) {
276 qemu_mutex_lock(¶m->mutex);
277 /* Re-check the quit_comp_thread in case of
278 * terminate_compression_threads is called just before
279 * qemu_mutex_lock(¶m->mutex) and after
280 * while(!quit_comp_thread), re-check it here can make
281 * sure the compression thread terminate as expected.
283 while (!param->start && !quit_comp_thread) {
284 qemu_cond_wait(¶m->cond, ¶m->mutex);
286 if (!quit_comp_thread) {
287 do_compress_ram_page(param);
289 param->start = false;
290 qemu_mutex_unlock(¶m->mutex);
292 qemu_mutex_lock(comp_done_lock);
294 qemu_cond_signal(comp_done_cond);
295 qemu_mutex_unlock(comp_done_lock);
301 static inline void terminate_compression_threads(void)
303 int idx, thread_count;
305 thread_count = migrate_compress_threads();
306 quit_comp_thread = true;
307 for (idx = 0; idx < thread_count; idx++) {
308 qemu_mutex_lock(&comp_param[idx].mutex);
309 qemu_cond_signal(&comp_param[idx].cond);
310 qemu_mutex_unlock(&comp_param[idx].mutex);
314 void migrate_compress_threads_join(void)
318 if (!migrate_use_compression()) {
321 terminate_compression_threads();
322 thread_count = migrate_compress_threads();
323 for (i = 0; i < thread_count; i++) {
324 qemu_thread_join(compress_threads + i);
325 qemu_fclose(comp_param[i].file);
326 qemu_mutex_destroy(&comp_param[i].mutex);
327 qemu_cond_destroy(&comp_param[i].cond);
329 qemu_mutex_destroy(comp_done_lock);
330 qemu_cond_destroy(comp_done_cond);
331 g_free(compress_threads);
333 g_free(comp_done_cond);
334 g_free(comp_done_lock);
335 compress_threads = NULL;
337 comp_done_cond = NULL;
338 comp_done_lock = NULL;
341 void migrate_compress_threads_create(void)
345 if (!migrate_use_compression()) {
348 quit_comp_thread = false;
349 compression_switch = true;
350 thread_count = migrate_compress_threads();
351 compress_threads = g_new0(QemuThread, thread_count);
352 comp_param = g_new0(CompressParam, thread_count);
353 comp_done_cond = g_new0(QemuCond, 1);
354 comp_done_lock = g_new0(QemuMutex, 1);
355 qemu_cond_init(comp_done_cond);
356 qemu_mutex_init(comp_done_lock);
357 for (i = 0; i < thread_count; i++) {
358 /* com_param[i].file is just used as a dummy buffer to save data, set
361 comp_param[i].file = qemu_fopen_ops(NULL, &empty_ops);
362 comp_param[i].done = true;
363 qemu_mutex_init(&comp_param[i].mutex);
364 qemu_cond_init(&comp_param[i].cond);
365 qemu_thread_create(compress_threads + i, "compress",
366 do_data_compress, comp_param + i,
367 QEMU_THREAD_JOINABLE);
372 * save_page_header: Write page header to wire
374 * If this is the 1st block, it also writes the block identification
376 * Returns: Number of bytes written
378 * @f: QEMUFile where to send the data
379 * @block: block that contains the page we want to send
380 * @offset: offset inside the block for the page
381 * in the lower bits, it contains flags
383 static size_t save_page_header(QEMUFile *f, RAMBlock *block, ram_addr_t offset)
387 qemu_put_be64(f, offset);
390 if (!(offset & RAM_SAVE_FLAG_CONTINUE)) {
391 len = strlen(block->idstr);
392 qemu_put_byte(f, len);
393 qemu_put_buffer(f, (uint8_t *)block->idstr, len);
399 /* Update the xbzrle cache to reflect a page that's been sent as all 0.
400 * The important thing is that a stale (not-yet-0'd) page be replaced
402 * As a bonus, if the page wasn't in the cache it gets added so that
403 * when a small write is made into the 0'd page it gets XBZRLE sent
405 static void xbzrle_cache_zero_page(ram_addr_t current_addr)
407 if (ram_bulk_stage || !migrate_use_xbzrle()) {
411 /* We don't care if this fails to allocate a new cache page
412 * as long as it updated an old one */
413 cache_insert(XBZRLE.cache, current_addr, ZERO_TARGET_PAGE,
417 #define ENCODING_FLAG_XBZRLE 0x1
420 * save_xbzrle_page: compress and send current page
422 * Returns: 1 means that we wrote the page
423 * 0 means that page is identical to the one already sent
424 * -1 means that xbzrle would be longer than normal
426 * @f: QEMUFile where to send the data
429 * @block: block that contains the page we want to send
430 * @offset: offset inside the block for the page
431 * @last_stage: if we are at the completion stage
432 * @bytes_transferred: increase it with the number of transferred bytes
434 static int save_xbzrle_page(QEMUFile *f, uint8_t **current_data,
435 ram_addr_t current_addr, RAMBlock *block,
436 ram_addr_t offset, bool last_stage,
437 uint64_t *bytes_transferred)
439 int encoded_len = 0, bytes_xbzrle;
440 uint8_t *prev_cached_page;
442 if (!cache_is_cached(XBZRLE.cache, current_addr, bitmap_sync_count)) {
443 acct_info.xbzrle_cache_miss++;
445 if (cache_insert(XBZRLE.cache, current_addr, *current_data,
446 bitmap_sync_count) == -1) {
449 /* update *current_data when the page has been
450 inserted into cache */
451 *current_data = get_cached_data(XBZRLE.cache, current_addr);
457 prev_cached_page = get_cached_data(XBZRLE.cache, current_addr);
459 /* save current buffer into memory */
460 memcpy(XBZRLE.current_buf, *current_data, TARGET_PAGE_SIZE);
462 /* XBZRLE encoding (if there is no overflow) */
463 encoded_len = xbzrle_encode_buffer(prev_cached_page, XBZRLE.current_buf,
464 TARGET_PAGE_SIZE, XBZRLE.encoded_buf,
466 if (encoded_len == 0) {
467 DPRINTF("Skipping unmodified page\n");
469 } else if (encoded_len == -1) {
470 DPRINTF("Overflow\n");
471 acct_info.xbzrle_overflows++;
472 /* update data in the cache */
474 memcpy(prev_cached_page, *current_data, TARGET_PAGE_SIZE);
475 *current_data = prev_cached_page;
480 /* we need to update the data in the cache, in order to get the same data */
482 memcpy(prev_cached_page, XBZRLE.current_buf, TARGET_PAGE_SIZE);
485 /* Send XBZRLE based compressed page */
486 bytes_xbzrle = save_page_header(f, block, offset | RAM_SAVE_FLAG_XBZRLE);
487 qemu_put_byte(f, ENCODING_FLAG_XBZRLE);
488 qemu_put_be16(f, encoded_len);
489 qemu_put_buffer(f, XBZRLE.encoded_buf, encoded_len);
490 bytes_xbzrle += encoded_len + 1 + 2;
491 acct_info.xbzrle_pages++;
492 acct_info.xbzrle_bytes += bytes_xbzrle;
493 *bytes_transferred += bytes_xbzrle;
498 /* Called with rcu_read_lock() to protect migration_bitmap */
500 ram_addr_t migration_bitmap_find_and_reset_dirty(MemoryRegion *mr,
503 unsigned long base = mr->ram_addr >> TARGET_PAGE_BITS;
504 unsigned long nr = base + (start >> TARGET_PAGE_BITS);
505 uint64_t mr_size = TARGET_PAGE_ALIGN(memory_region_size(mr));
506 unsigned long size = base + (mr_size >> TARGET_PAGE_BITS);
507 unsigned long *bitmap;
511 bitmap = atomic_rcu_read(&migration_bitmap);
512 if (ram_bulk_stage && nr > base) {
515 next = find_next_bit(bitmap, size, nr);
519 clear_bit(next, bitmap);
520 migration_dirty_pages--;
522 return (next - base) << TARGET_PAGE_BITS;
525 /* Called with rcu_read_lock() to protect migration_bitmap */
526 static void migration_bitmap_sync_range(ram_addr_t start, ram_addr_t length)
528 unsigned long *bitmap;
529 bitmap = atomic_rcu_read(&migration_bitmap);
530 migration_dirty_pages +=
531 cpu_physical_memory_sync_dirty_bitmap(bitmap, start, length);
535 /* Fix me: there are too many global variables used in migration process. */
536 static int64_t start_time;
537 static int64_t bytes_xfer_prev;
538 static int64_t num_dirty_pages_period;
539 static uint64_t xbzrle_cache_miss_prev;
540 static uint64_t iterations_prev;
542 static void migration_bitmap_sync_init(void)
546 num_dirty_pages_period = 0;
547 xbzrle_cache_miss_prev = 0;
551 /* Called with iothread lock held, to protect ram_list.dirty_memory[] */
552 static void migration_bitmap_sync(void)
555 uint64_t num_dirty_pages_init = migration_dirty_pages;
556 MigrationState *s = migrate_get_current();
558 int64_t bytes_xfer_now;
562 if (!bytes_xfer_prev) {
563 bytes_xfer_prev = ram_bytes_transferred();
567 start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
570 trace_migration_bitmap_sync_start();
571 address_space_sync_dirty_bitmap(&address_space_memory);
573 qemu_mutex_lock(&migration_bitmap_mutex);
575 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
576 migration_bitmap_sync_range(block->mr->ram_addr, block->used_length);
579 qemu_mutex_unlock(&migration_bitmap_mutex);
581 trace_migration_bitmap_sync_end(migration_dirty_pages
582 - num_dirty_pages_init);
583 num_dirty_pages_period += migration_dirty_pages - num_dirty_pages_init;
584 end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
586 /* more than 1 second = 1000 millisecons */
587 if (end_time > start_time + 1000) {
588 if (migrate_auto_converge()) {
589 /* The following detection logic can be refined later. For now:
590 Check to see if the dirtied bytes is 50% more than the approx.
591 amount of bytes that just got transferred since the last time we
592 were in this routine. If that happens >N times (for now N==4)
593 we turn on the throttle down logic */
594 bytes_xfer_now = ram_bytes_transferred();
595 if (s->dirty_pages_rate &&
596 (num_dirty_pages_period * TARGET_PAGE_SIZE >
597 (bytes_xfer_now - bytes_xfer_prev)/2) &&
598 (dirty_rate_high_cnt++ > 4)) {
599 trace_migration_throttle();
600 mig_throttle_on = true;
601 dirty_rate_high_cnt = 0;
603 bytes_xfer_prev = bytes_xfer_now;
605 mig_throttle_on = false;
607 if (migrate_use_xbzrle()) {
608 if (iterations_prev != acct_info.iterations) {
609 acct_info.xbzrle_cache_miss_rate =
610 (double)(acct_info.xbzrle_cache_miss -
611 xbzrle_cache_miss_prev) /
612 (acct_info.iterations - iterations_prev);
614 iterations_prev = acct_info.iterations;
615 xbzrle_cache_miss_prev = acct_info.xbzrle_cache_miss;
617 s->dirty_pages_rate = num_dirty_pages_period * 1000
618 / (end_time - start_time);
619 s->dirty_bytes_rate = s->dirty_pages_rate * TARGET_PAGE_SIZE;
620 start_time = end_time;
621 num_dirty_pages_period = 0;
623 s->dirty_sync_count = bitmap_sync_count;
627 * save_zero_page: Send the zero page to the stream
629 * Returns: Number of pages written.
631 * @f: QEMUFile where to send the data
632 * @block: block that contains the page we want to send
633 * @offset: offset inside the block for the page
634 * @p: pointer to the page
635 * @bytes_transferred: increase it with the number of transferred bytes
637 static int save_zero_page(QEMUFile *f, RAMBlock *block, ram_addr_t offset,
638 uint8_t *p, uint64_t *bytes_transferred)
642 if (is_zero_range(p, TARGET_PAGE_SIZE)) {
643 acct_info.dup_pages++;
644 *bytes_transferred += save_page_header(f, block,
645 offset | RAM_SAVE_FLAG_COMPRESS);
647 *bytes_transferred += 1;
655 * ram_save_page: Send the given page to the stream
657 * Returns: Number of pages written.
659 * @f: QEMUFile where to send the data
660 * @block: block that contains the page we want to send
661 * @offset: offset inside the block for the page
662 * @last_stage: if we are at the completion stage
663 * @bytes_transferred: increase it with the number of transferred bytes
665 static int ram_save_page(QEMUFile *f, RAMBlock* block, ram_addr_t offset,
666 bool last_stage, uint64_t *bytes_transferred)
670 ram_addr_t current_addr;
671 MemoryRegion *mr = block->mr;
674 bool send_async = true;
676 p = memory_region_get_ram_ptr(mr) + offset;
678 /* In doubt sent page as normal */
680 ret = ram_control_save_page(f, block->offset,
681 offset, TARGET_PAGE_SIZE, &bytes_xmit);
683 *bytes_transferred += bytes_xmit;
689 current_addr = block->offset + offset;
691 if (block == last_sent_block) {
692 offset |= RAM_SAVE_FLAG_CONTINUE;
694 if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {
695 if (ret != RAM_SAVE_CONTROL_DELAYED) {
696 if (bytes_xmit > 0) {
697 acct_info.norm_pages++;
698 } else if (bytes_xmit == 0) {
699 acct_info.dup_pages++;
703 pages = save_zero_page(f, block, offset, p, bytes_transferred);
705 /* Must let xbzrle know, otherwise a previous (now 0'd) cached
706 * page would be stale
708 xbzrle_cache_zero_page(current_addr);
709 } else if (!ram_bulk_stage && migrate_use_xbzrle()) {
710 pages = save_xbzrle_page(f, &p, current_addr, block,
711 offset, last_stage, bytes_transferred);
713 /* Can't send this cached data async, since the cache page
714 * might get updated before it gets to the wire
721 /* XBZRLE overflow or normal page */
723 *bytes_transferred += save_page_header(f, block,
724 offset | RAM_SAVE_FLAG_PAGE);
726 qemu_put_buffer_async(f, p, TARGET_PAGE_SIZE);
728 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
730 *bytes_transferred += TARGET_PAGE_SIZE;
732 acct_info.norm_pages++;
735 XBZRLE_cache_unlock();
740 static int do_compress_ram_page(CompressParam *param)
742 int bytes_sent, blen;
744 RAMBlock *block = param->block;
745 ram_addr_t offset = param->offset;
747 p = memory_region_get_ram_ptr(block->mr) + (offset & TARGET_PAGE_MASK);
749 bytes_sent = save_page_header(param->file, block, offset |
750 RAM_SAVE_FLAG_COMPRESS_PAGE);
751 blen = qemu_put_compression_data(param->file, p, TARGET_PAGE_SIZE,
752 migrate_compress_level());
758 static inline void start_compression(CompressParam *param)
761 qemu_mutex_lock(¶m->mutex);
763 qemu_cond_signal(¶m->cond);
764 qemu_mutex_unlock(¶m->mutex);
767 static inline void start_decompression(DecompressParam *param)
769 qemu_mutex_lock(¶m->mutex);
771 qemu_cond_signal(¶m->cond);
772 qemu_mutex_unlock(¶m->mutex);
775 static uint64_t bytes_transferred;
777 static void flush_compressed_data(QEMUFile *f)
779 int idx, len, thread_count;
781 if (!migrate_use_compression()) {
784 thread_count = migrate_compress_threads();
785 for (idx = 0; idx < thread_count; idx++) {
786 if (!comp_param[idx].done) {
787 qemu_mutex_lock(comp_done_lock);
788 while (!comp_param[idx].done && !quit_comp_thread) {
789 qemu_cond_wait(comp_done_cond, comp_done_lock);
791 qemu_mutex_unlock(comp_done_lock);
793 if (!quit_comp_thread) {
794 len = qemu_put_qemu_file(f, comp_param[idx].file);
795 bytes_transferred += len;
800 static inline void set_compress_params(CompressParam *param, RAMBlock *block,
803 param->block = block;
804 param->offset = offset;
807 static int compress_page_with_multi_thread(QEMUFile *f, RAMBlock *block,
809 uint64_t *bytes_transferred)
811 int idx, thread_count, bytes_xmit = -1, pages = -1;
813 thread_count = migrate_compress_threads();
814 qemu_mutex_lock(comp_done_lock);
816 for (idx = 0; idx < thread_count; idx++) {
817 if (comp_param[idx].done) {
818 bytes_xmit = qemu_put_qemu_file(f, comp_param[idx].file);
819 set_compress_params(&comp_param[idx], block, offset);
820 start_compression(&comp_param[idx]);
822 acct_info.norm_pages++;
823 *bytes_transferred += bytes_xmit;
830 qemu_cond_wait(comp_done_cond, comp_done_lock);
833 qemu_mutex_unlock(comp_done_lock);
839 * ram_save_compressed_page: compress the given page and send it to the stream
841 * Returns: Number of pages written.
843 * @f: QEMUFile where to send the data
844 * @block: block that contains the page we want to send
845 * @offset: offset inside the block for the page
846 * @last_stage: if we are at the completion stage
847 * @bytes_transferred: increase it with the number of transferred bytes
849 static int ram_save_compressed_page(QEMUFile *f, RAMBlock *block,
850 ram_addr_t offset, bool last_stage,
851 uint64_t *bytes_transferred)
855 MemoryRegion *mr = block->mr;
859 p = memory_region_get_ram_ptr(mr) + offset;
862 ret = ram_control_save_page(f, block->offset,
863 offset, TARGET_PAGE_SIZE, &bytes_xmit);
865 *bytes_transferred += bytes_xmit;
868 if (block == last_sent_block) {
869 offset |= RAM_SAVE_FLAG_CONTINUE;
871 if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {
872 if (ret != RAM_SAVE_CONTROL_DELAYED) {
873 if (bytes_xmit > 0) {
874 acct_info.norm_pages++;
875 } else if (bytes_xmit == 0) {
876 acct_info.dup_pages++;
880 /* When starting the process of a new block, the first page of
881 * the block should be sent out before other pages in the same
882 * block, and all the pages in last block should have been sent
883 * out, keeping this order is important, because the 'cont' flag
884 * is used to avoid resending the block name.
886 if (block != last_sent_block) {
887 flush_compressed_data(f);
888 pages = save_zero_page(f, block, offset, p, bytes_transferred);
890 set_compress_params(&comp_param[0], block, offset);
891 /* Use the qemu thread to compress the data to make sure the
892 * first page is sent out before other pages
894 bytes_xmit = do_compress_ram_page(&comp_param[0]);
895 acct_info.norm_pages++;
896 qemu_put_qemu_file(f, comp_param[0].file);
897 *bytes_transferred += bytes_xmit;
901 pages = save_zero_page(f, block, offset, p, bytes_transferred);
903 pages = compress_page_with_multi_thread(f, block, offset,
913 * ram_find_and_save_block: Finds a dirty page and sends it to f
915 * Called within an RCU critical section.
917 * Returns: The number of pages written
918 * 0 means no dirty pages
920 * @f: QEMUFile where to send the data
921 * @last_stage: if we are at the completion stage
922 * @bytes_transferred: increase it with the number of transferred bytes
925 static int ram_find_and_save_block(QEMUFile *f, bool last_stage,
926 uint64_t *bytes_transferred)
928 RAMBlock *block = last_seen_block;
929 ram_addr_t offset = last_offset;
930 bool complete_round = false;
935 block = QLIST_FIRST_RCU(&ram_list.blocks);
939 offset = migration_bitmap_find_and_reset_dirty(mr, offset);
940 if (complete_round && block == last_seen_block &&
941 offset >= last_offset) {
944 if (offset >= block->used_length) {
946 block = QLIST_NEXT_RCU(block, next);
948 block = QLIST_FIRST_RCU(&ram_list.blocks);
949 complete_round = true;
950 ram_bulk_stage = false;
951 if (migrate_use_xbzrle()) {
952 /* If xbzrle is on, stop using the data compression at this
953 * point. In theory, xbzrle can do better than compression.
955 flush_compressed_data(f);
956 compression_switch = false;
960 if (compression_switch && migrate_use_compression()) {
961 pages = ram_save_compressed_page(f, block, offset, last_stage,
964 pages = ram_save_page(f, block, offset, last_stage,
968 /* if page is unmodified, continue to the next */
970 last_sent_block = block;
976 last_seen_block = block;
977 last_offset = offset;
982 void acct_update_position(QEMUFile *f, size_t size, bool zero)
984 uint64_t pages = size / TARGET_PAGE_SIZE;
986 acct_info.dup_pages += pages;
988 acct_info.norm_pages += pages;
989 bytes_transferred += size;
990 qemu_update_position(f, size);
994 static ram_addr_t ram_save_remaining(void)
996 return migration_dirty_pages;
999 uint64_t ram_bytes_remaining(void)
1001 return ram_save_remaining() * TARGET_PAGE_SIZE;
1004 uint64_t ram_bytes_transferred(void)
1006 return bytes_transferred;
1009 uint64_t ram_bytes_total(void)
1015 QLIST_FOREACH_RCU(block, &ram_list.blocks, next)
1016 total += block->used_length;
1021 void free_xbzrle_decoded_buf(void)
1023 g_free(xbzrle_decoded_buf);
1024 xbzrle_decoded_buf = NULL;
1027 static void migration_end(void)
1029 /* caller have hold iothread lock or is in a bh, so there is
1030 * no writing race against this migration_bitmap
1032 unsigned long *bitmap = migration_bitmap;
1033 atomic_rcu_set(&migration_bitmap, NULL);
1035 memory_global_dirty_log_stop();
1040 XBZRLE_cache_lock();
1042 cache_fini(XBZRLE.cache);
1043 g_free(XBZRLE.encoded_buf);
1044 g_free(XBZRLE.current_buf);
1045 XBZRLE.cache = NULL;
1046 XBZRLE.encoded_buf = NULL;
1047 XBZRLE.current_buf = NULL;
1049 XBZRLE_cache_unlock();
1052 static void ram_migration_cancel(void *opaque)
1057 static void reset_ram_globals(void)
1059 last_seen_block = NULL;
1060 last_sent_block = NULL;
1062 last_version = ram_list.version;
1063 ram_bulk_stage = true;
1066 #define MAX_WAIT 50 /* ms, half buffered_file limit */
1068 void migration_bitmap_extend(ram_addr_t old, ram_addr_t new)
1070 /* called in qemu main thread, so there is
1071 * no writing race against this migration_bitmap
1073 if (migration_bitmap) {
1074 unsigned long *old_bitmap = migration_bitmap, *bitmap;
1075 bitmap = bitmap_new(new);
1077 /* prevent migration_bitmap content from being set bit
1078 * by migration_bitmap_sync_range() at the same time.
1079 * it is safe to migration if migration_bitmap is cleared bit
1082 qemu_mutex_lock(&migration_bitmap_mutex);
1083 bitmap_copy(bitmap, old_bitmap, old);
1084 bitmap_set(bitmap, old, new - old);
1085 atomic_rcu_set(&migration_bitmap, bitmap);
1086 qemu_mutex_unlock(&migration_bitmap_mutex);
1087 migration_dirty_pages += new - old;
1093 /* Each of ram_save_setup, ram_save_iterate and ram_save_complete has
1094 * long-running RCU critical section. When rcu-reclaims in the code
1095 * start to become numerous it will be necessary to reduce the
1096 * granularity of these critical sections.
1099 static int ram_save_setup(QEMUFile *f, void *opaque)
1102 int64_t ram_bitmap_pages; /* Size of bitmap in pages, including gaps */
1104 mig_throttle_on = false;
1105 dirty_rate_high_cnt = 0;
1106 bitmap_sync_count = 0;
1107 migration_bitmap_sync_init();
1108 qemu_mutex_init(&migration_bitmap_mutex);
1110 if (migrate_use_xbzrle()) {
1111 XBZRLE_cache_lock();
1112 XBZRLE.cache = cache_init(migrate_xbzrle_cache_size() /
1115 if (!XBZRLE.cache) {
1116 XBZRLE_cache_unlock();
1117 error_report("Error creating cache");
1120 XBZRLE_cache_unlock();
1122 /* We prefer not to abort if there is no memory */
1123 XBZRLE.encoded_buf = g_try_malloc0(TARGET_PAGE_SIZE);
1124 if (!XBZRLE.encoded_buf) {
1125 error_report("Error allocating encoded_buf");
1129 XBZRLE.current_buf = g_try_malloc(TARGET_PAGE_SIZE);
1130 if (!XBZRLE.current_buf) {
1131 error_report("Error allocating current_buf");
1132 g_free(XBZRLE.encoded_buf);
1133 XBZRLE.encoded_buf = NULL;
1140 /* iothread lock needed for ram_list.dirty_memory[] */
1141 qemu_mutex_lock_iothread();
1142 qemu_mutex_lock_ramlist();
1144 bytes_transferred = 0;
1145 reset_ram_globals();
1147 ram_bitmap_pages = last_ram_offset() >> TARGET_PAGE_BITS;
1148 migration_bitmap = bitmap_new(ram_bitmap_pages);
1149 bitmap_set(migration_bitmap, 0, ram_bitmap_pages);
1152 * Count the total number of pages used by ram blocks not including any
1153 * gaps due to alignment or unplugs.
1155 migration_dirty_pages = ram_bytes_total() >> TARGET_PAGE_BITS;
1157 memory_global_dirty_log_start();
1158 migration_bitmap_sync();
1159 qemu_mutex_unlock_ramlist();
1160 qemu_mutex_unlock_iothread();
1162 qemu_put_be64(f, ram_bytes_total() | RAM_SAVE_FLAG_MEM_SIZE);
1164 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1165 qemu_put_byte(f, strlen(block->idstr));
1166 qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));
1167 qemu_put_be64(f, block->used_length);
1172 ram_control_before_iterate(f, RAM_CONTROL_SETUP);
1173 ram_control_after_iterate(f, RAM_CONTROL_SETUP);
1175 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1180 static int ram_save_iterate(QEMUFile *f, void *opaque)
1188 if (ram_list.version != last_version) {
1189 reset_ram_globals();
1192 /* Read version before ram_list.blocks */
1195 ram_control_before_iterate(f, RAM_CONTROL_ROUND);
1197 t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1199 while ((ret = qemu_file_rate_limit(f)) == 0) {
1202 pages = ram_find_and_save_block(f, false, &bytes_transferred);
1203 /* no more pages to sent */
1207 pages_sent += pages;
1208 acct_info.iterations++;
1209 check_guest_throttling();
1210 /* we want to check in the 1st loop, just in case it was the 1st time
1211 and we had to sync the dirty bitmap.
1212 qemu_get_clock_ns() is a bit expensive, so we only check each some
1215 if ((i & 63) == 0) {
1216 uint64_t t1 = (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - t0) / 1000000;
1217 if (t1 > MAX_WAIT) {
1218 DPRINTF("big wait: %" PRIu64 " milliseconds, %d iterations\n",
1225 flush_compressed_data(f);
1229 * Must occur before EOS (or any QEMUFile operation)
1230 * because of RDMA protocol.
1232 ram_control_after_iterate(f, RAM_CONTROL_ROUND);
1234 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1235 bytes_transferred += 8;
1237 ret = qemu_file_get_error(f);
1245 /* Called with iothread lock */
1246 static int ram_save_complete(QEMUFile *f, void *opaque)
1250 migration_bitmap_sync();
1252 ram_control_before_iterate(f, RAM_CONTROL_FINISH);
1254 /* try transferring iterative blocks of memory */
1256 /* flush all remaining blocks regardless of rate limiting */
1260 pages = ram_find_and_save_block(f, true, &bytes_transferred);
1261 /* no more blocks to sent */
1267 flush_compressed_data(f);
1268 ram_control_after_iterate(f, RAM_CONTROL_FINISH);
1273 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1278 static uint64_t ram_save_pending(QEMUFile *f, void *opaque, uint64_t max_size)
1280 uint64_t remaining_size;
1282 remaining_size = ram_save_remaining() * TARGET_PAGE_SIZE;
1284 if (remaining_size < max_size) {
1285 qemu_mutex_lock_iothread();
1287 migration_bitmap_sync();
1289 qemu_mutex_unlock_iothread();
1290 remaining_size = ram_save_remaining() * TARGET_PAGE_SIZE;
1292 return remaining_size;
1295 static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host)
1297 unsigned int xh_len;
1300 if (!xbzrle_decoded_buf) {
1301 xbzrle_decoded_buf = g_malloc(TARGET_PAGE_SIZE);
1304 /* extract RLE header */
1305 xh_flags = qemu_get_byte(f);
1306 xh_len = qemu_get_be16(f);
1308 if (xh_flags != ENCODING_FLAG_XBZRLE) {
1309 error_report("Failed to load XBZRLE page - wrong compression!");
1313 if (xh_len > TARGET_PAGE_SIZE) {
1314 error_report("Failed to load XBZRLE page - len overflow!");
1317 /* load data and decode */
1318 qemu_get_buffer(f, xbzrle_decoded_buf, xh_len);
1321 if (xbzrle_decode_buffer(xbzrle_decoded_buf, xh_len, host,
1322 TARGET_PAGE_SIZE) == -1) {
1323 error_report("Failed to load XBZRLE page - decode error!");
1330 /* Must be called from within a rcu critical section.
1331 * Returns a pointer from within the RCU-protected ram_list.
1333 static inline void *host_from_stream_offset(QEMUFile *f,
1337 static RAMBlock *block = NULL;
1341 if (flags & RAM_SAVE_FLAG_CONTINUE) {
1342 if (!block || block->max_length <= offset) {
1343 error_report("Ack, bad migration stream!");
1347 return memory_region_get_ram_ptr(block->mr) + offset;
1350 len = qemu_get_byte(f);
1351 qemu_get_buffer(f, (uint8_t *)id, len);
1354 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1355 if (!strncmp(id, block->idstr, sizeof(id)) &&
1356 block->max_length > offset) {
1357 return memory_region_get_ram_ptr(block->mr) + offset;
1361 error_report("Can't find block %s!", id);
1366 * If a page (or a whole RDMA chunk) has been
1367 * determined to be zero, then zap it.
1369 void ram_handle_compressed(void *host, uint8_t ch, uint64_t size)
1371 if (ch != 0 || !is_zero_range(host, size)) {
1372 memset(host, ch, size);
1376 static void *do_data_decompress(void *opaque)
1378 DecompressParam *param = opaque;
1379 unsigned long pagesize;
1381 while (!quit_decomp_thread) {
1382 qemu_mutex_lock(¶m->mutex);
1383 while (!param->start && !quit_decomp_thread) {
1384 qemu_cond_wait(¶m->cond, ¶m->mutex);
1385 pagesize = TARGET_PAGE_SIZE;
1386 if (!quit_decomp_thread) {
1387 /* uncompress() will return failed in some case, especially
1388 * when the page is dirted when doing the compression, it's
1389 * not a problem because the dirty page will be retransferred
1390 * and uncompress() won't break the data in other pages.
1392 uncompress((Bytef *)param->des, &pagesize,
1393 (const Bytef *)param->compbuf, param->len);
1395 param->start = false;
1397 qemu_mutex_unlock(¶m->mutex);
1403 void migrate_decompress_threads_create(void)
1405 int i, thread_count;
1407 thread_count = migrate_decompress_threads();
1408 decompress_threads = g_new0(QemuThread, thread_count);
1409 decomp_param = g_new0(DecompressParam, thread_count);
1410 compressed_data_buf = g_malloc0(compressBound(TARGET_PAGE_SIZE));
1411 quit_decomp_thread = false;
1412 for (i = 0; i < thread_count; i++) {
1413 qemu_mutex_init(&decomp_param[i].mutex);
1414 qemu_cond_init(&decomp_param[i].cond);
1415 decomp_param[i].compbuf = g_malloc0(compressBound(TARGET_PAGE_SIZE));
1416 qemu_thread_create(decompress_threads + i, "decompress",
1417 do_data_decompress, decomp_param + i,
1418 QEMU_THREAD_JOINABLE);
1422 void migrate_decompress_threads_join(void)
1424 int i, thread_count;
1426 quit_decomp_thread = true;
1427 thread_count = migrate_decompress_threads();
1428 for (i = 0; i < thread_count; i++) {
1429 qemu_mutex_lock(&decomp_param[i].mutex);
1430 qemu_cond_signal(&decomp_param[i].cond);
1431 qemu_mutex_unlock(&decomp_param[i].mutex);
1433 for (i = 0; i < thread_count; i++) {
1434 qemu_thread_join(decompress_threads + i);
1435 qemu_mutex_destroy(&decomp_param[i].mutex);
1436 qemu_cond_destroy(&decomp_param[i].cond);
1437 g_free(decomp_param[i].compbuf);
1439 g_free(decompress_threads);
1440 g_free(decomp_param);
1441 g_free(compressed_data_buf);
1442 decompress_threads = NULL;
1443 decomp_param = NULL;
1444 compressed_data_buf = NULL;
1447 static void decompress_data_with_multi_threads(uint8_t *compbuf,
1448 void *host, int len)
1450 int idx, thread_count;
1452 thread_count = migrate_decompress_threads();
1454 for (idx = 0; idx < thread_count; idx++) {
1455 if (!decomp_param[idx].start) {
1456 memcpy(decomp_param[idx].compbuf, compbuf, len);
1457 decomp_param[idx].des = host;
1458 decomp_param[idx].len = len;
1459 start_decompression(&decomp_param[idx]);
1463 if (idx < thread_count) {
1469 static int ram_load(QEMUFile *f, void *opaque, int version_id)
1471 int flags = 0, ret = 0;
1472 static uint64_t seq_iter;
1477 if (version_id != 4) {
1481 /* This RCU critical section can be very long running.
1482 * When RCU reclaims in the code start to become numerous,
1483 * it will be necessary to reduce the granularity of this
1487 while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
1488 ram_addr_t addr, total_ram_bytes;
1492 addr = qemu_get_be64(f);
1493 flags = addr & ~TARGET_PAGE_MASK;
1494 addr &= TARGET_PAGE_MASK;
1496 switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
1497 case RAM_SAVE_FLAG_MEM_SIZE:
1498 /* Synchronize RAM block list */
1499 total_ram_bytes = addr;
1500 while (!ret && total_ram_bytes) {
1505 len = qemu_get_byte(f);
1506 qemu_get_buffer(f, (uint8_t *)id, len);
1508 length = qemu_get_be64(f);
1510 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1511 if (!strncmp(id, block->idstr, sizeof(id))) {
1512 if (length != block->used_length) {
1513 Error *local_err = NULL;
1515 ret = qemu_ram_resize(block->offset, length, &local_err);
1517 error_report_err(local_err);
1520 ram_control_load_hook(f, RAM_CONTROL_BLOCK_REG,
1527 error_report("Unknown ramblock \"%s\", cannot "
1528 "accept migration", id);
1532 total_ram_bytes -= length;
1535 case RAM_SAVE_FLAG_COMPRESS:
1536 host = host_from_stream_offset(f, addr, flags);
1538 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
1542 ch = qemu_get_byte(f);
1543 ram_handle_compressed(host, ch, TARGET_PAGE_SIZE);
1545 case RAM_SAVE_FLAG_PAGE:
1546 host = host_from_stream_offset(f, addr, flags);
1548 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
1552 qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
1554 case RAM_SAVE_FLAG_COMPRESS_PAGE:
1555 host = host_from_stream_offset(f, addr, flags);
1557 error_report("Invalid RAM offset " RAM_ADDR_FMT, addr);
1562 len = qemu_get_be32(f);
1563 if (len < 0 || len > compressBound(TARGET_PAGE_SIZE)) {
1564 error_report("Invalid compressed data length: %d", len);
1568 qemu_get_buffer(f, compressed_data_buf, len);
1569 decompress_data_with_multi_threads(compressed_data_buf, host, len);
1571 case RAM_SAVE_FLAG_XBZRLE:
1572 host = host_from_stream_offset(f, addr, flags);
1574 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
1578 if (load_xbzrle(f, addr, host) < 0) {
1579 error_report("Failed to decompress XBZRLE page at "
1580 RAM_ADDR_FMT, addr);
1585 case RAM_SAVE_FLAG_EOS:
1589 if (flags & RAM_SAVE_FLAG_HOOK) {
1590 ram_control_load_hook(f, RAM_CONTROL_HOOK, NULL);
1592 error_report("Unknown combination of migration flags: %#x",
1598 ret = qemu_file_get_error(f);
1603 DPRINTF("Completed load of VM with exit code %d seq iteration "
1604 "%" PRIu64 "\n", ret, seq_iter);
1608 static SaveVMHandlers savevm_ram_handlers = {
1609 .save_live_setup = ram_save_setup,
1610 .save_live_iterate = ram_save_iterate,
1611 .save_live_complete = ram_save_complete,
1612 .save_live_pending = ram_save_pending,
1613 .load_state = ram_load,
1614 .cancel = ram_migration_cancel,
1617 void ram_mig_init(void)
1619 qemu_mutex_init(&XBZRLE.lock);
1620 register_savevm_live(NULL, "ram", 0, 4, &savevm_ram_handlers, NULL);
1622 /* Stub function that's gets run on the vcpu when its brought out of the
1623 VM to run inside qemu via async_run_on_cpu()*/
1625 static void mig_sleep_cpu(void *opq)
1627 qemu_mutex_unlock_iothread();
1629 qemu_mutex_lock_iothread();
1632 /* To reduce the dirty rate explicitly disallow the VCPUs from spending
1633 much time in the VM. The migration thread will try to catchup.
1634 Workload will experience a performance drop.
1636 static void mig_throttle_guest_down(void)
1640 qemu_mutex_lock_iothread();
1642 async_run_on_cpu(cpu, mig_sleep_cpu, NULL);
1644 qemu_mutex_unlock_iothread();
1647 static void check_guest_throttling(void)
1652 if (!mig_throttle_on) {
1657 t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1661 t1 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1663 /* If it has been more than 40 ms since the last time the guest
1664 * was throttled then do it again.
1666 if (40 < (t1-t0)/1000000) {
1667 mig_throttle_guest_down();