4 * Copyright (c) 2003-2008 Fabrice Bellard
5 * Copyright (c) 2011-2015 Red Hat Inc
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
28 #include "qemu/osdep.h"
29 #include "qemu-common.h"
32 #include "qapi-event.h"
33 #include "qemu/cutils.h"
34 #include "qemu/bitops.h"
35 #include "qemu/bitmap.h"
36 #include "qemu/timer.h"
37 #include "qemu/main-loop.h"
38 #include "migration/migration.h"
39 #include "migration/postcopy-ram.h"
40 #include "exec/address-spaces.h"
41 #include "migration/page_cache.h"
42 #include "qemu/error-report.h"
44 #include "exec/ram_addr.h"
45 #include "qemu/rcu_queue.h"
46 #include "migration/colo.h"
48 /***********************************************************/
49 /* ram save/restore */
51 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
52 #define RAM_SAVE_FLAG_COMPRESS 0x02
53 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
54 #define RAM_SAVE_FLAG_PAGE 0x08
55 #define RAM_SAVE_FLAG_EOS 0x10
56 #define RAM_SAVE_FLAG_CONTINUE 0x20
57 #define RAM_SAVE_FLAG_XBZRLE 0x40
58 /* 0x80 is reserved in migration.h start with 0x100 next */
59 #define RAM_SAVE_FLAG_COMPRESS_PAGE 0x100
61 static uint8_t *ZERO_TARGET_PAGE;
63 static inline bool is_zero_range(uint8_t *p, uint64_t size)
65 return buffer_is_zero(p, size);
68 /* struct contains XBZRLE cache and a static page
69 used by the compression */
71 /* buffer used for XBZRLE encoding */
73 /* buffer for storing page content */
75 /* Cache for XBZRLE, Protected by lock. */
80 /* buffer used for XBZRLE decoding */
81 static uint8_t *xbzrle_decoded_buf;
83 static void XBZRLE_cache_lock(void)
85 if (migrate_use_xbzrle())
86 qemu_mutex_lock(&XBZRLE.lock);
89 static void XBZRLE_cache_unlock(void)
91 if (migrate_use_xbzrle())
92 qemu_mutex_unlock(&XBZRLE.lock);
96 * xbzrle_cache_resize: resize the xbzrle cache
98 * This function is called from qmp_migrate_set_cache_size in main
99 * thread, possibly while a migration is in progress. A running
100 * migration may be using the cache and might finish during this call,
101 * hence changes to the cache are protected by XBZRLE.lock().
103 * Returns the new_size or negative in case of error.
105 * @new_size: new cache size
107 int64_t xbzrle_cache_resize(int64_t new_size)
109 PageCache *new_cache;
112 if (new_size < TARGET_PAGE_SIZE) {
118 if (XBZRLE.cache != NULL) {
119 if (pow2floor(new_size) == migrate_xbzrle_cache_size()) {
122 new_cache = cache_init(new_size / TARGET_PAGE_SIZE,
125 error_report("Error creating cache");
130 cache_fini(XBZRLE.cache);
131 XBZRLE.cache = new_cache;
135 ret = pow2floor(new_size);
137 XBZRLE_cache_unlock();
141 /* State of RAM for migration */
143 /* Last block that we have visited searching for dirty pages */
144 RAMBlock *last_seen_block;
145 /* Last block from where we have sent data */
146 RAMBlock *last_sent_block;
147 /* Last offset we have sent data from */
148 ram_addr_t last_offset;
149 /* last ram version we have seen */
150 uint32_t last_version;
151 /* We are in the first round */
153 /* How many times we have dirty too many pages */
154 int dirty_rate_high_cnt;
155 /* How many times we have synchronized the bitmap */
156 uint64_t bitmap_sync_count;
157 /* these variables are used for bitmap sync */
158 /* last time we did a full bitmap_sync */
159 int64_t time_last_bitmap_sync;
160 /* bytes transferred at start_time */
161 uint64_t bytes_xfer_prev;
162 /* number of dirty pages since start_time */
163 uint64_t num_dirty_pages_period;
164 /* xbzrle misses since the beginning of the period */
165 uint64_t xbzrle_cache_miss_prev;
167 typedef struct RAMState RAMState;
169 static RAMState ram_state;
171 /* accounting for migration statistics */
172 typedef struct AccountingInfo {
174 uint64_t skipped_pages;
177 uint64_t xbzrle_bytes;
178 uint64_t xbzrle_pages;
179 uint64_t xbzrle_cache_miss;
180 double xbzrle_cache_miss_rate;
181 uint64_t xbzrle_overflows;
184 static AccountingInfo acct_info;
186 static void acct_clear(void)
188 memset(&acct_info, 0, sizeof(acct_info));
191 uint64_t dup_mig_bytes_transferred(void)
193 return acct_info.dup_pages * TARGET_PAGE_SIZE;
196 uint64_t dup_mig_pages_transferred(void)
198 return acct_info.dup_pages;
201 uint64_t skipped_mig_bytes_transferred(void)
203 return acct_info.skipped_pages * TARGET_PAGE_SIZE;
206 uint64_t skipped_mig_pages_transferred(void)
208 return acct_info.skipped_pages;
211 uint64_t norm_mig_bytes_transferred(void)
213 return acct_info.norm_pages * TARGET_PAGE_SIZE;
216 uint64_t norm_mig_pages_transferred(void)
218 return acct_info.norm_pages;
221 uint64_t xbzrle_mig_bytes_transferred(void)
223 return acct_info.xbzrle_bytes;
226 uint64_t xbzrle_mig_pages_transferred(void)
228 return acct_info.xbzrle_pages;
231 uint64_t xbzrle_mig_pages_cache_miss(void)
233 return acct_info.xbzrle_cache_miss;
236 double xbzrle_mig_cache_miss_rate(void)
238 return acct_info.xbzrle_cache_miss_rate;
241 uint64_t xbzrle_mig_pages_overflow(void)
243 return acct_info.xbzrle_overflows;
246 static QemuMutex migration_bitmap_mutex;
247 static uint64_t migration_dirty_pages;
249 /* used by the search for pages to send */
250 struct PageSearchStatus {
251 /* Current block being searched */
253 /* Current offset to search from */
255 /* Set once we wrap around */
258 typedef struct PageSearchStatus PageSearchStatus;
260 static struct BitmapRcu {
262 /* Main migration bitmap */
264 /* bitmap of pages that haven't been sent even once
265 * only maintained and used in postcopy at the moment
266 * where it's used to send the dirtymap at the start
267 * of the postcopy phase
269 unsigned long *unsentmap;
270 } *migration_bitmap_rcu;
272 struct CompressParam {
281 typedef struct CompressParam CompressParam;
283 struct DecompressParam {
292 typedef struct DecompressParam DecompressParam;
294 static CompressParam *comp_param;
295 static QemuThread *compress_threads;
296 /* comp_done_cond is used to wake up the migration thread when
297 * one of the compression threads has finished the compression.
298 * comp_done_lock is used to co-work with comp_done_cond.
300 static QemuMutex comp_done_lock;
301 static QemuCond comp_done_cond;
302 /* The empty QEMUFileOps will be used by file in CompressParam */
303 static const QEMUFileOps empty_ops = { };
305 static bool compression_switch;
306 static DecompressParam *decomp_param;
307 static QemuThread *decompress_threads;
308 static QemuMutex decomp_done_lock;
309 static QemuCond decomp_done_cond;
311 static int do_compress_ram_page(QEMUFile *f, RAMBlock *block,
314 static void *do_data_compress(void *opaque)
316 CompressParam *param = opaque;
320 qemu_mutex_lock(¶m->mutex);
321 while (!param->quit) {
323 block = param->block;
324 offset = param->offset;
326 qemu_mutex_unlock(¶m->mutex);
328 do_compress_ram_page(param->file, block, offset);
330 qemu_mutex_lock(&comp_done_lock);
332 qemu_cond_signal(&comp_done_cond);
333 qemu_mutex_unlock(&comp_done_lock);
335 qemu_mutex_lock(¶m->mutex);
337 qemu_cond_wait(¶m->cond, ¶m->mutex);
340 qemu_mutex_unlock(¶m->mutex);
345 static inline void terminate_compression_threads(void)
347 int idx, thread_count;
349 thread_count = migrate_compress_threads();
351 for (idx = 0; idx < thread_count; idx++) {
352 qemu_mutex_lock(&comp_param[idx].mutex);
353 comp_param[idx].quit = true;
354 qemu_cond_signal(&comp_param[idx].cond);
355 qemu_mutex_unlock(&comp_param[idx].mutex);
359 void migrate_compress_threads_join(void)
363 if (!migrate_use_compression()) {
366 terminate_compression_threads();
367 thread_count = migrate_compress_threads();
368 for (i = 0; i < thread_count; i++) {
369 qemu_thread_join(compress_threads + i);
370 qemu_fclose(comp_param[i].file);
371 qemu_mutex_destroy(&comp_param[i].mutex);
372 qemu_cond_destroy(&comp_param[i].cond);
374 qemu_mutex_destroy(&comp_done_lock);
375 qemu_cond_destroy(&comp_done_cond);
376 g_free(compress_threads);
378 compress_threads = NULL;
382 void migrate_compress_threads_create(void)
386 if (!migrate_use_compression()) {
389 compression_switch = true;
390 thread_count = migrate_compress_threads();
391 compress_threads = g_new0(QemuThread, thread_count);
392 comp_param = g_new0(CompressParam, thread_count);
393 qemu_cond_init(&comp_done_cond);
394 qemu_mutex_init(&comp_done_lock);
395 for (i = 0; i < thread_count; i++) {
396 /* comp_param[i].file is just used as a dummy buffer to save data,
397 * set its ops to empty.
399 comp_param[i].file = qemu_fopen_ops(NULL, &empty_ops);
400 comp_param[i].done = true;
401 comp_param[i].quit = false;
402 qemu_mutex_init(&comp_param[i].mutex);
403 qemu_cond_init(&comp_param[i].cond);
404 qemu_thread_create(compress_threads + i, "compress",
405 do_data_compress, comp_param + i,
406 QEMU_THREAD_JOINABLE);
411 * save_page_header: write page header to wire
413 * If this is the 1st block, it also writes the block identification
415 * Returns the number of bytes written
417 * @f: QEMUFile where to send the data
418 * @block: block that contains the page we want to send
419 * @offset: offset inside the block for the page
420 * in the lower bits, it contains flags
422 static size_t save_page_header(QEMUFile *f, RAMBlock *block, ram_addr_t offset)
426 qemu_put_be64(f, offset);
429 if (!(offset & RAM_SAVE_FLAG_CONTINUE)) {
430 len = strlen(block->idstr);
431 qemu_put_byte(f, len);
432 qemu_put_buffer(f, (uint8_t *)block->idstr, len);
439 * mig_throttle_guest_down: throotle down the guest
441 * Reduce amount of guest cpu execution to hopefully slow down memory
442 * writes. If guest dirty memory rate is reduced below the rate at
443 * which we can transfer pages to the destination then we should be
444 * able to complete migration. Some workloads dirty memory way too
445 * fast and will not effectively converge, even with auto-converge.
447 static void mig_throttle_guest_down(void)
449 MigrationState *s = migrate_get_current();
450 uint64_t pct_initial = s->parameters.cpu_throttle_initial;
451 uint64_t pct_icrement = s->parameters.cpu_throttle_increment;
453 /* We have not started throttling yet. Let's start it. */
454 if (!cpu_throttle_active()) {
455 cpu_throttle_set(pct_initial);
457 /* Throttling already on, just increase the rate */
458 cpu_throttle_set(cpu_throttle_get_percentage() + pct_icrement);
463 * xbzrle_cache_zero_page: insert a zero page in the XBZRLE cache
465 * @rs: current RAM state
466 * @current_addr: address for the zero page
468 * Update the xbzrle cache to reflect a page that's been sent as all 0.
469 * The important thing is that a stale (not-yet-0'd) page be replaced
471 * As a bonus, if the page wasn't in the cache it gets added so that
472 * when a small write is made into the 0'd page it gets XBZRLE sent.
474 static void xbzrle_cache_zero_page(RAMState *rs, ram_addr_t current_addr)
476 if (rs->ram_bulk_stage || !migrate_use_xbzrle()) {
480 /* We don't care if this fails to allocate a new cache page
481 * as long as it updated an old one */
482 cache_insert(XBZRLE.cache, current_addr, ZERO_TARGET_PAGE,
483 rs->bitmap_sync_count);
486 #define ENCODING_FLAG_XBZRLE 0x1
489 * save_xbzrle_page: compress and send current page
491 * Returns: 1 means that we wrote the page
492 * 0 means that page is identical to the one already sent
493 * -1 means that xbzrle would be longer than normal
495 * @rs: current RAM state
496 * @f: QEMUFile where to send the data
497 * @current_data: pointer to the address of the page contents
498 * @current_addr: addr of the page
499 * @block: block that contains the page we want to send
500 * @offset: offset inside the block for the page
501 * @last_stage: if we are at the completion stage
502 * @bytes_transferred: increase it with the number of transferred bytes
504 static int save_xbzrle_page(RAMState *rs, QEMUFile *f, uint8_t **current_data,
505 ram_addr_t current_addr, RAMBlock *block,
506 ram_addr_t offset, bool last_stage,
507 uint64_t *bytes_transferred)
509 int encoded_len = 0, bytes_xbzrle;
510 uint8_t *prev_cached_page;
512 if (!cache_is_cached(XBZRLE.cache, current_addr, rs->bitmap_sync_count)) {
513 acct_info.xbzrle_cache_miss++;
515 if (cache_insert(XBZRLE.cache, current_addr, *current_data,
516 rs->bitmap_sync_count) == -1) {
519 /* update *current_data when the page has been
520 inserted into cache */
521 *current_data = get_cached_data(XBZRLE.cache, current_addr);
527 prev_cached_page = get_cached_data(XBZRLE.cache, current_addr);
529 /* save current buffer into memory */
530 memcpy(XBZRLE.current_buf, *current_data, TARGET_PAGE_SIZE);
532 /* XBZRLE encoding (if there is no overflow) */
533 encoded_len = xbzrle_encode_buffer(prev_cached_page, XBZRLE.current_buf,
534 TARGET_PAGE_SIZE, XBZRLE.encoded_buf,
536 if (encoded_len == 0) {
537 trace_save_xbzrle_page_skipping();
539 } else if (encoded_len == -1) {
540 trace_save_xbzrle_page_overflow();
541 acct_info.xbzrle_overflows++;
542 /* update data in the cache */
544 memcpy(prev_cached_page, *current_data, TARGET_PAGE_SIZE);
545 *current_data = prev_cached_page;
550 /* we need to update the data in the cache, in order to get the same data */
552 memcpy(prev_cached_page, XBZRLE.current_buf, TARGET_PAGE_SIZE);
555 /* Send XBZRLE based compressed page */
556 bytes_xbzrle = save_page_header(f, block, offset | RAM_SAVE_FLAG_XBZRLE);
557 qemu_put_byte(f, ENCODING_FLAG_XBZRLE);
558 qemu_put_be16(f, encoded_len);
559 qemu_put_buffer(f, XBZRLE.encoded_buf, encoded_len);
560 bytes_xbzrle += encoded_len + 1 + 2;
561 acct_info.xbzrle_pages++;
562 acct_info.xbzrle_bytes += bytes_xbzrle;
563 *bytes_transferred += bytes_xbzrle;
569 * migration_bitmap_find_dirty: find the next dirty page from start
571 * Called with rcu_read_lock() to protect migration_bitmap
573 * Returns the byte offset within memory region of the start of a dirty page
575 * @rs: current RAM state
576 * @rb: RAMBlock where to search for dirty pages
577 * @start: starting address (typically so we can continue from previous page)
578 * @ram_addr_abs: pointer into which to store the address of the dirty page
579 * within the global ram_addr space
582 ram_addr_t migration_bitmap_find_dirty(RAMState *rs, RAMBlock *rb,
584 ram_addr_t *ram_addr_abs)
586 unsigned long base = rb->offset >> TARGET_PAGE_BITS;
587 unsigned long nr = base + (start >> TARGET_PAGE_BITS);
588 uint64_t rb_size = rb->used_length;
589 unsigned long size = base + (rb_size >> TARGET_PAGE_BITS);
590 unsigned long *bitmap;
594 bitmap = atomic_rcu_read(&migration_bitmap_rcu)->bmap;
595 if (rs->ram_bulk_stage && nr > base) {
598 next = find_next_bit(bitmap, size, nr);
601 *ram_addr_abs = next << TARGET_PAGE_BITS;
602 return (next - base) << TARGET_PAGE_BITS;
605 static inline bool migration_bitmap_clear_dirty(ram_addr_t addr)
608 int nr = addr >> TARGET_PAGE_BITS;
609 unsigned long *bitmap = atomic_rcu_read(&migration_bitmap_rcu)->bmap;
611 ret = test_and_clear_bit(nr, bitmap);
614 migration_dirty_pages--;
619 static void migration_bitmap_sync_range(RAMState *rs, ram_addr_t start,
622 unsigned long *bitmap;
623 bitmap = atomic_rcu_read(&migration_bitmap_rcu)->bmap;
624 migration_dirty_pages += cpu_physical_memory_sync_dirty_bitmap(bitmap,
625 start, length, &rs->num_dirty_pages_period);
628 /* Fix me: there are too many global variables used in migration process. */
629 static uint64_t iterations_prev;
631 static void migration_bitmap_sync_init(RAMState *rs)
633 rs->time_last_bitmap_sync = 0;
634 rs->bytes_xfer_prev = 0;
635 rs->num_dirty_pages_period = 0;
636 rs->xbzrle_cache_miss_prev = 0;
641 * ram_pagesize_summary: calculate all the pagesizes of a VM
643 * Returns a summary bitmap of the page sizes of all RAMBlocks
645 * For VMs with just normal pages this is equivalent to the host page
646 * size. If it's got some huge pages then it's the OR of all the
647 * different page sizes.
649 uint64_t ram_pagesize_summary(void)
652 uint64_t summary = 0;
654 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
655 summary |= block->page_size;
661 static void migration_bitmap_sync(RAMState *rs)
664 MigrationState *s = migrate_get_current();
666 uint64_t bytes_xfer_now;
668 rs->bitmap_sync_count++;
670 if (!rs->bytes_xfer_prev) {
671 rs->bytes_xfer_prev = ram_bytes_transferred();
674 if (!rs->time_last_bitmap_sync) {
675 rs->time_last_bitmap_sync = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
678 trace_migration_bitmap_sync_start();
679 memory_global_dirty_log_sync();
681 qemu_mutex_lock(&migration_bitmap_mutex);
683 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
684 migration_bitmap_sync_range(rs, block->offset, block->used_length);
687 qemu_mutex_unlock(&migration_bitmap_mutex);
689 trace_migration_bitmap_sync_end(rs->num_dirty_pages_period);
691 end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
693 /* more than 1 second = 1000 millisecons */
694 if (end_time > rs->time_last_bitmap_sync + 1000) {
695 if (migrate_auto_converge()) {
696 /* The following detection logic can be refined later. For now:
697 Check to see if the dirtied bytes is 50% more than the approx.
698 amount of bytes that just got transferred since the last time we
699 were in this routine. If that happens twice, start or increase
701 bytes_xfer_now = ram_bytes_transferred();
703 if (s->dirty_pages_rate &&
704 (rs->num_dirty_pages_period * TARGET_PAGE_SIZE >
705 (bytes_xfer_now - rs->bytes_xfer_prev) / 2) &&
706 (rs->dirty_rate_high_cnt++ >= 2)) {
707 trace_migration_throttle();
708 rs->dirty_rate_high_cnt = 0;
709 mig_throttle_guest_down();
711 rs->bytes_xfer_prev = bytes_xfer_now;
714 if (migrate_use_xbzrle()) {
715 if (iterations_prev != acct_info.iterations) {
716 acct_info.xbzrle_cache_miss_rate =
717 (double)(acct_info.xbzrle_cache_miss -
718 rs->xbzrle_cache_miss_prev) /
719 (acct_info.iterations - iterations_prev);
721 iterations_prev = acct_info.iterations;
722 rs->xbzrle_cache_miss_prev = acct_info.xbzrle_cache_miss;
724 s->dirty_pages_rate = rs->num_dirty_pages_period * 1000
725 / (end_time - rs->time_last_bitmap_sync);
726 s->dirty_bytes_rate = s->dirty_pages_rate * TARGET_PAGE_SIZE;
727 rs->time_last_bitmap_sync = end_time;
728 rs->num_dirty_pages_period = 0;
730 s->dirty_sync_count = rs->bitmap_sync_count;
731 if (migrate_use_events()) {
732 qapi_event_send_migration_pass(rs->bitmap_sync_count, NULL);
737 * save_zero_page: send the zero page to the stream
739 * Returns the number of pages written.
741 * @f: QEMUFile where to send the data
742 * @block: block that contains the page we want to send
743 * @offset: offset inside the block for the page
744 * @p: pointer to the page
745 * @bytes_transferred: increase it with the number of transferred bytes
747 static int save_zero_page(QEMUFile *f, RAMBlock *block, ram_addr_t offset,
748 uint8_t *p, uint64_t *bytes_transferred)
752 if (is_zero_range(p, TARGET_PAGE_SIZE)) {
753 acct_info.dup_pages++;
754 *bytes_transferred += save_page_header(f, block,
755 offset | RAM_SAVE_FLAG_COMPRESS);
757 *bytes_transferred += 1;
764 static void ram_release_pages(MigrationState *ms, const char *rbname,
765 uint64_t offset, int pages)
767 if (!migrate_release_ram() || !migration_in_postcopy(ms)) {
771 ram_discard_range(NULL, rbname, offset, pages << TARGET_PAGE_BITS);
775 * ram_save_page: send the given page to the stream
777 * Returns the number of pages written.
779 * >=0 - Number of pages written - this might legally be 0
780 * if xbzrle noticed the page was the same.
782 * @rs: current RAM state
783 * @ms: current migration state
784 * @f: QEMUFile where to send the data
785 * @block: block that contains the page we want to send
786 * @offset: offset inside the block for the page
787 * @last_stage: if we are at the completion stage
788 * @bytes_transferred: increase it with the number of transferred bytes
790 static int ram_save_page(RAMState *rs, MigrationState *ms, QEMUFile *f,
791 PageSearchStatus *pss, bool last_stage,
792 uint64_t *bytes_transferred)
796 ram_addr_t current_addr;
799 bool send_async = true;
800 RAMBlock *block = pss->block;
801 ram_addr_t offset = pss->offset;
803 p = block->host + offset;
805 /* In doubt sent page as normal */
807 ret = ram_control_save_page(f, block->offset,
808 offset, TARGET_PAGE_SIZE, &bytes_xmit);
810 *bytes_transferred += bytes_xmit;
816 current_addr = block->offset + offset;
818 if (block == rs->last_sent_block) {
819 offset |= RAM_SAVE_FLAG_CONTINUE;
821 if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {
822 if (ret != RAM_SAVE_CONTROL_DELAYED) {
823 if (bytes_xmit > 0) {
824 acct_info.norm_pages++;
825 } else if (bytes_xmit == 0) {
826 acct_info.dup_pages++;
830 pages = save_zero_page(f, block, offset, p, bytes_transferred);
832 /* Must let xbzrle know, otherwise a previous (now 0'd) cached
833 * page would be stale
835 xbzrle_cache_zero_page(rs, current_addr);
836 ram_release_pages(ms, block->idstr, pss->offset, pages);
837 } else if (!rs->ram_bulk_stage &&
838 !migration_in_postcopy(ms) && migrate_use_xbzrle()) {
839 pages = save_xbzrle_page(rs, f, &p, current_addr, block,
840 offset, last_stage, bytes_transferred);
842 /* Can't send this cached data async, since the cache page
843 * might get updated before it gets to the wire
850 /* XBZRLE overflow or normal page */
852 *bytes_transferred += save_page_header(f, block,
853 offset | RAM_SAVE_FLAG_PAGE);
855 qemu_put_buffer_async(f, p, TARGET_PAGE_SIZE,
856 migrate_release_ram() &
857 migration_in_postcopy(ms));
859 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
861 *bytes_transferred += TARGET_PAGE_SIZE;
863 acct_info.norm_pages++;
866 XBZRLE_cache_unlock();
871 static int do_compress_ram_page(QEMUFile *f, RAMBlock *block,
874 int bytes_sent, blen;
875 uint8_t *p = block->host + (offset & TARGET_PAGE_MASK);
877 bytes_sent = save_page_header(f, block, offset |
878 RAM_SAVE_FLAG_COMPRESS_PAGE);
879 blen = qemu_put_compression_data(f, p, TARGET_PAGE_SIZE,
880 migrate_compress_level());
883 qemu_file_set_error(migrate_get_current()->to_dst_file, blen);
884 error_report("compressed data failed!");
887 ram_release_pages(migrate_get_current(), block->idstr,
888 offset & TARGET_PAGE_MASK, 1);
894 static uint64_t bytes_transferred;
896 static void flush_compressed_data(QEMUFile *f)
898 int idx, len, thread_count;
900 if (!migrate_use_compression()) {
903 thread_count = migrate_compress_threads();
905 qemu_mutex_lock(&comp_done_lock);
906 for (idx = 0; idx < thread_count; idx++) {
907 while (!comp_param[idx].done) {
908 qemu_cond_wait(&comp_done_cond, &comp_done_lock);
911 qemu_mutex_unlock(&comp_done_lock);
913 for (idx = 0; idx < thread_count; idx++) {
914 qemu_mutex_lock(&comp_param[idx].mutex);
915 if (!comp_param[idx].quit) {
916 len = qemu_put_qemu_file(f, comp_param[idx].file);
917 bytes_transferred += len;
919 qemu_mutex_unlock(&comp_param[idx].mutex);
923 static inline void set_compress_params(CompressParam *param, RAMBlock *block,
926 param->block = block;
927 param->offset = offset;
930 static int compress_page_with_multi_thread(QEMUFile *f, RAMBlock *block,
932 uint64_t *bytes_transferred)
934 int idx, thread_count, bytes_xmit = -1, pages = -1;
936 thread_count = migrate_compress_threads();
937 qemu_mutex_lock(&comp_done_lock);
939 for (idx = 0; idx < thread_count; idx++) {
940 if (comp_param[idx].done) {
941 comp_param[idx].done = false;
942 bytes_xmit = qemu_put_qemu_file(f, comp_param[idx].file);
943 qemu_mutex_lock(&comp_param[idx].mutex);
944 set_compress_params(&comp_param[idx], block, offset);
945 qemu_cond_signal(&comp_param[idx].cond);
946 qemu_mutex_unlock(&comp_param[idx].mutex);
948 acct_info.norm_pages++;
949 *bytes_transferred += bytes_xmit;
956 qemu_cond_wait(&comp_done_cond, &comp_done_lock);
959 qemu_mutex_unlock(&comp_done_lock);
965 * ram_save_compressed_page: compress the given page and send it to the stream
967 * Returns the number of pages written.
969 * @rs: current RAM state
970 * @ms: current migration state
971 * @f: QEMUFile where to send the data
972 * @block: block that contains the page we want to send
973 * @offset: offset inside the block for the page
974 * @last_stage: if we are at the completion stage
975 * @bytes_transferred: increase it with the number of transferred bytes
977 static int ram_save_compressed_page(RAMState *rs, MigrationState *ms,
979 PageSearchStatus *pss, bool last_stage,
980 uint64_t *bytes_transferred)
983 uint64_t bytes_xmit = 0;
986 RAMBlock *block = pss->block;
987 ram_addr_t offset = pss->offset;
989 p = block->host + offset;
991 ret = ram_control_save_page(f, block->offset,
992 offset, TARGET_PAGE_SIZE, &bytes_xmit);
994 *bytes_transferred += bytes_xmit;
997 if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {
998 if (ret != RAM_SAVE_CONTROL_DELAYED) {
999 if (bytes_xmit > 0) {
1000 acct_info.norm_pages++;
1001 } else if (bytes_xmit == 0) {
1002 acct_info.dup_pages++;
1006 /* When starting the process of a new block, the first page of
1007 * the block should be sent out before other pages in the same
1008 * block, and all the pages in last block should have been sent
1009 * out, keeping this order is important, because the 'cont' flag
1010 * is used to avoid resending the block name.
1012 if (block != rs->last_sent_block) {
1013 flush_compressed_data(f);
1014 pages = save_zero_page(f, block, offset, p, bytes_transferred);
1016 /* Make sure the first page is sent out before other pages */
1017 bytes_xmit = save_page_header(f, block, offset |
1018 RAM_SAVE_FLAG_COMPRESS_PAGE);
1019 blen = qemu_put_compression_data(f, p, TARGET_PAGE_SIZE,
1020 migrate_compress_level());
1022 *bytes_transferred += bytes_xmit + blen;
1023 acct_info.norm_pages++;
1026 qemu_file_set_error(f, blen);
1027 error_report("compressed data failed!");
1031 ram_release_pages(ms, block->idstr, pss->offset, pages);
1034 offset |= RAM_SAVE_FLAG_CONTINUE;
1035 pages = save_zero_page(f, block, offset, p, bytes_transferred);
1037 pages = compress_page_with_multi_thread(f, block, offset,
1040 ram_release_pages(ms, block->idstr, pss->offset, pages);
1049 * find_dirty_block: find the next dirty page and update any state
1050 * associated with the search process.
1052 * Returns if a page is found
1054 * @rs: current RAM state
1055 * @f: QEMUFile where to send the data
1056 * @pss: data about the state of the current dirty page scan
1057 * @again: set to false if the search has scanned the whole of RAM
1058 * @ram_addr_abs: pointer into which to store the address of the dirty page
1059 * within the global ram_addr space
1061 static bool find_dirty_block(RAMState *rs, QEMUFile *f, PageSearchStatus *pss,
1062 bool *again, ram_addr_t *ram_addr_abs)
1064 pss->offset = migration_bitmap_find_dirty(rs, pss->block, pss->offset,
1066 if (pss->complete_round && pss->block == rs->last_seen_block &&
1067 pss->offset >= rs->last_offset) {
1069 * We've been once around the RAM and haven't found anything.
1075 if (pss->offset >= pss->block->used_length) {
1076 /* Didn't find anything in this RAM Block */
1078 pss->block = QLIST_NEXT_RCU(pss->block, next);
1080 /* Hit the end of the list */
1081 pss->block = QLIST_FIRST_RCU(&ram_list.blocks);
1082 /* Flag that we've looped */
1083 pss->complete_round = true;
1084 rs->ram_bulk_stage = false;
1085 if (migrate_use_xbzrle()) {
1086 /* If xbzrle is on, stop using the data compression at this
1087 * point. In theory, xbzrle can do better than compression.
1089 flush_compressed_data(f);
1090 compression_switch = false;
1093 /* Didn't find anything this time, but try again on the new block */
1097 /* Can go around again, but... */
1099 /* We've found something so probably don't need to */
1105 * unqueue_page: gets a page of the queue
1107 * Helper for 'get_queued_page' - gets a page off the queue
1109 * Returns the block of the page (or NULL if none available)
1111 * @ms: current migration state
1112 * @offset: used to return the offset within the RAMBlock
1113 * @ram_addr_abs: pointer into which to store the address of the dirty page
1114 * within the global ram_addr space
1116 static RAMBlock *unqueue_page(MigrationState *ms, ram_addr_t *offset,
1117 ram_addr_t *ram_addr_abs)
1119 RAMBlock *block = NULL;
1121 qemu_mutex_lock(&ms->src_page_req_mutex);
1122 if (!QSIMPLEQ_EMPTY(&ms->src_page_requests)) {
1123 struct MigrationSrcPageRequest *entry =
1124 QSIMPLEQ_FIRST(&ms->src_page_requests);
1126 *offset = entry->offset;
1127 *ram_addr_abs = (entry->offset + entry->rb->offset) &
1130 if (entry->len > TARGET_PAGE_SIZE) {
1131 entry->len -= TARGET_PAGE_SIZE;
1132 entry->offset += TARGET_PAGE_SIZE;
1134 memory_region_unref(block->mr);
1135 QSIMPLEQ_REMOVE_HEAD(&ms->src_page_requests, next_req);
1139 qemu_mutex_unlock(&ms->src_page_req_mutex);
1145 * get_queued_page: unqueue a page from the postocpy requests
1147 * Skips pages that are already sent (!dirty)
1149 * Returns if a queued page is found
1151 * @rs: current RAM state
1152 * @ms: current migration state
1153 * @pss: data about the state of the current dirty page scan
1154 * @ram_addr_abs: pointer into which to store the address of the dirty page
1155 * within the global ram_addr space
1157 static bool get_queued_page(RAMState *rs, MigrationState *ms,
1158 PageSearchStatus *pss,
1159 ram_addr_t *ram_addr_abs)
1166 block = unqueue_page(ms, &offset, ram_addr_abs);
1168 * We're sending this page, and since it's postcopy nothing else
1169 * will dirty it, and we must make sure it doesn't get sent again
1170 * even if this queue request was received after the background
1171 * search already sent it.
1174 unsigned long *bitmap;
1175 bitmap = atomic_rcu_read(&migration_bitmap_rcu)->bmap;
1176 dirty = test_bit(*ram_addr_abs >> TARGET_PAGE_BITS, bitmap);
1178 trace_get_queued_page_not_dirty(
1179 block->idstr, (uint64_t)offset,
1180 (uint64_t)*ram_addr_abs,
1181 test_bit(*ram_addr_abs >> TARGET_PAGE_BITS,
1182 atomic_rcu_read(&migration_bitmap_rcu)->unsentmap));
1184 trace_get_queued_page(block->idstr,
1186 (uint64_t)*ram_addr_abs);
1190 } while (block && !dirty);
1194 * As soon as we start servicing pages out of order, then we have
1195 * to kill the bulk stage, since the bulk stage assumes
1196 * in (migration_bitmap_find_and_reset_dirty) that every page is
1197 * dirty, that's no longer true.
1199 rs->ram_bulk_stage = false;
1202 * We want the background search to continue from the queued page
1203 * since the guest is likely to want other pages near to the page
1204 * it just requested.
1207 pss->offset = offset;
1214 * migration_page_queue_free: drop any remaining pages in the ram
1217 * It should be empty at the end anyway, but in error cases there may
1218 * be some left. in case that there is any page left, we drop it.
1220 * @ms: current migration state
1222 void migration_page_queue_free(MigrationState *ms)
1224 struct MigrationSrcPageRequest *mspr, *next_mspr;
1225 /* This queue generally should be empty - but in the case of a failed
1226 * migration might have some droppings in.
1229 QSIMPLEQ_FOREACH_SAFE(mspr, &ms->src_page_requests, next_req, next_mspr) {
1230 memory_region_unref(mspr->rb->mr);
1231 QSIMPLEQ_REMOVE_HEAD(&ms->src_page_requests, next_req);
1238 * ram_save_queue_pages: queue the page for transmission
1240 * A request from postcopy destination for example.
1242 * Returns zero on success or negative on error
1244 * @ms: current migration state
1245 * @rbname: Name of the RAMBLock of the request. NULL means the
1246 * same that last one.
1247 * @start: starting address from the start of the RAMBlock
1248 * @len: length (in bytes) to send
1250 int ram_save_queue_pages(MigrationState *ms, const char *rbname,
1251 ram_addr_t start, ram_addr_t len)
1255 ms->postcopy_requests++;
1258 /* Reuse last RAMBlock */
1259 ramblock = ms->last_req_rb;
1263 * Shouldn't happen, we can't reuse the last RAMBlock if
1264 * it's the 1st request.
1266 error_report("ram_save_queue_pages no previous block");
1270 ramblock = qemu_ram_block_by_name(rbname);
1273 /* We shouldn't be asked for a non-existent RAMBlock */
1274 error_report("ram_save_queue_pages no block '%s'", rbname);
1277 ms->last_req_rb = ramblock;
1279 trace_ram_save_queue_pages(ramblock->idstr, start, len);
1280 if (start+len > ramblock->used_length) {
1281 error_report("%s request overrun start=" RAM_ADDR_FMT " len="
1282 RAM_ADDR_FMT " blocklen=" RAM_ADDR_FMT,
1283 __func__, start, len, ramblock->used_length);
1287 struct MigrationSrcPageRequest *new_entry =
1288 g_malloc0(sizeof(struct MigrationSrcPageRequest));
1289 new_entry->rb = ramblock;
1290 new_entry->offset = start;
1291 new_entry->len = len;
1293 memory_region_ref(ramblock->mr);
1294 qemu_mutex_lock(&ms->src_page_req_mutex);
1295 QSIMPLEQ_INSERT_TAIL(&ms->src_page_requests, new_entry, next_req);
1296 qemu_mutex_unlock(&ms->src_page_req_mutex);
1307 * ram_save_target_page: save one target page
1309 * Returns the number of pages written
1311 * @rs: current RAM state
1312 * @ms: current migration state
1313 * @f: QEMUFile where to send the data
1314 * @pss: data about the page we want to send
1315 * @last_stage: if we are at the completion stage
1316 * @bytes_transferred: increase it with the number of transferred bytes
1317 * @dirty_ram_abs: address of the start of the dirty page in ram_addr_t space
1319 static int ram_save_target_page(RAMState *rs, MigrationState *ms, QEMUFile *f,
1320 PageSearchStatus *pss,
1322 uint64_t *bytes_transferred,
1323 ram_addr_t dirty_ram_abs)
1327 /* Check the pages is dirty and if it is send it */
1328 if (migration_bitmap_clear_dirty(dirty_ram_abs)) {
1329 unsigned long *unsentmap;
1330 if (compression_switch && migrate_use_compression()) {
1331 res = ram_save_compressed_page(rs, ms, f, pss,
1335 res = ram_save_page(rs, ms, f, pss, last_stage,
1342 unsentmap = atomic_rcu_read(&migration_bitmap_rcu)->unsentmap;
1344 clear_bit(dirty_ram_abs >> TARGET_PAGE_BITS, unsentmap);
1346 /* Only update last_sent_block if a block was actually sent; xbzrle
1347 * might have decided the page was identical so didn't bother writing
1351 rs->last_sent_block = pss->block;
1359 * ram_save_host_page: save a whole host page
1361 * Starting at *offset send pages up to the end of the current host
1362 * page. It's valid for the initial offset to point into the middle of
1363 * a host page in which case the remainder of the hostpage is sent.
1364 * Only dirty target pages are sent. Note that the host page size may
1365 * be a huge page for this block.
1367 * Returns the number of pages written or negative on error
1369 * @rs: current RAM state
1370 * @ms: current migration state
1371 * @f: QEMUFile where to send the data
1372 * @pss: data about the page we want to send
1373 * @last_stage: if we are at the completion stage
1374 * @bytes_transferred: increase it with the number of transferred bytes
1375 * @dirty_ram_abs: Address of the start of the dirty page in ram_addr_t space
1377 static int ram_save_host_page(RAMState *rs, MigrationState *ms, QEMUFile *f,
1378 PageSearchStatus *pss,
1380 uint64_t *bytes_transferred,
1381 ram_addr_t dirty_ram_abs)
1383 int tmppages, pages = 0;
1384 size_t pagesize = qemu_ram_pagesize(pss->block);
1387 tmppages = ram_save_target_page(rs, ms, f, pss, last_stage,
1388 bytes_transferred, dirty_ram_abs);
1394 pss->offset += TARGET_PAGE_SIZE;
1395 dirty_ram_abs += TARGET_PAGE_SIZE;
1396 } while (pss->offset & (pagesize - 1));
1398 /* The offset we leave with is the last one we looked at */
1399 pss->offset -= TARGET_PAGE_SIZE;
1404 * ram_find_and_save_block: finds a dirty page and sends it to f
1406 * Called within an RCU critical section.
1408 * Returns the number of pages written where zero means no dirty pages
1410 * @rs: current RAM state
1411 * @f: QEMUFile where to send the data
1412 * @last_stage: if we are at the completion stage
1413 * @bytes_transferred: increase it with the number of transferred bytes
1415 * On systems where host-page-size > target-page-size it will send all the
1416 * pages in a host page that are dirty.
1419 static int ram_find_and_save_block(RAMState *rs, QEMUFile *f, bool last_stage,
1420 uint64_t *bytes_transferred)
1422 PageSearchStatus pss;
1423 MigrationState *ms = migrate_get_current();
1426 ram_addr_t dirty_ram_abs; /* Address of the start of the dirty page in
1429 /* No dirty page as there is zero RAM */
1430 if (!ram_bytes_total()) {
1434 pss.block = rs->last_seen_block;
1435 pss.offset = rs->last_offset;
1436 pss.complete_round = false;
1439 pss.block = QLIST_FIRST_RCU(&ram_list.blocks);
1444 found = get_queued_page(rs, ms, &pss, &dirty_ram_abs);
1447 /* priority queue empty, so just search for something dirty */
1448 found = find_dirty_block(rs, f, &pss, &again, &dirty_ram_abs);
1452 pages = ram_save_host_page(rs, ms, f, &pss,
1453 last_stage, bytes_transferred,
1456 } while (!pages && again);
1458 rs->last_seen_block = pss.block;
1459 rs->last_offset = pss.offset;
1464 void acct_update_position(QEMUFile *f, size_t size, bool zero)
1466 uint64_t pages = size / TARGET_PAGE_SIZE;
1468 acct_info.dup_pages += pages;
1470 acct_info.norm_pages += pages;
1471 bytes_transferred += size;
1472 qemu_update_position(f, size);
1476 static ram_addr_t ram_save_remaining(void)
1478 return migration_dirty_pages;
1481 uint64_t ram_bytes_remaining(void)
1483 return ram_save_remaining() * TARGET_PAGE_SIZE;
1486 uint64_t ram_bytes_transferred(void)
1488 return bytes_transferred;
1491 uint64_t ram_bytes_total(void)
1497 QLIST_FOREACH_RCU(block, &ram_list.blocks, next)
1498 total += block->used_length;
1503 void free_xbzrle_decoded_buf(void)
1505 g_free(xbzrle_decoded_buf);
1506 xbzrle_decoded_buf = NULL;
1509 static void migration_bitmap_free(struct BitmapRcu *bmap)
1512 g_free(bmap->unsentmap);
1516 static void ram_migration_cleanup(void *opaque)
1518 /* caller have hold iothread lock or is in a bh, so there is
1519 * no writing race against this migration_bitmap
1521 struct BitmapRcu *bitmap = migration_bitmap_rcu;
1522 atomic_rcu_set(&migration_bitmap_rcu, NULL);
1524 memory_global_dirty_log_stop();
1525 call_rcu(bitmap, migration_bitmap_free, rcu);
1528 XBZRLE_cache_lock();
1530 cache_fini(XBZRLE.cache);
1531 g_free(XBZRLE.encoded_buf);
1532 g_free(XBZRLE.current_buf);
1533 g_free(ZERO_TARGET_PAGE);
1534 XBZRLE.cache = NULL;
1535 XBZRLE.encoded_buf = NULL;
1536 XBZRLE.current_buf = NULL;
1538 XBZRLE_cache_unlock();
1541 static void ram_state_reset(RAMState *rs)
1543 rs->last_seen_block = NULL;
1544 rs->last_sent_block = NULL;
1545 rs->last_offset = 0;
1546 rs->last_version = ram_list.version;
1547 rs->ram_bulk_stage = true;
1550 #define MAX_WAIT 50 /* ms, half buffered_file limit */
1552 void migration_bitmap_extend(ram_addr_t old, ram_addr_t new)
1554 /* called in qemu main thread, so there is
1555 * no writing race against this migration_bitmap
1557 if (migration_bitmap_rcu) {
1558 struct BitmapRcu *old_bitmap = migration_bitmap_rcu, *bitmap;
1559 bitmap = g_new(struct BitmapRcu, 1);
1560 bitmap->bmap = bitmap_new(new);
1562 /* prevent migration_bitmap content from being set bit
1563 * by migration_bitmap_sync_range() at the same time.
1564 * it is safe to migration if migration_bitmap is cleared bit
1567 qemu_mutex_lock(&migration_bitmap_mutex);
1568 bitmap_copy(bitmap->bmap, old_bitmap->bmap, old);
1569 bitmap_set(bitmap->bmap, old, new - old);
1571 /* We don't have a way to safely extend the sentmap
1572 * with RCU; so mark it as missing, entry to postcopy
1575 bitmap->unsentmap = NULL;
1577 atomic_rcu_set(&migration_bitmap_rcu, bitmap);
1578 qemu_mutex_unlock(&migration_bitmap_mutex);
1579 migration_dirty_pages += new - old;
1580 call_rcu(old_bitmap, migration_bitmap_free, rcu);
1585 * 'expected' is the value you expect the bitmap mostly to be full
1586 * of; it won't bother printing lines that are all this value.
1587 * If 'todump' is null the migration bitmap is dumped.
1589 void ram_debug_dump_bitmap(unsigned long *todump, bool expected)
1591 int64_t ram_pages = last_ram_offset() >> TARGET_PAGE_BITS;
1594 int64_t linelen = 128;
1598 todump = atomic_rcu_read(&migration_bitmap_rcu)->bmap;
1601 for (cur = 0; cur < ram_pages; cur += linelen) {
1605 * Last line; catch the case where the line length
1606 * is longer than remaining ram
1608 if (cur + linelen > ram_pages) {
1609 linelen = ram_pages - cur;
1611 for (curb = 0; curb < linelen; curb++) {
1612 bool thisbit = test_bit(cur + curb, todump);
1613 linebuf[curb] = thisbit ? '1' : '.';
1614 found = found || (thisbit != expected);
1617 linebuf[curb] = '\0';
1618 fprintf(stderr, "0x%08" PRIx64 " : %s\n", cur, linebuf);
1623 /* **** functions for postcopy ***** */
1625 void ram_postcopy_migrated_memory_release(MigrationState *ms)
1627 struct RAMBlock *block;
1628 unsigned long *bitmap = atomic_rcu_read(&migration_bitmap_rcu)->bmap;
1630 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1631 unsigned long first = block->offset >> TARGET_PAGE_BITS;
1632 unsigned long range = first + (block->used_length >> TARGET_PAGE_BITS);
1633 unsigned long run_start = find_next_zero_bit(bitmap, range, first);
1635 while (run_start < range) {
1636 unsigned long run_end = find_next_bit(bitmap, range, run_start + 1);
1637 ram_discard_range(NULL, block->idstr, run_start << TARGET_PAGE_BITS,
1638 (run_end - run_start) << TARGET_PAGE_BITS);
1639 run_start = find_next_zero_bit(bitmap, range, run_end + 1);
1645 * postcopy_send_discard_bm_ram: discard a RAMBlock
1647 * Returns zero on success
1649 * Callback from postcopy_each_ram_send_discard for each RAMBlock
1650 * Note: At this point the 'unsentmap' is the processed bitmap combined
1651 * with the dirtymap; so a '1' means it's either dirty or unsent.
1653 * @ms: current migration state
1654 * @pds: state for postcopy
1655 * @start: RAMBlock starting page
1656 * @length: RAMBlock size
1658 static int postcopy_send_discard_bm_ram(MigrationState *ms,
1659 PostcopyDiscardState *pds,
1660 unsigned long start,
1661 unsigned long length)
1663 unsigned long end = start + length; /* one after the end */
1664 unsigned long current;
1665 unsigned long *unsentmap;
1667 unsentmap = atomic_rcu_read(&migration_bitmap_rcu)->unsentmap;
1668 for (current = start; current < end; ) {
1669 unsigned long one = find_next_bit(unsentmap, end, current);
1672 unsigned long zero = find_next_zero_bit(unsentmap, end, one + 1);
1673 unsigned long discard_length;
1676 discard_length = end - one;
1678 discard_length = zero - one;
1680 if (discard_length) {
1681 postcopy_discard_send_range(ms, pds, one, discard_length);
1683 current = one + discard_length;
1693 * postcopy_each_ram_send_discard: discard all RAMBlocks
1695 * Returns 0 for success or negative for error
1697 * Utility for the outgoing postcopy code.
1698 * Calls postcopy_send_discard_bm_ram for each RAMBlock
1699 * passing it bitmap indexes and name.
1700 * (qemu_ram_foreach_block ends up passing unscaled lengths
1701 * which would mean postcopy code would have to deal with target page)
1703 * @ms: current migration state
1705 static int postcopy_each_ram_send_discard(MigrationState *ms)
1707 struct RAMBlock *block;
1710 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1711 unsigned long first = block->offset >> TARGET_PAGE_BITS;
1712 PostcopyDiscardState *pds = postcopy_discard_send_init(ms,
1717 * Postcopy sends chunks of bitmap over the wire, but it
1718 * just needs indexes at this point, avoids it having
1719 * target page specific code.
1721 ret = postcopy_send_discard_bm_ram(ms, pds, first,
1722 block->used_length >> TARGET_PAGE_BITS);
1723 postcopy_discard_send_finish(ms, pds);
1733 * postcopy_chunk_hostpages_pass: canocalize bitmap in hostpages
1735 * Helper for postcopy_chunk_hostpages; it's called twice to
1736 * canonicalize the two bitmaps, that are similar, but one is
1739 * Postcopy requires that all target pages in a hostpage are dirty or
1740 * clean, not a mix. This function canonicalizes the bitmaps.
1742 * @ms: current migration state
1743 * @unsent_pass: if true we need to canonicalize partially unsent host pages
1744 * otherwise we need to canonicalize partially dirty host pages
1745 * @block: block that contains the page we want to canonicalize
1746 * @pds: state for postcopy
1748 static void postcopy_chunk_hostpages_pass(MigrationState *ms, bool unsent_pass,
1750 PostcopyDiscardState *pds)
1752 unsigned long *bitmap;
1753 unsigned long *unsentmap;
1754 unsigned int host_ratio = block->page_size / TARGET_PAGE_SIZE;
1755 unsigned long first = block->offset >> TARGET_PAGE_BITS;
1756 unsigned long len = block->used_length >> TARGET_PAGE_BITS;
1757 unsigned long last = first + (len - 1);
1758 unsigned long run_start;
1760 if (block->page_size == TARGET_PAGE_SIZE) {
1761 /* Easy case - TPS==HPS for a non-huge page RAMBlock */
1765 bitmap = atomic_rcu_read(&migration_bitmap_rcu)->bmap;
1766 unsentmap = atomic_rcu_read(&migration_bitmap_rcu)->unsentmap;
1769 /* Find a sent page */
1770 run_start = find_next_zero_bit(unsentmap, last + 1, first);
1772 /* Find a dirty page */
1773 run_start = find_next_bit(bitmap, last + 1, first);
1776 while (run_start <= last) {
1777 bool do_fixup = false;
1778 unsigned long fixup_start_addr;
1779 unsigned long host_offset;
1782 * If the start of this run of pages is in the middle of a host
1783 * page, then we need to fixup this host page.
1785 host_offset = run_start % host_ratio;
1788 run_start -= host_offset;
1789 fixup_start_addr = run_start;
1790 /* For the next pass */
1791 run_start = run_start + host_ratio;
1793 /* Find the end of this run */
1794 unsigned long run_end;
1796 run_end = find_next_bit(unsentmap, last + 1, run_start + 1);
1798 run_end = find_next_zero_bit(bitmap, last + 1, run_start + 1);
1801 * If the end isn't at the start of a host page, then the
1802 * run doesn't finish at the end of a host page
1803 * and we need to discard.
1805 host_offset = run_end % host_ratio;
1808 fixup_start_addr = run_end - host_offset;
1810 * This host page has gone, the next loop iteration starts
1811 * from after the fixup
1813 run_start = fixup_start_addr + host_ratio;
1816 * No discards on this iteration, next loop starts from
1817 * next sent/dirty page
1819 run_start = run_end + 1;
1826 /* Tell the destination to discard this page */
1827 if (unsent_pass || !test_bit(fixup_start_addr, unsentmap)) {
1828 /* For the unsent_pass we:
1829 * discard partially sent pages
1830 * For the !unsent_pass (dirty) we:
1831 * discard partially dirty pages that were sent
1832 * (any partially sent pages were already discarded
1833 * by the previous unsent_pass)
1835 postcopy_discard_send_range(ms, pds, fixup_start_addr,
1839 /* Clean up the bitmap */
1840 for (page = fixup_start_addr;
1841 page < fixup_start_addr + host_ratio; page++) {
1842 /* All pages in this host page are now not sent */
1843 set_bit(page, unsentmap);
1846 * Remark them as dirty, updating the count for any pages
1847 * that weren't previously dirty.
1849 migration_dirty_pages += !test_and_set_bit(page, bitmap);
1854 /* Find the next sent page for the next iteration */
1855 run_start = find_next_zero_bit(unsentmap, last + 1,
1858 /* Find the next dirty page for the next iteration */
1859 run_start = find_next_bit(bitmap, last + 1, run_start);
1865 * postcopy_chuck_hostpages: discrad any partially sent host page
1867 * Utility for the outgoing postcopy code.
1869 * Discard any partially sent host-page size chunks, mark any partially
1870 * dirty host-page size chunks as all dirty. In this case the host-page
1871 * is the host-page for the particular RAMBlock, i.e. it might be a huge page
1873 * Returns zero on success
1875 * @ms: current migration state
1877 static int postcopy_chunk_hostpages(MigrationState *ms)
1879 RAMState *rs = &ram_state;
1880 struct RAMBlock *block;
1882 /* Easiest way to make sure we don't resume in the middle of a host-page */
1883 rs->last_seen_block = NULL;
1884 rs->last_sent_block = NULL;
1885 rs->last_offset = 0;
1887 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1888 unsigned long first = block->offset >> TARGET_PAGE_BITS;
1890 PostcopyDiscardState *pds =
1891 postcopy_discard_send_init(ms, first, block->idstr);
1893 /* First pass: Discard all partially sent host pages */
1894 postcopy_chunk_hostpages_pass(ms, true, block, pds);
1896 * Second pass: Ensure that all partially dirty host pages are made
1899 postcopy_chunk_hostpages_pass(ms, false, block, pds);
1901 postcopy_discard_send_finish(ms, pds);
1902 } /* ram_list loop */
1908 * ram_postcopy_send_discard_bitmap: transmit the discard bitmap
1910 * Returns zero on success
1912 * Transmit the set of pages to be discarded after precopy to the target
1913 * these are pages that:
1914 * a) Have been previously transmitted but are now dirty again
1915 * b) Pages that have never been transmitted, this ensures that
1916 * any pages on the destination that have been mapped by background
1917 * tasks get discarded (transparent huge pages is the specific concern)
1918 * Hopefully this is pretty sparse
1920 * @ms: current migration state
1922 int ram_postcopy_send_discard_bitmap(MigrationState *ms)
1925 unsigned long *bitmap, *unsentmap;
1929 /* This should be our last sync, the src is now paused */
1930 migration_bitmap_sync(&ram_state);
1932 unsentmap = atomic_rcu_read(&migration_bitmap_rcu)->unsentmap;
1934 /* We don't have a safe way to resize the sentmap, so
1935 * if the bitmap was resized it will be NULL at this
1938 error_report("migration ram resized during precopy phase");
1943 /* Deal with TPS != HPS and huge pages */
1944 ret = postcopy_chunk_hostpages(ms);
1951 * Update the unsentmap to be unsentmap = unsentmap | dirty
1953 bitmap = atomic_rcu_read(&migration_bitmap_rcu)->bmap;
1954 bitmap_or(unsentmap, unsentmap, bitmap,
1955 last_ram_offset() >> TARGET_PAGE_BITS);
1958 trace_ram_postcopy_send_discard_bitmap();
1959 #ifdef DEBUG_POSTCOPY
1960 ram_debug_dump_bitmap(unsentmap, true);
1963 ret = postcopy_each_ram_send_discard(ms);
1970 * ram_discard_range: discard dirtied pages at the beginning of postcopy
1972 * Returns zero on success
1974 * @mis: current migration incoming state
1975 * @rbname: name of the RAMBlock of the request. NULL means the
1976 * same that last one.
1977 * @start: RAMBlock starting page
1978 * @length: RAMBlock size
1980 int ram_discard_range(MigrationIncomingState *mis,
1982 uint64_t start, size_t length)
1986 trace_ram_discard_range(rbname, start, length);
1989 RAMBlock *rb = qemu_ram_block_by_name(rbname);
1992 error_report("ram_discard_range: Failed to find block '%s'", rbname);
1996 ret = ram_block_discard_range(rb, start, length);
2004 static int ram_save_init_globals(RAMState *rs)
2006 int64_t ram_bitmap_pages; /* Size of bitmap in pages, including gaps */
2008 rs->dirty_rate_high_cnt = 0;
2009 rs->bitmap_sync_count = 0;
2010 migration_bitmap_sync_init(rs);
2011 qemu_mutex_init(&migration_bitmap_mutex);
2013 if (migrate_use_xbzrle()) {
2014 XBZRLE_cache_lock();
2015 ZERO_TARGET_PAGE = g_malloc0(TARGET_PAGE_SIZE);
2016 XBZRLE.cache = cache_init(migrate_xbzrle_cache_size() /
2019 if (!XBZRLE.cache) {
2020 XBZRLE_cache_unlock();
2021 error_report("Error creating cache");
2024 XBZRLE_cache_unlock();
2026 /* We prefer not to abort if there is no memory */
2027 XBZRLE.encoded_buf = g_try_malloc0(TARGET_PAGE_SIZE);
2028 if (!XBZRLE.encoded_buf) {
2029 error_report("Error allocating encoded_buf");
2033 XBZRLE.current_buf = g_try_malloc(TARGET_PAGE_SIZE);
2034 if (!XBZRLE.current_buf) {
2035 error_report("Error allocating current_buf");
2036 g_free(XBZRLE.encoded_buf);
2037 XBZRLE.encoded_buf = NULL;
2044 /* For memory_global_dirty_log_start below. */
2045 qemu_mutex_lock_iothread();
2047 qemu_mutex_lock_ramlist();
2049 bytes_transferred = 0;
2050 ram_state_reset(rs);
2052 migration_bitmap_rcu = g_new0(struct BitmapRcu, 1);
2053 /* Skip setting bitmap if there is no RAM */
2054 if (ram_bytes_total()) {
2055 ram_bitmap_pages = last_ram_offset() >> TARGET_PAGE_BITS;
2056 migration_bitmap_rcu->bmap = bitmap_new(ram_bitmap_pages);
2057 bitmap_set(migration_bitmap_rcu->bmap, 0, ram_bitmap_pages);
2059 if (migrate_postcopy_ram()) {
2060 migration_bitmap_rcu->unsentmap = bitmap_new(ram_bitmap_pages);
2061 bitmap_set(migration_bitmap_rcu->unsentmap, 0, ram_bitmap_pages);
2066 * Count the total number of pages used by ram blocks not including any
2067 * gaps due to alignment or unplugs.
2069 migration_dirty_pages = ram_bytes_total() >> TARGET_PAGE_BITS;
2071 memory_global_dirty_log_start();
2072 migration_bitmap_sync(rs);
2073 qemu_mutex_unlock_ramlist();
2074 qemu_mutex_unlock_iothread();
2081 * Each of ram_save_setup, ram_save_iterate and ram_save_complete has
2082 * long-running RCU critical section. When rcu-reclaims in the code
2083 * start to become numerous it will be necessary to reduce the
2084 * granularity of these critical sections.
2088 * ram_save_setup: Setup RAM for migration
2090 * Returns zero to indicate success and negative for error
2092 * @f: QEMUFile where to send the data
2093 * @opaque: RAMState pointer
2095 static int ram_save_setup(QEMUFile *f, void *opaque)
2097 RAMState *rs = opaque;
2100 /* migration has already setup the bitmap, reuse it. */
2101 if (!migration_in_colo_state()) {
2102 if (ram_save_init_globals(rs) < 0) {
2109 qemu_put_be64(f, ram_bytes_total() | RAM_SAVE_FLAG_MEM_SIZE);
2111 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
2112 qemu_put_byte(f, strlen(block->idstr));
2113 qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));
2114 qemu_put_be64(f, block->used_length);
2115 if (migrate_postcopy_ram() && block->page_size != qemu_host_page_size) {
2116 qemu_put_be64(f, block->page_size);
2122 ram_control_before_iterate(f, RAM_CONTROL_SETUP);
2123 ram_control_after_iterate(f, RAM_CONTROL_SETUP);
2125 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2131 * ram_save_iterate: iterative stage for migration
2133 * Returns zero to indicate success and negative for error
2135 * @f: QEMUFile where to send the data
2136 * @opaque: RAMState pointer
2138 static int ram_save_iterate(QEMUFile *f, void *opaque)
2140 RAMState *rs = opaque;
2147 if (ram_list.version != rs->last_version) {
2148 ram_state_reset(rs);
2151 /* Read version before ram_list.blocks */
2154 ram_control_before_iterate(f, RAM_CONTROL_ROUND);
2156 t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
2158 while ((ret = qemu_file_rate_limit(f)) == 0) {
2161 pages = ram_find_and_save_block(rs, f, false, &bytes_transferred);
2162 /* no more pages to sent */
2167 acct_info.iterations++;
2169 /* we want to check in the 1st loop, just in case it was the 1st time
2170 and we had to sync the dirty bitmap.
2171 qemu_get_clock_ns() is a bit expensive, so we only check each some
2174 if ((i & 63) == 0) {
2175 uint64_t t1 = (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - t0) / 1000000;
2176 if (t1 > MAX_WAIT) {
2177 trace_ram_save_iterate_big_wait(t1, i);
2183 flush_compressed_data(f);
2187 * Must occur before EOS (or any QEMUFile operation)
2188 * because of RDMA protocol.
2190 ram_control_after_iterate(f, RAM_CONTROL_ROUND);
2192 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2193 bytes_transferred += 8;
2195 ret = qemu_file_get_error(f);
2204 * ram_save_complete: function called to send the remaining amount of ram
2206 * Returns zero to indicate success
2208 * Called with iothread lock
2210 * @f: QEMUFile where to send the data
2211 * @opaque: RAMState pointer
2213 static int ram_save_complete(QEMUFile *f, void *opaque)
2215 RAMState *rs = opaque;
2219 if (!migration_in_postcopy(migrate_get_current())) {
2220 migration_bitmap_sync(rs);
2223 ram_control_before_iterate(f, RAM_CONTROL_FINISH);
2225 /* try transferring iterative blocks of memory */
2227 /* flush all remaining blocks regardless of rate limiting */
2231 pages = ram_find_and_save_block(rs, f, !migration_in_colo_state(),
2232 &bytes_transferred);
2233 /* no more blocks to sent */
2239 flush_compressed_data(f);
2240 ram_control_after_iterate(f, RAM_CONTROL_FINISH);
2244 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2249 static void ram_save_pending(QEMUFile *f, void *opaque, uint64_t max_size,
2250 uint64_t *non_postcopiable_pending,
2251 uint64_t *postcopiable_pending)
2253 RAMState *rs = opaque;
2254 uint64_t remaining_size;
2256 remaining_size = ram_save_remaining() * TARGET_PAGE_SIZE;
2258 if (!migration_in_postcopy(migrate_get_current()) &&
2259 remaining_size < max_size) {
2260 qemu_mutex_lock_iothread();
2262 migration_bitmap_sync(rs);
2264 qemu_mutex_unlock_iothread();
2265 remaining_size = ram_save_remaining() * TARGET_PAGE_SIZE;
2268 /* We can do postcopy, and all the data is postcopiable */
2269 *postcopiable_pending += remaining_size;
2272 static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host)
2274 unsigned int xh_len;
2276 uint8_t *loaded_data;
2278 if (!xbzrle_decoded_buf) {
2279 xbzrle_decoded_buf = g_malloc(TARGET_PAGE_SIZE);
2281 loaded_data = xbzrle_decoded_buf;
2283 /* extract RLE header */
2284 xh_flags = qemu_get_byte(f);
2285 xh_len = qemu_get_be16(f);
2287 if (xh_flags != ENCODING_FLAG_XBZRLE) {
2288 error_report("Failed to load XBZRLE page - wrong compression!");
2292 if (xh_len > TARGET_PAGE_SIZE) {
2293 error_report("Failed to load XBZRLE page - len overflow!");
2296 /* load data and decode */
2297 qemu_get_buffer_in_place(f, &loaded_data, xh_len);
2300 if (xbzrle_decode_buffer(loaded_data, xh_len, host,
2301 TARGET_PAGE_SIZE) == -1) {
2302 error_report("Failed to load XBZRLE page - decode error!");
2310 * ram_block_from_stream: read a RAMBlock id from the migration stream
2312 * Must be called from within a rcu critical section.
2314 * Returns a pointer from within the RCU-protected ram_list.
2316 * @f: QEMUFile where to read the data from
2317 * @flags: Page flags (mostly to see if it's a continuation of previous block)
2319 static inline RAMBlock *ram_block_from_stream(QEMUFile *f, int flags)
2321 static RAMBlock *block = NULL;
2325 if (flags & RAM_SAVE_FLAG_CONTINUE) {
2327 error_report("Ack, bad migration stream!");
2333 len = qemu_get_byte(f);
2334 qemu_get_buffer(f, (uint8_t *)id, len);
2337 block = qemu_ram_block_by_name(id);
2339 error_report("Can't find block %s", id);
2346 static inline void *host_from_ram_block_offset(RAMBlock *block,
2349 if (!offset_in_ramblock(block, offset)) {
2353 return block->host + offset;
2357 * ram_handle_compressed: handle the zero page case
2359 * If a page (or a whole RDMA chunk) has been
2360 * determined to be zero, then zap it.
2362 * @host: host address for the zero page
2363 * @ch: what the page is filled from. We only support zero
2364 * @size: size of the zero page
2366 void ram_handle_compressed(void *host, uint8_t ch, uint64_t size)
2368 if (ch != 0 || !is_zero_range(host, size)) {
2369 memset(host, ch, size);
2373 static void *do_data_decompress(void *opaque)
2375 DecompressParam *param = opaque;
2376 unsigned long pagesize;
2380 qemu_mutex_lock(¶m->mutex);
2381 while (!param->quit) {
2386 qemu_mutex_unlock(¶m->mutex);
2388 pagesize = TARGET_PAGE_SIZE;
2389 /* uncompress() will return failed in some case, especially
2390 * when the page is dirted when doing the compression, it's
2391 * not a problem because the dirty page will be retransferred
2392 * and uncompress() won't break the data in other pages.
2394 uncompress((Bytef *)des, &pagesize,
2395 (const Bytef *)param->compbuf, len);
2397 qemu_mutex_lock(&decomp_done_lock);
2399 qemu_cond_signal(&decomp_done_cond);
2400 qemu_mutex_unlock(&decomp_done_lock);
2402 qemu_mutex_lock(¶m->mutex);
2404 qemu_cond_wait(¶m->cond, ¶m->mutex);
2407 qemu_mutex_unlock(¶m->mutex);
2412 static void wait_for_decompress_done(void)
2414 int idx, thread_count;
2416 if (!migrate_use_compression()) {
2420 thread_count = migrate_decompress_threads();
2421 qemu_mutex_lock(&decomp_done_lock);
2422 for (idx = 0; idx < thread_count; idx++) {
2423 while (!decomp_param[idx].done) {
2424 qemu_cond_wait(&decomp_done_cond, &decomp_done_lock);
2427 qemu_mutex_unlock(&decomp_done_lock);
2430 void migrate_decompress_threads_create(void)
2432 int i, thread_count;
2434 thread_count = migrate_decompress_threads();
2435 decompress_threads = g_new0(QemuThread, thread_count);
2436 decomp_param = g_new0(DecompressParam, thread_count);
2437 qemu_mutex_init(&decomp_done_lock);
2438 qemu_cond_init(&decomp_done_cond);
2439 for (i = 0; i < thread_count; i++) {
2440 qemu_mutex_init(&decomp_param[i].mutex);
2441 qemu_cond_init(&decomp_param[i].cond);
2442 decomp_param[i].compbuf = g_malloc0(compressBound(TARGET_PAGE_SIZE));
2443 decomp_param[i].done = true;
2444 decomp_param[i].quit = false;
2445 qemu_thread_create(decompress_threads + i, "decompress",
2446 do_data_decompress, decomp_param + i,
2447 QEMU_THREAD_JOINABLE);
2451 void migrate_decompress_threads_join(void)
2453 int i, thread_count;
2455 thread_count = migrate_decompress_threads();
2456 for (i = 0; i < thread_count; i++) {
2457 qemu_mutex_lock(&decomp_param[i].mutex);
2458 decomp_param[i].quit = true;
2459 qemu_cond_signal(&decomp_param[i].cond);
2460 qemu_mutex_unlock(&decomp_param[i].mutex);
2462 for (i = 0; i < thread_count; i++) {
2463 qemu_thread_join(decompress_threads + i);
2464 qemu_mutex_destroy(&decomp_param[i].mutex);
2465 qemu_cond_destroy(&decomp_param[i].cond);
2466 g_free(decomp_param[i].compbuf);
2468 g_free(decompress_threads);
2469 g_free(decomp_param);
2470 decompress_threads = NULL;
2471 decomp_param = NULL;
2474 static void decompress_data_with_multi_threads(QEMUFile *f,
2475 void *host, int len)
2477 int idx, thread_count;
2479 thread_count = migrate_decompress_threads();
2480 qemu_mutex_lock(&decomp_done_lock);
2482 for (idx = 0; idx < thread_count; idx++) {
2483 if (decomp_param[idx].done) {
2484 decomp_param[idx].done = false;
2485 qemu_mutex_lock(&decomp_param[idx].mutex);
2486 qemu_get_buffer(f, decomp_param[idx].compbuf, len);
2487 decomp_param[idx].des = host;
2488 decomp_param[idx].len = len;
2489 qemu_cond_signal(&decomp_param[idx].cond);
2490 qemu_mutex_unlock(&decomp_param[idx].mutex);
2494 if (idx < thread_count) {
2497 qemu_cond_wait(&decomp_done_cond, &decomp_done_lock);
2500 qemu_mutex_unlock(&decomp_done_lock);
2504 * ram_postcopy_incoming_init: allocate postcopy data structures
2506 * Returns 0 for success and negative if there was one error
2508 * @mis: current migration incoming state
2510 * Allocate data structures etc needed by incoming migration with
2511 * postcopy-ram. postcopy-ram's similarly names
2512 * postcopy_ram_incoming_init does the work.
2514 int ram_postcopy_incoming_init(MigrationIncomingState *mis)
2516 size_t ram_pages = last_ram_offset() >> TARGET_PAGE_BITS;
2518 return postcopy_ram_incoming_init(mis, ram_pages);
2522 * ram_load_postcopy: load a page in postcopy case
2524 * Returns 0 for success or -errno in case of error
2526 * Called in postcopy mode by ram_load().
2527 * rcu_read_lock is taken prior to this being called.
2529 * @f: QEMUFile where to send the data
2531 static int ram_load_postcopy(QEMUFile *f)
2533 int flags = 0, ret = 0;
2534 bool place_needed = false;
2535 bool matching_page_sizes = false;
2536 MigrationIncomingState *mis = migration_incoming_get_current();
2537 /* Temporary page that is later 'placed' */
2538 void *postcopy_host_page = postcopy_get_tmp_page(mis);
2539 void *last_host = NULL;
2540 bool all_zero = false;
2542 while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
2545 void *page_buffer = NULL;
2546 void *place_source = NULL;
2547 RAMBlock *block = NULL;
2550 addr = qemu_get_be64(f);
2551 flags = addr & ~TARGET_PAGE_MASK;
2552 addr &= TARGET_PAGE_MASK;
2554 trace_ram_load_postcopy_loop((uint64_t)addr, flags);
2555 place_needed = false;
2556 if (flags & (RAM_SAVE_FLAG_COMPRESS | RAM_SAVE_FLAG_PAGE)) {
2557 block = ram_block_from_stream(f, flags);
2559 host = host_from_ram_block_offset(block, addr);
2561 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
2565 matching_page_sizes = block->page_size == TARGET_PAGE_SIZE;
2567 * Postcopy requires that we place whole host pages atomically;
2568 * these may be huge pages for RAMBlocks that are backed by
2570 * To make it atomic, the data is read into a temporary page
2571 * that's moved into place later.
2572 * The migration protocol uses, possibly smaller, target-pages
2573 * however the source ensures it always sends all the components
2574 * of a host page in order.
2576 page_buffer = postcopy_host_page +
2577 ((uintptr_t)host & (block->page_size - 1));
2578 /* If all TP are zero then we can optimise the place */
2579 if (!((uintptr_t)host & (block->page_size - 1))) {
2582 /* not the 1st TP within the HP */
2583 if (host != (last_host + TARGET_PAGE_SIZE)) {
2584 error_report("Non-sequential target page %p/%p",
2593 * If it's the last part of a host page then we place the host
2596 place_needed = (((uintptr_t)host + TARGET_PAGE_SIZE) &
2597 (block->page_size - 1)) == 0;
2598 place_source = postcopy_host_page;
2602 switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
2603 case RAM_SAVE_FLAG_COMPRESS:
2604 ch = qemu_get_byte(f);
2605 memset(page_buffer, ch, TARGET_PAGE_SIZE);
2611 case RAM_SAVE_FLAG_PAGE:
2613 if (!place_needed || !matching_page_sizes) {
2614 qemu_get_buffer(f, page_buffer, TARGET_PAGE_SIZE);
2616 /* Avoids the qemu_file copy during postcopy, which is
2617 * going to do a copy later; can only do it when we
2618 * do this read in one go (matching page sizes)
2620 qemu_get_buffer_in_place(f, (uint8_t **)&place_source,
2624 case RAM_SAVE_FLAG_EOS:
2628 error_report("Unknown combination of migration flags: %#x"
2629 " (postcopy mode)", flags);
2634 /* This gets called at the last target page in the host page */
2635 void *place_dest = host + TARGET_PAGE_SIZE - block->page_size;
2638 ret = postcopy_place_page_zero(mis, place_dest,
2641 ret = postcopy_place_page(mis, place_dest,
2642 place_source, block->page_size);
2646 ret = qemu_file_get_error(f);
2653 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2655 int flags = 0, ret = 0;
2656 static uint64_t seq_iter;
2659 * If system is running in postcopy mode, page inserts to host memory must
2662 bool postcopy_running = postcopy_state_get() >= POSTCOPY_INCOMING_LISTENING;
2663 /* ADVISE is earlier, it shows the source has the postcopy capability on */
2664 bool postcopy_advised = postcopy_state_get() >= POSTCOPY_INCOMING_ADVISE;
2668 if (version_id != 4) {
2672 /* This RCU critical section can be very long running.
2673 * When RCU reclaims in the code start to become numerous,
2674 * it will be necessary to reduce the granularity of this
2679 if (postcopy_running) {
2680 ret = ram_load_postcopy(f);
2683 while (!postcopy_running && !ret && !(flags & RAM_SAVE_FLAG_EOS)) {
2684 ram_addr_t addr, total_ram_bytes;
2688 addr = qemu_get_be64(f);
2689 flags = addr & ~TARGET_PAGE_MASK;
2690 addr &= TARGET_PAGE_MASK;
2692 if (flags & (RAM_SAVE_FLAG_COMPRESS | RAM_SAVE_FLAG_PAGE |
2693 RAM_SAVE_FLAG_COMPRESS_PAGE | RAM_SAVE_FLAG_XBZRLE)) {
2694 RAMBlock *block = ram_block_from_stream(f, flags);
2696 host = host_from_ram_block_offset(block, addr);
2698 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
2704 switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
2705 case RAM_SAVE_FLAG_MEM_SIZE:
2706 /* Synchronize RAM block list */
2707 total_ram_bytes = addr;
2708 while (!ret && total_ram_bytes) {
2713 len = qemu_get_byte(f);
2714 qemu_get_buffer(f, (uint8_t *)id, len);
2716 length = qemu_get_be64(f);
2718 block = qemu_ram_block_by_name(id);
2720 if (length != block->used_length) {
2721 Error *local_err = NULL;
2723 ret = qemu_ram_resize(block, length,
2726 error_report_err(local_err);
2729 /* For postcopy we need to check hugepage sizes match */
2730 if (postcopy_advised &&
2731 block->page_size != qemu_host_page_size) {
2732 uint64_t remote_page_size = qemu_get_be64(f);
2733 if (remote_page_size != block->page_size) {
2734 error_report("Mismatched RAM page size %s "
2735 "(local) %zd != %" PRId64,
2736 id, block->page_size,
2741 ram_control_load_hook(f, RAM_CONTROL_BLOCK_REG,
2744 error_report("Unknown ramblock \"%s\", cannot "
2745 "accept migration", id);
2749 total_ram_bytes -= length;
2753 case RAM_SAVE_FLAG_COMPRESS:
2754 ch = qemu_get_byte(f);
2755 ram_handle_compressed(host, ch, TARGET_PAGE_SIZE);
2758 case RAM_SAVE_FLAG_PAGE:
2759 qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
2762 case RAM_SAVE_FLAG_COMPRESS_PAGE:
2763 len = qemu_get_be32(f);
2764 if (len < 0 || len > compressBound(TARGET_PAGE_SIZE)) {
2765 error_report("Invalid compressed data length: %d", len);
2769 decompress_data_with_multi_threads(f, host, len);
2772 case RAM_SAVE_FLAG_XBZRLE:
2773 if (load_xbzrle(f, addr, host) < 0) {
2774 error_report("Failed to decompress XBZRLE page at "
2775 RAM_ADDR_FMT, addr);
2780 case RAM_SAVE_FLAG_EOS:
2784 if (flags & RAM_SAVE_FLAG_HOOK) {
2785 ram_control_load_hook(f, RAM_CONTROL_HOOK, NULL);
2787 error_report("Unknown combination of migration flags: %#x",
2793 ret = qemu_file_get_error(f);
2797 wait_for_decompress_done();
2799 trace_ram_load_complete(ret, seq_iter);
2803 static SaveVMHandlers savevm_ram_handlers = {
2804 .save_live_setup = ram_save_setup,
2805 .save_live_iterate = ram_save_iterate,
2806 .save_live_complete_postcopy = ram_save_complete,
2807 .save_live_complete_precopy = ram_save_complete,
2808 .save_live_pending = ram_save_pending,
2809 .load_state = ram_load,
2810 .cleanup = ram_migration_cleanup,
2813 void ram_mig_init(void)
2815 qemu_mutex_init(&XBZRLE.lock);
2816 register_savevm_live(NULL, "ram", 0, 4, &savevm_ram_handlers, &ram_state);