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
29 #include "qemu/osdep.h"
30 #include "qemu/cutils.h"
31 #include "qemu/bitops.h"
32 #include "qemu/bitmap.h"
33 #include "qemu/madvise.h"
34 #include "qemu/main-loop.h"
36 #include "ram-compress.h"
38 #include "migration.h"
39 #include "migration-stats.h"
40 #include "migration/register.h"
41 #include "migration/misc.h"
42 #include "qemu-file.h"
43 #include "postcopy-ram.h"
44 #include "page_cache.h"
45 #include "qemu/error-report.h"
46 #include "qapi/error.h"
47 #include "qapi/qapi-types-migration.h"
48 #include "qapi/qapi-events-migration.h"
49 #include "qapi/qapi-commands-migration.h"
50 #include "qapi/qmp/qerror.h"
52 #include "exec/ram_addr.h"
53 #include "exec/target_page.h"
54 #include "qemu/rcu_queue.h"
55 #include "migration/colo.h"
57 #include "sysemu/cpu-throttle.h"
61 #include "sysemu/runstate.h"
63 #include "sysemu/dirtylimit.h"
64 #include "sysemu/kvm.h"
66 #include "hw/boards.h" /* for machine_dump_guest_core() */
68 #if defined(__linux__)
69 #include "qemu/userfaultfd.h"
70 #endif /* defined(__linux__) */
72 /***********************************************************/
73 /* ram save/restore */
76 * RAM_SAVE_FLAG_ZERO used to be named RAM_SAVE_FLAG_COMPRESS, it
77 * worked for pages that were filled with the same char. We switched
78 * it to only search for the zero value. And to avoid confusion with
79 * RAM_SAVE_FLAG_COMPRESS_PAGE just rename it.
82 * RAM_SAVE_FLAG_FULL was obsoleted in 2009, it can be reused now
84 #define RAM_SAVE_FLAG_FULL 0x01
85 #define RAM_SAVE_FLAG_ZERO 0x02
86 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
87 #define RAM_SAVE_FLAG_PAGE 0x08
88 #define RAM_SAVE_FLAG_EOS 0x10
89 #define RAM_SAVE_FLAG_CONTINUE 0x20
90 #define RAM_SAVE_FLAG_XBZRLE 0x40
91 /* 0x80 is reserved in qemu-file.h for RAM_SAVE_FLAG_HOOK */
92 #define RAM_SAVE_FLAG_COMPRESS_PAGE 0x100
93 #define RAM_SAVE_FLAG_MULTIFD_FLUSH 0x200
94 /* We can't use any flag that is bigger than 0x200 */
96 XBZRLECacheStats xbzrle_counters
;
98 /* used by the search for pages to send */
99 struct PageSearchStatus
{
100 /* The migration channel used for a specific host page */
101 QEMUFile
*pss_channel
;
102 /* Last block from where we have sent data */
103 RAMBlock
*last_sent_block
;
104 /* Current block being searched */
106 /* Current page to search from */
108 /* Set once we wrap around */
110 /* Whether we're sending a host page */
111 bool host_page_sending
;
112 /* The start/end of current host page. Invalid if host_page_sending==false */
113 unsigned long host_page_start
;
114 unsigned long host_page_end
;
116 typedef struct PageSearchStatus PageSearchStatus
;
118 /* struct contains XBZRLE cache and a static page
119 used by the compression */
121 /* buffer used for XBZRLE encoding */
122 uint8_t *encoded_buf
;
123 /* buffer for storing page content */
124 uint8_t *current_buf
;
125 /* Cache for XBZRLE, Protected by lock. */
128 /* it will store a page full of zeros */
129 uint8_t *zero_target_page
;
130 /* buffer used for XBZRLE decoding */
131 uint8_t *decoded_buf
;
134 static void XBZRLE_cache_lock(void)
136 if (migrate_xbzrle()) {
137 qemu_mutex_lock(&XBZRLE
.lock
);
141 static void XBZRLE_cache_unlock(void)
143 if (migrate_xbzrle()) {
144 qemu_mutex_unlock(&XBZRLE
.lock
);
149 * xbzrle_cache_resize: resize the xbzrle cache
151 * This function is called from migrate_params_apply in main
152 * thread, possibly while a migration is in progress. A running
153 * migration may be using the cache and might finish during this call,
154 * hence changes to the cache are protected by XBZRLE.lock().
156 * Returns 0 for success or -1 for error
158 * @new_size: new cache size
159 * @errp: set *errp if the check failed, with reason
161 int xbzrle_cache_resize(uint64_t new_size
, Error
**errp
)
163 PageCache
*new_cache
;
166 /* Check for truncation */
167 if (new_size
!= (size_t)new_size
) {
168 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
169 "exceeding address space");
173 if (new_size
== migrate_xbzrle_cache_size()) {
180 if (XBZRLE
.cache
!= NULL
) {
181 new_cache
= cache_init(new_size
, TARGET_PAGE_SIZE
, errp
);
187 cache_fini(XBZRLE
.cache
);
188 XBZRLE
.cache
= new_cache
;
191 XBZRLE_cache_unlock();
195 static bool postcopy_preempt_active(void)
197 return migrate_postcopy_preempt() && migration_in_postcopy();
200 bool migrate_ram_is_ignored(RAMBlock
*block
)
202 return !qemu_ram_is_migratable(block
) ||
203 (migrate_ignore_shared() && qemu_ram_is_shared(block
)
204 && qemu_ram_is_named_file(block
));
207 #undef RAMBLOCK_FOREACH
209 int foreach_not_ignored_block(RAMBlockIterFunc func
, void *opaque
)
214 RCU_READ_LOCK_GUARD();
216 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
217 ret
= func(block
, opaque
);
225 static void ramblock_recv_map_init(void)
229 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
230 assert(!rb
->receivedmap
);
231 rb
->receivedmap
= bitmap_new(rb
->max_length
>> qemu_target_page_bits());
235 int ramblock_recv_bitmap_test(RAMBlock
*rb
, void *host_addr
)
237 return test_bit(ramblock_recv_bitmap_offset(host_addr
, rb
),
241 bool ramblock_recv_bitmap_test_byte_offset(RAMBlock
*rb
, uint64_t byte_offset
)
243 return test_bit(byte_offset
>> TARGET_PAGE_BITS
, rb
->receivedmap
);
246 void ramblock_recv_bitmap_set(RAMBlock
*rb
, void *host_addr
)
248 set_bit_atomic(ramblock_recv_bitmap_offset(host_addr
, rb
), rb
->receivedmap
);
251 void ramblock_recv_bitmap_set_range(RAMBlock
*rb
, void *host_addr
,
254 bitmap_set_atomic(rb
->receivedmap
,
255 ramblock_recv_bitmap_offset(host_addr
, rb
),
259 #define RAMBLOCK_RECV_BITMAP_ENDING (0x0123456789abcdefULL)
262 * Format: bitmap_size (8 bytes) + whole_bitmap (N bytes).
264 * Returns >0 if success with sent bytes, or <0 if error.
266 int64_t ramblock_recv_bitmap_send(QEMUFile
*file
,
267 const char *block_name
)
269 RAMBlock
*block
= qemu_ram_block_by_name(block_name
);
270 unsigned long *le_bitmap
, nbits
;
274 error_report("%s: invalid block name: %s", __func__
, block_name
);
278 nbits
= block
->postcopy_length
>> TARGET_PAGE_BITS
;
281 * Make sure the tmp bitmap buffer is big enough, e.g., on 32bit
282 * machines we may need 4 more bytes for padding (see below
283 * comment). So extend it a bit before hand.
285 le_bitmap
= bitmap_new(nbits
+ BITS_PER_LONG
);
288 * Always use little endian when sending the bitmap. This is
289 * required that when source and destination VMs are not using the
290 * same endianness. (Note: big endian won't work.)
292 bitmap_to_le(le_bitmap
, block
->receivedmap
, nbits
);
294 /* Size of the bitmap, in bytes */
295 size
= DIV_ROUND_UP(nbits
, 8);
298 * size is always aligned to 8 bytes for 64bit machines, but it
299 * may not be true for 32bit machines. We need this padding to
300 * make sure the migration can survive even between 32bit and
303 size
= ROUND_UP(size
, 8);
305 qemu_put_be64(file
, size
);
306 qemu_put_buffer(file
, (const uint8_t *)le_bitmap
, size
);
308 * Mark as an end, in case the middle part is screwed up due to
309 * some "mysterious" reason.
311 qemu_put_be64(file
, RAMBLOCK_RECV_BITMAP_ENDING
);
316 if (qemu_file_get_error(file
)) {
317 return qemu_file_get_error(file
);
320 return size
+ sizeof(size
);
324 * An outstanding page request, on the source, having been received
327 struct RAMSrcPageRequest
{
332 QSIMPLEQ_ENTRY(RAMSrcPageRequest
) next_req
;
335 /* State of RAM for migration */
338 * PageSearchStatus structures for the channels when send pages.
339 * Protected by the bitmap_mutex.
341 PageSearchStatus pss
[RAM_CHANNEL_MAX
];
342 /* UFFD file descriptor, used in 'write-tracking' migration */
344 /* total ram size in bytes */
345 uint64_t ram_bytes_total
;
346 /* Last block that we have visited searching for dirty pages */
347 RAMBlock
*last_seen_block
;
348 /* Last dirty target page we have sent */
349 ram_addr_t last_page
;
350 /* last ram version we have seen */
351 uint32_t last_version
;
352 /* How many times we have dirty too many pages */
353 int dirty_rate_high_cnt
;
354 /* these variables are used for bitmap sync */
355 /* last time we did a full bitmap_sync */
356 int64_t time_last_bitmap_sync
;
357 /* bytes transferred at start_time */
358 uint64_t bytes_xfer_prev
;
359 /* number of dirty pages since start_time */
360 uint64_t num_dirty_pages_period
;
361 /* xbzrle misses since the beginning of the period */
362 uint64_t xbzrle_cache_miss_prev
;
363 /* Amount of xbzrle pages since the beginning of the period */
364 uint64_t xbzrle_pages_prev
;
365 /* Amount of xbzrle encoded bytes since the beginning of the period */
366 uint64_t xbzrle_bytes_prev
;
367 /* Are we really using XBZRLE (e.g., after the first round). */
369 /* Are we on the last stage of migration */
371 /* compression statistics since the beginning of the period */
372 /* amount of count that no free thread to compress data */
373 uint64_t compress_thread_busy_prev
;
374 /* amount bytes after compression */
375 uint64_t compressed_size_prev
;
376 /* amount of compressed pages */
377 uint64_t compress_pages_prev
;
379 /* total handled target pages at the beginning of period */
380 uint64_t target_page_count_prev
;
381 /* total handled target pages since start */
382 uint64_t target_page_count
;
383 /* number of dirty bits in the bitmap */
384 uint64_t migration_dirty_pages
;
387 * - dirty/clear bitmap
388 * - migration_dirty_pages
391 QemuMutex bitmap_mutex
;
392 /* The RAMBlock used in the last src_page_requests */
393 RAMBlock
*last_req_rb
;
394 /* Queue of outstanding page requests from the destination */
395 QemuMutex src_page_req_mutex
;
396 QSIMPLEQ_HEAD(, RAMSrcPageRequest
) src_page_requests
;
398 typedef struct RAMState RAMState
;
400 static RAMState
*ram_state
;
402 static NotifierWithReturnList precopy_notifier_list
;
404 /* Whether postcopy has queued requests? */
405 static bool postcopy_has_request(RAMState
*rs
)
407 return !QSIMPLEQ_EMPTY_ATOMIC(&rs
->src_page_requests
);
410 void precopy_infrastructure_init(void)
412 notifier_with_return_list_init(&precopy_notifier_list
);
415 void precopy_add_notifier(NotifierWithReturn
*n
)
417 notifier_with_return_list_add(&precopy_notifier_list
, n
);
420 void precopy_remove_notifier(NotifierWithReturn
*n
)
422 notifier_with_return_remove(n
);
425 int precopy_notify(PrecopyNotifyReason reason
, Error
**errp
)
427 PrecopyNotifyData pnd
;
431 return notifier_with_return_list_notify(&precopy_notifier_list
, &pnd
);
434 uint64_t ram_bytes_remaining(void)
436 return ram_state
? (ram_state
->migration_dirty_pages
* TARGET_PAGE_SIZE
) :
440 void ram_transferred_add(uint64_t bytes
)
442 if (runstate_is_running()) {
443 stat64_add(&mig_stats
.precopy_bytes
, bytes
);
444 } else if (migration_in_postcopy()) {
445 stat64_add(&mig_stats
.postcopy_bytes
, bytes
);
447 stat64_add(&mig_stats
.downtime_bytes
, bytes
);
449 stat64_add(&mig_stats
.transferred
, bytes
);
452 struct MigrationOps
{
453 int (*ram_save_target_page
)(RAMState
*rs
, PageSearchStatus
*pss
);
455 typedef struct MigrationOps MigrationOps
;
457 MigrationOps
*migration_ops
;
459 static int ram_save_host_page_urgent(PageSearchStatus
*pss
);
461 /* NOTE: page is the PFN not real ram_addr_t. */
462 static void pss_init(PageSearchStatus
*pss
, RAMBlock
*rb
, ram_addr_t page
)
466 pss
->complete_round
= false;
470 * Check whether two PSSs are actively sending the same page. Return true
471 * if it is, false otherwise.
473 static bool pss_overlap(PageSearchStatus
*pss1
, PageSearchStatus
*pss2
)
475 return pss1
->host_page_sending
&& pss2
->host_page_sending
&&
476 (pss1
->host_page_start
== pss2
->host_page_start
);
480 * save_page_header: write page header to wire
482 * If this is the 1st block, it also writes the block identification
484 * Returns the number of bytes written
486 * @pss: current PSS channel status
487 * @block: block that contains the page we want to send
488 * @offset: offset inside the block for the page
489 * in the lower bits, it contains flags
491 static size_t save_page_header(PageSearchStatus
*pss
, QEMUFile
*f
,
492 RAMBlock
*block
, ram_addr_t offset
)
495 bool same_block
= (block
== pss
->last_sent_block
);
498 offset
|= RAM_SAVE_FLAG_CONTINUE
;
500 qemu_put_be64(f
, offset
);
504 len
= strlen(block
->idstr
);
505 qemu_put_byte(f
, len
);
506 qemu_put_buffer(f
, (uint8_t *)block
->idstr
, len
);
508 pss
->last_sent_block
= block
;
514 * mig_throttle_guest_down: throttle down the guest
516 * Reduce amount of guest cpu execution to hopefully slow down memory
517 * writes. If guest dirty memory rate is reduced below the rate at
518 * which we can transfer pages to the destination then we should be
519 * able to complete migration. Some workloads dirty memory way too
520 * fast and will not effectively converge, even with auto-converge.
522 static void mig_throttle_guest_down(uint64_t bytes_dirty_period
,
523 uint64_t bytes_dirty_threshold
)
525 uint64_t pct_initial
= migrate_cpu_throttle_initial();
526 uint64_t pct_increment
= migrate_cpu_throttle_increment();
527 bool pct_tailslow
= migrate_cpu_throttle_tailslow();
528 int pct_max
= migrate_max_cpu_throttle();
530 uint64_t throttle_now
= cpu_throttle_get_percentage();
531 uint64_t cpu_now
, cpu_ideal
, throttle_inc
;
533 /* We have not started throttling yet. Let's start it. */
534 if (!cpu_throttle_active()) {
535 cpu_throttle_set(pct_initial
);
537 /* Throttling already on, just increase the rate */
539 throttle_inc
= pct_increment
;
541 /* Compute the ideal CPU percentage used by Guest, which may
542 * make the dirty rate match the dirty rate threshold. */
543 cpu_now
= 100 - throttle_now
;
544 cpu_ideal
= cpu_now
* (bytes_dirty_threshold
* 1.0 /
546 throttle_inc
= MIN(cpu_now
- cpu_ideal
, pct_increment
);
548 cpu_throttle_set(MIN(throttle_now
+ throttle_inc
, pct_max
));
552 void mig_throttle_counter_reset(void)
554 RAMState
*rs
= ram_state
;
556 rs
->time_last_bitmap_sync
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
557 rs
->num_dirty_pages_period
= 0;
558 rs
->bytes_xfer_prev
= stat64_get(&mig_stats
.transferred
);
562 * xbzrle_cache_zero_page: insert a zero page in the XBZRLE cache
564 * @rs: current RAM state
565 * @current_addr: address for the zero page
567 * Update the xbzrle cache to reflect a page that's been sent as all 0.
568 * The important thing is that a stale (not-yet-0'd) page be replaced
570 * As a bonus, if the page wasn't in the cache it gets added so that
571 * when a small write is made into the 0'd page it gets XBZRLE sent.
573 static void xbzrle_cache_zero_page(RAMState
*rs
, ram_addr_t current_addr
)
575 /* We don't care if this fails to allocate a new cache page
576 * as long as it updated an old one */
577 cache_insert(XBZRLE
.cache
, current_addr
, XBZRLE
.zero_target_page
,
578 stat64_get(&mig_stats
.dirty_sync_count
));
581 #define ENCODING_FLAG_XBZRLE 0x1
584 * save_xbzrle_page: compress and send current page
586 * Returns: 1 means that we wrote the page
587 * 0 means that page is identical to the one already sent
588 * -1 means that xbzrle would be longer than normal
590 * @rs: current RAM state
591 * @pss: current PSS channel
592 * @current_data: pointer to the address of the page contents
593 * @current_addr: addr of the page
594 * @block: block that contains the page we want to send
595 * @offset: offset inside the block for the page
597 static int save_xbzrle_page(RAMState
*rs
, PageSearchStatus
*pss
,
598 uint8_t **current_data
, ram_addr_t current_addr
,
599 RAMBlock
*block
, ram_addr_t offset
)
601 int encoded_len
= 0, bytes_xbzrle
;
602 uint8_t *prev_cached_page
;
603 QEMUFile
*file
= pss
->pss_channel
;
604 uint64_t generation
= stat64_get(&mig_stats
.dirty_sync_count
);
606 if (!cache_is_cached(XBZRLE
.cache
, current_addr
, generation
)) {
607 xbzrle_counters
.cache_miss
++;
608 if (!rs
->last_stage
) {
609 if (cache_insert(XBZRLE
.cache
, current_addr
, *current_data
,
613 /* update *current_data when the page has been
614 inserted into cache */
615 *current_data
= get_cached_data(XBZRLE
.cache
, current_addr
);
622 * Reaching here means the page has hit the xbzrle cache, no matter what
623 * encoding result it is (normal encoding, overflow or skipping the page),
624 * count the page as encoded. This is used to calculate the encoding rate.
626 * Example: 2 pages (8KB) being encoded, first page encoding generates 2KB,
627 * 2nd page turns out to be skipped (i.e. no new bytes written to the
628 * page), the overall encoding rate will be 8KB / 2KB = 4, which has the
629 * skipped page included. In this way, the encoding rate can tell if the
630 * guest page is good for xbzrle encoding.
632 xbzrle_counters
.pages
++;
633 prev_cached_page
= get_cached_data(XBZRLE
.cache
, current_addr
);
635 /* save current buffer into memory */
636 memcpy(XBZRLE
.current_buf
, *current_data
, TARGET_PAGE_SIZE
);
638 /* XBZRLE encoding (if there is no overflow) */
639 encoded_len
= xbzrle_encode_buffer(prev_cached_page
, XBZRLE
.current_buf
,
640 TARGET_PAGE_SIZE
, XBZRLE
.encoded_buf
,
644 * Update the cache contents, so that it corresponds to the data
645 * sent, in all cases except where we skip the page.
647 if (!rs
->last_stage
&& encoded_len
!= 0) {
648 memcpy(prev_cached_page
, XBZRLE
.current_buf
, TARGET_PAGE_SIZE
);
650 * In the case where we couldn't compress, ensure that the caller
651 * sends the data from the cache, since the guest might have
652 * changed the RAM since we copied it.
654 *current_data
= prev_cached_page
;
657 if (encoded_len
== 0) {
658 trace_save_xbzrle_page_skipping();
660 } else if (encoded_len
== -1) {
661 trace_save_xbzrle_page_overflow();
662 xbzrle_counters
.overflow
++;
663 xbzrle_counters
.bytes
+= TARGET_PAGE_SIZE
;
667 /* Send XBZRLE based compressed page */
668 bytes_xbzrle
= save_page_header(pss
, pss
->pss_channel
, block
,
669 offset
| RAM_SAVE_FLAG_XBZRLE
);
670 qemu_put_byte(file
, ENCODING_FLAG_XBZRLE
);
671 qemu_put_be16(file
, encoded_len
);
672 qemu_put_buffer(file
, XBZRLE
.encoded_buf
, encoded_len
);
673 bytes_xbzrle
+= encoded_len
+ 1 + 2;
675 * Like compressed_size (please see update_compress_thread_counts),
676 * the xbzrle encoded bytes don't count the 8 byte header with
677 * RAM_SAVE_FLAG_CONTINUE.
679 xbzrle_counters
.bytes
+= bytes_xbzrle
- 8;
680 ram_transferred_add(bytes_xbzrle
);
686 * pss_find_next_dirty: find the next dirty page of current ramblock
688 * This function updates pss->page to point to the next dirty page index
689 * within the ramblock to migrate, or the end of ramblock when nothing
690 * found. Note that when pss->host_page_sending==true it means we're
691 * during sending a host page, so we won't look for dirty page that is
692 * outside the host page boundary.
694 * @pss: the current page search status
696 static void pss_find_next_dirty(PageSearchStatus
*pss
)
698 RAMBlock
*rb
= pss
->block
;
699 unsigned long size
= rb
->used_length
>> TARGET_PAGE_BITS
;
700 unsigned long *bitmap
= rb
->bmap
;
702 if (migrate_ram_is_ignored(rb
)) {
703 /* Points directly to the end, so we know no dirty page */
709 * If during sending a host page, only look for dirty pages within the
710 * current host page being send.
712 if (pss
->host_page_sending
) {
713 assert(pss
->host_page_end
);
714 size
= MIN(size
, pss
->host_page_end
);
717 pss
->page
= find_next_bit(bitmap
, size
, pss
->page
);
720 static void migration_clear_memory_region_dirty_bitmap(RAMBlock
*rb
,
726 if (!rb
->clear_bmap
|| !clear_bmap_test_and_clear(rb
, page
)) {
730 shift
= rb
->clear_bmap_shift
;
732 * CLEAR_BITMAP_SHIFT_MIN should always guarantee this... this
733 * can make things easier sometimes since then start address
734 * of the small chunk will always be 64 pages aligned so the
735 * bitmap will always be aligned to unsigned long. We should
736 * even be able to remove this restriction but I'm simply
741 size
= 1ULL << (TARGET_PAGE_BITS
+ shift
);
742 start
= QEMU_ALIGN_DOWN((ram_addr_t
)page
<< TARGET_PAGE_BITS
, size
);
743 trace_migration_bitmap_clear_dirty(rb
->idstr
, start
, size
, page
);
744 memory_region_clear_dirty_bitmap(rb
->mr
, start
, size
);
748 migration_clear_memory_region_dirty_bitmap_range(RAMBlock
*rb
,
750 unsigned long npages
)
752 unsigned long i
, chunk_pages
= 1UL << rb
->clear_bmap_shift
;
753 unsigned long chunk_start
= QEMU_ALIGN_DOWN(start
, chunk_pages
);
754 unsigned long chunk_end
= QEMU_ALIGN_UP(start
+ npages
, chunk_pages
);
757 * Clear pages from start to start + npages - 1, so the end boundary is
760 for (i
= chunk_start
; i
< chunk_end
; i
+= chunk_pages
) {
761 migration_clear_memory_region_dirty_bitmap(rb
, i
);
766 * colo_bitmap_find_diry:find contiguous dirty pages from start
768 * Returns the page offset within memory region of the start of the contiguout
771 * @rs: current RAM state
772 * @rb: RAMBlock where to search for dirty pages
773 * @start: page where we start the search
774 * @num: the number of contiguous dirty pages
777 unsigned long colo_bitmap_find_dirty(RAMState
*rs
, RAMBlock
*rb
,
778 unsigned long start
, unsigned long *num
)
780 unsigned long size
= rb
->used_length
>> TARGET_PAGE_BITS
;
781 unsigned long *bitmap
= rb
->bmap
;
782 unsigned long first
, next
;
786 if (migrate_ram_is_ignored(rb
)) {
790 first
= find_next_bit(bitmap
, size
, start
);
794 next
= find_next_zero_bit(bitmap
, size
, first
+ 1);
795 assert(next
>= first
);
800 static inline bool migration_bitmap_clear_dirty(RAMState
*rs
,
807 * Clear dirty bitmap if needed. This _must_ be called before we
808 * send any of the page in the chunk because we need to make sure
809 * we can capture further page content changes when we sync dirty
810 * log the next time. So as long as we are going to send any of
811 * the page in the chunk we clear the remote dirty bitmap for all.
812 * Clearing it earlier won't be a problem, but too late will.
814 migration_clear_memory_region_dirty_bitmap(rb
, page
);
816 ret
= test_and_clear_bit(page
, rb
->bmap
);
818 rs
->migration_dirty_pages
--;
824 static void dirty_bitmap_clear_section(MemoryRegionSection
*section
,
827 const hwaddr offset
= section
->offset_within_region
;
828 const hwaddr size
= int128_get64(section
->size
);
829 const unsigned long start
= offset
>> TARGET_PAGE_BITS
;
830 const unsigned long npages
= size
>> TARGET_PAGE_BITS
;
831 RAMBlock
*rb
= section
->mr
->ram_block
;
832 uint64_t *cleared_bits
= opaque
;
835 * We don't grab ram_state->bitmap_mutex because we expect to run
836 * only when starting migration or during postcopy recovery where
837 * we don't have concurrent access.
839 if (!migration_in_postcopy() && !migrate_background_snapshot()) {
840 migration_clear_memory_region_dirty_bitmap_range(rb
, start
, npages
);
842 *cleared_bits
+= bitmap_count_one_with_offset(rb
->bmap
, start
, npages
);
843 bitmap_clear(rb
->bmap
, start
, npages
);
847 * Exclude all dirty pages from migration that fall into a discarded range as
848 * managed by a RamDiscardManager responsible for the mapped memory region of
849 * the RAMBlock. Clear the corresponding bits in the dirty bitmaps.
851 * Discarded pages ("logically unplugged") have undefined content and must
852 * not get migrated, because even reading these pages for migration might
853 * result in undesired behavior.
855 * Returns the number of cleared bits in the RAMBlock dirty bitmap.
857 * Note: The result is only stable while migrating (precopy/postcopy).
859 static uint64_t ramblock_dirty_bitmap_clear_discarded_pages(RAMBlock
*rb
)
861 uint64_t cleared_bits
= 0;
863 if (rb
->mr
&& rb
->bmap
&& memory_region_has_ram_discard_manager(rb
->mr
)) {
864 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(rb
->mr
);
865 MemoryRegionSection section
= {
867 .offset_within_region
= 0,
868 .size
= int128_make64(qemu_ram_get_used_length(rb
)),
871 ram_discard_manager_replay_discarded(rdm
, §ion
,
872 dirty_bitmap_clear_section
,
879 * Check if a host-page aligned page falls into a discarded range as managed by
880 * a RamDiscardManager responsible for the mapped memory region of the RAMBlock.
882 * Note: The result is only stable while migrating (precopy/postcopy).
884 bool ramblock_page_is_discarded(RAMBlock
*rb
, ram_addr_t start
)
886 if (rb
->mr
&& memory_region_has_ram_discard_manager(rb
->mr
)) {
887 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(rb
->mr
);
888 MemoryRegionSection section
= {
890 .offset_within_region
= start
,
891 .size
= int128_make64(qemu_ram_pagesize(rb
)),
894 return !ram_discard_manager_is_populated(rdm
, §ion
);
899 /* Called with RCU critical section */
900 static void ramblock_sync_dirty_bitmap(RAMState
*rs
, RAMBlock
*rb
)
902 uint64_t new_dirty_pages
=
903 cpu_physical_memory_sync_dirty_bitmap(rb
, 0, rb
->used_length
);
905 rs
->migration_dirty_pages
+= new_dirty_pages
;
906 rs
->num_dirty_pages_period
+= new_dirty_pages
;
910 * ram_pagesize_summary: calculate all the pagesizes of a VM
912 * Returns a summary bitmap of the page sizes of all RAMBlocks
914 * For VMs with just normal pages this is equivalent to the host page
915 * size. If it's got some huge pages then it's the OR of all the
916 * different page sizes.
918 uint64_t ram_pagesize_summary(void)
921 uint64_t summary
= 0;
923 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
924 summary
|= block
->page_size
;
930 uint64_t ram_get_total_transferred_pages(void)
932 return stat64_get(&mig_stats
.normal_pages
) +
933 stat64_get(&mig_stats
.zero_pages
) +
934 compression_counters
.pages
+ xbzrle_counters
.pages
;
937 static void migration_update_rates(RAMState
*rs
, int64_t end_time
)
939 uint64_t page_count
= rs
->target_page_count
- rs
->target_page_count_prev
;
940 double compressed_size
;
942 /* calculate period counters */
943 stat64_set(&mig_stats
.dirty_pages_rate
,
944 rs
->num_dirty_pages_period
* 1000 /
945 (end_time
- rs
->time_last_bitmap_sync
));
951 if (migrate_xbzrle()) {
952 double encoded_size
, unencoded_size
;
954 xbzrle_counters
.cache_miss_rate
= (double)(xbzrle_counters
.cache_miss
-
955 rs
->xbzrle_cache_miss_prev
) / page_count
;
956 rs
->xbzrle_cache_miss_prev
= xbzrle_counters
.cache_miss
;
957 unencoded_size
= (xbzrle_counters
.pages
- rs
->xbzrle_pages_prev
) *
959 encoded_size
= xbzrle_counters
.bytes
- rs
->xbzrle_bytes_prev
;
960 if (xbzrle_counters
.pages
== rs
->xbzrle_pages_prev
|| !encoded_size
) {
961 xbzrle_counters
.encoding_rate
= 0;
963 xbzrle_counters
.encoding_rate
= unencoded_size
/ encoded_size
;
965 rs
->xbzrle_pages_prev
= xbzrle_counters
.pages
;
966 rs
->xbzrle_bytes_prev
= xbzrle_counters
.bytes
;
969 if (migrate_compress()) {
970 compression_counters
.busy_rate
= (double)(compression_counters
.busy
-
971 rs
->compress_thread_busy_prev
) / page_count
;
972 rs
->compress_thread_busy_prev
= compression_counters
.busy
;
974 compressed_size
= compression_counters
.compressed_size
-
975 rs
->compressed_size_prev
;
976 if (compressed_size
) {
977 double uncompressed_size
= (compression_counters
.pages
-
978 rs
->compress_pages_prev
) * TARGET_PAGE_SIZE
;
980 /* Compression-Ratio = Uncompressed-size / Compressed-size */
981 compression_counters
.compression_rate
=
982 uncompressed_size
/ compressed_size
;
984 rs
->compress_pages_prev
= compression_counters
.pages
;
985 rs
->compressed_size_prev
= compression_counters
.compressed_size
;
991 * Enable dirty-limit to throttle down the guest
993 static void migration_dirty_limit_guest(void)
996 * dirty page rate quota for all vCPUs fetched from
997 * migration parameter 'vcpu_dirty_limit'
999 static int64_t quota_dirtyrate
;
1000 MigrationState
*s
= migrate_get_current();
1003 * If dirty limit already enabled and migration parameter
1004 * vcpu-dirty-limit untouched.
1006 if (dirtylimit_in_service() &&
1007 quota_dirtyrate
== s
->parameters
.vcpu_dirty_limit
) {
1011 quota_dirtyrate
= s
->parameters
.vcpu_dirty_limit
;
1014 * Set all vCPU a quota dirtyrate, note that the second
1015 * parameter will be ignored if setting all vCPU for the vm
1017 qmp_set_vcpu_dirty_limit(false, -1, quota_dirtyrate
, NULL
);
1018 trace_migration_dirty_limit_guest(quota_dirtyrate
);
1021 static void migration_trigger_throttle(RAMState
*rs
)
1023 uint64_t threshold
= migrate_throttle_trigger_threshold();
1024 uint64_t bytes_xfer_period
=
1025 stat64_get(&mig_stats
.transferred
) - rs
->bytes_xfer_prev
;
1026 uint64_t bytes_dirty_period
= rs
->num_dirty_pages_period
* TARGET_PAGE_SIZE
;
1027 uint64_t bytes_dirty_threshold
= bytes_xfer_period
* threshold
/ 100;
1029 /* During block migration the auto-converge logic incorrectly detects
1030 * that ram migration makes no progress. Avoid this by disabling the
1031 * throttling logic during the bulk phase of block migration. */
1032 if (blk_mig_bulk_active()) {
1037 * The following detection logic can be refined later. For now:
1038 * Check to see if the ratio between dirtied bytes and the approx.
1039 * amount of bytes that just got transferred since the last time
1040 * we were in this routine reaches the threshold. If that happens
1041 * twice, start or increase throttling.
1043 if ((bytes_dirty_period
> bytes_dirty_threshold
) &&
1044 (++rs
->dirty_rate_high_cnt
>= 2)) {
1045 rs
->dirty_rate_high_cnt
= 0;
1046 if (migrate_auto_converge()) {
1047 trace_migration_throttle();
1048 mig_throttle_guest_down(bytes_dirty_period
,
1049 bytes_dirty_threshold
);
1050 } else if (migrate_dirty_limit()) {
1051 migration_dirty_limit_guest();
1056 static void migration_bitmap_sync(RAMState
*rs
, bool last_stage
)
1061 stat64_add(&mig_stats
.dirty_sync_count
, 1);
1063 if (!rs
->time_last_bitmap_sync
) {
1064 rs
->time_last_bitmap_sync
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1067 trace_migration_bitmap_sync_start();
1068 memory_global_dirty_log_sync(last_stage
);
1070 qemu_mutex_lock(&rs
->bitmap_mutex
);
1071 WITH_RCU_READ_LOCK_GUARD() {
1072 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1073 ramblock_sync_dirty_bitmap(rs
, block
);
1075 stat64_set(&mig_stats
.dirty_bytes_last_sync
, ram_bytes_remaining());
1077 qemu_mutex_unlock(&rs
->bitmap_mutex
);
1079 memory_global_after_dirty_log_sync();
1080 trace_migration_bitmap_sync_end(rs
->num_dirty_pages_period
);
1082 end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1084 /* more than 1 second = 1000 millisecons */
1085 if (end_time
> rs
->time_last_bitmap_sync
+ 1000) {
1086 migration_trigger_throttle(rs
);
1088 migration_update_rates(rs
, end_time
);
1090 rs
->target_page_count_prev
= rs
->target_page_count
;
1092 /* reset period counters */
1093 rs
->time_last_bitmap_sync
= end_time
;
1094 rs
->num_dirty_pages_period
= 0;
1095 rs
->bytes_xfer_prev
= stat64_get(&mig_stats
.transferred
);
1097 if (migrate_events()) {
1098 uint64_t generation
= stat64_get(&mig_stats
.dirty_sync_count
);
1099 qapi_event_send_migration_pass(generation
);
1103 static void migration_bitmap_sync_precopy(RAMState
*rs
, bool last_stage
)
1105 Error
*local_err
= NULL
;
1108 * The current notifier usage is just an optimization to migration, so we
1109 * don't stop the normal migration process in the error case.
1111 if (precopy_notify(PRECOPY_NOTIFY_BEFORE_BITMAP_SYNC
, &local_err
)) {
1112 error_report_err(local_err
);
1116 migration_bitmap_sync(rs
, last_stage
);
1118 if (precopy_notify(PRECOPY_NOTIFY_AFTER_BITMAP_SYNC
, &local_err
)) {
1119 error_report_err(local_err
);
1123 void ram_release_page(const char *rbname
, uint64_t offset
)
1125 if (!migrate_release_ram() || !migration_in_postcopy()) {
1129 ram_discard_range(rbname
, offset
, TARGET_PAGE_SIZE
);
1133 * save_zero_page_to_file: send the zero page to the file
1135 * Returns the size of data written to the file, 0 means the page is not
1138 * @pss: current PSS channel
1139 * @block: block that contains the page we want to send
1140 * @offset: offset inside the block for the page
1142 static int save_zero_page_to_file(PageSearchStatus
*pss
, QEMUFile
*file
,
1143 RAMBlock
*block
, ram_addr_t offset
)
1145 uint8_t *p
= block
->host
+ offset
;
1148 if (buffer_is_zero(p
, TARGET_PAGE_SIZE
)) {
1149 len
+= save_page_header(pss
, file
, block
, offset
| RAM_SAVE_FLAG_ZERO
);
1150 qemu_put_byte(file
, 0);
1152 ram_release_page(block
->idstr
, offset
);
1158 * save_zero_page: send the zero page to the stream
1160 * Returns the number of pages written.
1162 * @pss: current PSS channel
1163 * @block: block that contains the page we want to send
1164 * @offset: offset inside the block for the page
1166 static int save_zero_page(PageSearchStatus
*pss
, QEMUFile
*f
, RAMBlock
*block
,
1169 int len
= save_zero_page_to_file(pss
, f
, block
, offset
);
1172 stat64_add(&mig_stats
.zero_pages
, 1);
1173 ram_transferred_add(len
);
1180 * @pages: the number of pages written by the control path,
1182 * > 0 - number of pages written
1184 * Return true if the pages has been saved, otherwise false is returned.
1186 static bool control_save_page(PageSearchStatus
*pss
, RAMBlock
*block
,
1187 ram_addr_t offset
, int *pages
)
1191 ret
= ram_control_save_page(pss
->pss_channel
, block
->offset
, offset
,
1193 if (ret
== RAM_SAVE_CONTROL_NOT_SUPP
) {
1197 if (ret
== RAM_SAVE_CONTROL_DELAYED
) {
1206 * directly send the page to the stream
1208 * Returns the number of pages written.
1210 * @pss: current PSS channel
1211 * @block: block that contains the page we want to send
1212 * @offset: offset inside the block for the page
1213 * @buf: the page to be sent
1214 * @async: send to page asyncly
1216 static int save_normal_page(PageSearchStatus
*pss
, RAMBlock
*block
,
1217 ram_addr_t offset
, uint8_t *buf
, bool async
)
1219 QEMUFile
*file
= pss
->pss_channel
;
1221 ram_transferred_add(save_page_header(pss
, pss
->pss_channel
, block
,
1222 offset
| RAM_SAVE_FLAG_PAGE
));
1224 qemu_put_buffer_async(file
, buf
, TARGET_PAGE_SIZE
,
1225 migrate_release_ram() &&
1226 migration_in_postcopy());
1228 qemu_put_buffer(file
, buf
, TARGET_PAGE_SIZE
);
1230 ram_transferred_add(TARGET_PAGE_SIZE
);
1231 stat64_add(&mig_stats
.normal_pages
, 1);
1236 * ram_save_page: send the given page to the stream
1238 * Returns the number of pages written.
1240 * >=0 - Number of pages written - this might legally be 0
1241 * if xbzrle noticed the page was the same.
1243 * @rs: current RAM state
1244 * @block: block that contains the page we want to send
1245 * @offset: offset inside the block for the page
1247 static int ram_save_page(RAMState
*rs
, PageSearchStatus
*pss
)
1251 bool send_async
= true;
1252 RAMBlock
*block
= pss
->block
;
1253 ram_addr_t offset
= ((ram_addr_t
)pss
->page
) << TARGET_PAGE_BITS
;
1254 ram_addr_t current_addr
= block
->offset
+ offset
;
1256 p
= block
->host
+ offset
;
1257 trace_ram_save_page(block
->idstr
, (uint64_t)offset
, p
);
1259 XBZRLE_cache_lock();
1260 if (rs
->xbzrle_started
&& !migration_in_postcopy()) {
1261 pages
= save_xbzrle_page(rs
, pss
, &p
, current_addr
,
1263 if (!rs
->last_stage
) {
1264 /* Can't send this cached data async, since the cache page
1265 * might get updated before it gets to the wire
1271 /* XBZRLE overflow or normal page */
1273 pages
= save_normal_page(pss
, block
, offset
, p
, send_async
);
1276 XBZRLE_cache_unlock();
1281 static int ram_save_multifd_page(QEMUFile
*file
, RAMBlock
*block
,
1284 if (multifd_queue_page(file
, block
, offset
) < 0) {
1287 stat64_add(&mig_stats
.normal_pages
, 1);
1293 update_compress_thread_counts(const CompressParam
*param
, int bytes_xmit
)
1295 ram_transferred_add(bytes_xmit
);
1297 if (param
->result
== RES_ZEROPAGE
) {
1298 stat64_add(&mig_stats
.zero_pages
, 1);
1302 /* 8 means a header with RAM_SAVE_FLAG_CONTINUE. */
1303 compression_counters
.compressed_size
+= bytes_xmit
- 8;
1304 compression_counters
.pages
++;
1307 static bool save_page_use_compression(RAMState
*rs
);
1309 static int send_queued_data(CompressParam
*param
)
1311 PageSearchStatus
*pss
= &ram_state
->pss
[RAM_CHANNEL_PRECOPY
];
1312 MigrationState
*ms
= migrate_get_current();
1313 QEMUFile
*file
= ms
->to_dst_file
;
1316 RAMBlock
*block
= param
->block
;
1317 ram_addr_t offset
= param
->offset
;
1319 if (param
->result
== RES_NONE
) {
1323 assert(block
== pss
->last_sent_block
);
1325 if (param
->result
== RES_ZEROPAGE
) {
1326 assert(qemu_file_buffer_empty(param
->file
));
1327 len
+= save_page_header(pss
, file
, block
, offset
| RAM_SAVE_FLAG_ZERO
);
1328 qemu_put_byte(file
, 0);
1330 ram_release_page(block
->idstr
, offset
);
1331 } else if (param
->result
== RES_COMPRESS
) {
1332 assert(!qemu_file_buffer_empty(param
->file
));
1333 len
+= save_page_header(pss
, file
, block
,
1334 offset
| RAM_SAVE_FLAG_COMPRESS_PAGE
);
1335 len
+= qemu_put_qemu_file(file
, param
->file
);
1340 update_compress_thread_counts(param
, len
);
1345 static void ram_flush_compressed_data(RAMState
*rs
)
1347 if (!save_page_use_compression(rs
)) {
1351 flush_compressed_data(send_queued_data
);
1354 #define PAGE_ALL_CLEAN 0
1355 #define PAGE_TRY_AGAIN 1
1356 #define PAGE_DIRTY_FOUND 2
1358 * find_dirty_block: find the next dirty page and update any state
1359 * associated with the search process.
1362 * <0: An error happened
1363 * PAGE_ALL_CLEAN: no dirty page found, give up
1364 * PAGE_TRY_AGAIN: no dirty page found, retry for next block
1365 * PAGE_DIRTY_FOUND: dirty page found
1367 * @rs: current RAM state
1368 * @pss: data about the state of the current dirty page scan
1369 * @again: set to false if the search has scanned the whole of RAM
1371 static int find_dirty_block(RAMState
*rs
, PageSearchStatus
*pss
)
1373 /* Update pss->page for the next dirty bit in ramblock */
1374 pss_find_next_dirty(pss
);
1376 if (pss
->complete_round
&& pss
->block
== rs
->last_seen_block
&&
1377 pss
->page
>= rs
->last_page
) {
1379 * We've been once around the RAM and haven't found anything.
1382 return PAGE_ALL_CLEAN
;
1384 if (!offset_in_ramblock(pss
->block
,
1385 ((ram_addr_t
)pss
->page
) << TARGET_PAGE_BITS
)) {
1386 /* Didn't find anything in this RAM Block */
1388 pss
->block
= QLIST_NEXT_RCU(pss
->block
, next
);
1390 if (!migrate_multifd_flush_after_each_section()) {
1391 QEMUFile
*f
= rs
->pss
[RAM_CHANNEL_PRECOPY
].pss_channel
;
1392 int ret
= multifd_send_sync_main(f
);
1396 qemu_put_be64(f
, RAM_SAVE_FLAG_MULTIFD_FLUSH
);
1400 * If memory migration starts over, we will meet a dirtied page
1401 * which may still exists in compression threads's ring, so we
1402 * should flush the compressed data to make sure the new page
1403 * is not overwritten by the old one in the destination.
1405 * Also If xbzrle is on, stop using the data compression at this
1406 * point. In theory, xbzrle can do better than compression.
1408 ram_flush_compressed_data(rs
);
1410 /* Hit the end of the list */
1411 pss
->block
= QLIST_FIRST_RCU(&ram_list
.blocks
);
1412 /* Flag that we've looped */
1413 pss
->complete_round
= true;
1414 /* After the first round, enable XBZRLE. */
1415 if (migrate_xbzrle()) {
1416 rs
->xbzrle_started
= true;
1419 /* Didn't find anything this time, but try again on the new block */
1420 return PAGE_TRY_AGAIN
;
1422 /* We've found something */
1423 return PAGE_DIRTY_FOUND
;
1428 * unqueue_page: gets a page of the queue
1430 * Helper for 'get_queued_page' - gets a page off the queue
1432 * Returns the block of the page (or NULL if none available)
1434 * @rs: current RAM state
1435 * @offset: used to return the offset within the RAMBlock
1437 static RAMBlock
*unqueue_page(RAMState
*rs
, ram_addr_t
*offset
)
1439 struct RAMSrcPageRequest
*entry
;
1440 RAMBlock
*block
= NULL
;
1442 if (!postcopy_has_request(rs
)) {
1446 QEMU_LOCK_GUARD(&rs
->src_page_req_mutex
);
1449 * This should _never_ change even after we take the lock, because no one
1450 * should be taking anything off the request list other than us.
1452 assert(postcopy_has_request(rs
));
1454 entry
= QSIMPLEQ_FIRST(&rs
->src_page_requests
);
1456 *offset
= entry
->offset
;
1458 if (entry
->len
> TARGET_PAGE_SIZE
) {
1459 entry
->len
-= TARGET_PAGE_SIZE
;
1460 entry
->offset
+= TARGET_PAGE_SIZE
;
1462 memory_region_unref(block
->mr
);
1463 QSIMPLEQ_REMOVE_HEAD(&rs
->src_page_requests
, next_req
);
1465 migration_consume_urgent_request();
1471 #if defined(__linux__)
1473 * poll_fault_page: try to get next UFFD write fault page and, if pending fault
1474 * is found, return RAM block pointer and page offset
1476 * Returns pointer to the RAMBlock containing faulting page,
1477 * NULL if no write faults are pending
1479 * @rs: current RAM state
1480 * @offset: page offset from the beginning of the block
1482 static RAMBlock
*poll_fault_page(RAMState
*rs
, ram_addr_t
*offset
)
1484 struct uffd_msg uffd_msg
;
1489 if (!migrate_background_snapshot()) {
1493 res
= uffd_read_events(rs
->uffdio_fd
, &uffd_msg
, 1);
1498 page_address
= (void *)(uintptr_t) uffd_msg
.arg
.pagefault
.address
;
1499 block
= qemu_ram_block_from_host(page_address
, false, offset
);
1500 assert(block
&& (block
->flags
& RAM_UF_WRITEPROTECT
) != 0);
1505 * ram_save_release_protection: release UFFD write protection after
1506 * a range of pages has been saved
1508 * @rs: current RAM state
1509 * @pss: page-search-status structure
1510 * @start_page: index of the first page in the range relative to pss->block
1512 * Returns 0 on success, negative value in case of an error
1514 static int ram_save_release_protection(RAMState
*rs
, PageSearchStatus
*pss
,
1515 unsigned long start_page
)
1519 /* Check if page is from UFFD-managed region. */
1520 if (pss
->block
->flags
& RAM_UF_WRITEPROTECT
) {
1521 void *page_address
= pss
->block
->host
+ (start_page
<< TARGET_PAGE_BITS
);
1522 uint64_t run_length
= (pss
->page
- start_page
) << TARGET_PAGE_BITS
;
1524 /* Flush async buffers before un-protect. */
1525 qemu_fflush(pss
->pss_channel
);
1526 /* Un-protect memory range. */
1527 res
= uffd_change_protection(rs
->uffdio_fd
, page_address
, run_length
,
1534 /* ram_write_tracking_available: check if kernel supports required UFFD features
1536 * Returns true if supports, false otherwise
1538 bool ram_write_tracking_available(void)
1540 uint64_t uffd_features
;
1543 res
= uffd_query_features(&uffd_features
);
1545 (uffd_features
& UFFD_FEATURE_PAGEFAULT_FLAG_WP
) != 0);
1548 /* ram_write_tracking_compatible: check if guest configuration is
1549 * compatible with 'write-tracking'
1551 * Returns true if compatible, false otherwise
1553 bool ram_write_tracking_compatible(void)
1555 const uint64_t uffd_ioctls_mask
= BIT(_UFFDIO_WRITEPROTECT
);
1560 /* Open UFFD file descriptor */
1561 uffd_fd
= uffd_create_fd(UFFD_FEATURE_PAGEFAULT_FLAG_WP
, false);
1566 RCU_READ_LOCK_GUARD();
1568 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1569 uint64_t uffd_ioctls
;
1571 /* Nothing to do with read-only and MMIO-writable regions */
1572 if (block
->mr
->readonly
|| block
->mr
->rom_device
) {
1575 /* Try to register block memory via UFFD-IO to track writes */
1576 if (uffd_register_memory(uffd_fd
, block
->host
, block
->max_length
,
1577 UFFDIO_REGISTER_MODE_WP
, &uffd_ioctls
)) {
1580 if ((uffd_ioctls
& uffd_ioctls_mask
) != uffd_ioctls_mask
) {
1587 uffd_close_fd(uffd_fd
);
1591 static inline void populate_read_range(RAMBlock
*block
, ram_addr_t offset
,
1594 const ram_addr_t end
= offset
+ size
;
1597 * We read one byte of each page; this will preallocate page tables if
1598 * required and populate the shared zeropage on MAP_PRIVATE anonymous memory
1599 * where no page was populated yet. This might require adaption when
1600 * supporting other mappings, like shmem.
1602 for (; offset
< end
; offset
+= block
->page_size
) {
1603 char tmp
= *((char *)block
->host
+ offset
);
1605 /* Don't optimize the read out */
1606 asm volatile("" : "+r" (tmp
));
1610 static inline int populate_read_section(MemoryRegionSection
*section
,
1613 const hwaddr size
= int128_get64(section
->size
);
1614 hwaddr offset
= section
->offset_within_region
;
1615 RAMBlock
*block
= section
->mr
->ram_block
;
1617 populate_read_range(block
, offset
, size
);
1622 * ram_block_populate_read: preallocate page tables and populate pages in the
1623 * RAM block by reading a byte of each page.
1625 * Since it's solely used for userfault_fd WP feature, here we just
1626 * hardcode page size to qemu_real_host_page_size.
1628 * @block: RAM block to populate
1630 static void ram_block_populate_read(RAMBlock
*rb
)
1633 * Skip populating all pages that fall into a discarded range as managed by
1634 * a RamDiscardManager responsible for the mapped memory region of the
1635 * RAMBlock. Such discarded ("logically unplugged") parts of a RAMBlock
1636 * must not get populated automatically. We don't have to track
1637 * modifications via userfaultfd WP reliably, because these pages will
1638 * not be part of the migration stream either way -- see
1639 * ramblock_dirty_bitmap_exclude_discarded_pages().
1641 * Note: The result is only stable while migrating (precopy/postcopy).
1643 if (rb
->mr
&& memory_region_has_ram_discard_manager(rb
->mr
)) {
1644 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(rb
->mr
);
1645 MemoryRegionSection section
= {
1647 .offset_within_region
= 0,
1648 .size
= rb
->mr
->size
,
1651 ram_discard_manager_replay_populated(rdm
, §ion
,
1652 populate_read_section
, NULL
);
1654 populate_read_range(rb
, 0, rb
->used_length
);
1659 * ram_write_tracking_prepare: prepare for UFFD-WP memory tracking
1661 void ram_write_tracking_prepare(void)
1665 RCU_READ_LOCK_GUARD();
1667 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1668 /* Nothing to do with read-only and MMIO-writable regions */
1669 if (block
->mr
->readonly
|| block
->mr
->rom_device
) {
1674 * Populate pages of the RAM block before enabling userfault_fd
1677 * This stage is required since ioctl(UFFDIO_WRITEPROTECT) with
1678 * UFFDIO_WRITEPROTECT_MODE_WP mode setting would silently skip
1679 * pages with pte_none() entries in page table.
1681 ram_block_populate_read(block
);
1685 static inline int uffd_protect_section(MemoryRegionSection
*section
,
1688 const hwaddr size
= int128_get64(section
->size
);
1689 const hwaddr offset
= section
->offset_within_region
;
1690 RAMBlock
*rb
= section
->mr
->ram_block
;
1691 int uffd_fd
= (uintptr_t)opaque
;
1693 return uffd_change_protection(uffd_fd
, rb
->host
+ offset
, size
, true,
1697 static int ram_block_uffd_protect(RAMBlock
*rb
, int uffd_fd
)
1699 assert(rb
->flags
& RAM_UF_WRITEPROTECT
);
1701 /* See ram_block_populate_read() */
1702 if (rb
->mr
&& memory_region_has_ram_discard_manager(rb
->mr
)) {
1703 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(rb
->mr
);
1704 MemoryRegionSection section
= {
1706 .offset_within_region
= 0,
1707 .size
= rb
->mr
->size
,
1710 return ram_discard_manager_replay_populated(rdm
, §ion
,
1711 uffd_protect_section
,
1712 (void *)(uintptr_t)uffd_fd
);
1714 return uffd_change_protection(uffd_fd
, rb
->host
,
1715 rb
->used_length
, true, false);
1719 * ram_write_tracking_start: start UFFD-WP memory tracking
1721 * Returns 0 for success or negative value in case of error
1723 int ram_write_tracking_start(void)
1726 RAMState
*rs
= ram_state
;
1729 /* Open UFFD file descriptor */
1730 uffd_fd
= uffd_create_fd(UFFD_FEATURE_PAGEFAULT_FLAG_WP
, true);
1734 rs
->uffdio_fd
= uffd_fd
;
1736 RCU_READ_LOCK_GUARD();
1738 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1739 /* Nothing to do with read-only and MMIO-writable regions */
1740 if (block
->mr
->readonly
|| block
->mr
->rom_device
) {
1744 /* Register block memory with UFFD to track writes */
1745 if (uffd_register_memory(rs
->uffdio_fd
, block
->host
,
1746 block
->max_length
, UFFDIO_REGISTER_MODE_WP
, NULL
)) {
1749 block
->flags
|= RAM_UF_WRITEPROTECT
;
1750 memory_region_ref(block
->mr
);
1752 /* Apply UFFD write protection to the block memory range */
1753 if (ram_block_uffd_protect(block
, uffd_fd
)) {
1757 trace_ram_write_tracking_ramblock_start(block
->idstr
, block
->page_size
,
1758 block
->host
, block
->max_length
);
1764 error_report("ram_write_tracking_start() failed: restoring initial memory state");
1766 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1767 if ((block
->flags
& RAM_UF_WRITEPROTECT
) == 0) {
1770 uffd_unregister_memory(rs
->uffdio_fd
, block
->host
, block
->max_length
);
1771 /* Cleanup flags and remove reference */
1772 block
->flags
&= ~RAM_UF_WRITEPROTECT
;
1773 memory_region_unref(block
->mr
);
1776 uffd_close_fd(uffd_fd
);
1782 * ram_write_tracking_stop: stop UFFD-WP memory tracking and remove protection
1784 void ram_write_tracking_stop(void)
1786 RAMState
*rs
= ram_state
;
1789 RCU_READ_LOCK_GUARD();
1791 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1792 if ((block
->flags
& RAM_UF_WRITEPROTECT
) == 0) {
1795 uffd_unregister_memory(rs
->uffdio_fd
, block
->host
, block
->max_length
);
1797 trace_ram_write_tracking_ramblock_stop(block
->idstr
, block
->page_size
,
1798 block
->host
, block
->max_length
);
1800 /* Cleanup flags and remove reference */
1801 block
->flags
&= ~RAM_UF_WRITEPROTECT
;
1802 memory_region_unref(block
->mr
);
1805 /* Finally close UFFD file descriptor */
1806 uffd_close_fd(rs
->uffdio_fd
);
1811 /* No target OS support, stubs just fail or ignore */
1813 static RAMBlock
*poll_fault_page(RAMState
*rs
, ram_addr_t
*offset
)
1821 static int ram_save_release_protection(RAMState
*rs
, PageSearchStatus
*pss
,
1822 unsigned long start_page
)
1831 bool ram_write_tracking_available(void)
1836 bool ram_write_tracking_compatible(void)
1842 int ram_write_tracking_start(void)
1848 void ram_write_tracking_stop(void)
1852 #endif /* defined(__linux__) */
1855 * get_queued_page: unqueue a page from the postcopy requests
1857 * Skips pages that are already sent (!dirty)
1859 * Returns true if a queued page is found
1861 * @rs: current RAM state
1862 * @pss: data about the state of the current dirty page scan
1864 static bool get_queued_page(RAMState
*rs
, PageSearchStatus
*pss
)
1871 block
= unqueue_page(rs
, &offset
);
1873 * We're sending this page, and since it's postcopy nothing else
1874 * will dirty it, and we must make sure it doesn't get sent again
1875 * even if this queue request was received after the background
1876 * search already sent it.
1881 page
= offset
>> TARGET_PAGE_BITS
;
1882 dirty
= test_bit(page
, block
->bmap
);
1884 trace_get_queued_page_not_dirty(block
->idstr
, (uint64_t)offset
,
1887 trace_get_queued_page(block
->idstr
, (uint64_t)offset
, page
);
1891 } while (block
&& !dirty
);
1895 * Poll write faults too if background snapshot is enabled; that's
1896 * when we have vcpus got blocked by the write protected pages.
1898 block
= poll_fault_page(rs
, &offset
);
1903 * We want the background search to continue from the queued page
1904 * since the guest is likely to want other pages near to the page
1905 * it just requested.
1908 pss
->page
= offset
>> TARGET_PAGE_BITS
;
1911 * This unqueued page would break the "one round" check, even is
1914 pss
->complete_round
= false;
1921 * migration_page_queue_free: drop any remaining pages in the ram
1924 * It should be empty at the end anyway, but in error cases there may
1925 * be some left. in case that there is any page left, we drop it.
1928 static void migration_page_queue_free(RAMState
*rs
)
1930 struct RAMSrcPageRequest
*mspr
, *next_mspr
;
1931 /* This queue generally should be empty - but in the case of a failed
1932 * migration might have some droppings in.
1934 RCU_READ_LOCK_GUARD();
1935 QSIMPLEQ_FOREACH_SAFE(mspr
, &rs
->src_page_requests
, next_req
, next_mspr
) {
1936 memory_region_unref(mspr
->rb
->mr
);
1937 QSIMPLEQ_REMOVE_HEAD(&rs
->src_page_requests
, next_req
);
1943 * ram_save_queue_pages: queue the page for transmission
1945 * A request from postcopy destination for example.
1947 * Returns zero on success or negative on error
1949 * @rbname: Name of the RAMBLock of the request. NULL means the
1950 * same that last one.
1951 * @start: starting address from the start of the RAMBlock
1952 * @len: length (in bytes) to send
1954 int ram_save_queue_pages(const char *rbname
, ram_addr_t start
, ram_addr_t len
)
1957 RAMState
*rs
= ram_state
;
1959 stat64_add(&mig_stats
.postcopy_requests
, 1);
1960 RCU_READ_LOCK_GUARD();
1963 /* Reuse last RAMBlock */
1964 ramblock
= rs
->last_req_rb
;
1968 * Shouldn't happen, we can't reuse the last RAMBlock if
1969 * it's the 1st request.
1971 error_report("ram_save_queue_pages no previous block");
1975 ramblock
= qemu_ram_block_by_name(rbname
);
1978 /* We shouldn't be asked for a non-existent RAMBlock */
1979 error_report("ram_save_queue_pages no block '%s'", rbname
);
1982 rs
->last_req_rb
= ramblock
;
1984 trace_ram_save_queue_pages(ramblock
->idstr
, start
, len
);
1985 if (!offset_in_ramblock(ramblock
, start
+ len
- 1)) {
1986 error_report("%s request overrun start=" RAM_ADDR_FMT
" len="
1987 RAM_ADDR_FMT
" blocklen=" RAM_ADDR_FMT
,
1988 __func__
, start
, len
, ramblock
->used_length
);
1993 * When with postcopy preempt, we send back the page directly in the
1996 if (postcopy_preempt_active()) {
1997 ram_addr_t page_start
= start
>> TARGET_PAGE_BITS
;
1998 size_t page_size
= qemu_ram_pagesize(ramblock
);
1999 PageSearchStatus
*pss
= &ram_state
->pss
[RAM_CHANNEL_POSTCOPY
];
2002 qemu_mutex_lock(&rs
->bitmap_mutex
);
2004 pss_init(pss
, ramblock
, page_start
);
2006 * Always use the preempt channel, and make sure it's there. It's
2007 * safe to access without lock, because when rp-thread is running
2008 * we should be the only one who operates on the qemufile
2010 pss
->pss_channel
= migrate_get_current()->postcopy_qemufile_src
;
2011 assert(pss
->pss_channel
);
2014 * It must be either one or multiple of host page size. Just
2015 * assert; if something wrong we're mostly split brain anyway.
2017 assert(len
% page_size
== 0);
2019 if (ram_save_host_page_urgent(pss
)) {
2020 error_report("%s: ram_save_host_page_urgent() failed: "
2021 "ramblock=%s, start_addr=0x"RAM_ADDR_FMT
,
2022 __func__
, ramblock
->idstr
, start
);
2027 * NOTE: after ram_save_host_page_urgent() succeeded, pss->page
2028 * will automatically be moved and point to the next host page
2029 * we're going to send, so no need to update here.
2031 * Normally QEMU never sends >1 host page in requests, so
2032 * logically we don't even need that as the loop should only
2033 * run once, but just to be consistent.
2037 qemu_mutex_unlock(&rs
->bitmap_mutex
);
2042 struct RAMSrcPageRequest
*new_entry
=
2043 g_new0(struct RAMSrcPageRequest
, 1);
2044 new_entry
->rb
= ramblock
;
2045 new_entry
->offset
= start
;
2046 new_entry
->len
= len
;
2048 memory_region_ref(ramblock
->mr
);
2049 qemu_mutex_lock(&rs
->src_page_req_mutex
);
2050 QSIMPLEQ_INSERT_TAIL(&rs
->src_page_requests
, new_entry
, next_req
);
2051 migration_make_urgent_request();
2052 qemu_mutex_unlock(&rs
->src_page_req_mutex
);
2057 static bool save_page_use_compression(RAMState
*rs
)
2059 if (!migrate_compress()) {
2064 * If xbzrle is enabled (e.g., after first round of migration), stop
2065 * using the data compression. In theory, xbzrle can do better than
2068 if (rs
->xbzrle_started
) {
2076 * try to compress the page before posting it out, return true if the page
2077 * has been properly handled by compression, otherwise needs other
2078 * paths to handle it
2080 static bool save_compress_page(RAMState
*rs
, PageSearchStatus
*pss
,
2081 RAMBlock
*block
, ram_addr_t offset
)
2083 if (!save_page_use_compression(rs
)) {
2088 * When starting the process of a new block, the first page of
2089 * the block should be sent out before other pages in the same
2090 * block, and all the pages in last block should have been sent
2091 * out, keeping this order is important, because the 'cont' flag
2092 * is used to avoid resending the block name.
2094 * We post the fist page as normal page as compression will take
2095 * much CPU resource.
2097 if (block
!= pss
->last_sent_block
) {
2098 ram_flush_compressed_data(rs
);
2102 if (compress_page_with_multi_thread(block
, offset
, send_queued_data
) > 0) {
2106 compression_counters
.busy
++;
2111 * ram_save_target_page_legacy: save one target page
2113 * Returns the number of pages written
2115 * @rs: current RAM state
2116 * @pss: data about the page we want to send
2118 static int ram_save_target_page_legacy(RAMState
*rs
, PageSearchStatus
*pss
)
2120 RAMBlock
*block
= pss
->block
;
2121 ram_addr_t offset
= ((ram_addr_t
)pss
->page
) << TARGET_PAGE_BITS
;
2124 if (control_save_page(pss
, block
, offset
, &res
)) {
2128 if (save_compress_page(rs
, pss
, block
, offset
)) {
2132 res
= save_zero_page(pss
, pss
->pss_channel
, block
, offset
);
2134 /* Must let xbzrle know, otherwise a previous (now 0'd) cached
2135 * page would be stale
2137 if (rs
->xbzrle_started
) {
2138 XBZRLE_cache_lock();
2139 xbzrle_cache_zero_page(rs
, block
->offset
+ offset
);
2140 XBZRLE_cache_unlock();
2146 * Do not use multifd in postcopy as one whole host page should be
2147 * placed. Meanwhile postcopy requires atomic update of pages, so even
2148 * if host page size == guest page size the dest guest during run may
2149 * still see partially copied pages which is data corruption.
2151 if (migrate_multifd() && !migration_in_postcopy()) {
2152 return ram_save_multifd_page(pss
->pss_channel
, block
, offset
);
2155 return ram_save_page(rs
, pss
);
2158 /* Should be called before sending a host page */
2159 static void pss_host_page_prepare(PageSearchStatus
*pss
)
2161 /* How many guest pages are there in one host page? */
2162 size_t guest_pfns
= qemu_ram_pagesize(pss
->block
) >> TARGET_PAGE_BITS
;
2164 pss
->host_page_sending
= true;
2165 if (guest_pfns
<= 1) {
2167 * This covers both when guest psize == host psize, or when guest
2168 * has larger psize than the host (guest_pfns==0).
2170 * For the latter, we always send one whole guest page per
2171 * iteration of the host page (example: an Alpha VM on x86 host
2172 * will have guest psize 8K while host psize 4K).
2174 pss
->host_page_start
= pss
->page
;
2175 pss
->host_page_end
= pss
->page
+ 1;
2178 * The host page spans over multiple guest pages, we send them
2179 * within the same host page iteration.
2181 pss
->host_page_start
= ROUND_DOWN(pss
->page
, guest_pfns
);
2182 pss
->host_page_end
= ROUND_UP(pss
->page
+ 1, guest_pfns
);
2187 * Whether the page pointed by PSS is within the host page being sent.
2188 * Must be called after a previous pss_host_page_prepare().
2190 static bool pss_within_range(PageSearchStatus
*pss
)
2192 ram_addr_t ram_addr
;
2194 assert(pss
->host_page_sending
);
2196 /* Over host-page boundary? */
2197 if (pss
->page
>= pss
->host_page_end
) {
2201 ram_addr
= ((ram_addr_t
)pss
->page
) << TARGET_PAGE_BITS
;
2203 return offset_in_ramblock(pss
->block
, ram_addr
);
2206 static void pss_host_page_finish(PageSearchStatus
*pss
)
2208 pss
->host_page_sending
= false;
2209 /* This is not needed, but just to reset it */
2210 pss
->host_page_start
= pss
->host_page_end
= 0;
2214 * Send an urgent host page specified by `pss'. Need to be called with
2215 * bitmap_mutex held.
2217 * Returns 0 if save host page succeeded, false otherwise.
2219 static int ram_save_host_page_urgent(PageSearchStatus
*pss
)
2221 bool page_dirty
, sent
= false;
2222 RAMState
*rs
= ram_state
;
2225 trace_postcopy_preempt_send_host_page(pss
->block
->idstr
, pss
->page
);
2226 pss_host_page_prepare(pss
);
2229 * If precopy is sending the same page, let it be done in precopy, or
2230 * we could send the same page in two channels and none of them will
2231 * receive the whole page.
2233 if (pss_overlap(pss
, &ram_state
->pss
[RAM_CHANNEL_PRECOPY
])) {
2234 trace_postcopy_preempt_hit(pss
->block
->idstr
,
2235 pss
->page
<< TARGET_PAGE_BITS
);
2240 page_dirty
= migration_bitmap_clear_dirty(rs
, pss
->block
, pss
->page
);
2243 /* Be strict to return code; it must be 1, or what else? */
2244 if (migration_ops
->ram_save_target_page(rs
, pss
) != 1) {
2245 error_report_once("%s: ram_save_target_page failed", __func__
);
2251 pss_find_next_dirty(pss
);
2252 } while (pss_within_range(pss
));
2254 pss_host_page_finish(pss
);
2255 /* For urgent requests, flush immediately if sent */
2257 qemu_fflush(pss
->pss_channel
);
2263 * ram_save_host_page: save a whole host page
2265 * Starting at *offset send pages up to the end of the current host
2266 * page. It's valid for the initial offset to point into the middle of
2267 * a host page in which case the remainder of the hostpage is sent.
2268 * Only dirty target pages are sent. Note that the host page size may
2269 * be a huge page for this block.
2271 * The saving stops at the boundary of the used_length of the block
2272 * if the RAMBlock isn't a multiple of the host page size.
2274 * The caller must be with ram_state.bitmap_mutex held to call this
2275 * function. Note that this function can temporarily release the lock, but
2276 * when the function is returned it'll make sure the lock is still held.
2278 * Returns the number of pages written or negative on error
2280 * @rs: current RAM state
2281 * @pss: data about the page we want to send
2283 static int ram_save_host_page(RAMState
*rs
, PageSearchStatus
*pss
)
2285 bool page_dirty
, preempt_active
= postcopy_preempt_active();
2286 int tmppages
, pages
= 0;
2287 size_t pagesize_bits
=
2288 qemu_ram_pagesize(pss
->block
) >> TARGET_PAGE_BITS
;
2289 unsigned long start_page
= pss
->page
;
2292 if (migrate_ram_is_ignored(pss
->block
)) {
2293 error_report("block %s should not be migrated !", pss
->block
->idstr
);
2297 /* Update host page boundary information */
2298 pss_host_page_prepare(pss
);
2301 page_dirty
= migration_bitmap_clear_dirty(rs
, pss
->block
, pss
->page
);
2303 /* Check the pages is dirty and if it is send it */
2306 * Properly yield the lock only in postcopy preempt mode
2307 * because both migration thread and rp-return thread can
2308 * operate on the bitmaps.
2310 if (preempt_active
) {
2311 qemu_mutex_unlock(&rs
->bitmap_mutex
);
2313 tmppages
= migration_ops
->ram_save_target_page(rs
, pss
);
2314 if (tmppages
>= 0) {
2317 * Allow rate limiting to happen in the middle of huge pages if
2318 * something is sent in the current iteration.
2320 if (pagesize_bits
> 1 && tmppages
> 0) {
2321 migration_rate_limit();
2324 if (preempt_active
) {
2325 qemu_mutex_lock(&rs
->bitmap_mutex
);
2332 pss_host_page_finish(pss
);
2336 pss_find_next_dirty(pss
);
2337 } while (pss_within_range(pss
));
2339 pss_host_page_finish(pss
);
2341 res
= ram_save_release_protection(rs
, pss
, start_page
);
2342 return (res
< 0 ? res
: pages
);
2346 * ram_find_and_save_block: finds a dirty page and sends it to f
2348 * Called within an RCU critical section.
2350 * Returns the number of pages written where zero means no dirty pages,
2351 * or negative on error
2353 * @rs: current RAM state
2355 * On systems where host-page-size > target-page-size it will send all the
2356 * pages in a host page that are dirty.
2358 static int ram_find_and_save_block(RAMState
*rs
)
2360 PageSearchStatus
*pss
= &rs
->pss
[RAM_CHANNEL_PRECOPY
];
2363 /* No dirty page as there is zero RAM */
2364 if (!rs
->ram_bytes_total
) {
2369 * Always keep last_seen_block/last_page valid during this procedure,
2370 * because find_dirty_block() relies on these values (e.g., we compare
2371 * last_seen_block with pss.block to see whether we searched all the
2372 * ramblocks) to detect the completion of migration. Having NULL value
2373 * of last_seen_block can conditionally cause below loop to run forever.
2375 if (!rs
->last_seen_block
) {
2376 rs
->last_seen_block
= QLIST_FIRST_RCU(&ram_list
.blocks
);
2380 pss_init(pss
, rs
->last_seen_block
, rs
->last_page
);
2383 if (!get_queued_page(rs
, pss
)) {
2384 /* priority queue empty, so just search for something dirty */
2385 int res
= find_dirty_block(rs
, pss
);
2386 if (res
!= PAGE_DIRTY_FOUND
) {
2387 if (res
== PAGE_ALL_CLEAN
) {
2389 } else if (res
== PAGE_TRY_AGAIN
) {
2391 } else if (res
< 0) {
2397 pages
= ram_save_host_page(rs
, pss
);
2403 rs
->last_seen_block
= pss
->block
;
2404 rs
->last_page
= pss
->page
;
2409 static uint64_t ram_bytes_total_with_ignored(void)
2414 RCU_READ_LOCK_GUARD();
2416 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
2417 total
+= block
->used_length
;
2422 uint64_t ram_bytes_total(void)
2427 RCU_READ_LOCK_GUARD();
2429 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2430 total
+= block
->used_length
;
2435 static void xbzrle_load_setup(void)
2437 XBZRLE
.decoded_buf
= g_malloc(TARGET_PAGE_SIZE
);
2440 static void xbzrle_load_cleanup(void)
2442 g_free(XBZRLE
.decoded_buf
);
2443 XBZRLE
.decoded_buf
= NULL
;
2446 static void ram_state_cleanup(RAMState
**rsp
)
2449 migration_page_queue_free(*rsp
);
2450 qemu_mutex_destroy(&(*rsp
)->bitmap_mutex
);
2451 qemu_mutex_destroy(&(*rsp
)->src_page_req_mutex
);
2457 static void xbzrle_cleanup(void)
2459 XBZRLE_cache_lock();
2461 cache_fini(XBZRLE
.cache
);
2462 g_free(XBZRLE
.encoded_buf
);
2463 g_free(XBZRLE
.current_buf
);
2464 g_free(XBZRLE
.zero_target_page
);
2465 XBZRLE
.cache
= NULL
;
2466 XBZRLE
.encoded_buf
= NULL
;
2467 XBZRLE
.current_buf
= NULL
;
2468 XBZRLE
.zero_target_page
= NULL
;
2470 XBZRLE_cache_unlock();
2473 static void ram_save_cleanup(void *opaque
)
2475 RAMState
**rsp
= opaque
;
2478 /* We don't use dirty log with background snapshots */
2479 if (!migrate_background_snapshot()) {
2480 /* caller have hold iothread lock or is in a bh, so there is
2481 * no writing race against the migration bitmap
2483 if (global_dirty_tracking
& GLOBAL_DIRTY_MIGRATION
) {
2485 * do not stop dirty log without starting it, since
2486 * memory_global_dirty_log_stop will assert that
2487 * memory_global_dirty_log_start/stop used in pairs
2489 memory_global_dirty_log_stop(GLOBAL_DIRTY_MIGRATION
);
2493 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2494 g_free(block
->clear_bmap
);
2495 block
->clear_bmap
= NULL
;
2496 g_free(block
->bmap
);
2501 compress_threads_save_cleanup();
2502 ram_state_cleanup(rsp
);
2503 g_free(migration_ops
);
2504 migration_ops
= NULL
;
2507 static void ram_state_reset(RAMState
*rs
)
2511 for (i
= 0; i
< RAM_CHANNEL_MAX
; i
++) {
2512 rs
->pss
[i
].last_sent_block
= NULL
;
2515 rs
->last_seen_block
= NULL
;
2517 rs
->last_version
= ram_list
.version
;
2518 rs
->xbzrle_started
= false;
2521 #define MAX_WAIT 50 /* ms, half buffered_file limit */
2523 /* **** functions for postcopy ***** */
2525 void ram_postcopy_migrated_memory_release(MigrationState
*ms
)
2527 struct RAMBlock
*block
;
2529 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2530 unsigned long *bitmap
= block
->bmap
;
2531 unsigned long range
= block
->used_length
>> TARGET_PAGE_BITS
;
2532 unsigned long run_start
= find_next_zero_bit(bitmap
, range
, 0);
2534 while (run_start
< range
) {
2535 unsigned long run_end
= find_next_bit(bitmap
, range
, run_start
+ 1);
2536 ram_discard_range(block
->idstr
,
2537 ((ram_addr_t
)run_start
) << TARGET_PAGE_BITS
,
2538 ((ram_addr_t
)(run_end
- run_start
))
2539 << TARGET_PAGE_BITS
);
2540 run_start
= find_next_zero_bit(bitmap
, range
, run_end
+ 1);
2546 * postcopy_send_discard_bm_ram: discard a RAMBlock
2548 * Callback from postcopy_each_ram_send_discard for each RAMBlock
2550 * @ms: current migration state
2551 * @block: RAMBlock to discard
2553 static void postcopy_send_discard_bm_ram(MigrationState
*ms
, RAMBlock
*block
)
2555 unsigned long end
= block
->used_length
>> TARGET_PAGE_BITS
;
2556 unsigned long current
;
2557 unsigned long *bitmap
= block
->bmap
;
2559 for (current
= 0; current
< end
; ) {
2560 unsigned long one
= find_next_bit(bitmap
, end
, current
);
2561 unsigned long zero
, discard_length
;
2567 zero
= find_next_zero_bit(bitmap
, end
, one
+ 1);
2570 discard_length
= end
- one
;
2572 discard_length
= zero
- one
;
2574 postcopy_discard_send_range(ms
, one
, discard_length
);
2575 current
= one
+ discard_length
;
2579 static void postcopy_chunk_hostpages_pass(MigrationState
*ms
, RAMBlock
*block
);
2582 * postcopy_each_ram_send_discard: discard all RAMBlocks
2584 * Utility for the outgoing postcopy code.
2585 * Calls postcopy_send_discard_bm_ram for each RAMBlock
2586 * passing it bitmap indexes and name.
2587 * (qemu_ram_foreach_block ends up passing unscaled lengths
2588 * which would mean postcopy code would have to deal with target page)
2590 * @ms: current migration state
2592 static void postcopy_each_ram_send_discard(MigrationState
*ms
)
2594 struct RAMBlock
*block
;
2596 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2597 postcopy_discard_send_init(ms
, block
->idstr
);
2600 * Deal with TPS != HPS and huge pages. It discard any partially sent
2601 * host-page size chunks, mark any partially dirty host-page size
2602 * chunks as all dirty. In this case the host-page is the host-page
2603 * for the particular RAMBlock, i.e. it might be a huge page.
2605 postcopy_chunk_hostpages_pass(ms
, block
);
2608 * Postcopy sends chunks of bitmap over the wire, but it
2609 * just needs indexes at this point, avoids it having
2610 * target page specific code.
2612 postcopy_send_discard_bm_ram(ms
, block
);
2613 postcopy_discard_send_finish(ms
);
2618 * postcopy_chunk_hostpages_pass: canonicalize bitmap in hostpages
2620 * Helper for postcopy_chunk_hostpages; it's called twice to
2621 * canonicalize the two bitmaps, that are similar, but one is
2624 * Postcopy requires that all target pages in a hostpage are dirty or
2625 * clean, not a mix. This function canonicalizes the bitmaps.
2627 * @ms: current migration state
2628 * @block: block that contains the page we want to canonicalize
2630 static void postcopy_chunk_hostpages_pass(MigrationState
*ms
, RAMBlock
*block
)
2632 RAMState
*rs
= ram_state
;
2633 unsigned long *bitmap
= block
->bmap
;
2634 unsigned int host_ratio
= block
->page_size
/ TARGET_PAGE_SIZE
;
2635 unsigned long pages
= block
->used_length
>> TARGET_PAGE_BITS
;
2636 unsigned long run_start
;
2638 if (block
->page_size
== TARGET_PAGE_SIZE
) {
2639 /* Easy case - TPS==HPS for a non-huge page RAMBlock */
2643 /* Find a dirty page */
2644 run_start
= find_next_bit(bitmap
, pages
, 0);
2646 while (run_start
< pages
) {
2649 * If the start of this run of pages is in the middle of a host
2650 * page, then we need to fixup this host page.
2652 if (QEMU_IS_ALIGNED(run_start
, host_ratio
)) {
2653 /* Find the end of this run */
2654 run_start
= find_next_zero_bit(bitmap
, pages
, run_start
+ 1);
2656 * If the end isn't at the start of a host page, then the
2657 * run doesn't finish at the end of a host page
2658 * and we need to discard.
2662 if (!QEMU_IS_ALIGNED(run_start
, host_ratio
)) {
2664 unsigned long fixup_start_addr
= QEMU_ALIGN_DOWN(run_start
,
2666 run_start
= QEMU_ALIGN_UP(run_start
, host_ratio
);
2668 /* Clean up the bitmap */
2669 for (page
= fixup_start_addr
;
2670 page
< fixup_start_addr
+ host_ratio
; page
++) {
2672 * Remark them as dirty, updating the count for any pages
2673 * that weren't previously dirty.
2675 rs
->migration_dirty_pages
+= !test_and_set_bit(page
, bitmap
);
2679 /* Find the next dirty page for the next iteration */
2680 run_start
= find_next_bit(bitmap
, pages
, run_start
);
2685 * ram_postcopy_send_discard_bitmap: transmit the discard bitmap
2687 * Transmit the set of pages to be discarded after precopy to the target
2688 * these are pages that:
2689 * a) Have been previously transmitted but are now dirty again
2690 * b) Pages that have never been transmitted, this ensures that
2691 * any pages on the destination that have been mapped by background
2692 * tasks get discarded (transparent huge pages is the specific concern)
2693 * Hopefully this is pretty sparse
2695 * @ms: current migration state
2697 void ram_postcopy_send_discard_bitmap(MigrationState
*ms
)
2699 RAMState
*rs
= ram_state
;
2701 RCU_READ_LOCK_GUARD();
2703 /* This should be our last sync, the src is now paused */
2704 migration_bitmap_sync(rs
, false);
2706 /* Easiest way to make sure we don't resume in the middle of a host-page */
2707 rs
->pss
[RAM_CHANNEL_PRECOPY
].last_sent_block
= NULL
;
2708 rs
->last_seen_block
= NULL
;
2711 postcopy_each_ram_send_discard(ms
);
2713 trace_ram_postcopy_send_discard_bitmap();
2717 * ram_discard_range: discard dirtied pages at the beginning of postcopy
2719 * Returns zero on success
2721 * @rbname: name of the RAMBlock of the request. NULL means the
2722 * same that last one.
2723 * @start: RAMBlock starting page
2724 * @length: RAMBlock size
2726 int ram_discard_range(const char *rbname
, uint64_t start
, size_t length
)
2728 trace_ram_discard_range(rbname
, start
, length
);
2730 RCU_READ_LOCK_GUARD();
2731 RAMBlock
*rb
= qemu_ram_block_by_name(rbname
);
2734 error_report("ram_discard_range: Failed to find block '%s'", rbname
);
2739 * On source VM, we don't need to update the received bitmap since
2740 * we don't even have one.
2742 if (rb
->receivedmap
) {
2743 bitmap_clear(rb
->receivedmap
, start
>> qemu_target_page_bits(),
2744 length
>> qemu_target_page_bits());
2747 return ram_block_discard_range(rb
, start
, length
);
2751 * For every allocation, we will try not to crash the VM if the
2752 * allocation failed.
2754 static int xbzrle_init(void)
2756 Error
*local_err
= NULL
;
2758 if (!migrate_xbzrle()) {
2762 XBZRLE_cache_lock();
2764 XBZRLE
.zero_target_page
= g_try_malloc0(TARGET_PAGE_SIZE
);
2765 if (!XBZRLE
.zero_target_page
) {
2766 error_report("%s: Error allocating zero page", __func__
);
2770 XBZRLE
.cache
= cache_init(migrate_xbzrle_cache_size(),
2771 TARGET_PAGE_SIZE
, &local_err
);
2772 if (!XBZRLE
.cache
) {
2773 error_report_err(local_err
);
2774 goto free_zero_page
;
2777 XBZRLE
.encoded_buf
= g_try_malloc0(TARGET_PAGE_SIZE
);
2778 if (!XBZRLE
.encoded_buf
) {
2779 error_report("%s: Error allocating encoded_buf", __func__
);
2783 XBZRLE
.current_buf
= g_try_malloc(TARGET_PAGE_SIZE
);
2784 if (!XBZRLE
.current_buf
) {
2785 error_report("%s: Error allocating current_buf", __func__
);
2786 goto free_encoded_buf
;
2789 /* We are all good */
2790 XBZRLE_cache_unlock();
2794 g_free(XBZRLE
.encoded_buf
);
2795 XBZRLE
.encoded_buf
= NULL
;
2797 cache_fini(XBZRLE
.cache
);
2798 XBZRLE
.cache
= NULL
;
2800 g_free(XBZRLE
.zero_target_page
);
2801 XBZRLE
.zero_target_page
= NULL
;
2803 XBZRLE_cache_unlock();
2807 static int ram_state_init(RAMState
**rsp
)
2809 *rsp
= g_try_new0(RAMState
, 1);
2812 error_report("%s: Init ramstate fail", __func__
);
2816 qemu_mutex_init(&(*rsp
)->bitmap_mutex
);
2817 qemu_mutex_init(&(*rsp
)->src_page_req_mutex
);
2818 QSIMPLEQ_INIT(&(*rsp
)->src_page_requests
);
2819 (*rsp
)->ram_bytes_total
= ram_bytes_total();
2822 * Count the total number of pages used by ram blocks not including any
2823 * gaps due to alignment or unplugs.
2824 * This must match with the initial values of dirty bitmap.
2826 (*rsp
)->migration_dirty_pages
= (*rsp
)->ram_bytes_total
>> TARGET_PAGE_BITS
;
2827 ram_state_reset(*rsp
);
2832 static void ram_list_init_bitmaps(void)
2834 MigrationState
*ms
= migrate_get_current();
2836 unsigned long pages
;
2839 /* Skip setting bitmap if there is no RAM */
2840 if (ram_bytes_total()) {
2841 shift
= ms
->clear_bitmap_shift
;
2842 if (shift
> CLEAR_BITMAP_SHIFT_MAX
) {
2843 error_report("clear_bitmap_shift (%u) too big, using "
2844 "max value (%u)", shift
, CLEAR_BITMAP_SHIFT_MAX
);
2845 shift
= CLEAR_BITMAP_SHIFT_MAX
;
2846 } else if (shift
< CLEAR_BITMAP_SHIFT_MIN
) {
2847 error_report("clear_bitmap_shift (%u) too small, using "
2848 "min value (%u)", shift
, CLEAR_BITMAP_SHIFT_MIN
);
2849 shift
= CLEAR_BITMAP_SHIFT_MIN
;
2852 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2853 pages
= block
->max_length
>> TARGET_PAGE_BITS
;
2855 * The initial dirty bitmap for migration must be set with all
2856 * ones to make sure we'll migrate every guest RAM page to
2858 * Here we set RAMBlock.bmap all to 1 because when rebegin a
2859 * new migration after a failed migration, ram_list.
2860 * dirty_memory[DIRTY_MEMORY_MIGRATION] don't include the whole
2863 block
->bmap
= bitmap_new(pages
);
2864 bitmap_set(block
->bmap
, 0, pages
);
2865 block
->clear_bmap_shift
= shift
;
2866 block
->clear_bmap
= bitmap_new(clear_bmap_size(pages
, shift
));
2871 static void migration_bitmap_clear_discarded_pages(RAMState
*rs
)
2873 unsigned long pages
;
2876 RCU_READ_LOCK_GUARD();
2878 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
2879 pages
= ramblock_dirty_bitmap_clear_discarded_pages(rb
);
2880 rs
->migration_dirty_pages
-= pages
;
2884 static void ram_init_bitmaps(RAMState
*rs
)
2886 /* For memory_global_dirty_log_start below. */
2887 qemu_mutex_lock_iothread();
2888 qemu_mutex_lock_ramlist();
2890 WITH_RCU_READ_LOCK_GUARD() {
2891 ram_list_init_bitmaps();
2892 /* We don't use dirty log with background snapshots */
2893 if (!migrate_background_snapshot()) {
2894 memory_global_dirty_log_start(GLOBAL_DIRTY_MIGRATION
);
2895 migration_bitmap_sync_precopy(rs
, false);
2898 qemu_mutex_unlock_ramlist();
2899 qemu_mutex_unlock_iothread();
2902 * After an eventual first bitmap sync, fixup the initial bitmap
2903 * containing all 1s to exclude any discarded pages from migration.
2905 migration_bitmap_clear_discarded_pages(rs
);
2908 static int ram_init_all(RAMState
**rsp
)
2910 if (ram_state_init(rsp
)) {
2914 if (xbzrle_init()) {
2915 ram_state_cleanup(rsp
);
2919 ram_init_bitmaps(*rsp
);
2924 static void ram_state_resume_prepare(RAMState
*rs
, QEMUFile
*out
)
2930 * Postcopy is not using xbzrle/compression, so no need for that.
2931 * Also, since source are already halted, we don't need to care
2932 * about dirty page logging as well.
2935 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2936 pages
+= bitmap_count_one(block
->bmap
,
2937 block
->used_length
>> TARGET_PAGE_BITS
);
2940 /* This may not be aligned with current bitmaps. Recalculate. */
2941 rs
->migration_dirty_pages
= pages
;
2943 ram_state_reset(rs
);
2945 /* Update RAMState cache of output QEMUFile */
2946 rs
->pss
[RAM_CHANNEL_PRECOPY
].pss_channel
= out
;
2948 trace_ram_state_resume_prepare(pages
);
2952 * This function clears bits of the free pages reported by the caller from the
2953 * migration dirty bitmap. @addr is the host address corresponding to the
2954 * start of the continuous guest free pages, and @len is the total bytes of
2957 void qemu_guest_free_page_hint(void *addr
, size_t len
)
2961 size_t used_len
, start
, npages
;
2962 MigrationState
*s
= migrate_get_current();
2964 /* This function is currently expected to be used during live migration */
2965 if (!migration_is_setup_or_active(s
->state
)) {
2969 for (; len
> 0; len
-= used_len
, addr
+= used_len
) {
2970 block
= qemu_ram_block_from_host(addr
, false, &offset
);
2971 if (unlikely(!block
|| offset
>= block
->used_length
)) {
2973 * The implementation might not support RAMBlock resize during
2974 * live migration, but it could happen in theory with future
2975 * updates. So we add a check here to capture that case.
2977 error_report_once("%s unexpected error", __func__
);
2981 if (len
<= block
->used_length
- offset
) {
2984 used_len
= block
->used_length
- offset
;
2987 start
= offset
>> TARGET_PAGE_BITS
;
2988 npages
= used_len
>> TARGET_PAGE_BITS
;
2990 qemu_mutex_lock(&ram_state
->bitmap_mutex
);
2992 * The skipped free pages are equavalent to be sent from clear_bmap's
2993 * perspective, so clear the bits from the memory region bitmap which
2994 * are initially set. Otherwise those skipped pages will be sent in
2995 * the next round after syncing from the memory region bitmap.
2997 migration_clear_memory_region_dirty_bitmap_range(block
, start
, npages
);
2998 ram_state
->migration_dirty_pages
-=
2999 bitmap_count_one_with_offset(block
->bmap
, start
, npages
);
3000 bitmap_clear(block
->bmap
, start
, npages
);
3001 qemu_mutex_unlock(&ram_state
->bitmap_mutex
);
3006 * Each of ram_save_setup, ram_save_iterate and ram_save_complete has
3007 * long-running RCU critical section. When rcu-reclaims in the code
3008 * start to become numerous it will be necessary to reduce the
3009 * granularity of these critical sections.
3013 * ram_save_setup: Setup RAM for migration
3015 * Returns zero to indicate success and negative for error
3017 * @f: QEMUFile where to send the data
3018 * @opaque: RAMState pointer
3020 static int ram_save_setup(QEMUFile
*f
, void *opaque
)
3022 RAMState
**rsp
= opaque
;
3026 if (compress_threads_save_setup()) {
3030 /* migration has already setup the bitmap, reuse it. */
3031 if (!migration_in_colo_state()) {
3032 if (ram_init_all(rsp
) != 0) {
3033 compress_threads_save_cleanup();
3037 (*rsp
)->pss
[RAM_CHANNEL_PRECOPY
].pss_channel
= f
;
3039 WITH_RCU_READ_LOCK_GUARD() {
3040 qemu_put_be64(f
, ram_bytes_total_with_ignored()
3041 | RAM_SAVE_FLAG_MEM_SIZE
);
3043 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
3044 qemu_put_byte(f
, strlen(block
->idstr
));
3045 qemu_put_buffer(f
, (uint8_t *)block
->idstr
, strlen(block
->idstr
));
3046 qemu_put_be64(f
, block
->used_length
);
3047 if (migrate_postcopy_ram() && block
->page_size
!=
3048 qemu_host_page_size
) {
3049 qemu_put_be64(f
, block
->page_size
);
3051 if (migrate_ignore_shared()) {
3052 qemu_put_be64(f
, block
->mr
->addr
);
3057 ram_control_before_iterate(f
, RAM_CONTROL_SETUP
);
3058 ram_control_after_iterate(f
, RAM_CONTROL_SETUP
);
3060 migration_ops
= g_malloc0(sizeof(MigrationOps
));
3061 migration_ops
->ram_save_target_page
= ram_save_target_page_legacy
;
3062 ret
= multifd_send_sync_main(f
);
3067 if (!migrate_multifd_flush_after_each_section()) {
3068 qemu_put_be64(f
, RAM_SAVE_FLAG_MULTIFD_FLUSH
);
3071 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3078 * ram_save_iterate: iterative stage for migration
3080 * Returns zero to indicate success and negative for error
3082 * @f: QEMUFile where to send the data
3083 * @opaque: RAMState pointer
3085 static int ram_save_iterate(QEMUFile
*f
, void *opaque
)
3087 RAMState
**temp
= opaque
;
3088 RAMState
*rs
= *temp
;
3094 if (blk_mig_bulk_active()) {
3095 /* Avoid transferring ram during bulk phase of block migration as
3096 * the bulk phase will usually take a long time and transferring
3097 * ram updates during that time is pointless. */
3102 * We'll take this lock a little bit long, but it's okay for two reasons.
3103 * Firstly, the only possible other thread to take it is who calls
3104 * qemu_guest_free_page_hint(), which should be rare; secondly, see
3105 * MAX_WAIT (if curious, further see commit 4508bd9ed8053ce) below, which
3106 * guarantees that we'll at least released it in a regular basis.
3108 qemu_mutex_lock(&rs
->bitmap_mutex
);
3109 WITH_RCU_READ_LOCK_GUARD() {
3110 if (ram_list
.version
!= rs
->last_version
) {
3111 ram_state_reset(rs
);
3114 /* Read version before ram_list.blocks */
3117 ram_control_before_iterate(f
, RAM_CONTROL_ROUND
);
3119 t0
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
3121 while ((ret
= migration_rate_exceeded(f
)) == 0 ||
3122 postcopy_has_request(rs
)) {
3125 if (qemu_file_get_error(f
)) {
3129 pages
= ram_find_and_save_block(rs
);
3130 /* no more pages to sent */
3137 qemu_file_set_error(f
, pages
);
3141 rs
->target_page_count
+= pages
;
3144 * During postcopy, it is necessary to make sure one whole host
3145 * page is sent in one chunk.
3147 if (migrate_postcopy_ram()) {
3148 ram_flush_compressed_data(rs
);
3152 * we want to check in the 1st loop, just in case it was the 1st
3153 * time and we had to sync the dirty bitmap.
3154 * qemu_clock_get_ns() is a bit expensive, so we only check each
3157 if ((i
& 63) == 0) {
3158 uint64_t t1
= (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) - t0
) /
3160 if (t1
> MAX_WAIT
) {
3161 trace_ram_save_iterate_big_wait(t1
, i
);
3168 qemu_mutex_unlock(&rs
->bitmap_mutex
);
3171 * Must occur before EOS (or any QEMUFile operation)
3172 * because of RDMA protocol.
3174 ram_control_after_iterate(f
, RAM_CONTROL_ROUND
);
3178 && migration_is_setup_or_active(migrate_get_current()->state
)) {
3179 if (migrate_multifd_flush_after_each_section()) {
3180 ret
= multifd_send_sync_main(rs
->pss
[RAM_CHANNEL_PRECOPY
].pss_channel
);
3186 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3188 ram_transferred_add(8);
3190 ret
= qemu_file_get_error(f
);
3200 * ram_save_complete: function called to send the remaining amount of ram
3202 * Returns zero to indicate success or negative on error
3204 * Called with iothread lock
3206 * @f: QEMUFile where to send the data
3207 * @opaque: RAMState pointer
3209 static int ram_save_complete(QEMUFile
*f
, void *opaque
)
3211 RAMState
**temp
= opaque
;
3212 RAMState
*rs
= *temp
;
3215 rs
->last_stage
= !migration_in_colo_state();
3217 WITH_RCU_READ_LOCK_GUARD() {
3218 if (!migration_in_postcopy()) {
3219 migration_bitmap_sync_precopy(rs
, true);
3222 ram_control_before_iterate(f
, RAM_CONTROL_FINISH
);
3224 /* try transferring iterative blocks of memory */
3226 /* flush all remaining blocks regardless of rate limiting */
3227 qemu_mutex_lock(&rs
->bitmap_mutex
);
3231 pages
= ram_find_and_save_block(rs
);
3232 /* no more blocks to sent */
3241 qemu_mutex_unlock(&rs
->bitmap_mutex
);
3243 ram_flush_compressed_data(rs
);
3244 ram_control_after_iterate(f
, RAM_CONTROL_FINISH
);
3251 ret
= multifd_send_sync_main(rs
->pss
[RAM_CHANNEL_PRECOPY
].pss_channel
);
3256 if (!migrate_multifd_flush_after_each_section()) {
3257 qemu_put_be64(f
, RAM_SAVE_FLAG_MULTIFD_FLUSH
);
3259 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3265 static void ram_state_pending_estimate(void *opaque
, uint64_t *must_precopy
,
3266 uint64_t *can_postcopy
)
3268 RAMState
**temp
= opaque
;
3269 RAMState
*rs
= *temp
;
3271 uint64_t remaining_size
= rs
->migration_dirty_pages
* TARGET_PAGE_SIZE
;
3273 if (migrate_postcopy_ram()) {
3274 /* We can do postcopy, and all the data is postcopiable */
3275 *can_postcopy
+= remaining_size
;
3277 *must_precopy
+= remaining_size
;
3281 static void ram_state_pending_exact(void *opaque
, uint64_t *must_precopy
,
3282 uint64_t *can_postcopy
)
3284 MigrationState
*s
= migrate_get_current();
3285 RAMState
**temp
= opaque
;
3286 RAMState
*rs
= *temp
;
3288 uint64_t remaining_size
= rs
->migration_dirty_pages
* TARGET_PAGE_SIZE
;
3290 if (!migration_in_postcopy() && remaining_size
< s
->threshold_size
) {
3291 qemu_mutex_lock_iothread();
3292 WITH_RCU_READ_LOCK_GUARD() {
3293 migration_bitmap_sync_precopy(rs
, false);
3295 qemu_mutex_unlock_iothread();
3296 remaining_size
= rs
->migration_dirty_pages
* TARGET_PAGE_SIZE
;
3299 if (migrate_postcopy_ram()) {
3300 /* We can do postcopy, and all the data is postcopiable */
3301 *can_postcopy
+= remaining_size
;
3303 *must_precopy
+= remaining_size
;
3307 static int load_xbzrle(QEMUFile
*f
, ram_addr_t addr
, void *host
)
3309 unsigned int xh_len
;
3311 uint8_t *loaded_data
;
3313 /* extract RLE header */
3314 xh_flags
= qemu_get_byte(f
);
3315 xh_len
= qemu_get_be16(f
);
3317 if (xh_flags
!= ENCODING_FLAG_XBZRLE
) {
3318 error_report("Failed to load XBZRLE page - wrong compression!");
3322 if (xh_len
> TARGET_PAGE_SIZE
) {
3323 error_report("Failed to load XBZRLE page - len overflow!");
3326 loaded_data
= XBZRLE
.decoded_buf
;
3327 /* load data and decode */
3328 /* it can change loaded_data to point to an internal buffer */
3329 qemu_get_buffer_in_place(f
, &loaded_data
, xh_len
);
3332 if (xbzrle_decode_buffer(loaded_data
, xh_len
, host
,
3333 TARGET_PAGE_SIZE
) == -1) {
3334 error_report("Failed to load XBZRLE page - decode error!");
3342 * ram_block_from_stream: read a RAMBlock id from the migration stream
3344 * Must be called from within a rcu critical section.
3346 * Returns a pointer from within the RCU-protected ram_list.
3348 * @mis: the migration incoming state pointer
3349 * @f: QEMUFile where to read the data from
3350 * @flags: Page flags (mostly to see if it's a continuation of previous block)
3351 * @channel: the channel we're using
3353 static inline RAMBlock
*ram_block_from_stream(MigrationIncomingState
*mis
,
3354 QEMUFile
*f
, int flags
,
3357 RAMBlock
*block
= mis
->last_recv_block
[channel
];
3361 if (flags
& RAM_SAVE_FLAG_CONTINUE
) {
3363 error_report("Ack, bad migration stream!");
3369 len
= qemu_get_byte(f
);
3370 qemu_get_buffer(f
, (uint8_t *)id
, len
);
3373 block
= qemu_ram_block_by_name(id
);
3375 error_report("Can't find block %s", id
);
3379 if (migrate_ram_is_ignored(block
)) {
3380 error_report("block %s should not be migrated !", id
);
3384 mis
->last_recv_block
[channel
] = block
;
3389 static inline void *host_from_ram_block_offset(RAMBlock
*block
,
3392 if (!offset_in_ramblock(block
, offset
)) {
3396 return block
->host
+ offset
;
3399 static void *host_page_from_ram_block_offset(RAMBlock
*block
,
3402 /* Note: Explicitly no check against offset_in_ramblock(). */
3403 return (void *)QEMU_ALIGN_DOWN((uintptr_t)(block
->host
+ offset
),
3407 static ram_addr_t
host_page_offset_from_ram_block_offset(RAMBlock
*block
,
3410 return ((uintptr_t)block
->host
+ offset
) & (block
->page_size
- 1);
3413 void colo_record_bitmap(RAMBlock
*block
, ram_addr_t
*normal
, uint32_t pages
)
3415 qemu_mutex_lock(&ram_state
->bitmap_mutex
);
3416 for (int i
= 0; i
< pages
; i
++) {
3417 ram_addr_t offset
= normal
[i
];
3418 ram_state
->migration_dirty_pages
+= !test_and_set_bit(
3419 offset
>> TARGET_PAGE_BITS
,
3422 qemu_mutex_unlock(&ram_state
->bitmap_mutex
);
3425 static inline void *colo_cache_from_block_offset(RAMBlock
*block
,
3426 ram_addr_t offset
, bool record_bitmap
)
3428 if (!offset_in_ramblock(block
, offset
)) {
3431 if (!block
->colo_cache
) {
3432 error_report("%s: colo_cache is NULL in block :%s",
3433 __func__
, block
->idstr
);
3438 * During colo checkpoint, we need bitmap of these migrated pages.
3439 * It help us to decide which pages in ram cache should be flushed
3440 * into VM's RAM later.
3442 if (record_bitmap
) {
3443 colo_record_bitmap(block
, &offset
, 1);
3445 return block
->colo_cache
+ offset
;
3449 * ram_handle_compressed: handle the zero page case
3451 * If a page (or a whole RDMA chunk) has been
3452 * determined to be zero, then zap it.
3454 * @host: host address for the zero page
3455 * @ch: what the page is filled from. We only support zero
3456 * @size: size of the zero page
3458 void ram_handle_compressed(void *host
, uint8_t ch
, uint64_t size
)
3460 if (ch
!= 0 || !buffer_is_zero(host
, size
)) {
3461 memset(host
, ch
, size
);
3465 static void colo_init_ram_state(void)
3467 ram_state_init(&ram_state
);
3471 * colo cache: this is for secondary VM, we cache the whole
3472 * memory of the secondary VM, it is need to hold the global lock
3473 * to call this helper.
3475 int colo_init_ram_cache(void)
3479 WITH_RCU_READ_LOCK_GUARD() {
3480 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3481 block
->colo_cache
= qemu_anon_ram_alloc(block
->used_length
,
3482 NULL
, false, false);
3483 if (!block
->colo_cache
) {
3484 error_report("%s: Can't alloc memory for COLO cache of block %s,"
3485 "size 0x" RAM_ADDR_FMT
, __func__
, block
->idstr
,
3486 block
->used_length
);
3487 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3488 if (block
->colo_cache
) {
3489 qemu_anon_ram_free(block
->colo_cache
, block
->used_length
);
3490 block
->colo_cache
= NULL
;
3495 if (!machine_dump_guest_core(current_machine
)) {
3496 qemu_madvise(block
->colo_cache
, block
->used_length
,
3497 QEMU_MADV_DONTDUMP
);
3503 * Record the dirty pages that sent by PVM, we use this dirty bitmap together
3504 * with to decide which page in cache should be flushed into SVM's RAM. Here
3505 * we use the same name 'ram_bitmap' as for migration.
3507 if (ram_bytes_total()) {
3508 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3509 unsigned long pages
= block
->max_length
>> TARGET_PAGE_BITS
;
3510 block
->bmap
= bitmap_new(pages
);
3514 colo_init_ram_state();
3518 /* TODO: duplicated with ram_init_bitmaps */
3519 void colo_incoming_start_dirty_log(void)
3521 RAMBlock
*block
= NULL
;
3522 /* For memory_global_dirty_log_start below. */
3523 qemu_mutex_lock_iothread();
3524 qemu_mutex_lock_ramlist();
3526 memory_global_dirty_log_sync(false);
3527 WITH_RCU_READ_LOCK_GUARD() {
3528 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3529 ramblock_sync_dirty_bitmap(ram_state
, block
);
3530 /* Discard this dirty bitmap record */
3531 bitmap_zero(block
->bmap
, block
->max_length
>> TARGET_PAGE_BITS
);
3533 memory_global_dirty_log_start(GLOBAL_DIRTY_MIGRATION
);
3535 ram_state
->migration_dirty_pages
= 0;
3536 qemu_mutex_unlock_ramlist();
3537 qemu_mutex_unlock_iothread();
3540 /* It is need to hold the global lock to call this helper */
3541 void colo_release_ram_cache(void)
3545 memory_global_dirty_log_stop(GLOBAL_DIRTY_MIGRATION
);
3546 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3547 g_free(block
->bmap
);
3551 WITH_RCU_READ_LOCK_GUARD() {
3552 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3553 if (block
->colo_cache
) {
3554 qemu_anon_ram_free(block
->colo_cache
, block
->used_length
);
3555 block
->colo_cache
= NULL
;
3559 ram_state_cleanup(&ram_state
);
3563 * ram_load_setup: Setup RAM for migration incoming side
3565 * Returns zero to indicate success and negative for error
3567 * @f: QEMUFile where to receive the data
3568 * @opaque: RAMState pointer
3570 static int ram_load_setup(QEMUFile
*f
, void *opaque
)
3572 xbzrle_load_setup();
3573 ramblock_recv_map_init();
3578 static int ram_load_cleanup(void *opaque
)
3582 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
3583 qemu_ram_block_writeback(rb
);
3586 xbzrle_load_cleanup();
3588 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
3589 g_free(rb
->receivedmap
);
3590 rb
->receivedmap
= NULL
;
3597 * ram_postcopy_incoming_init: allocate postcopy data structures
3599 * Returns 0 for success and negative if there was one error
3601 * @mis: current migration incoming state
3603 * Allocate data structures etc needed by incoming migration with
3604 * postcopy-ram. postcopy-ram's similarly names
3605 * postcopy_ram_incoming_init does the work.
3607 int ram_postcopy_incoming_init(MigrationIncomingState
*mis
)
3609 return postcopy_ram_incoming_init(mis
);
3613 * ram_load_postcopy: load a page in postcopy case
3615 * Returns 0 for success or -errno in case of error
3617 * Called in postcopy mode by ram_load().
3618 * rcu_read_lock is taken prior to this being called.
3620 * @f: QEMUFile where to send the data
3621 * @channel: the channel to use for loading
3623 int ram_load_postcopy(QEMUFile
*f
, int channel
)
3625 int flags
= 0, ret
= 0;
3626 bool place_needed
= false;
3627 bool matches_target_page_size
= false;
3628 MigrationIncomingState
*mis
= migration_incoming_get_current();
3629 PostcopyTmpPage
*tmp_page
= &mis
->postcopy_tmp_pages
[channel
];
3631 while (!ret
&& !(flags
& RAM_SAVE_FLAG_EOS
)) {
3633 void *page_buffer
= NULL
;
3634 void *place_source
= NULL
;
3635 RAMBlock
*block
= NULL
;
3639 addr
= qemu_get_be64(f
);
3642 * If qemu file error, we should stop here, and then "addr"
3645 ret
= qemu_file_get_error(f
);
3650 flags
= addr
& ~TARGET_PAGE_MASK
;
3651 addr
&= TARGET_PAGE_MASK
;
3653 trace_ram_load_postcopy_loop(channel
, (uint64_t)addr
, flags
);
3654 if (flags
& (RAM_SAVE_FLAG_ZERO
| RAM_SAVE_FLAG_PAGE
|
3655 RAM_SAVE_FLAG_COMPRESS_PAGE
)) {
3656 block
= ram_block_from_stream(mis
, f
, flags
, channel
);
3663 * Relying on used_length is racy and can result in false positives.
3664 * We might place pages beyond used_length in case RAM was shrunk
3665 * while in postcopy, which is fine - trying to place via
3666 * UFFDIO_COPY/UFFDIO_ZEROPAGE will never segfault.
3668 if (!block
->host
|| addr
>= block
->postcopy_length
) {
3669 error_report("Illegal RAM offset " RAM_ADDR_FMT
, addr
);
3673 tmp_page
->target_pages
++;
3674 matches_target_page_size
= block
->page_size
== TARGET_PAGE_SIZE
;
3676 * Postcopy requires that we place whole host pages atomically;
3677 * these may be huge pages for RAMBlocks that are backed by
3679 * To make it atomic, the data is read into a temporary page
3680 * that's moved into place later.
3681 * The migration protocol uses, possibly smaller, target-pages
3682 * however the source ensures it always sends all the components
3683 * of a host page in one chunk.
3685 page_buffer
= tmp_page
->tmp_huge_page
+
3686 host_page_offset_from_ram_block_offset(block
, addr
);
3687 /* If all TP are zero then we can optimise the place */
3688 if (tmp_page
->target_pages
== 1) {
3689 tmp_page
->host_addr
=
3690 host_page_from_ram_block_offset(block
, addr
);
3691 } else if (tmp_page
->host_addr
!=
3692 host_page_from_ram_block_offset(block
, addr
)) {
3693 /* not the 1st TP within the HP */
3694 error_report("Non-same host page detected on channel %d: "
3695 "Target host page %p, received host page %p "
3696 "(rb %s offset 0x"RAM_ADDR_FMT
" target_pages %d)",
3697 channel
, tmp_page
->host_addr
,
3698 host_page_from_ram_block_offset(block
, addr
),
3699 block
->idstr
, addr
, tmp_page
->target_pages
);
3705 * If it's the last part of a host page then we place the host
3708 if (tmp_page
->target_pages
==
3709 (block
->page_size
/ TARGET_PAGE_SIZE
)) {
3710 place_needed
= true;
3712 place_source
= tmp_page
->tmp_huge_page
;
3715 switch (flags
& ~RAM_SAVE_FLAG_CONTINUE
) {
3716 case RAM_SAVE_FLAG_ZERO
:
3717 ch
= qemu_get_byte(f
);
3719 * Can skip to set page_buffer when
3720 * this is a zero page and (block->page_size == TARGET_PAGE_SIZE).
3722 if (ch
|| !matches_target_page_size
) {
3723 memset(page_buffer
, ch
, TARGET_PAGE_SIZE
);
3726 tmp_page
->all_zero
= false;
3730 case RAM_SAVE_FLAG_PAGE
:
3731 tmp_page
->all_zero
= false;
3732 if (!matches_target_page_size
) {
3733 /* For huge pages, we always use temporary buffer */
3734 qemu_get_buffer(f
, page_buffer
, TARGET_PAGE_SIZE
);
3737 * For small pages that matches target page size, we
3738 * avoid the qemu_file copy. Instead we directly use
3739 * the buffer of QEMUFile to place the page. Note: we
3740 * cannot do any QEMUFile operation before using that
3741 * buffer to make sure the buffer is valid when
3744 qemu_get_buffer_in_place(f
, (uint8_t **)&place_source
,
3748 case RAM_SAVE_FLAG_COMPRESS_PAGE
:
3749 tmp_page
->all_zero
= false;
3750 len
= qemu_get_be32(f
);
3751 if (len
< 0 || len
> compressBound(TARGET_PAGE_SIZE
)) {
3752 error_report("Invalid compressed data length: %d", len
);
3756 decompress_data_with_multi_threads(f
, page_buffer
, len
);
3758 case RAM_SAVE_FLAG_MULTIFD_FLUSH
:
3759 multifd_recv_sync_main();
3761 case RAM_SAVE_FLAG_EOS
:
3763 if (migrate_multifd_flush_after_each_section()) {
3764 multifd_recv_sync_main();
3768 error_report("Unknown combination of migration flags: 0x%x"
3769 " (postcopy mode)", flags
);
3774 /* Got the whole host page, wait for decompress before placing. */
3776 ret
|= wait_for_decompress_done();
3779 /* Detect for any possible file errors */
3780 if (!ret
&& qemu_file_get_error(f
)) {
3781 ret
= qemu_file_get_error(f
);
3784 if (!ret
&& place_needed
) {
3785 if (tmp_page
->all_zero
) {
3786 ret
= postcopy_place_page_zero(mis
, tmp_page
->host_addr
, block
);
3788 ret
= postcopy_place_page(mis
, tmp_page
->host_addr
,
3789 place_source
, block
);
3791 place_needed
= false;
3792 postcopy_temp_page_reset(tmp_page
);
3799 static bool postcopy_is_running(void)
3801 PostcopyState ps
= postcopy_state_get();
3802 return ps
>= POSTCOPY_INCOMING_LISTENING
&& ps
< POSTCOPY_INCOMING_END
;
3806 * Flush content of RAM cache into SVM's memory.
3807 * Only flush the pages that be dirtied by PVM or SVM or both.
3809 void colo_flush_ram_cache(void)
3811 RAMBlock
*block
= NULL
;
3814 unsigned long offset
= 0;
3816 memory_global_dirty_log_sync(false);
3817 qemu_mutex_lock(&ram_state
->bitmap_mutex
);
3818 WITH_RCU_READ_LOCK_GUARD() {
3819 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3820 ramblock_sync_dirty_bitmap(ram_state
, block
);
3824 trace_colo_flush_ram_cache_begin(ram_state
->migration_dirty_pages
);
3825 WITH_RCU_READ_LOCK_GUARD() {
3826 block
= QLIST_FIRST_RCU(&ram_list
.blocks
);
3829 unsigned long num
= 0;
3831 offset
= colo_bitmap_find_dirty(ram_state
, block
, offset
, &num
);
3832 if (!offset_in_ramblock(block
,
3833 ((ram_addr_t
)offset
) << TARGET_PAGE_BITS
)) {
3836 block
= QLIST_NEXT_RCU(block
, next
);
3838 unsigned long i
= 0;
3840 for (i
= 0; i
< num
; i
++) {
3841 migration_bitmap_clear_dirty(ram_state
, block
, offset
+ i
);
3843 dst_host
= block
->host
3844 + (((ram_addr_t
)offset
) << TARGET_PAGE_BITS
);
3845 src_host
= block
->colo_cache
3846 + (((ram_addr_t
)offset
) << TARGET_PAGE_BITS
);
3847 memcpy(dst_host
, src_host
, TARGET_PAGE_SIZE
* num
);
3852 qemu_mutex_unlock(&ram_state
->bitmap_mutex
);
3853 trace_colo_flush_ram_cache_end();
3857 * ram_load_precopy: load pages in precopy case
3859 * Returns 0 for success or -errno in case of error
3861 * Called in precopy mode by ram_load().
3862 * rcu_read_lock is taken prior to this being called.
3864 * @f: QEMUFile where to send the data
3866 static int ram_load_precopy(QEMUFile
*f
)
3868 MigrationIncomingState
*mis
= migration_incoming_get_current();
3869 int flags
= 0, ret
= 0, invalid_flags
= 0, len
= 0, i
= 0;
3870 /* ADVISE is earlier, it shows the source has the postcopy capability on */
3871 bool postcopy_advised
= migration_incoming_postcopy_advised();
3872 if (!migrate_compress()) {
3873 invalid_flags
|= RAM_SAVE_FLAG_COMPRESS_PAGE
;
3876 while (!ret
&& !(flags
& RAM_SAVE_FLAG_EOS
)) {
3877 ram_addr_t addr
, total_ram_bytes
;
3878 void *host
= NULL
, *host_bak
= NULL
;
3882 * Yield periodically to let main loop run, but an iteration of
3883 * the main loop is expensive, so do it each some iterations
3885 if ((i
& 32767) == 0 && qemu_in_coroutine()) {
3886 aio_co_schedule(qemu_get_current_aio_context(),
3887 qemu_coroutine_self());
3888 qemu_coroutine_yield();
3892 addr
= qemu_get_be64(f
);
3893 flags
= addr
& ~TARGET_PAGE_MASK
;
3894 addr
&= TARGET_PAGE_MASK
;
3896 if (flags
& invalid_flags
) {
3897 if (flags
& invalid_flags
& RAM_SAVE_FLAG_COMPRESS_PAGE
) {
3898 error_report("Received an unexpected compressed page");
3905 if (flags
& (RAM_SAVE_FLAG_ZERO
| RAM_SAVE_FLAG_PAGE
|
3906 RAM_SAVE_FLAG_COMPRESS_PAGE
| RAM_SAVE_FLAG_XBZRLE
)) {
3907 RAMBlock
*block
= ram_block_from_stream(mis
, f
, flags
,
3908 RAM_CHANNEL_PRECOPY
);
3910 host
= host_from_ram_block_offset(block
, addr
);
3912 * After going into COLO stage, we should not load the page
3913 * into SVM's memory directly, we put them into colo_cache firstly.
3914 * NOTE: We need to keep a copy of SVM's ram in colo_cache.
3915 * Previously, we copied all these memory in preparing stage of COLO
3916 * while we need to stop VM, which is a time-consuming process.
3917 * Here we optimize it by a trick, back-up every page while in
3918 * migration process while COLO is enabled, though it affects the
3919 * speed of the migration, but it obviously reduce the downtime of
3920 * back-up all SVM'S memory in COLO preparing stage.
3922 if (migration_incoming_colo_enabled()) {
3923 if (migration_incoming_in_colo_state()) {
3924 /* In COLO stage, put all pages into cache temporarily */
3925 host
= colo_cache_from_block_offset(block
, addr
, true);
3928 * In migration stage but before COLO stage,
3929 * Put all pages into both cache and SVM's memory.
3931 host_bak
= colo_cache_from_block_offset(block
, addr
, false);
3935 error_report("Illegal RAM offset " RAM_ADDR_FMT
, addr
);
3939 if (!migration_incoming_in_colo_state()) {
3940 ramblock_recv_bitmap_set(block
, host
);
3943 trace_ram_load_loop(block
->idstr
, (uint64_t)addr
, flags
, host
);
3946 switch (flags
& ~RAM_SAVE_FLAG_CONTINUE
) {
3947 case RAM_SAVE_FLAG_MEM_SIZE
:
3948 /* Synchronize RAM block list */
3949 total_ram_bytes
= addr
;
3950 while (!ret
&& total_ram_bytes
) {
3955 len
= qemu_get_byte(f
);
3956 qemu_get_buffer(f
, (uint8_t *)id
, len
);
3958 length
= qemu_get_be64(f
);
3960 block
= qemu_ram_block_by_name(id
);
3961 if (block
&& !qemu_ram_is_migratable(block
)) {
3962 error_report("block %s should not be migrated !", id
);
3965 if (length
!= block
->used_length
) {
3966 Error
*local_err
= NULL
;
3968 ret
= qemu_ram_resize(block
, length
,
3971 error_report_err(local_err
);
3974 /* For postcopy we need to check hugepage sizes match */
3975 if (postcopy_advised
&& migrate_postcopy_ram() &&
3976 block
->page_size
!= qemu_host_page_size
) {
3977 uint64_t remote_page_size
= qemu_get_be64(f
);
3978 if (remote_page_size
!= block
->page_size
) {
3979 error_report("Mismatched RAM page size %s "
3980 "(local) %zd != %" PRId64
,
3981 id
, block
->page_size
,
3986 if (migrate_ignore_shared()) {
3987 hwaddr addr2
= qemu_get_be64(f
);
3988 if (migrate_ram_is_ignored(block
) &&
3989 block
->mr
->addr
!= addr2
) {
3990 error_report("Mismatched GPAs for block %s "
3991 "%" PRId64
"!= %" PRId64
,
3992 id
, (uint64_t)addr2
,
3993 (uint64_t)block
->mr
->addr
);
3997 ram_control_load_hook(f
, RAM_CONTROL_BLOCK_REG
,
4000 error_report("Unknown ramblock \"%s\", cannot "
4001 "accept migration", id
);
4005 total_ram_bytes
-= length
;
4009 case RAM_SAVE_FLAG_ZERO
:
4010 ch
= qemu_get_byte(f
);
4011 ram_handle_compressed(host
, ch
, TARGET_PAGE_SIZE
);
4014 case RAM_SAVE_FLAG_PAGE
:
4015 qemu_get_buffer(f
, host
, TARGET_PAGE_SIZE
);
4018 case RAM_SAVE_FLAG_COMPRESS_PAGE
:
4019 len
= qemu_get_be32(f
);
4020 if (len
< 0 || len
> compressBound(TARGET_PAGE_SIZE
)) {
4021 error_report("Invalid compressed data length: %d", len
);
4025 decompress_data_with_multi_threads(f
, host
, len
);
4028 case RAM_SAVE_FLAG_XBZRLE
:
4029 if (load_xbzrle(f
, addr
, host
) < 0) {
4030 error_report("Failed to decompress XBZRLE page at "
4031 RAM_ADDR_FMT
, addr
);
4036 case RAM_SAVE_FLAG_MULTIFD_FLUSH
:
4037 multifd_recv_sync_main();
4039 case RAM_SAVE_FLAG_EOS
:
4041 if (migrate_multifd_flush_after_each_section()) {
4042 multifd_recv_sync_main();
4045 case RAM_SAVE_FLAG_HOOK
:
4046 ram_control_load_hook(f
, RAM_CONTROL_HOOK
, NULL
);
4049 error_report("Unknown combination of migration flags: 0x%x", flags
);
4053 ret
= qemu_file_get_error(f
);
4055 if (!ret
&& host_bak
) {
4056 memcpy(host_bak
, host
, TARGET_PAGE_SIZE
);
4060 ret
|= wait_for_decompress_done();
4064 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
4067 static uint64_t seq_iter
;
4069 * If system is running in postcopy mode, page inserts to host memory must
4072 bool postcopy_running
= postcopy_is_running();
4076 if (version_id
!= 4) {
4081 * This RCU critical section can be very long running.
4082 * When RCU reclaims in the code start to become numerous,
4083 * it will be necessary to reduce the granularity of this
4086 WITH_RCU_READ_LOCK_GUARD() {
4087 if (postcopy_running
) {
4089 * Note! Here RAM_CHANNEL_PRECOPY is the precopy channel of
4090 * postcopy migration, we have another RAM_CHANNEL_POSTCOPY to
4091 * service fast page faults.
4093 ret
= ram_load_postcopy(f
, RAM_CHANNEL_PRECOPY
);
4095 ret
= ram_load_precopy(f
);
4098 trace_ram_load_complete(ret
, seq_iter
);
4103 static bool ram_has_postcopy(void *opaque
)
4106 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
4107 if (ramblock_is_pmem(rb
)) {
4108 info_report("Block: %s, host: %p is a nvdimm memory, postcopy"
4109 "is not supported now!", rb
->idstr
, rb
->host
);
4114 return migrate_postcopy_ram();
4117 /* Sync all the dirty bitmap with destination VM. */
4118 static int ram_dirty_bitmap_sync_all(MigrationState
*s
, RAMState
*rs
)
4121 QEMUFile
*file
= s
->to_dst_file
;
4122 int ramblock_count
= 0;
4124 trace_ram_dirty_bitmap_sync_start();
4126 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
4127 qemu_savevm_send_recv_bitmap(file
, block
->idstr
);
4128 trace_ram_dirty_bitmap_request(block
->idstr
);
4132 trace_ram_dirty_bitmap_sync_wait();
4134 /* Wait until all the ramblocks' dirty bitmap synced */
4135 while (ramblock_count
--) {
4136 qemu_sem_wait(&s
->rp_state
.rp_sem
);
4139 trace_ram_dirty_bitmap_sync_complete();
4144 static void ram_dirty_bitmap_reload_notify(MigrationState
*s
)
4146 qemu_sem_post(&s
->rp_state
.rp_sem
);
4150 * Read the received bitmap, revert it as the initial dirty bitmap.
4151 * This is only used when the postcopy migration is paused but wants
4152 * to resume from a middle point.
4154 int ram_dirty_bitmap_reload(MigrationState
*s
, RAMBlock
*block
)
4157 /* from_dst_file is always valid because we're within rp_thread */
4158 QEMUFile
*file
= s
->rp_state
.from_dst_file
;
4159 unsigned long *le_bitmap
, nbits
= block
->used_length
>> TARGET_PAGE_BITS
;
4160 uint64_t local_size
= DIV_ROUND_UP(nbits
, 8);
4161 uint64_t size
, end_mark
;
4163 trace_ram_dirty_bitmap_reload_begin(block
->idstr
);
4165 if (s
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
4166 error_report("%s: incorrect state %s", __func__
,
4167 MigrationStatus_str(s
->state
));
4172 * Note: see comments in ramblock_recv_bitmap_send() on why we
4173 * need the endianness conversion, and the paddings.
4175 local_size
= ROUND_UP(local_size
, 8);
4178 le_bitmap
= bitmap_new(nbits
+ BITS_PER_LONG
);
4180 size
= qemu_get_be64(file
);
4182 /* The size of the bitmap should match with our ramblock */
4183 if (size
!= local_size
) {
4184 error_report("%s: ramblock '%s' bitmap size mismatch "
4185 "(0x%"PRIx64
" != 0x%"PRIx64
")", __func__
,
4186 block
->idstr
, size
, local_size
);
4191 size
= qemu_get_buffer(file
, (uint8_t *)le_bitmap
, local_size
);
4192 end_mark
= qemu_get_be64(file
);
4194 ret
= qemu_file_get_error(file
);
4195 if (ret
|| size
!= local_size
) {
4196 error_report("%s: read bitmap failed for ramblock '%s': %d"
4197 " (size 0x%"PRIx64
", got: 0x%"PRIx64
")",
4198 __func__
, block
->idstr
, ret
, local_size
, size
);
4203 if (end_mark
!= RAMBLOCK_RECV_BITMAP_ENDING
) {
4204 error_report("%s: ramblock '%s' end mark incorrect: 0x%"PRIx64
,
4205 __func__
, block
->idstr
, end_mark
);
4211 * Endianness conversion. We are during postcopy (though paused).
4212 * The dirty bitmap won't change. We can directly modify it.
4214 bitmap_from_le(block
->bmap
, le_bitmap
, nbits
);
4217 * What we received is "received bitmap". Revert it as the initial
4218 * dirty bitmap for this ramblock.
4220 bitmap_complement(block
->bmap
, block
->bmap
, nbits
);
4222 /* Clear dirty bits of discarded ranges that we don't want to migrate. */
4223 ramblock_dirty_bitmap_clear_discarded_pages(block
);
4225 /* We'll recalculate migration_dirty_pages in ram_state_resume_prepare(). */
4226 trace_ram_dirty_bitmap_reload_complete(block
->idstr
);
4229 * We succeeded to sync bitmap for current ramblock. If this is
4230 * the last one to sync, we need to notify the main send thread.
4232 ram_dirty_bitmap_reload_notify(s
);
4240 static int ram_resume_prepare(MigrationState
*s
, void *opaque
)
4242 RAMState
*rs
= *(RAMState
**)opaque
;
4245 ret
= ram_dirty_bitmap_sync_all(s
, rs
);
4250 ram_state_resume_prepare(rs
, s
->to_dst_file
);
4255 void postcopy_preempt_shutdown_file(MigrationState
*s
)
4257 qemu_put_be64(s
->postcopy_qemufile_src
, RAM_SAVE_FLAG_EOS
);
4258 qemu_fflush(s
->postcopy_qemufile_src
);
4261 static SaveVMHandlers savevm_ram_handlers
= {
4262 .save_setup
= ram_save_setup
,
4263 .save_live_iterate
= ram_save_iterate
,
4264 .save_live_complete_postcopy
= ram_save_complete
,
4265 .save_live_complete_precopy
= ram_save_complete
,
4266 .has_postcopy
= ram_has_postcopy
,
4267 .state_pending_exact
= ram_state_pending_exact
,
4268 .state_pending_estimate
= ram_state_pending_estimate
,
4269 .load_state
= ram_load
,
4270 .save_cleanup
= ram_save_cleanup
,
4271 .load_setup
= ram_load_setup
,
4272 .load_cleanup
= ram_load_cleanup
,
4273 .resume_prepare
= ram_resume_prepare
,
4276 static void ram_mig_ram_block_resized(RAMBlockNotifier
*n
, void *host
,
4277 size_t old_size
, size_t new_size
)
4279 PostcopyState ps
= postcopy_state_get();
4281 RAMBlock
*rb
= qemu_ram_block_from_host(host
, false, &offset
);
4284 if (migrate_ram_is_ignored(rb
)) {
4288 if (!migration_is_idle()) {
4290 * Precopy code on the source cannot deal with the size of RAM blocks
4291 * changing at random points in time - especially after sending the
4292 * RAM block sizes in the migration stream, they must no longer change.
4293 * Abort and indicate a proper reason.
4295 error_setg(&err
, "RAM block '%s' resized during precopy.", rb
->idstr
);
4296 migration_cancel(err
);
4301 case POSTCOPY_INCOMING_ADVISE
:
4303 * Update what ram_postcopy_incoming_init()->init_range() does at the
4304 * time postcopy was advised. Syncing RAM blocks with the source will
4305 * result in RAM resizes.
4307 if (old_size
< new_size
) {
4308 if (ram_discard_range(rb
->idstr
, old_size
, new_size
- old_size
)) {
4309 error_report("RAM block '%s' discard of resized RAM failed",
4313 rb
->postcopy_length
= new_size
;
4315 case POSTCOPY_INCOMING_NONE
:
4316 case POSTCOPY_INCOMING_RUNNING
:
4317 case POSTCOPY_INCOMING_END
:
4319 * Once our guest is running, postcopy does no longer care about
4320 * resizes. When growing, the new memory was not available on the
4321 * source, no handler needed.
4325 error_report("RAM block '%s' resized during postcopy state: %d",
4331 static RAMBlockNotifier ram_mig_ram_notifier
= {
4332 .ram_block_resized
= ram_mig_ram_block_resized
,
4335 void ram_mig_init(void)
4337 qemu_mutex_init(&XBZRLE
.lock
);
4338 register_savevm_live("ram", 0, 4, &savevm_ram_handlers
, &ram_state
);
4339 ram_block_notifier_add(&ram_mig_ram_notifier
);