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"
64 #include "sysemu/dirtylimit.h"
65 #include "sysemu/kvm.h"
67 #include "hw/boards.h" /* for machine_dump_guest_core() */
69 #if defined(__linux__)
70 #include "qemu/userfaultfd.h"
71 #endif /* defined(__linux__) */
73 /***********************************************************/
74 /* ram save/restore */
77 * RAM_SAVE_FLAG_ZERO used to be named RAM_SAVE_FLAG_COMPRESS, it
78 * worked for pages that were filled with the same char. We switched
79 * it to only search for the zero value. And to avoid confusion with
80 * RAM_SAVE_FLAG_COMPRESS_PAGE just rename it.
83 * RAM_SAVE_FLAG_FULL was obsoleted in 2009, it can be reused now
85 #define RAM_SAVE_FLAG_FULL 0x01
86 #define RAM_SAVE_FLAG_ZERO 0x02
87 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
88 #define RAM_SAVE_FLAG_PAGE 0x08
89 #define RAM_SAVE_FLAG_EOS 0x10
90 #define RAM_SAVE_FLAG_CONTINUE 0x20
91 #define RAM_SAVE_FLAG_XBZRLE 0x40
92 /* 0x80 is reserved in rdma.h for RAM_SAVE_FLAG_HOOK */
93 #define RAM_SAVE_FLAG_COMPRESS_PAGE 0x100
94 #define RAM_SAVE_FLAG_MULTIFD_FLUSH 0x200
95 /* We can't use any flag that is bigger than 0x200 */
97 XBZRLECacheStats xbzrle_counters
;
99 /* used by the search for pages to send */
100 struct PageSearchStatus
{
101 /* The migration channel used for a specific host page */
102 QEMUFile
*pss_channel
;
103 /* Last block from where we have sent data */
104 RAMBlock
*last_sent_block
;
105 /* Current block being searched */
107 /* Current page to search from */
109 /* Set once we wrap around */
111 /* Whether we're sending a host page */
112 bool host_page_sending
;
113 /* The start/end of current host page. Invalid if host_page_sending==false */
114 unsigned long host_page_start
;
115 unsigned long host_page_end
;
117 typedef struct PageSearchStatus PageSearchStatus
;
119 /* struct contains XBZRLE cache and a static page
120 used by the compression */
122 /* buffer used for XBZRLE encoding */
123 uint8_t *encoded_buf
;
124 /* buffer for storing page content */
125 uint8_t *current_buf
;
126 /* Cache for XBZRLE, Protected by lock. */
129 /* it will store a page full of zeros */
130 uint8_t *zero_target_page
;
131 /* buffer used for XBZRLE decoding */
132 uint8_t *decoded_buf
;
135 static void XBZRLE_cache_lock(void)
137 if (migrate_xbzrle()) {
138 qemu_mutex_lock(&XBZRLE
.lock
);
142 static void XBZRLE_cache_unlock(void)
144 if (migrate_xbzrle()) {
145 qemu_mutex_unlock(&XBZRLE
.lock
);
150 * xbzrle_cache_resize: resize the xbzrle cache
152 * This function is called from migrate_params_apply in main
153 * thread, possibly while a migration is in progress. A running
154 * migration may be using the cache and might finish during this call,
155 * hence changes to the cache are protected by XBZRLE.lock().
157 * Returns 0 for success or -1 for error
159 * @new_size: new cache size
160 * @errp: set *errp if the check failed, with reason
162 int xbzrle_cache_resize(uint64_t new_size
, Error
**errp
)
164 PageCache
*new_cache
;
167 /* Check for truncation */
168 if (new_size
!= (size_t)new_size
) {
169 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
170 "exceeding address space");
174 if (new_size
== migrate_xbzrle_cache_size()) {
181 if (XBZRLE
.cache
!= NULL
) {
182 new_cache
= cache_init(new_size
, TARGET_PAGE_SIZE
, errp
);
188 cache_fini(XBZRLE
.cache
);
189 XBZRLE
.cache
= new_cache
;
192 XBZRLE_cache_unlock();
196 static bool postcopy_preempt_active(void)
198 return migrate_postcopy_preempt() && migration_in_postcopy();
201 bool migrate_ram_is_ignored(RAMBlock
*block
)
203 return !qemu_ram_is_migratable(block
) ||
204 (migrate_ignore_shared() && qemu_ram_is_shared(block
)
205 && qemu_ram_is_named_file(block
));
208 #undef RAMBLOCK_FOREACH
210 int foreach_not_ignored_block(RAMBlockIterFunc func
, void *opaque
)
215 RCU_READ_LOCK_GUARD();
217 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
218 ret
= func(block
, opaque
);
226 static void ramblock_recv_map_init(void)
230 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
231 assert(!rb
->receivedmap
);
232 rb
->receivedmap
= bitmap_new(rb
->max_length
>> qemu_target_page_bits());
236 int ramblock_recv_bitmap_test(RAMBlock
*rb
, void *host_addr
)
238 return test_bit(ramblock_recv_bitmap_offset(host_addr
, rb
),
242 bool ramblock_recv_bitmap_test_byte_offset(RAMBlock
*rb
, uint64_t byte_offset
)
244 return test_bit(byte_offset
>> TARGET_PAGE_BITS
, rb
->receivedmap
);
247 void ramblock_recv_bitmap_set(RAMBlock
*rb
, void *host_addr
)
249 set_bit_atomic(ramblock_recv_bitmap_offset(host_addr
, rb
), rb
->receivedmap
);
252 void ramblock_recv_bitmap_set_range(RAMBlock
*rb
, void *host_addr
,
255 bitmap_set_atomic(rb
->receivedmap
,
256 ramblock_recv_bitmap_offset(host_addr
, rb
),
260 #define RAMBLOCK_RECV_BITMAP_ENDING (0x0123456789abcdefULL)
263 * Format: bitmap_size (8 bytes) + whole_bitmap (N bytes).
265 * Returns >0 if success with sent bytes, or <0 if error.
267 int64_t ramblock_recv_bitmap_send(QEMUFile
*file
,
268 const char *block_name
)
270 RAMBlock
*block
= qemu_ram_block_by_name(block_name
);
271 unsigned long *le_bitmap
, nbits
;
275 error_report("%s: invalid block name: %s", __func__
, block_name
);
279 nbits
= block
->postcopy_length
>> TARGET_PAGE_BITS
;
282 * Make sure the tmp bitmap buffer is big enough, e.g., on 32bit
283 * machines we may need 4 more bytes for padding (see below
284 * comment). So extend it a bit before hand.
286 le_bitmap
= bitmap_new(nbits
+ BITS_PER_LONG
);
289 * Always use little endian when sending the bitmap. This is
290 * required that when source and destination VMs are not using the
291 * same endianness. (Note: big endian won't work.)
293 bitmap_to_le(le_bitmap
, block
->receivedmap
, nbits
);
295 /* Size of the bitmap, in bytes */
296 size
= DIV_ROUND_UP(nbits
, 8);
299 * size is always aligned to 8 bytes for 64bit machines, but it
300 * may not be true for 32bit machines. We need this padding to
301 * make sure the migration can survive even between 32bit and
304 size
= ROUND_UP(size
, 8);
306 qemu_put_be64(file
, size
);
307 qemu_put_buffer(file
, (const uint8_t *)le_bitmap
, size
);
310 * Mark as an end, in case the middle part is screwed up due to
311 * some "mysterious" reason.
313 qemu_put_be64(file
, RAMBLOCK_RECV_BITMAP_ENDING
);
314 int ret
= qemu_fflush(file
);
319 return size
+ sizeof(size
);
323 * An outstanding page request, on the source, having been received
326 struct RAMSrcPageRequest
{
331 QSIMPLEQ_ENTRY(RAMSrcPageRequest
) next_req
;
334 /* State of RAM for migration */
337 * PageSearchStatus structures for the channels when send pages.
338 * Protected by the bitmap_mutex.
340 PageSearchStatus pss
[RAM_CHANNEL_MAX
];
341 /* UFFD file descriptor, used in 'write-tracking' migration */
343 /* total ram size in bytes */
344 uint64_t ram_bytes_total
;
345 /* Last block that we have visited searching for dirty pages */
346 RAMBlock
*last_seen_block
;
347 /* Last dirty target page we have sent */
348 ram_addr_t last_page
;
349 /* last ram version we have seen */
350 uint32_t last_version
;
351 /* How many times we have dirty too many pages */
352 int dirty_rate_high_cnt
;
353 /* these variables are used for bitmap sync */
354 /* last time we did a full bitmap_sync */
355 int64_t time_last_bitmap_sync
;
356 /* bytes transferred at start_time */
357 uint64_t bytes_xfer_prev
;
358 /* number of dirty pages since start_time */
359 uint64_t num_dirty_pages_period
;
360 /* xbzrle misses since the beginning of the period */
361 uint64_t xbzrle_cache_miss_prev
;
362 /* Amount of xbzrle pages since the beginning of the period */
363 uint64_t xbzrle_pages_prev
;
364 /* Amount of xbzrle encoded bytes since the beginning of the period */
365 uint64_t xbzrle_bytes_prev
;
366 /* Are we really using XBZRLE (e.g., after the first round). */
368 /* Are we on the last stage of migration */
371 /* total handled target pages at the beginning of period */
372 uint64_t target_page_count_prev
;
373 /* total handled target pages since start */
374 uint64_t target_page_count
;
375 /* number of dirty bits in the bitmap */
376 uint64_t migration_dirty_pages
;
379 * - dirty/clear bitmap
380 * - migration_dirty_pages
383 QemuMutex bitmap_mutex
;
384 /* The RAMBlock used in the last src_page_requests */
385 RAMBlock
*last_req_rb
;
386 /* Queue of outstanding page requests from the destination */
387 QemuMutex src_page_req_mutex
;
388 QSIMPLEQ_HEAD(, RAMSrcPageRequest
) src_page_requests
;
391 * This is only used when postcopy is in recovery phase, to communicate
392 * between the migration thread and the return path thread on dirty
393 * bitmap synchronizations. This field is unused in other stages of
396 unsigned int postcopy_bmap_sync_requested
;
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
);
451 struct MigrationOps
{
452 int (*ram_save_target_page
)(RAMState
*rs
, PageSearchStatus
*pss
);
454 typedef struct MigrationOps MigrationOps
;
456 MigrationOps
*migration_ops
;
458 static int ram_save_host_page_urgent(PageSearchStatus
*pss
);
460 /* NOTE: page is the PFN not real ram_addr_t. */
461 static void pss_init(PageSearchStatus
*pss
, RAMBlock
*rb
, ram_addr_t page
)
465 pss
->complete_round
= false;
469 * Check whether two PSSs are actively sending the same page. Return true
470 * if it is, false otherwise.
472 static bool pss_overlap(PageSearchStatus
*pss1
, PageSearchStatus
*pss2
)
474 return pss1
->host_page_sending
&& pss2
->host_page_sending
&&
475 (pss1
->host_page_start
== pss2
->host_page_start
);
479 * save_page_header: write page header to wire
481 * If this is the 1st block, it also writes the block identification
483 * Returns the number of bytes written
485 * @pss: current PSS channel status
486 * @block: block that contains the page we want to send
487 * @offset: offset inside the block for the page
488 * in the lower bits, it contains flags
490 static size_t save_page_header(PageSearchStatus
*pss
, QEMUFile
*f
,
491 RAMBlock
*block
, ram_addr_t offset
)
494 bool same_block
= (block
== pss
->last_sent_block
);
497 offset
|= RAM_SAVE_FLAG_CONTINUE
;
499 qemu_put_be64(f
, offset
);
503 len
= strlen(block
->idstr
);
504 qemu_put_byte(f
, len
);
505 qemu_put_buffer(f
, (uint8_t *)block
->idstr
, len
);
507 pss
->last_sent_block
= block
;
513 * mig_throttle_guest_down: throttle down the guest
515 * Reduce amount of guest cpu execution to hopefully slow down memory
516 * writes. If guest dirty memory rate is reduced below the rate at
517 * which we can transfer pages to the destination then we should be
518 * able to complete migration. Some workloads dirty memory way too
519 * fast and will not effectively converge, even with auto-converge.
521 static void mig_throttle_guest_down(uint64_t bytes_dirty_period
,
522 uint64_t bytes_dirty_threshold
)
524 uint64_t pct_initial
= migrate_cpu_throttle_initial();
525 uint64_t pct_increment
= migrate_cpu_throttle_increment();
526 bool pct_tailslow
= migrate_cpu_throttle_tailslow();
527 int pct_max
= migrate_max_cpu_throttle();
529 uint64_t throttle_now
= cpu_throttle_get_percentage();
530 uint64_t cpu_now
, cpu_ideal
, throttle_inc
;
532 /* We have not started throttling yet. Let's start it. */
533 if (!cpu_throttle_active()) {
534 cpu_throttle_set(pct_initial
);
536 /* Throttling already on, just increase the rate */
538 throttle_inc
= pct_increment
;
540 /* Compute the ideal CPU percentage used by Guest, which may
541 * make the dirty rate match the dirty rate threshold. */
542 cpu_now
= 100 - throttle_now
;
543 cpu_ideal
= cpu_now
* (bytes_dirty_threshold
* 1.0 /
545 throttle_inc
= MIN(cpu_now
- cpu_ideal
, pct_increment
);
547 cpu_throttle_set(MIN(throttle_now
+ throttle_inc
, pct_max
));
551 void mig_throttle_counter_reset(void)
553 RAMState
*rs
= ram_state
;
555 rs
->time_last_bitmap_sync
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
556 rs
->num_dirty_pages_period
= 0;
557 rs
->bytes_xfer_prev
= migration_transferred_bytes();
561 * xbzrle_cache_zero_page: insert a zero page in the XBZRLE cache
563 * @current_addr: address for the zero page
565 * Update the xbzrle cache to reflect a page that's been sent as all 0.
566 * The important thing is that a stale (not-yet-0'd) page be replaced
568 * As a bonus, if the page wasn't in the cache it gets added so that
569 * when a small write is made into the 0'd page it gets XBZRLE sent.
571 static void xbzrle_cache_zero_page(ram_addr_t current_addr
)
573 /* We don't care if this fails to allocate a new cache page
574 * as long as it updated an old one */
575 cache_insert(XBZRLE
.cache
, current_addr
, XBZRLE
.zero_target_page
,
576 stat64_get(&mig_stats
.dirty_sync_count
));
579 #define ENCODING_FLAG_XBZRLE 0x1
582 * save_xbzrle_page: compress and send current page
584 * Returns: 1 means that we wrote the page
585 * 0 means that page is identical to the one already sent
586 * -1 means that xbzrle would be longer than normal
588 * @rs: current RAM state
589 * @pss: current PSS channel
590 * @current_data: pointer to the address of the page contents
591 * @current_addr: addr of the page
592 * @block: block that contains the page we want to send
593 * @offset: offset inside the block for the page
595 static int save_xbzrle_page(RAMState
*rs
, PageSearchStatus
*pss
,
596 uint8_t **current_data
, ram_addr_t current_addr
,
597 RAMBlock
*block
, ram_addr_t offset
)
599 int encoded_len
= 0, bytes_xbzrle
;
600 uint8_t *prev_cached_page
;
601 QEMUFile
*file
= pss
->pss_channel
;
602 uint64_t generation
= stat64_get(&mig_stats
.dirty_sync_count
);
604 if (!cache_is_cached(XBZRLE
.cache
, current_addr
, generation
)) {
605 xbzrle_counters
.cache_miss
++;
606 if (!rs
->last_stage
) {
607 if (cache_insert(XBZRLE
.cache
, current_addr
, *current_data
,
611 /* update *current_data when the page has been
612 inserted into cache */
613 *current_data
= get_cached_data(XBZRLE
.cache
, current_addr
);
620 * Reaching here means the page has hit the xbzrle cache, no matter what
621 * encoding result it is (normal encoding, overflow or skipping the page),
622 * count the page as encoded. This is used to calculate the encoding rate.
624 * Example: 2 pages (8KB) being encoded, first page encoding generates 2KB,
625 * 2nd page turns out to be skipped (i.e. no new bytes written to the
626 * page), the overall encoding rate will be 8KB / 2KB = 4, which has the
627 * skipped page included. In this way, the encoding rate can tell if the
628 * guest page is good for xbzrle encoding.
630 xbzrle_counters
.pages
++;
631 prev_cached_page
= get_cached_data(XBZRLE
.cache
, current_addr
);
633 /* save current buffer into memory */
634 memcpy(XBZRLE
.current_buf
, *current_data
, TARGET_PAGE_SIZE
);
636 /* XBZRLE encoding (if there is no overflow) */
637 encoded_len
= xbzrle_encode_buffer(prev_cached_page
, XBZRLE
.current_buf
,
638 TARGET_PAGE_SIZE
, XBZRLE
.encoded_buf
,
642 * Update the cache contents, so that it corresponds to the data
643 * sent, in all cases except where we skip the page.
645 if (!rs
->last_stage
&& encoded_len
!= 0) {
646 memcpy(prev_cached_page
, XBZRLE
.current_buf
, TARGET_PAGE_SIZE
);
648 * In the case where we couldn't compress, ensure that the caller
649 * sends the data from the cache, since the guest might have
650 * changed the RAM since we copied it.
652 *current_data
= prev_cached_page
;
655 if (encoded_len
== 0) {
656 trace_save_xbzrle_page_skipping();
658 } else if (encoded_len
== -1) {
659 trace_save_xbzrle_page_overflow();
660 xbzrle_counters
.overflow
++;
661 xbzrle_counters
.bytes
+= TARGET_PAGE_SIZE
;
665 /* Send XBZRLE based compressed page */
666 bytes_xbzrle
= save_page_header(pss
, pss
->pss_channel
, block
,
667 offset
| RAM_SAVE_FLAG_XBZRLE
);
668 qemu_put_byte(file
, ENCODING_FLAG_XBZRLE
);
669 qemu_put_be16(file
, encoded_len
);
670 qemu_put_buffer(file
, XBZRLE
.encoded_buf
, encoded_len
);
671 bytes_xbzrle
+= encoded_len
+ 1 + 2;
673 * Like compressed_size (please see update_compress_thread_counts),
674 * the xbzrle encoded bytes don't count the 8 byte header with
675 * RAM_SAVE_FLAG_CONTINUE.
677 xbzrle_counters
.bytes
+= bytes_xbzrle
- 8;
678 ram_transferred_add(bytes_xbzrle
);
684 * pss_find_next_dirty: find the next dirty page of current ramblock
686 * This function updates pss->page to point to the next dirty page index
687 * within the ramblock to migrate, or the end of ramblock when nothing
688 * found. Note that when pss->host_page_sending==true it means we're
689 * during sending a host page, so we won't look for dirty page that is
690 * outside the host page boundary.
692 * @pss: the current page search status
694 static void pss_find_next_dirty(PageSearchStatus
*pss
)
696 RAMBlock
*rb
= pss
->block
;
697 unsigned long size
= rb
->used_length
>> TARGET_PAGE_BITS
;
698 unsigned long *bitmap
= rb
->bmap
;
700 if (migrate_ram_is_ignored(rb
)) {
701 /* Points directly to the end, so we know no dirty page */
707 * If during sending a host page, only look for dirty pages within the
708 * current host page being send.
710 if (pss
->host_page_sending
) {
711 assert(pss
->host_page_end
);
712 size
= MIN(size
, pss
->host_page_end
);
715 pss
->page
= find_next_bit(bitmap
, size
, pss
->page
);
718 static void migration_clear_memory_region_dirty_bitmap(RAMBlock
*rb
,
724 if (!rb
->clear_bmap
|| !clear_bmap_test_and_clear(rb
, page
)) {
728 shift
= rb
->clear_bmap_shift
;
730 * CLEAR_BITMAP_SHIFT_MIN should always guarantee this... this
731 * can make things easier sometimes since then start address
732 * of the small chunk will always be 64 pages aligned so the
733 * bitmap will always be aligned to unsigned long. We should
734 * even be able to remove this restriction but I'm simply
739 size
= 1ULL << (TARGET_PAGE_BITS
+ shift
);
740 start
= QEMU_ALIGN_DOWN((ram_addr_t
)page
<< TARGET_PAGE_BITS
, size
);
741 trace_migration_bitmap_clear_dirty(rb
->idstr
, start
, size
, page
);
742 memory_region_clear_dirty_bitmap(rb
->mr
, start
, size
);
746 migration_clear_memory_region_dirty_bitmap_range(RAMBlock
*rb
,
748 unsigned long npages
)
750 unsigned long i
, chunk_pages
= 1UL << rb
->clear_bmap_shift
;
751 unsigned long chunk_start
= QEMU_ALIGN_DOWN(start
, chunk_pages
);
752 unsigned long chunk_end
= QEMU_ALIGN_UP(start
+ npages
, chunk_pages
);
755 * Clear pages from start to start + npages - 1, so the end boundary is
758 for (i
= chunk_start
; i
< chunk_end
; i
+= chunk_pages
) {
759 migration_clear_memory_region_dirty_bitmap(rb
, i
);
764 * colo_bitmap_find_diry:find contiguous dirty pages from start
766 * Returns the page offset within memory region of the start of the contiguout
769 * @rs: current RAM state
770 * @rb: RAMBlock where to search for dirty pages
771 * @start: page where we start the search
772 * @num: the number of contiguous dirty pages
775 unsigned long colo_bitmap_find_dirty(RAMState
*rs
, RAMBlock
*rb
,
776 unsigned long start
, unsigned long *num
)
778 unsigned long size
= rb
->used_length
>> TARGET_PAGE_BITS
;
779 unsigned long *bitmap
= rb
->bmap
;
780 unsigned long first
, next
;
784 if (migrate_ram_is_ignored(rb
)) {
788 first
= find_next_bit(bitmap
, size
, start
);
792 next
= find_next_zero_bit(bitmap
, size
, first
+ 1);
793 assert(next
>= first
);
798 static inline bool migration_bitmap_clear_dirty(RAMState
*rs
,
805 * Clear dirty bitmap if needed. This _must_ be called before we
806 * send any of the page in the chunk because we need to make sure
807 * we can capture further page content changes when we sync dirty
808 * log the next time. So as long as we are going to send any of
809 * the page in the chunk we clear the remote dirty bitmap for all.
810 * Clearing it earlier won't be a problem, but too late will.
812 migration_clear_memory_region_dirty_bitmap(rb
, page
);
814 ret
= test_and_clear_bit(page
, rb
->bmap
);
816 rs
->migration_dirty_pages
--;
822 static void dirty_bitmap_clear_section(MemoryRegionSection
*section
,
825 const hwaddr offset
= section
->offset_within_region
;
826 const hwaddr size
= int128_get64(section
->size
);
827 const unsigned long start
= offset
>> TARGET_PAGE_BITS
;
828 const unsigned long npages
= size
>> TARGET_PAGE_BITS
;
829 RAMBlock
*rb
= section
->mr
->ram_block
;
830 uint64_t *cleared_bits
= opaque
;
833 * We don't grab ram_state->bitmap_mutex because we expect to run
834 * only when starting migration or during postcopy recovery where
835 * we don't have concurrent access.
837 if (!migration_in_postcopy() && !migrate_background_snapshot()) {
838 migration_clear_memory_region_dirty_bitmap_range(rb
, start
, npages
);
840 *cleared_bits
+= bitmap_count_one_with_offset(rb
->bmap
, start
, npages
);
841 bitmap_clear(rb
->bmap
, start
, npages
);
845 * Exclude all dirty pages from migration that fall into a discarded range as
846 * managed by a RamDiscardManager responsible for the mapped memory region of
847 * the RAMBlock. Clear the corresponding bits in the dirty bitmaps.
849 * Discarded pages ("logically unplugged") have undefined content and must
850 * not get migrated, because even reading these pages for migration might
851 * result in undesired behavior.
853 * Returns the number of cleared bits in the RAMBlock dirty bitmap.
855 * Note: The result is only stable while migrating (precopy/postcopy).
857 static uint64_t ramblock_dirty_bitmap_clear_discarded_pages(RAMBlock
*rb
)
859 uint64_t cleared_bits
= 0;
861 if (rb
->mr
&& rb
->bmap
&& memory_region_has_ram_discard_manager(rb
->mr
)) {
862 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(rb
->mr
);
863 MemoryRegionSection section
= {
865 .offset_within_region
= 0,
866 .size
= int128_make64(qemu_ram_get_used_length(rb
)),
869 ram_discard_manager_replay_discarded(rdm
, §ion
,
870 dirty_bitmap_clear_section
,
877 * Check if a host-page aligned page falls into a discarded range as managed by
878 * a RamDiscardManager responsible for the mapped memory region of the RAMBlock.
880 * Note: The result is only stable while migrating (precopy/postcopy).
882 bool ramblock_page_is_discarded(RAMBlock
*rb
, ram_addr_t start
)
884 if (rb
->mr
&& memory_region_has_ram_discard_manager(rb
->mr
)) {
885 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(rb
->mr
);
886 MemoryRegionSection section
= {
888 .offset_within_region
= start
,
889 .size
= int128_make64(qemu_ram_pagesize(rb
)),
892 return !ram_discard_manager_is_populated(rdm
, §ion
);
897 /* Called with RCU critical section */
898 static void ramblock_sync_dirty_bitmap(RAMState
*rs
, RAMBlock
*rb
)
900 uint64_t new_dirty_pages
=
901 cpu_physical_memory_sync_dirty_bitmap(rb
, 0, rb
->used_length
);
903 rs
->migration_dirty_pages
+= new_dirty_pages
;
904 rs
->num_dirty_pages_period
+= new_dirty_pages
;
908 * ram_pagesize_summary: calculate all the pagesizes of a VM
910 * Returns a summary bitmap of the page sizes of all RAMBlocks
912 * For VMs with just normal pages this is equivalent to the host page
913 * size. If it's got some huge pages then it's the OR of all the
914 * different page sizes.
916 uint64_t ram_pagesize_summary(void)
919 uint64_t summary
= 0;
921 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
922 summary
|= block
->page_size
;
928 uint64_t ram_get_total_transferred_pages(void)
930 return stat64_get(&mig_stats
.normal_pages
) +
931 stat64_get(&mig_stats
.zero_pages
) +
932 compress_ram_pages() + xbzrle_counters
.pages
;
935 static void migration_update_rates(RAMState
*rs
, int64_t end_time
)
937 uint64_t page_count
= rs
->target_page_count
- rs
->target_page_count_prev
;
939 /* calculate period counters */
940 stat64_set(&mig_stats
.dirty_pages_rate
,
941 rs
->num_dirty_pages_period
* 1000 /
942 (end_time
- rs
->time_last_bitmap_sync
));
948 if (migrate_xbzrle()) {
949 double encoded_size
, unencoded_size
;
951 xbzrle_counters
.cache_miss_rate
= (double)(xbzrle_counters
.cache_miss
-
952 rs
->xbzrle_cache_miss_prev
) / page_count
;
953 rs
->xbzrle_cache_miss_prev
= xbzrle_counters
.cache_miss
;
954 unencoded_size
= (xbzrle_counters
.pages
- rs
->xbzrle_pages_prev
) *
956 encoded_size
= xbzrle_counters
.bytes
- rs
->xbzrle_bytes_prev
;
957 if (xbzrle_counters
.pages
== rs
->xbzrle_pages_prev
|| !encoded_size
) {
958 xbzrle_counters
.encoding_rate
= 0;
960 xbzrle_counters
.encoding_rate
= unencoded_size
/ encoded_size
;
962 rs
->xbzrle_pages_prev
= xbzrle_counters
.pages
;
963 rs
->xbzrle_bytes_prev
= xbzrle_counters
.bytes
;
965 compress_update_rates(page_count
);
969 * Enable dirty-limit to throttle down the guest
971 static void migration_dirty_limit_guest(void)
974 * dirty page rate quota for all vCPUs fetched from
975 * migration parameter 'vcpu_dirty_limit'
977 static int64_t quota_dirtyrate
;
978 MigrationState
*s
= migrate_get_current();
981 * If dirty limit already enabled and migration parameter
982 * vcpu-dirty-limit untouched.
984 if (dirtylimit_in_service() &&
985 quota_dirtyrate
== s
->parameters
.vcpu_dirty_limit
) {
989 quota_dirtyrate
= s
->parameters
.vcpu_dirty_limit
;
992 * Set all vCPU a quota dirtyrate, note that the second
993 * parameter will be ignored if setting all vCPU for the vm
995 qmp_set_vcpu_dirty_limit(false, -1, quota_dirtyrate
, NULL
);
996 trace_migration_dirty_limit_guest(quota_dirtyrate
);
999 static void migration_trigger_throttle(RAMState
*rs
)
1001 uint64_t threshold
= migrate_throttle_trigger_threshold();
1002 uint64_t bytes_xfer_period
=
1003 migration_transferred_bytes() - rs
->bytes_xfer_prev
;
1004 uint64_t bytes_dirty_period
= rs
->num_dirty_pages_period
* TARGET_PAGE_SIZE
;
1005 uint64_t bytes_dirty_threshold
= bytes_xfer_period
* threshold
/ 100;
1007 /* During block migration the auto-converge logic incorrectly detects
1008 * that ram migration makes no progress. Avoid this by disabling the
1009 * throttling logic during the bulk phase of block migration. */
1010 if (blk_mig_bulk_active()) {
1015 * The following detection logic can be refined later. For now:
1016 * Check to see if the ratio between dirtied bytes and the approx.
1017 * amount of bytes that just got transferred since the last time
1018 * we were in this routine reaches the threshold. If that happens
1019 * twice, start or increase throttling.
1021 if ((bytes_dirty_period
> bytes_dirty_threshold
) &&
1022 (++rs
->dirty_rate_high_cnt
>= 2)) {
1023 rs
->dirty_rate_high_cnt
= 0;
1024 if (migrate_auto_converge()) {
1025 trace_migration_throttle();
1026 mig_throttle_guest_down(bytes_dirty_period
,
1027 bytes_dirty_threshold
);
1028 } else if (migrate_dirty_limit()) {
1029 migration_dirty_limit_guest();
1034 static void migration_bitmap_sync(RAMState
*rs
, bool last_stage
)
1039 stat64_add(&mig_stats
.dirty_sync_count
, 1);
1041 if (!rs
->time_last_bitmap_sync
) {
1042 rs
->time_last_bitmap_sync
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1045 trace_migration_bitmap_sync_start();
1046 memory_global_dirty_log_sync(last_stage
);
1048 qemu_mutex_lock(&rs
->bitmap_mutex
);
1049 WITH_RCU_READ_LOCK_GUARD() {
1050 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1051 ramblock_sync_dirty_bitmap(rs
, block
);
1053 stat64_set(&mig_stats
.dirty_bytes_last_sync
, ram_bytes_remaining());
1055 qemu_mutex_unlock(&rs
->bitmap_mutex
);
1057 memory_global_after_dirty_log_sync();
1058 trace_migration_bitmap_sync_end(rs
->num_dirty_pages_period
);
1060 end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1062 /* more than 1 second = 1000 millisecons */
1063 if (end_time
> rs
->time_last_bitmap_sync
+ 1000) {
1064 migration_trigger_throttle(rs
);
1066 migration_update_rates(rs
, end_time
);
1068 rs
->target_page_count_prev
= rs
->target_page_count
;
1070 /* reset period counters */
1071 rs
->time_last_bitmap_sync
= end_time
;
1072 rs
->num_dirty_pages_period
= 0;
1073 rs
->bytes_xfer_prev
= migration_transferred_bytes();
1075 if (migrate_events()) {
1076 uint64_t generation
= stat64_get(&mig_stats
.dirty_sync_count
);
1077 qapi_event_send_migration_pass(generation
);
1081 static void migration_bitmap_sync_precopy(RAMState
*rs
, bool last_stage
)
1083 Error
*local_err
= NULL
;
1086 * The current notifier usage is just an optimization to migration, so we
1087 * don't stop the normal migration process in the error case.
1089 if (precopy_notify(PRECOPY_NOTIFY_BEFORE_BITMAP_SYNC
, &local_err
)) {
1090 error_report_err(local_err
);
1094 migration_bitmap_sync(rs
, last_stage
);
1096 if (precopy_notify(PRECOPY_NOTIFY_AFTER_BITMAP_SYNC
, &local_err
)) {
1097 error_report_err(local_err
);
1101 void ram_release_page(const char *rbname
, uint64_t offset
)
1103 if (!migrate_release_ram() || !migration_in_postcopy()) {
1107 ram_discard_range(rbname
, offset
, TARGET_PAGE_SIZE
);
1111 * save_zero_page: send the zero page to the stream
1113 * Returns the number of pages written.
1115 * @rs: current RAM state
1116 * @pss: current PSS channel
1117 * @offset: offset inside the block for the page
1119 static int save_zero_page(RAMState
*rs
, PageSearchStatus
*pss
,
1122 uint8_t *p
= pss
->block
->host
+ offset
;
1123 QEMUFile
*file
= pss
->pss_channel
;
1126 if (!buffer_is_zero(p
, TARGET_PAGE_SIZE
)) {
1130 len
+= save_page_header(pss
, file
, pss
->block
, offset
| RAM_SAVE_FLAG_ZERO
);
1131 qemu_put_byte(file
, 0);
1133 ram_release_page(pss
->block
->idstr
, offset
);
1135 stat64_add(&mig_stats
.zero_pages
, 1);
1136 ram_transferred_add(len
);
1139 * Must let xbzrle know, otherwise a previous (now 0'd) cached
1140 * page would be stale.
1142 if (rs
->xbzrle_started
) {
1143 XBZRLE_cache_lock();
1144 xbzrle_cache_zero_page(pss
->block
->offset
+ offset
);
1145 XBZRLE_cache_unlock();
1152 * @pages: the number of pages written by the control path,
1154 * > 0 - number of pages written
1156 * Return true if the pages has been saved, otherwise false is returned.
1158 static bool control_save_page(PageSearchStatus
*pss
,
1159 ram_addr_t offset
, int *pages
)
1163 ret
= rdma_control_save_page(pss
->pss_channel
, pss
->block
->offset
, offset
,
1165 if (ret
== RAM_SAVE_CONTROL_NOT_SUPP
) {
1169 if (ret
== RAM_SAVE_CONTROL_DELAYED
) {
1178 * directly send the page to the stream
1180 * Returns the number of pages written.
1182 * @pss: current PSS channel
1183 * @block: block that contains the page we want to send
1184 * @offset: offset inside the block for the page
1185 * @buf: the page to be sent
1186 * @async: send to page asyncly
1188 static int save_normal_page(PageSearchStatus
*pss
, RAMBlock
*block
,
1189 ram_addr_t offset
, uint8_t *buf
, bool async
)
1191 QEMUFile
*file
= pss
->pss_channel
;
1193 ram_transferred_add(save_page_header(pss
, pss
->pss_channel
, block
,
1194 offset
| RAM_SAVE_FLAG_PAGE
));
1196 qemu_put_buffer_async(file
, buf
, TARGET_PAGE_SIZE
,
1197 migrate_release_ram() &&
1198 migration_in_postcopy());
1200 qemu_put_buffer(file
, buf
, TARGET_PAGE_SIZE
);
1202 ram_transferred_add(TARGET_PAGE_SIZE
);
1203 stat64_add(&mig_stats
.normal_pages
, 1);
1208 * ram_save_page: send the given page to the stream
1210 * Returns the number of pages written.
1212 * >=0 - Number of pages written - this might legally be 0
1213 * if xbzrle noticed the page was the same.
1215 * @rs: current RAM state
1216 * @block: block that contains the page we want to send
1217 * @offset: offset inside the block for the page
1219 static int ram_save_page(RAMState
*rs
, PageSearchStatus
*pss
)
1223 bool send_async
= true;
1224 RAMBlock
*block
= pss
->block
;
1225 ram_addr_t offset
= ((ram_addr_t
)pss
->page
) << TARGET_PAGE_BITS
;
1226 ram_addr_t current_addr
= block
->offset
+ offset
;
1228 p
= block
->host
+ offset
;
1229 trace_ram_save_page(block
->idstr
, (uint64_t)offset
, p
);
1231 XBZRLE_cache_lock();
1232 if (rs
->xbzrle_started
&& !migration_in_postcopy()) {
1233 pages
= save_xbzrle_page(rs
, pss
, &p
, current_addr
,
1235 if (!rs
->last_stage
) {
1236 /* Can't send this cached data async, since the cache page
1237 * might get updated before it gets to the wire
1243 /* XBZRLE overflow or normal page */
1245 pages
= save_normal_page(pss
, block
, offset
, p
, send_async
);
1248 XBZRLE_cache_unlock();
1253 static int ram_save_multifd_page(RAMBlock
*block
, ram_addr_t offset
)
1255 if (multifd_queue_page(block
, offset
) < 0) {
1258 stat64_add(&mig_stats
.normal_pages
, 1);
1263 int compress_send_queued_data(CompressParam
*param
)
1265 PageSearchStatus
*pss
= &ram_state
->pss
[RAM_CHANNEL_PRECOPY
];
1266 MigrationState
*ms
= migrate_get_current();
1267 QEMUFile
*file
= ms
->to_dst_file
;
1270 RAMBlock
*block
= param
->block
;
1271 ram_addr_t offset
= param
->offset
;
1273 if (param
->result
== RES_NONE
) {
1277 assert(block
== pss
->last_sent_block
);
1279 if (param
->result
== RES_ZEROPAGE
) {
1280 assert(qemu_file_buffer_empty(param
->file
));
1281 len
+= save_page_header(pss
, file
, block
, offset
| RAM_SAVE_FLAG_ZERO
);
1282 qemu_put_byte(file
, 0);
1284 ram_release_page(block
->idstr
, offset
);
1285 } else if (param
->result
== RES_COMPRESS
) {
1286 assert(!qemu_file_buffer_empty(param
->file
));
1287 len
+= save_page_header(pss
, file
, block
,
1288 offset
| RAM_SAVE_FLAG_COMPRESS_PAGE
);
1289 len
+= qemu_put_qemu_file(file
, param
->file
);
1294 update_compress_thread_counts(param
, len
);
1299 #define PAGE_ALL_CLEAN 0
1300 #define PAGE_TRY_AGAIN 1
1301 #define PAGE_DIRTY_FOUND 2
1303 * find_dirty_block: find the next dirty page and update any state
1304 * associated with the search process.
1307 * <0: An error happened
1308 * PAGE_ALL_CLEAN: no dirty page found, give up
1309 * PAGE_TRY_AGAIN: no dirty page found, retry for next block
1310 * PAGE_DIRTY_FOUND: dirty page found
1312 * @rs: current RAM state
1313 * @pss: data about the state of the current dirty page scan
1314 * @again: set to false if the search has scanned the whole of RAM
1316 static int find_dirty_block(RAMState
*rs
, PageSearchStatus
*pss
)
1318 /* Update pss->page for the next dirty bit in ramblock */
1319 pss_find_next_dirty(pss
);
1321 if (pss
->complete_round
&& pss
->block
== rs
->last_seen_block
&&
1322 pss
->page
>= rs
->last_page
) {
1324 * We've been once around the RAM and haven't found anything.
1327 return PAGE_ALL_CLEAN
;
1329 if (!offset_in_ramblock(pss
->block
,
1330 ((ram_addr_t
)pss
->page
) << TARGET_PAGE_BITS
)) {
1331 /* Didn't find anything in this RAM Block */
1333 pss
->block
= QLIST_NEXT_RCU(pss
->block
, next
);
1335 if (migrate_multifd() &&
1336 !migrate_multifd_flush_after_each_section()) {
1337 QEMUFile
*f
= rs
->pss
[RAM_CHANNEL_PRECOPY
].pss_channel
;
1338 int ret
= multifd_send_sync_main();
1342 qemu_put_be64(f
, RAM_SAVE_FLAG_MULTIFD_FLUSH
);
1346 * If memory migration starts over, we will meet a dirtied page
1347 * which may still exists in compression threads's ring, so we
1348 * should flush the compressed data to make sure the new page
1349 * is not overwritten by the old one in the destination.
1351 * Also If xbzrle is on, stop using the data compression at this
1352 * point. In theory, xbzrle can do better than compression.
1354 compress_flush_data();
1356 /* Hit the end of the list */
1357 pss
->block
= QLIST_FIRST_RCU(&ram_list
.blocks
);
1358 /* Flag that we've looped */
1359 pss
->complete_round
= true;
1360 /* After the first round, enable XBZRLE. */
1361 if (migrate_xbzrle()) {
1362 rs
->xbzrle_started
= true;
1365 /* Didn't find anything this time, but try again on the new block */
1366 return PAGE_TRY_AGAIN
;
1368 /* We've found something */
1369 return PAGE_DIRTY_FOUND
;
1374 * unqueue_page: gets a page of the queue
1376 * Helper for 'get_queued_page' - gets a page off the queue
1378 * Returns the block of the page (or NULL if none available)
1380 * @rs: current RAM state
1381 * @offset: used to return the offset within the RAMBlock
1383 static RAMBlock
*unqueue_page(RAMState
*rs
, ram_addr_t
*offset
)
1385 struct RAMSrcPageRequest
*entry
;
1386 RAMBlock
*block
= NULL
;
1388 if (!postcopy_has_request(rs
)) {
1392 QEMU_LOCK_GUARD(&rs
->src_page_req_mutex
);
1395 * This should _never_ change even after we take the lock, because no one
1396 * should be taking anything off the request list other than us.
1398 assert(postcopy_has_request(rs
));
1400 entry
= QSIMPLEQ_FIRST(&rs
->src_page_requests
);
1402 *offset
= entry
->offset
;
1404 if (entry
->len
> TARGET_PAGE_SIZE
) {
1405 entry
->len
-= TARGET_PAGE_SIZE
;
1406 entry
->offset
+= TARGET_PAGE_SIZE
;
1408 memory_region_unref(block
->mr
);
1409 QSIMPLEQ_REMOVE_HEAD(&rs
->src_page_requests
, next_req
);
1411 migration_consume_urgent_request();
1417 #if defined(__linux__)
1419 * poll_fault_page: try to get next UFFD write fault page and, if pending fault
1420 * is found, return RAM block pointer and page offset
1422 * Returns pointer to the RAMBlock containing faulting page,
1423 * NULL if no write faults are pending
1425 * @rs: current RAM state
1426 * @offset: page offset from the beginning of the block
1428 static RAMBlock
*poll_fault_page(RAMState
*rs
, ram_addr_t
*offset
)
1430 struct uffd_msg uffd_msg
;
1435 if (!migrate_background_snapshot()) {
1439 res
= uffd_read_events(rs
->uffdio_fd
, &uffd_msg
, 1);
1444 page_address
= (void *)(uintptr_t) uffd_msg
.arg
.pagefault
.address
;
1445 block
= qemu_ram_block_from_host(page_address
, false, offset
);
1446 assert(block
&& (block
->flags
& RAM_UF_WRITEPROTECT
) != 0);
1451 * ram_save_release_protection: release UFFD write protection after
1452 * a range of pages has been saved
1454 * @rs: current RAM state
1455 * @pss: page-search-status structure
1456 * @start_page: index of the first page in the range relative to pss->block
1458 * Returns 0 on success, negative value in case of an error
1460 static int ram_save_release_protection(RAMState
*rs
, PageSearchStatus
*pss
,
1461 unsigned long start_page
)
1465 /* Check if page is from UFFD-managed region. */
1466 if (pss
->block
->flags
& RAM_UF_WRITEPROTECT
) {
1467 void *page_address
= pss
->block
->host
+ (start_page
<< TARGET_PAGE_BITS
);
1468 uint64_t run_length
= (pss
->page
- start_page
) << TARGET_PAGE_BITS
;
1470 /* Flush async buffers before un-protect. */
1471 qemu_fflush(pss
->pss_channel
);
1472 /* Un-protect memory range. */
1473 res
= uffd_change_protection(rs
->uffdio_fd
, page_address
, run_length
,
1480 /* ram_write_tracking_available: check if kernel supports required UFFD features
1482 * Returns true if supports, false otherwise
1484 bool ram_write_tracking_available(void)
1486 uint64_t uffd_features
;
1489 res
= uffd_query_features(&uffd_features
);
1491 (uffd_features
& UFFD_FEATURE_PAGEFAULT_FLAG_WP
) != 0);
1494 /* ram_write_tracking_compatible: check if guest configuration is
1495 * compatible with 'write-tracking'
1497 * Returns true if compatible, false otherwise
1499 bool ram_write_tracking_compatible(void)
1501 const uint64_t uffd_ioctls_mask
= BIT(_UFFDIO_WRITEPROTECT
);
1506 /* Open UFFD file descriptor */
1507 uffd_fd
= uffd_create_fd(UFFD_FEATURE_PAGEFAULT_FLAG_WP
, false);
1512 RCU_READ_LOCK_GUARD();
1514 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1515 uint64_t uffd_ioctls
;
1517 /* Nothing to do with read-only and MMIO-writable regions */
1518 if (block
->mr
->readonly
|| block
->mr
->rom_device
) {
1521 /* Try to register block memory via UFFD-IO to track writes */
1522 if (uffd_register_memory(uffd_fd
, block
->host
, block
->max_length
,
1523 UFFDIO_REGISTER_MODE_WP
, &uffd_ioctls
)) {
1526 if ((uffd_ioctls
& uffd_ioctls_mask
) != uffd_ioctls_mask
) {
1533 uffd_close_fd(uffd_fd
);
1537 static inline void populate_read_range(RAMBlock
*block
, ram_addr_t offset
,
1540 const ram_addr_t end
= offset
+ size
;
1543 * We read one byte of each page; this will preallocate page tables if
1544 * required and populate the shared zeropage on MAP_PRIVATE anonymous memory
1545 * where no page was populated yet. This might require adaption when
1546 * supporting other mappings, like shmem.
1548 for (; offset
< end
; offset
+= block
->page_size
) {
1549 char tmp
= *((char *)block
->host
+ offset
);
1551 /* Don't optimize the read out */
1552 asm volatile("" : "+r" (tmp
));
1556 static inline int populate_read_section(MemoryRegionSection
*section
,
1559 const hwaddr size
= int128_get64(section
->size
);
1560 hwaddr offset
= section
->offset_within_region
;
1561 RAMBlock
*block
= section
->mr
->ram_block
;
1563 populate_read_range(block
, offset
, size
);
1568 * ram_block_populate_read: preallocate page tables and populate pages in the
1569 * RAM block by reading a byte of each page.
1571 * Since it's solely used for userfault_fd WP feature, here we just
1572 * hardcode page size to qemu_real_host_page_size.
1574 * @block: RAM block to populate
1576 static void ram_block_populate_read(RAMBlock
*rb
)
1579 * Skip populating all pages that fall into a discarded range as managed by
1580 * a RamDiscardManager responsible for the mapped memory region of the
1581 * RAMBlock. Such discarded ("logically unplugged") parts of a RAMBlock
1582 * must not get populated automatically. We don't have to track
1583 * modifications via userfaultfd WP reliably, because these pages will
1584 * not be part of the migration stream either way -- see
1585 * ramblock_dirty_bitmap_exclude_discarded_pages().
1587 * Note: The result is only stable while migrating (precopy/postcopy).
1589 if (rb
->mr
&& memory_region_has_ram_discard_manager(rb
->mr
)) {
1590 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(rb
->mr
);
1591 MemoryRegionSection section
= {
1593 .offset_within_region
= 0,
1594 .size
= rb
->mr
->size
,
1597 ram_discard_manager_replay_populated(rdm
, §ion
,
1598 populate_read_section
, NULL
);
1600 populate_read_range(rb
, 0, rb
->used_length
);
1605 * ram_write_tracking_prepare: prepare for UFFD-WP memory tracking
1607 void ram_write_tracking_prepare(void)
1611 RCU_READ_LOCK_GUARD();
1613 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1614 /* Nothing to do with read-only and MMIO-writable regions */
1615 if (block
->mr
->readonly
|| block
->mr
->rom_device
) {
1620 * Populate pages of the RAM block before enabling userfault_fd
1623 * This stage is required since ioctl(UFFDIO_WRITEPROTECT) with
1624 * UFFDIO_WRITEPROTECT_MODE_WP mode setting would silently skip
1625 * pages with pte_none() entries in page table.
1627 ram_block_populate_read(block
);
1631 static inline int uffd_protect_section(MemoryRegionSection
*section
,
1634 const hwaddr size
= int128_get64(section
->size
);
1635 const hwaddr offset
= section
->offset_within_region
;
1636 RAMBlock
*rb
= section
->mr
->ram_block
;
1637 int uffd_fd
= (uintptr_t)opaque
;
1639 return uffd_change_protection(uffd_fd
, rb
->host
+ offset
, size
, true,
1643 static int ram_block_uffd_protect(RAMBlock
*rb
, int uffd_fd
)
1645 assert(rb
->flags
& RAM_UF_WRITEPROTECT
);
1647 /* See ram_block_populate_read() */
1648 if (rb
->mr
&& memory_region_has_ram_discard_manager(rb
->mr
)) {
1649 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(rb
->mr
);
1650 MemoryRegionSection section
= {
1652 .offset_within_region
= 0,
1653 .size
= rb
->mr
->size
,
1656 return ram_discard_manager_replay_populated(rdm
, §ion
,
1657 uffd_protect_section
,
1658 (void *)(uintptr_t)uffd_fd
);
1660 return uffd_change_protection(uffd_fd
, rb
->host
,
1661 rb
->used_length
, true, false);
1665 * ram_write_tracking_start: start UFFD-WP memory tracking
1667 * Returns 0 for success or negative value in case of error
1669 int ram_write_tracking_start(void)
1672 RAMState
*rs
= ram_state
;
1675 /* Open UFFD file descriptor */
1676 uffd_fd
= uffd_create_fd(UFFD_FEATURE_PAGEFAULT_FLAG_WP
, true);
1680 rs
->uffdio_fd
= uffd_fd
;
1682 RCU_READ_LOCK_GUARD();
1684 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1685 /* Nothing to do with read-only and MMIO-writable regions */
1686 if (block
->mr
->readonly
|| block
->mr
->rom_device
) {
1690 /* Register block memory with UFFD to track writes */
1691 if (uffd_register_memory(rs
->uffdio_fd
, block
->host
,
1692 block
->max_length
, UFFDIO_REGISTER_MODE_WP
, NULL
)) {
1695 block
->flags
|= RAM_UF_WRITEPROTECT
;
1696 memory_region_ref(block
->mr
);
1698 /* Apply UFFD write protection to the block memory range */
1699 if (ram_block_uffd_protect(block
, uffd_fd
)) {
1703 trace_ram_write_tracking_ramblock_start(block
->idstr
, block
->page_size
,
1704 block
->host
, block
->max_length
);
1710 error_report("ram_write_tracking_start() failed: restoring initial memory state");
1712 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1713 if ((block
->flags
& RAM_UF_WRITEPROTECT
) == 0) {
1716 uffd_unregister_memory(rs
->uffdio_fd
, block
->host
, block
->max_length
);
1717 /* Cleanup flags and remove reference */
1718 block
->flags
&= ~RAM_UF_WRITEPROTECT
;
1719 memory_region_unref(block
->mr
);
1722 uffd_close_fd(uffd_fd
);
1728 * ram_write_tracking_stop: stop UFFD-WP memory tracking and remove protection
1730 void ram_write_tracking_stop(void)
1732 RAMState
*rs
= ram_state
;
1735 RCU_READ_LOCK_GUARD();
1737 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1738 if ((block
->flags
& RAM_UF_WRITEPROTECT
) == 0) {
1741 uffd_unregister_memory(rs
->uffdio_fd
, block
->host
, block
->max_length
);
1743 trace_ram_write_tracking_ramblock_stop(block
->idstr
, block
->page_size
,
1744 block
->host
, block
->max_length
);
1746 /* Cleanup flags and remove reference */
1747 block
->flags
&= ~RAM_UF_WRITEPROTECT
;
1748 memory_region_unref(block
->mr
);
1751 /* Finally close UFFD file descriptor */
1752 uffd_close_fd(rs
->uffdio_fd
);
1757 /* No target OS support, stubs just fail or ignore */
1759 static RAMBlock
*poll_fault_page(RAMState
*rs
, ram_addr_t
*offset
)
1767 static int ram_save_release_protection(RAMState
*rs
, PageSearchStatus
*pss
,
1768 unsigned long start_page
)
1777 bool ram_write_tracking_available(void)
1782 bool ram_write_tracking_compatible(void)
1788 int ram_write_tracking_start(void)
1794 void ram_write_tracking_stop(void)
1798 #endif /* defined(__linux__) */
1801 * get_queued_page: unqueue a page from the postcopy requests
1803 * Skips pages that are already sent (!dirty)
1805 * Returns true if a queued page is found
1807 * @rs: current RAM state
1808 * @pss: data about the state of the current dirty page scan
1810 static bool get_queued_page(RAMState
*rs
, PageSearchStatus
*pss
)
1817 block
= unqueue_page(rs
, &offset
);
1819 * We're sending this page, and since it's postcopy nothing else
1820 * will dirty it, and we must make sure it doesn't get sent again
1821 * even if this queue request was received after the background
1822 * search already sent it.
1827 page
= offset
>> TARGET_PAGE_BITS
;
1828 dirty
= test_bit(page
, block
->bmap
);
1830 trace_get_queued_page_not_dirty(block
->idstr
, (uint64_t)offset
,
1833 trace_get_queued_page(block
->idstr
, (uint64_t)offset
, page
);
1837 } while (block
&& !dirty
);
1841 * Poll write faults too if background snapshot is enabled; that's
1842 * when we have vcpus got blocked by the write protected pages.
1844 block
= poll_fault_page(rs
, &offset
);
1849 * We want the background search to continue from the queued page
1850 * since the guest is likely to want other pages near to the page
1851 * it just requested.
1854 pss
->page
= offset
>> TARGET_PAGE_BITS
;
1857 * This unqueued page would break the "one round" check, even is
1860 pss
->complete_round
= false;
1867 * migration_page_queue_free: drop any remaining pages in the ram
1870 * It should be empty at the end anyway, but in error cases there may
1871 * be some left. in case that there is any page left, we drop it.
1874 static void migration_page_queue_free(RAMState
*rs
)
1876 struct RAMSrcPageRequest
*mspr
, *next_mspr
;
1877 /* This queue generally should be empty - but in the case of a failed
1878 * migration might have some droppings in.
1880 RCU_READ_LOCK_GUARD();
1881 QSIMPLEQ_FOREACH_SAFE(mspr
, &rs
->src_page_requests
, next_req
, next_mspr
) {
1882 memory_region_unref(mspr
->rb
->mr
);
1883 QSIMPLEQ_REMOVE_HEAD(&rs
->src_page_requests
, next_req
);
1889 * ram_save_queue_pages: queue the page for transmission
1891 * A request from postcopy destination for example.
1893 * Returns zero on success or negative on error
1895 * @rbname: Name of the RAMBLock of the request. NULL means the
1896 * same that last one.
1897 * @start: starting address from the start of the RAMBlock
1898 * @len: length (in bytes) to send
1900 int ram_save_queue_pages(const char *rbname
, ram_addr_t start
, ram_addr_t len
,
1904 RAMState
*rs
= ram_state
;
1906 stat64_add(&mig_stats
.postcopy_requests
, 1);
1907 RCU_READ_LOCK_GUARD();
1910 /* Reuse last RAMBlock */
1911 ramblock
= rs
->last_req_rb
;
1915 * Shouldn't happen, we can't reuse the last RAMBlock if
1916 * it's the 1st request.
1918 error_setg(errp
, "MIG_RP_MSG_REQ_PAGES has no previous block");
1922 ramblock
= qemu_ram_block_by_name(rbname
);
1925 /* We shouldn't be asked for a non-existent RAMBlock */
1926 error_setg(errp
, "MIG_RP_MSG_REQ_PAGES has no block '%s'", rbname
);
1929 rs
->last_req_rb
= ramblock
;
1931 trace_ram_save_queue_pages(ramblock
->idstr
, start
, len
);
1932 if (!offset_in_ramblock(ramblock
, start
+ len
- 1)) {
1933 error_setg(errp
, "MIG_RP_MSG_REQ_PAGES request overrun, "
1934 "start=" RAM_ADDR_FMT
" len="
1935 RAM_ADDR_FMT
" blocklen=" RAM_ADDR_FMT
,
1936 start
, len
, ramblock
->used_length
);
1941 * When with postcopy preempt, we send back the page directly in the
1944 if (postcopy_preempt_active()) {
1945 ram_addr_t page_start
= start
>> TARGET_PAGE_BITS
;
1946 size_t page_size
= qemu_ram_pagesize(ramblock
);
1947 PageSearchStatus
*pss
= &ram_state
->pss
[RAM_CHANNEL_POSTCOPY
];
1950 qemu_mutex_lock(&rs
->bitmap_mutex
);
1952 pss_init(pss
, ramblock
, page_start
);
1954 * Always use the preempt channel, and make sure it's there. It's
1955 * safe to access without lock, because when rp-thread is running
1956 * we should be the only one who operates on the qemufile
1958 pss
->pss_channel
= migrate_get_current()->postcopy_qemufile_src
;
1959 assert(pss
->pss_channel
);
1962 * It must be either one or multiple of host page size. Just
1963 * assert; if something wrong we're mostly split brain anyway.
1965 assert(len
% page_size
== 0);
1967 if (ram_save_host_page_urgent(pss
)) {
1968 error_setg(errp
, "ram_save_host_page_urgent() failed: "
1969 "ramblock=%s, start_addr=0x"RAM_ADDR_FMT
,
1970 ramblock
->idstr
, start
);
1975 * NOTE: after ram_save_host_page_urgent() succeeded, pss->page
1976 * will automatically be moved and point to the next host page
1977 * we're going to send, so no need to update here.
1979 * Normally QEMU never sends >1 host page in requests, so
1980 * logically we don't even need that as the loop should only
1981 * run once, but just to be consistent.
1985 qemu_mutex_unlock(&rs
->bitmap_mutex
);
1990 struct RAMSrcPageRequest
*new_entry
=
1991 g_new0(struct RAMSrcPageRequest
, 1);
1992 new_entry
->rb
= ramblock
;
1993 new_entry
->offset
= start
;
1994 new_entry
->len
= len
;
1996 memory_region_ref(ramblock
->mr
);
1997 qemu_mutex_lock(&rs
->src_page_req_mutex
);
1998 QSIMPLEQ_INSERT_TAIL(&rs
->src_page_requests
, new_entry
, next_req
);
1999 migration_make_urgent_request();
2000 qemu_mutex_unlock(&rs
->src_page_req_mutex
);
2006 * try to compress the page before posting it out, return true if the page
2007 * has been properly handled by compression, otherwise needs other
2008 * paths to handle it
2010 static bool save_compress_page(RAMState
*rs
, PageSearchStatus
*pss
,
2013 if (!migrate_compress()) {
2018 * When starting the process of a new block, the first page of
2019 * the block should be sent out before other pages in the same
2020 * block, and all the pages in last block should have been sent
2021 * out, keeping this order is important, because the 'cont' flag
2022 * is used to avoid resending the block name.
2024 * We post the fist page as normal page as compression will take
2025 * much CPU resource.
2027 if (pss
->block
!= pss
->last_sent_block
) {
2028 compress_flush_data();
2032 return compress_page_with_multi_thread(pss
->block
, offset
,
2033 compress_send_queued_data
);
2037 * ram_save_target_page_legacy: save one target page
2039 * Returns the number of pages written
2041 * @rs: current RAM state
2042 * @pss: data about the page we want to send
2044 static int ram_save_target_page_legacy(RAMState
*rs
, PageSearchStatus
*pss
)
2046 RAMBlock
*block
= pss
->block
;
2047 ram_addr_t offset
= ((ram_addr_t
)pss
->page
) << TARGET_PAGE_BITS
;
2050 if (control_save_page(pss
, offset
, &res
)) {
2054 if (save_compress_page(rs
, pss
, offset
)) {
2058 if (save_zero_page(rs
, pss
, offset
)) {
2063 * Do not use multifd in postcopy as one whole host page should be
2064 * placed. Meanwhile postcopy requires atomic update of pages, so even
2065 * if host page size == guest page size the dest guest during run may
2066 * still see partially copied pages which is data corruption.
2068 if (migrate_multifd() && !migration_in_postcopy()) {
2069 return ram_save_multifd_page(block
, offset
);
2072 return ram_save_page(rs
, pss
);
2075 /* Should be called before sending a host page */
2076 static void pss_host_page_prepare(PageSearchStatus
*pss
)
2078 /* How many guest pages are there in one host page? */
2079 size_t guest_pfns
= qemu_ram_pagesize(pss
->block
) >> TARGET_PAGE_BITS
;
2081 pss
->host_page_sending
= true;
2082 if (guest_pfns
<= 1) {
2084 * This covers both when guest psize == host psize, or when guest
2085 * has larger psize than the host (guest_pfns==0).
2087 * For the latter, we always send one whole guest page per
2088 * iteration of the host page (example: an Alpha VM on x86 host
2089 * will have guest psize 8K while host psize 4K).
2091 pss
->host_page_start
= pss
->page
;
2092 pss
->host_page_end
= pss
->page
+ 1;
2095 * The host page spans over multiple guest pages, we send them
2096 * within the same host page iteration.
2098 pss
->host_page_start
= ROUND_DOWN(pss
->page
, guest_pfns
);
2099 pss
->host_page_end
= ROUND_UP(pss
->page
+ 1, guest_pfns
);
2104 * Whether the page pointed by PSS is within the host page being sent.
2105 * Must be called after a previous pss_host_page_prepare().
2107 static bool pss_within_range(PageSearchStatus
*pss
)
2109 ram_addr_t ram_addr
;
2111 assert(pss
->host_page_sending
);
2113 /* Over host-page boundary? */
2114 if (pss
->page
>= pss
->host_page_end
) {
2118 ram_addr
= ((ram_addr_t
)pss
->page
) << TARGET_PAGE_BITS
;
2120 return offset_in_ramblock(pss
->block
, ram_addr
);
2123 static void pss_host_page_finish(PageSearchStatus
*pss
)
2125 pss
->host_page_sending
= false;
2126 /* This is not needed, but just to reset it */
2127 pss
->host_page_start
= pss
->host_page_end
= 0;
2131 * Send an urgent host page specified by `pss'. Need to be called with
2132 * bitmap_mutex held.
2134 * Returns 0 if save host page succeeded, false otherwise.
2136 static int ram_save_host_page_urgent(PageSearchStatus
*pss
)
2138 bool page_dirty
, sent
= false;
2139 RAMState
*rs
= ram_state
;
2142 trace_postcopy_preempt_send_host_page(pss
->block
->idstr
, pss
->page
);
2143 pss_host_page_prepare(pss
);
2146 * If precopy is sending the same page, let it be done in precopy, or
2147 * we could send the same page in two channels and none of them will
2148 * receive the whole page.
2150 if (pss_overlap(pss
, &ram_state
->pss
[RAM_CHANNEL_PRECOPY
])) {
2151 trace_postcopy_preempt_hit(pss
->block
->idstr
,
2152 pss
->page
<< TARGET_PAGE_BITS
);
2157 page_dirty
= migration_bitmap_clear_dirty(rs
, pss
->block
, pss
->page
);
2160 /* Be strict to return code; it must be 1, or what else? */
2161 if (migration_ops
->ram_save_target_page(rs
, pss
) != 1) {
2162 error_report_once("%s: ram_save_target_page failed", __func__
);
2168 pss_find_next_dirty(pss
);
2169 } while (pss_within_range(pss
));
2171 pss_host_page_finish(pss
);
2172 /* For urgent requests, flush immediately if sent */
2174 qemu_fflush(pss
->pss_channel
);
2180 * ram_save_host_page: save a whole host page
2182 * Starting at *offset send pages up to the end of the current host
2183 * page. It's valid for the initial offset to point into the middle of
2184 * a host page in which case the remainder of the hostpage is sent.
2185 * Only dirty target pages are sent. Note that the host page size may
2186 * be a huge page for this block.
2188 * The saving stops at the boundary of the used_length of the block
2189 * if the RAMBlock isn't a multiple of the host page size.
2191 * The caller must be with ram_state.bitmap_mutex held to call this
2192 * function. Note that this function can temporarily release the lock, but
2193 * when the function is returned it'll make sure the lock is still held.
2195 * Returns the number of pages written or negative on error
2197 * @rs: current RAM state
2198 * @pss: data about the page we want to send
2200 static int ram_save_host_page(RAMState
*rs
, PageSearchStatus
*pss
)
2202 bool page_dirty
, preempt_active
= postcopy_preempt_active();
2203 int tmppages
, pages
= 0;
2204 size_t pagesize_bits
=
2205 qemu_ram_pagesize(pss
->block
) >> TARGET_PAGE_BITS
;
2206 unsigned long start_page
= pss
->page
;
2209 if (migrate_ram_is_ignored(pss
->block
)) {
2210 error_report("block %s should not be migrated !", pss
->block
->idstr
);
2214 /* Update host page boundary information */
2215 pss_host_page_prepare(pss
);
2218 page_dirty
= migration_bitmap_clear_dirty(rs
, pss
->block
, pss
->page
);
2220 /* Check the pages is dirty and if it is send it */
2223 * Properly yield the lock only in postcopy preempt mode
2224 * because both migration thread and rp-return thread can
2225 * operate on the bitmaps.
2227 if (preempt_active
) {
2228 qemu_mutex_unlock(&rs
->bitmap_mutex
);
2230 tmppages
= migration_ops
->ram_save_target_page(rs
, pss
);
2231 if (tmppages
>= 0) {
2234 * Allow rate limiting to happen in the middle of huge pages if
2235 * something is sent in the current iteration.
2237 if (pagesize_bits
> 1 && tmppages
> 0) {
2238 migration_rate_limit();
2241 if (preempt_active
) {
2242 qemu_mutex_lock(&rs
->bitmap_mutex
);
2249 pss_host_page_finish(pss
);
2253 pss_find_next_dirty(pss
);
2254 } while (pss_within_range(pss
));
2256 pss_host_page_finish(pss
);
2258 res
= ram_save_release_protection(rs
, pss
, start_page
);
2259 return (res
< 0 ? res
: pages
);
2263 * ram_find_and_save_block: finds a dirty page and sends it to f
2265 * Called within an RCU critical section.
2267 * Returns the number of pages written where zero means no dirty pages,
2268 * or negative on error
2270 * @rs: current RAM state
2272 * On systems where host-page-size > target-page-size it will send all the
2273 * pages in a host page that are dirty.
2275 static int ram_find_and_save_block(RAMState
*rs
)
2277 PageSearchStatus
*pss
= &rs
->pss
[RAM_CHANNEL_PRECOPY
];
2280 /* No dirty page as there is zero RAM */
2281 if (!rs
->ram_bytes_total
) {
2286 * Always keep last_seen_block/last_page valid during this procedure,
2287 * because find_dirty_block() relies on these values (e.g., we compare
2288 * last_seen_block with pss.block to see whether we searched all the
2289 * ramblocks) to detect the completion of migration. Having NULL value
2290 * of last_seen_block can conditionally cause below loop to run forever.
2292 if (!rs
->last_seen_block
) {
2293 rs
->last_seen_block
= QLIST_FIRST_RCU(&ram_list
.blocks
);
2297 pss_init(pss
, rs
->last_seen_block
, rs
->last_page
);
2300 if (!get_queued_page(rs
, pss
)) {
2301 /* priority queue empty, so just search for something dirty */
2302 int res
= find_dirty_block(rs
, pss
);
2303 if (res
!= PAGE_DIRTY_FOUND
) {
2304 if (res
== PAGE_ALL_CLEAN
) {
2306 } else if (res
== PAGE_TRY_AGAIN
) {
2308 } else if (res
< 0) {
2314 pages
= ram_save_host_page(rs
, pss
);
2320 rs
->last_seen_block
= pss
->block
;
2321 rs
->last_page
= pss
->page
;
2326 static uint64_t ram_bytes_total_with_ignored(void)
2331 RCU_READ_LOCK_GUARD();
2333 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
2334 total
+= block
->used_length
;
2339 uint64_t ram_bytes_total(void)
2344 RCU_READ_LOCK_GUARD();
2346 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2347 total
+= block
->used_length
;
2352 static void xbzrle_load_setup(void)
2354 XBZRLE
.decoded_buf
= g_malloc(TARGET_PAGE_SIZE
);
2357 static void xbzrle_load_cleanup(void)
2359 g_free(XBZRLE
.decoded_buf
);
2360 XBZRLE
.decoded_buf
= NULL
;
2363 static void ram_state_cleanup(RAMState
**rsp
)
2366 migration_page_queue_free(*rsp
);
2367 qemu_mutex_destroy(&(*rsp
)->bitmap_mutex
);
2368 qemu_mutex_destroy(&(*rsp
)->src_page_req_mutex
);
2374 static void xbzrle_cleanup(void)
2376 XBZRLE_cache_lock();
2378 cache_fini(XBZRLE
.cache
);
2379 g_free(XBZRLE
.encoded_buf
);
2380 g_free(XBZRLE
.current_buf
);
2381 g_free(XBZRLE
.zero_target_page
);
2382 XBZRLE
.cache
= NULL
;
2383 XBZRLE
.encoded_buf
= NULL
;
2384 XBZRLE
.current_buf
= NULL
;
2385 XBZRLE
.zero_target_page
= NULL
;
2387 XBZRLE_cache_unlock();
2390 static void ram_save_cleanup(void *opaque
)
2392 RAMState
**rsp
= opaque
;
2395 /* We don't use dirty log with background snapshots */
2396 if (!migrate_background_snapshot()) {
2397 /* caller have hold BQL or is in a bh, so there is
2398 * no writing race against the migration bitmap
2400 if (global_dirty_tracking
& GLOBAL_DIRTY_MIGRATION
) {
2402 * do not stop dirty log without starting it, since
2403 * memory_global_dirty_log_stop will assert that
2404 * memory_global_dirty_log_start/stop used in pairs
2406 memory_global_dirty_log_stop(GLOBAL_DIRTY_MIGRATION
);
2410 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2411 g_free(block
->clear_bmap
);
2412 block
->clear_bmap
= NULL
;
2413 g_free(block
->bmap
);
2418 compress_threads_save_cleanup();
2419 ram_state_cleanup(rsp
);
2420 g_free(migration_ops
);
2421 migration_ops
= NULL
;
2424 static void ram_state_reset(RAMState
*rs
)
2428 for (i
= 0; i
< RAM_CHANNEL_MAX
; i
++) {
2429 rs
->pss
[i
].last_sent_block
= NULL
;
2432 rs
->last_seen_block
= NULL
;
2434 rs
->last_version
= ram_list
.version
;
2435 rs
->xbzrle_started
= false;
2438 #define MAX_WAIT 50 /* ms, half buffered_file limit */
2440 /* **** functions for postcopy ***** */
2442 void ram_postcopy_migrated_memory_release(MigrationState
*ms
)
2444 struct RAMBlock
*block
;
2446 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2447 unsigned long *bitmap
= block
->bmap
;
2448 unsigned long range
= block
->used_length
>> TARGET_PAGE_BITS
;
2449 unsigned long run_start
= find_next_zero_bit(bitmap
, range
, 0);
2451 while (run_start
< range
) {
2452 unsigned long run_end
= find_next_bit(bitmap
, range
, run_start
+ 1);
2453 ram_discard_range(block
->idstr
,
2454 ((ram_addr_t
)run_start
) << TARGET_PAGE_BITS
,
2455 ((ram_addr_t
)(run_end
- run_start
))
2456 << TARGET_PAGE_BITS
);
2457 run_start
= find_next_zero_bit(bitmap
, range
, run_end
+ 1);
2463 * postcopy_send_discard_bm_ram: discard a RAMBlock
2465 * Callback from postcopy_each_ram_send_discard for each RAMBlock
2467 * @ms: current migration state
2468 * @block: RAMBlock to discard
2470 static void postcopy_send_discard_bm_ram(MigrationState
*ms
, RAMBlock
*block
)
2472 unsigned long end
= block
->used_length
>> TARGET_PAGE_BITS
;
2473 unsigned long current
;
2474 unsigned long *bitmap
= block
->bmap
;
2476 for (current
= 0; current
< end
; ) {
2477 unsigned long one
= find_next_bit(bitmap
, end
, current
);
2478 unsigned long zero
, discard_length
;
2484 zero
= find_next_zero_bit(bitmap
, end
, one
+ 1);
2487 discard_length
= end
- one
;
2489 discard_length
= zero
- one
;
2491 postcopy_discard_send_range(ms
, one
, discard_length
);
2492 current
= one
+ discard_length
;
2496 static void postcopy_chunk_hostpages_pass(MigrationState
*ms
, RAMBlock
*block
);
2499 * postcopy_each_ram_send_discard: discard all RAMBlocks
2501 * Utility for the outgoing postcopy code.
2502 * Calls postcopy_send_discard_bm_ram for each RAMBlock
2503 * passing it bitmap indexes and name.
2504 * (qemu_ram_foreach_block ends up passing unscaled lengths
2505 * which would mean postcopy code would have to deal with target page)
2507 * @ms: current migration state
2509 static void postcopy_each_ram_send_discard(MigrationState
*ms
)
2511 struct RAMBlock
*block
;
2513 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2514 postcopy_discard_send_init(ms
, block
->idstr
);
2517 * Deal with TPS != HPS and huge pages. It discard any partially sent
2518 * host-page size chunks, mark any partially dirty host-page size
2519 * chunks as all dirty. In this case the host-page is the host-page
2520 * for the particular RAMBlock, i.e. it might be a huge page.
2522 postcopy_chunk_hostpages_pass(ms
, block
);
2525 * Postcopy sends chunks of bitmap over the wire, but it
2526 * just needs indexes at this point, avoids it having
2527 * target page specific code.
2529 postcopy_send_discard_bm_ram(ms
, block
);
2530 postcopy_discard_send_finish(ms
);
2535 * postcopy_chunk_hostpages_pass: canonicalize bitmap in hostpages
2537 * Helper for postcopy_chunk_hostpages; it's called twice to
2538 * canonicalize the two bitmaps, that are similar, but one is
2541 * Postcopy requires that all target pages in a hostpage are dirty or
2542 * clean, not a mix. This function canonicalizes the bitmaps.
2544 * @ms: current migration state
2545 * @block: block that contains the page we want to canonicalize
2547 static void postcopy_chunk_hostpages_pass(MigrationState
*ms
, RAMBlock
*block
)
2549 RAMState
*rs
= ram_state
;
2550 unsigned long *bitmap
= block
->bmap
;
2551 unsigned int host_ratio
= block
->page_size
/ TARGET_PAGE_SIZE
;
2552 unsigned long pages
= block
->used_length
>> TARGET_PAGE_BITS
;
2553 unsigned long run_start
;
2555 if (block
->page_size
== TARGET_PAGE_SIZE
) {
2556 /* Easy case - TPS==HPS for a non-huge page RAMBlock */
2560 /* Find a dirty page */
2561 run_start
= find_next_bit(bitmap
, pages
, 0);
2563 while (run_start
< pages
) {
2566 * If the start of this run of pages is in the middle of a host
2567 * page, then we need to fixup this host page.
2569 if (QEMU_IS_ALIGNED(run_start
, host_ratio
)) {
2570 /* Find the end of this run */
2571 run_start
= find_next_zero_bit(bitmap
, pages
, run_start
+ 1);
2573 * If the end isn't at the start of a host page, then the
2574 * run doesn't finish at the end of a host page
2575 * and we need to discard.
2579 if (!QEMU_IS_ALIGNED(run_start
, host_ratio
)) {
2581 unsigned long fixup_start_addr
= QEMU_ALIGN_DOWN(run_start
,
2583 run_start
= QEMU_ALIGN_UP(run_start
, host_ratio
);
2585 /* Clean up the bitmap */
2586 for (page
= fixup_start_addr
;
2587 page
< fixup_start_addr
+ host_ratio
; page
++) {
2589 * Remark them as dirty, updating the count for any pages
2590 * that weren't previously dirty.
2592 rs
->migration_dirty_pages
+= !test_and_set_bit(page
, bitmap
);
2596 /* Find the next dirty page for the next iteration */
2597 run_start
= find_next_bit(bitmap
, pages
, run_start
);
2602 * ram_postcopy_send_discard_bitmap: transmit the discard bitmap
2604 * Transmit the set of pages to be discarded after precopy to the target
2605 * these are pages that:
2606 * a) Have been previously transmitted but are now dirty again
2607 * b) Pages that have never been transmitted, this ensures that
2608 * any pages on the destination that have been mapped by background
2609 * tasks get discarded (transparent huge pages is the specific concern)
2610 * Hopefully this is pretty sparse
2612 * @ms: current migration state
2614 void ram_postcopy_send_discard_bitmap(MigrationState
*ms
)
2616 RAMState
*rs
= ram_state
;
2618 RCU_READ_LOCK_GUARD();
2620 /* This should be our last sync, the src is now paused */
2621 migration_bitmap_sync(rs
, false);
2623 /* Easiest way to make sure we don't resume in the middle of a host-page */
2624 rs
->pss
[RAM_CHANNEL_PRECOPY
].last_sent_block
= NULL
;
2625 rs
->last_seen_block
= NULL
;
2628 postcopy_each_ram_send_discard(ms
);
2630 trace_ram_postcopy_send_discard_bitmap();
2634 * ram_discard_range: discard dirtied pages at the beginning of postcopy
2636 * Returns zero on success
2638 * @rbname: name of the RAMBlock of the request. NULL means the
2639 * same that last one.
2640 * @start: RAMBlock starting page
2641 * @length: RAMBlock size
2643 int ram_discard_range(const char *rbname
, uint64_t start
, size_t length
)
2645 trace_ram_discard_range(rbname
, start
, length
);
2647 RCU_READ_LOCK_GUARD();
2648 RAMBlock
*rb
= qemu_ram_block_by_name(rbname
);
2651 error_report("ram_discard_range: Failed to find block '%s'", rbname
);
2656 * On source VM, we don't need to update the received bitmap since
2657 * we don't even have one.
2659 if (rb
->receivedmap
) {
2660 bitmap_clear(rb
->receivedmap
, start
>> qemu_target_page_bits(),
2661 length
>> qemu_target_page_bits());
2664 return ram_block_discard_range(rb
, start
, length
);
2668 * For every allocation, we will try not to crash the VM if the
2669 * allocation failed.
2671 static int xbzrle_init(void)
2673 Error
*local_err
= NULL
;
2675 if (!migrate_xbzrle()) {
2679 XBZRLE_cache_lock();
2681 XBZRLE
.zero_target_page
= g_try_malloc0(TARGET_PAGE_SIZE
);
2682 if (!XBZRLE
.zero_target_page
) {
2683 error_report("%s: Error allocating zero page", __func__
);
2687 XBZRLE
.cache
= cache_init(migrate_xbzrle_cache_size(),
2688 TARGET_PAGE_SIZE
, &local_err
);
2689 if (!XBZRLE
.cache
) {
2690 error_report_err(local_err
);
2691 goto free_zero_page
;
2694 XBZRLE
.encoded_buf
= g_try_malloc0(TARGET_PAGE_SIZE
);
2695 if (!XBZRLE
.encoded_buf
) {
2696 error_report("%s: Error allocating encoded_buf", __func__
);
2700 XBZRLE
.current_buf
= g_try_malloc(TARGET_PAGE_SIZE
);
2701 if (!XBZRLE
.current_buf
) {
2702 error_report("%s: Error allocating current_buf", __func__
);
2703 goto free_encoded_buf
;
2706 /* We are all good */
2707 XBZRLE_cache_unlock();
2711 g_free(XBZRLE
.encoded_buf
);
2712 XBZRLE
.encoded_buf
= NULL
;
2714 cache_fini(XBZRLE
.cache
);
2715 XBZRLE
.cache
= NULL
;
2717 g_free(XBZRLE
.zero_target_page
);
2718 XBZRLE
.zero_target_page
= NULL
;
2720 XBZRLE_cache_unlock();
2724 static int ram_state_init(RAMState
**rsp
)
2726 *rsp
= g_try_new0(RAMState
, 1);
2729 error_report("%s: Init ramstate fail", __func__
);
2733 qemu_mutex_init(&(*rsp
)->bitmap_mutex
);
2734 qemu_mutex_init(&(*rsp
)->src_page_req_mutex
);
2735 QSIMPLEQ_INIT(&(*rsp
)->src_page_requests
);
2736 (*rsp
)->ram_bytes_total
= ram_bytes_total();
2739 * Count the total number of pages used by ram blocks not including any
2740 * gaps due to alignment or unplugs.
2741 * This must match with the initial values of dirty bitmap.
2743 (*rsp
)->migration_dirty_pages
= (*rsp
)->ram_bytes_total
>> TARGET_PAGE_BITS
;
2744 ram_state_reset(*rsp
);
2749 static void ram_list_init_bitmaps(void)
2751 MigrationState
*ms
= migrate_get_current();
2753 unsigned long pages
;
2756 /* Skip setting bitmap if there is no RAM */
2757 if (ram_bytes_total()) {
2758 shift
= ms
->clear_bitmap_shift
;
2759 if (shift
> CLEAR_BITMAP_SHIFT_MAX
) {
2760 error_report("clear_bitmap_shift (%u) too big, using "
2761 "max value (%u)", shift
, CLEAR_BITMAP_SHIFT_MAX
);
2762 shift
= CLEAR_BITMAP_SHIFT_MAX
;
2763 } else if (shift
< CLEAR_BITMAP_SHIFT_MIN
) {
2764 error_report("clear_bitmap_shift (%u) too small, using "
2765 "min value (%u)", shift
, CLEAR_BITMAP_SHIFT_MIN
);
2766 shift
= CLEAR_BITMAP_SHIFT_MIN
;
2769 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2770 pages
= block
->max_length
>> TARGET_PAGE_BITS
;
2772 * The initial dirty bitmap for migration must be set with all
2773 * ones to make sure we'll migrate every guest RAM page to
2775 * Here we set RAMBlock.bmap all to 1 because when rebegin a
2776 * new migration after a failed migration, ram_list.
2777 * dirty_memory[DIRTY_MEMORY_MIGRATION] don't include the whole
2780 block
->bmap
= bitmap_new(pages
);
2781 bitmap_set(block
->bmap
, 0, pages
);
2782 block
->clear_bmap_shift
= shift
;
2783 block
->clear_bmap
= bitmap_new(clear_bmap_size(pages
, shift
));
2788 static void migration_bitmap_clear_discarded_pages(RAMState
*rs
)
2790 unsigned long pages
;
2793 RCU_READ_LOCK_GUARD();
2795 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
2796 pages
= ramblock_dirty_bitmap_clear_discarded_pages(rb
);
2797 rs
->migration_dirty_pages
-= pages
;
2801 static void ram_init_bitmaps(RAMState
*rs
)
2803 qemu_mutex_lock_ramlist();
2805 WITH_RCU_READ_LOCK_GUARD() {
2806 ram_list_init_bitmaps();
2807 /* We don't use dirty log with background snapshots */
2808 if (!migrate_background_snapshot()) {
2809 memory_global_dirty_log_start(GLOBAL_DIRTY_MIGRATION
);
2810 migration_bitmap_sync_precopy(rs
, false);
2813 qemu_mutex_unlock_ramlist();
2816 * After an eventual first bitmap sync, fixup the initial bitmap
2817 * containing all 1s to exclude any discarded pages from migration.
2819 migration_bitmap_clear_discarded_pages(rs
);
2822 static int ram_init_all(RAMState
**rsp
)
2824 if (ram_state_init(rsp
)) {
2828 if (xbzrle_init()) {
2829 ram_state_cleanup(rsp
);
2833 ram_init_bitmaps(*rsp
);
2838 static void ram_state_resume_prepare(RAMState
*rs
, QEMUFile
*out
)
2844 * Postcopy is not using xbzrle/compression, so no need for that.
2845 * Also, since source are already halted, we don't need to care
2846 * about dirty page logging as well.
2849 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2850 pages
+= bitmap_count_one(block
->bmap
,
2851 block
->used_length
>> TARGET_PAGE_BITS
);
2854 /* This may not be aligned with current bitmaps. Recalculate. */
2855 rs
->migration_dirty_pages
= pages
;
2857 ram_state_reset(rs
);
2859 /* Update RAMState cache of output QEMUFile */
2860 rs
->pss
[RAM_CHANNEL_PRECOPY
].pss_channel
= out
;
2862 trace_ram_state_resume_prepare(pages
);
2866 * This function clears bits of the free pages reported by the caller from the
2867 * migration dirty bitmap. @addr is the host address corresponding to the
2868 * start of the continuous guest free pages, and @len is the total bytes of
2871 void qemu_guest_free_page_hint(void *addr
, size_t len
)
2875 size_t used_len
, start
, npages
;
2876 MigrationState
*s
= migrate_get_current();
2878 /* This function is currently expected to be used during live migration */
2879 if (!migration_is_setup_or_active(s
->state
)) {
2883 for (; len
> 0; len
-= used_len
, addr
+= used_len
) {
2884 block
= qemu_ram_block_from_host(addr
, false, &offset
);
2885 if (unlikely(!block
|| offset
>= block
->used_length
)) {
2887 * The implementation might not support RAMBlock resize during
2888 * live migration, but it could happen in theory with future
2889 * updates. So we add a check here to capture that case.
2891 error_report_once("%s unexpected error", __func__
);
2895 if (len
<= block
->used_length
- offset
) {
2898 used_len
= block
->used_length
- offset
;
2901 start
= offset
>> TARGET_PAGE_BITS
;
2902 npages
= used_len
>> TARGET_PAGE_BITS
;
2904 qemu_mutex_lock(&ram_state
->bitmap_mutex
);
2906 * The skipped free pages are equavalent to be sent from clear_bmap's
2907 * perspective, so clear the bits from the memory region bitmap which
2908 * are initially set. Otherwise those skipped pages will be sent in
2909 * the next round after syncing from the memory region bitmap.
2911 migration_clear_memory_region_dirty_bitmap_range(block
, start
, npages
);
2912 ram_state
->migration_dirty_pages
-=
2913 bitmap_count_one_with_offset(block
->bmap
, start
, npages
);
2914 bitmap_clear(block
->bmap
, start
, npages
);
2915 qemu_mutex_unlock(&ram_state
->bitmap_mutex
);
2920 * Each of ram_save_setup, ram_save_iterate and ram_save_complete has
2921 * long-running RCU critical section. When rcu-reclaims in the code
2922 * start to become numerous it will be necessary to reduce the
2923 * granularity of these critical sections.
2927 * ram_save_setup: Setup RAM for migration
2929 * Returns zero to indicate success and negative for error
2931 * @f: QEMUFile where to send the data
2932 * @opaque: RAMState pointer
2934 static int ram_save_setup(QEMUFile
*f
, void *opaque
)
2936 RAMState
**rsp
= opaque
;
2940 if (compress_threads_save_setup()) {
2944 /* migration has already setup the bitmap, reuse it. */
2945 if (!migration_in_colo_state()) {
2946 if (ram_init_all(rsp
) != 0) {
2947 compress_threads_save_cleanup();
2951 (*rsp
)->pss
[RAM_CHANNEL_PRECOPY
].pss_channel
= f
;
2953 WITH_RCU_READ_LOCK_GUARD() {
2954 qemu_put_be64(f
, ram_bytes_total_with_ignored()
2955 | RAM_SAVE_FLAG_MEM_SIZE
);
2957 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
2958 qemu_put_byte(f
, strlen(block
->idstr
));
2959 qemu_put_buffer(f
, (uint8_t *)block
->idstr
, strlen(block
->idstr
));
2960 qemu_put_be64(f
, block
->used_length
);
2961 if (migrate_postcopy_ram() && block
->page_size
!=
2962 qemu_host_page_size
) {
2963 qemu_put_be64(f
, block
->page_size
);
2965 if (migrate_ignore_shared()) {
2966 qemu_put_be64(f
, block
->mr
->addr
);
2971 ret
= rdma_registration_start(f
, RAM_CONTROL_SETUP
);
2973 qemu_file_set_error(f
, ret
);
2977 ret
= rdma_registration_stop(f
, RAM_CONTROL_SETUP
);
2979 qemu_file_set_error(f
, ret
);
2983 migration_ops
= g_malloc0(sizeof(MigrationOps
));
2984 migration_ops
->ram_save_target_page
= ram_save_target_page_legacy
;
2987 ret
= multifd_send_sync_main();
2993 if (migrate_multifd() && !migrate_multifd_flush_after_each_section()) {
2994 qemu_put_be64(f
, RAM_SAVE_FLAG_MULTIFD_FLUSH
);
2997 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
2998 return qemu_fflush(f
);
3002 * ram_save_iterate: iterative stage for migration
3004 * Returns zero to indicate success and negative for error
3006 * @f: QEMUFile where to send the data
3007 * @opaque: RAMState pointer
3009 static int ram_save_iterate(QEMUFile
*f
, void *opaque
)
3011 RAMState
**temp
= opaque
;
3012 RAMState
*rs
= *temp
;
3018 if (blk_mig_bulk_active()) {
3019 /* Avoid transferring ram during bulk phase of block migration as
3020 * the bulk phase will usually take a long time and transferring
3021 * ram updates during that time is pointless. */
3026 * We'll take this lock a little bit long, but it's okay for two reasons.
3027 * Firstly, the only possible other thread to take it is who calls
3028 * qemu_guest_free_page_hint(), which should be rare; secondly, see
3029 * MAX_WAIT (if curious, further see commit 4508bd9ed8053ce) below, which
3030 * guarantees that we'll at least released it in a regular basis.
3032 WITH_QEMU_LOCK_GUARD(&rs
->bitmap_mutex
) {
3033 WITH_RCU_READ_LOCK_GUARD() {
3034 if (ram_list
.version
!= rs
->last_version
) {
3035 ram_state_reset(rs
);
3038 /* Read version before ram_list.blocks */
3041 ret
= rdma_registration_start(f
, RAM_CONTROL_ROUND
);
3043 qemu_file_set_error(f
, ret
);
3047 t0
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
3049 while ((ret
= migration_rate_exceeded(f
)) == 0 ||
3050 postcopy_has_request(rs
)) {
3053 if (qemu_file_get_error(f
)) {
3057 pages
= ram_find_and_save_block(rs
);
3058 /* no more pages to sent */
3065 qemu_file_set_error(f
, pages
);
3069 rs
->target_page_count
+= pages
;
3072 * During postcopy, it is necessary to make sure one whole host
3073 * page is sent in one chunk.
3075 if (migrate_postcopy_ram()) {
3076 compress_flush_data();
3080 * we want to check in the 1st loop, just in case it was the 1st
3081 * time and we had to sync the dirty bitmap.
3082 * qemu_clock_get_ns() is a bit expensive, so we only check each
3085 if ((i
& 63) == 0) {
3086 uint64_t t1
= (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) - t0
) /
3088 if (t1
> MAX_WAIT
) {
3089 trace_ram_save_iterate_big_wait(t1
, i
);
3099 * Must occur before EOS (or any QEMUFile operation)
3100 * because of RDMA protocol.
3102 ret
= rdma_registration_stop(f
, RAM_CONTROL_ROUND
);
3104 qemu_file_set_error(f
, ret
);
3109 && migration_is_setup_or_active(migrate_get_current()->state
)) {
3110 if (migrate_multifd() && migrate_multifd_flush_after_each_section()) {
3111 ret
= multifd_send_sync_main();
3117 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3118 ram_transferred_add(8);
3119 ret
= qemu_fflush(f
);
3129 * ram_save_complete: function called to send the remaining amount of ram
3131 * Returns zero to indicate success or negative on error
3133 * Called with the BQL
3135 * @f: QEMUFile where to send the data
3136 * @opaque: RAMState pointer
3138 static int ram_save_complete(QEMUFile
*f
, void *opaque
)
3140 RAMState
**temp
= opaque
;
3141 RAMState
*rs
= *temp
;
3144 rs
->last_stage
= !migration_in_colo_state();
3146 WITH_RCU_READ_LOCK_GUARD() {
3147 if (!migration_in_postcopy()) {
3148 migration_bitmap_sync_precopy(rs
, true);
3151 ret
= rdma_registration_start(f
, RAM_CONTROL_FINISH
);
3153 qemu_file_set_error(f
, ret
);
3157 /* try transferring iterative blocks of memory */
3159 /* flush all remaining blocks regardless of rate limiting */
3160 qemu_mutex_lock(&rs
->bitmap_mutex
);
3164 pages
= ram_find_and_save_block(rs
);
3165 /* no more blocks to sent */
3170 qemu_mutex_unlock(&rs
->bitmap_mutex
);
3174 qemu_mutex_unlock(&rs
->bitmap_mutex
);
3176 compress_flush_data();
3178 ret
= rdma_registration_stop(f
, RAM_CONTROL_FINISH
);
3180 qemu_file_set_error(f
, ret
);
3185 ret
= multifd_send_sync_main();
3190 if (migrate_multifd() && !migrate_multifd_flush_after_each_section()) {
3191 qemu_put_be64(f
, RAM_SAVE_FLAG_MULTIFD_FLUSH
);
3193 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3194 return qemu_fflush(f
);
3197 static void ram_state_pending_estimate(void *opaque
, uint64_t *must_precopy
,
3198 uint64_t *can_postcopy
)
3200 RAMState
**temp
= opaque
;
3201 RAMState
*rs
= *temp
;
3203 uint64_t remaining_size
= rs
->migration_dirty_pages
* TARGET_PAGE_SIZE
;
3205 if (migrate_postcopy_ram()) {
3206 /* We can do postcopy, and all the data is postcopiable */
3207 *can_postcopy
+= remaining_size
;
3209 *must_precopy
+= remaining_size
;
3213 static void ram_state_pending_exact(void *opaque
, uint64_t *must_precopy
,
3214 uint64_t *can_postcopy
)
3216 MigrationState
*s
= migrate_get_current();
3217 RAMState
**temp
= opaque
;
3218 RAMState
*rs
= *temp
;
3220 uint64_t remaining_size
= rs
->migration_dirty_pages
* TARGET_PAGE_SIZE
;
3222 if (!migration_in_postcopy() && remaining_size
< s
->threshold_size
) {
3224 WITH_RCU_READ_LOCK_GUARD() {
3225 migration_bitmap_sync_precopy(rs
, false);
3228 remaining_size
= rs
->migration_dirty_pages
* TARGET_PAGE_SIZE
;
3231 if (migrate_postcopy_ram()) {
3232 /* We can do postcopy, and all the data is postcopiable */
3233 *can_postcopy
+= remaining_size
;
3235 *must_precopy
+= remaining_size
;
3239 static int load_xbzrle(QEMUFile
*f
, ram_addr_t addr
, void *host
)
3241 unsigned int xh_len
;
3243 uint8_t *loaded_data
;
3245 /* extract RLE header */
3246 xh_flags
= qemu_get_byte(f
);
3247 xh_len
= qemu_get_be16(f
);
3249 if (xh_flags
!= ENCODING_FLAG_XBZRLE
) {
3250 error_report("Failed to load XBZRLE page - wrong compression!");
3254 if (xh_len
> TARGET_PAGE_SIZE
) {
3255 error_report("Failed to load XBZRLE page - len overflow!");
3258 loaded_data
= XBZRLE
.decoded_buf
;
3259 /* load data and decode */
3260 /* it can change loaded_data to point to an internal buffer */
3261 qemu_get_buffer_in_place(f
, &loaded_data
, xh_len
);
3264 if (xbzrle_decode_buffer(loaded_data
, xh_len
, host
,
3265 TARGET_PAGE_SIZE
) == -1) {
3266 error_report("Failed to load XBZRLE page - decode error!");
3274 * ram_block_from_stream: read a RAMBlock id from the migration stream
3276 * Must be called from within a rcu critical section.
3278 * Returns a pointer from within the RCU-protected ram_list.
3280 * @mis: the migration incoming state pointer
3281 * @f: QEMUFile where to read the data from
3282 * @flags: Page flags (mostly to see if it's a continuation of previous block)
3283 * @channel: the channel we're using
3285 static inline RAMBlock
*ram_block_from_stream(MigrationIncomingState
*mis
,
3286 QEMUFile
*f
, int flags
,
3289 RAMBlock
*block
= mis
->last_recv_block
[channel
];
3293 if (flags
& RAM_SAVE_FLAG_CONTINUE
) {
3295 error_report("Ack, bad migration stream!");
3301 len
= qemu_get_byte(f
);
3302 qemu_get_buffer(f
, (uint8_t *)id
, len
);
3305 block
= qemu_ram_block_by_name(id
);
3307 error_report("Can't find block %s", id
);
3311 if (migrate_ram_is_ignored(block
)) {
3312 error_report("block %s should not be migrated !", id
);
3316 mis
->last_recv_block
[channel
] = block
;
3321 static inline void *host_from_ram_block_offset(RAMBlock
*block
,
3324 if (!offset_in_ramblock(block
, offset
)) {
3328 return block
->host
+ offset
;
3331 static void *host_page_from_ram_block_offset(RAMBlock
*block
,
3334 /* Note: Explicitly no check against offset_in_ramblock(). */
3335 return (void *)QEMU_ALIGN_DOWN((uintptr_t)(block
->host
+ offset
),
3339 static ram_addr_t
host_page_offset_from_ram_block_offset(RAMBlock
*block
,
3342 return ((uintptr_t)block
->host
+ offset
) & (block
->page_size
- 1);
3345 void colo_record_bitmap(RAMBlock
*block
, ram_addr_t
*normal
, uint32_t pages
)
3347 qemu_mutex_lock(&ram_state
->bitmap_mutex
);
3348 for (int i
= 0; i
< pages
; i
++) {
3349 ram_addr_t offset
= normal
[i
];
3350 ram_state
->migration_dirty_pages
+= !test_and_set_bit(
3351 offset
>> TARGET_PAGE_BITS
,
3354 qemu_mutex_unlock(&ram_state
->bitmap_mutex
);
3357 static inline void *colo_cache_from_block_offset(RAMBlock
*block
,
3358 ram_addr_t offset
, bool record_bitmap
)
3360 if (!offset_in_ramblock(block
, offset
)) {
3363 if (!block
->colo_cache
) {
3364 error_report("%s: colo_cache is NULL in block :%s",
3365 __func__
, block
->idstr
);
3370 * During colo checkpoint, we need bitmap of these migrated pages.
3371 * It help us to decide which pages in ram cache should be flushed
3372 * into VM's RAM later.
3374 if (record_bitmap
) {
3375 colo_record_bitmap(block
, &offset
, 1);
3377 return block
->colo_cache
+ offset
;
3381 * ram_handle_zero: handle the zero page case
3383 * If a page (or a whole RDMA chunk) has been
3384 * determined to be zero, then zap it.
3386 * @host: host address for the zero page
3387 * @ch: what the page is filled from. We only support zero
3388 * @size: size of the zero page
3390 void ram_handle_zero(void *host
, uint64_t size
)
3392 if (!buffer_is_zero(host
, size
)) {
3393 memset(host
, 0, size
);
3397 static void colo_init_ram_state(void)
3399 ram_state_init(&ram_state
);
3403 * colo cache: this is for secondary VM, we cache the whole
3404 * memory of the secondary VM, it is need to hold the global lock
3405 * to call this helper.
3407 int colo_init_ram_cache(void)
3411 WITH_RCU_READ_LOCK_GUARD() {
3412 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3413 block
->colo_cache
= qemu_anon_ram_alloc(block
->used_length
,
3414 NULL
, false, false);
3415 if (!block
->colo_cache
) {
3416 error_report("%s: Can't alloc memory for COLO cache of block %s,"
3417 "size 0x" RAM_ADDR_FMT
, __func__
, block
->idstr
,
3418 block
->used_length
);
3419 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3420 if (block
->colo_cache
) {
3421 qemu_anon_ram_free(block
->colo_cache
, block
->used_length
);
3422 block
->colo_cache
= NULL
;
3427 if (!machine_dump_guest_core(current_machine
)) {
3428 qemu_madvise(block
->colo_cache
, block
->used_length
,
3429 QEMU_MADV_DONTDUMP
);
3435 * Record the dirty pages that sent by PVM, we use this dirty bitmap together
3436 * with to decide which page in cache should be flushed into SVM's RAM. Here
3437 * we use the same name 'ram_bitmap' as for migration.
3439 if (ram_bytes_total()) {
3440 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3441 unsigned long pages
= block
->max_length
>> TARGET_PAGE_BITS
;
3442 block
->bmap
= bitmap_new(pages
);
3446 colo_init_ram_state();
3450 /* TODO: duplicated with ram_init_bitmaps */
3451 void colo_incoming_start_dirty_log(void)
3453 RAMBlock
*block
= NULL
;
3454 /* For memory_global_dirty_log_start below. */
3456 qemu_mutex_lock_ramlist();
3458 memory_global_dirty_log_sync(false);
3459 WITH_RCU_READ_LOCK_GUARD() {
3460 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3461 ramblock_sync_dirty_bitmap(ram_state
, block
);
3462 /* Discard this dirty bitmap record */
3463 bitmap_zero(block
->bmap
, block
->max_length
>> TARGET_PAGE_BITS
);
3465 memory_global_dirty_log_start(GLOBAL_DIRTY_MIGRATION
);
3467 ram_state
->migration_dirty_pages
= 0;
3468 qemu_mutex_unlock_ramlist();
3472 /* It is need to hold the global lock to call this helper */
3473 void colo_release_ram_cache(void)
3477 memory_global_dirty_log_stop(GLOBAL_DIRTY_MIGRATION
);
3478 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3479 g_free(block
->bmap
);
3483 WITH_RCU_READ_LOCK_GUARD() {
3484 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3485 if (block
->colo_cache
) {
3486 qemu_anon_ram_free(block
->colo_cache
, block
->used_length
);
3487 block
->colo_cache
= NULL
;
3491 ram_state_cleanup(&ram_state
);
3495 * ram_load_setup: Setup RAM for migration incoming side
3497 * Returns zero to indicate success and negative for error
3499 * @f: QEMUFile where to receive the data
3500 * @opaque: RAMState pointer
3502 static int ram_load_setup(QEMUFile
*f
, void *opaque
)
3504 xbzrle_load_setup();
3505 ramblock_recv_map_init();
3510 static int ram_load_cleanup(void *opaque
)
3514 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
3515 qemu_ram_block_writeback(rb
);
3518 xbzrle_load_cleanup();
3520 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
3521 g_free(rb
->receivedmap
);
3522 rb
->receivedmap
= NULL
;
3529 * ram_postcopy_incoming_init: allocate postcopy data structures
3531 * Returns 0 for success and negative if there was one error
3533 * @mis: current migration incoming state
3535 * Allocate data structures etc needed by incoming migration with
3536 * postcopy-ram. postcopy-ram's similarly names
3537 * postcopy_ram_incoming_init does the work.
3539 int ram_postcopy_incoming_init(MigrationIncomingState
*mis
)
3541 return postcopy_ram_incoming_init(mis
);
3545 * ram_load_postcopy: load a page in postcopy case
3547 * Returns 0 for success or -errno in case of error
3549 * Called in postcopy mode by ram_load().
3550 * rcu_read_lock is taken prior to this being called.
3552 * @f: QEMUFile where to send the data
3553 * @channel: the channel to use for loading
3555 int ram_load_postcopy(QEMUFile
*f
, int channel
)
3557 int flags
= 0, ret
= 0;
3558 bool place_needed
= false;
3559 bool matches_target_page_size
= false;
3560 MigrationIncomingState
*mis
= migration_incoming_get_current();
3561 PostcopyTmpPage
*tmp_page
= &mis
->postcopy_tmp_pages
[channel
];
3563 while (!ret
&& !(flags
& RAM_SAVE_FLAG_EOS
)) {
3565 void *page_buffer
= NULL
;
3566 void *place_source
= NULL
;
3567 RAMBlock
*block
= NULL
;
3571 addr
= qemu_get_be64(f
);
3574 * If qemu file error, we should stop here, and then "addr"
3577 ret
= qemu_file_get_error(f
);
3582 flags
= addr
& ~TARGET_PAGE_MASK
;
3583 addr
&= TARGET_PAGE_MASK
;
3585 trace_ram_load_postcopy_loop(channel
, (uint64_t)addr
, flags
);
3586 if (flags
& (RAM_SAVE_FLAG_ZERO
| RAM_SAVE_FLAG_PAGE
|
3587 RAM_SAVE_FLAG_COMPRESS_PAGE
)) {
3588 block
= ram_block_from_stream(mis
, f
, flags
, channel
);
3595 * Relying on used_length is racy and can result in false positives.
3596 * We might place pages beyond used_length in case RAM was shrunk
3597 * while in postcopy, which is fine - trying to place via
3598 * UFFDIO_COPY/UFFDIO_ZEROPAGE will never segfault.
3600 if (!block
->host
|| addr
>= block
->postcopy_length
) {
3601 error_report("Illegal RAM offset " RAM_ADDR_FMT
, addr
);
3605 tmp_page
->target_pages
++;
3606 matches_target_page_size
= block
->page_size
== TARGET_PAGE_SIZE
;
3608 * Postcopy requires that we place whole host pages atomically;
3609 * these may be huge pages for RAMBlocks that are backed by
3611 * To make it atomic, the data is read into a temporary page
3612 * that's moved into place later.
3613 * The migration protocol uses, possibly smaller, target-pages
3614 * however the source ensures it always sends all the components
3615 * of a host page in one chunk.
3617 page_buffer
= tmp_page
->tmp_huge_page
+
3618 host_page_offset_from_ram_block_offset(block
, addr
);
3619 /* If all TP are zero then we can optimise the place */
3620 if (tmp_page
->target_pages
== 1) {
3621 tmp_page
->host_addr
=
3622 host_page_from_ram_block_offset(block
, addr
);
3623 } else if (tmp_page
->host_addr
!=
3624 host_page_from_ram_block_offset(block
, addr
)) {
3625 /* not the 1st TP within the HP */
3626 error_report("Non-same host page detected on channel %d: "
3627 "Target host page %p, received host page %p "
3628 "(rb %s offset 0x"RAM_ADDR_FMT
" target_pages %d)",
3629 channel
, tmp_page
->host_addr
,
3630 host_page_from_ram_block_offset(block
, addr
),
3631 block
->idstr
, addr
, tmp_page
->target_pages
);
3637 * If it's the last part of a host page then we place the host
3640 if (tmp_page
->target_pages
==
3641 (block
->page_size
/ TARGET_PAGE_SIZE
)) {
3642 place_needed
= true;
3644 place_source
= tmp_page
->tmp_huge_page
;
3647 switch (flags
& ~RAM_SAVE_FLAG_CONTINUE
) {
3648 case RAM_SAVE_FLAG_ZERO
:
3649 ch
= qemu_get_byte(f
);
3651 error_report("Found a zero page with value %d", ch
);
3656 * Can skip to set page_buffer when
3657 * this is a zero page and (block->page_size == TARGET_PAGE_SIZE).
3659 if (!matches_target_page_size
) {
3660 memset(page_buffer
, ch
, TARGET_PAGE_SIZE
);
3664 case RAM_SAVE_FLAG_PAGE
:
3665 tmp_page
->all_zero
= false;
3666 if (!matches_target_page_size
) {
3667 /* For huge pages, we always use temporary buffer */
3668 qemu_get_buffer(f
, page_buffer
, TARGET_PAGE_SIZE
);
3671 * For small pages that matches target page size, we
3672 * avoid the qemu_file copy. Instead we directly use
3673 * the buffer of QEMUFile to place the page. Note: we
3674 * cannot do any QEMUFile operation before using that
3675 * buffer to make sure the buffer is valid when
3678 qemu_get_buffer_in_place(f
, (uint8_t **)&place_source
,
3682 case RAM_SAVE_FLAG_COMPRESS_PAGE
:
3683 tmp_page
->all_zero
= false;
3684 len
= qemu_get_be32(f
);
3685 if (len
< 0 || len
> compressBound(TARGET_PAGE_SIZE
)) {
3686 error_report("Invalid compressed data length: %d", len
);
3690 decompress_data_with_multi_threads(f
, page_buffer
, len
);
3692 case RAM_SAVE_FLAG_MULTIFD_FLUSH
:
3693 multifd_recv_sync_main();
3695 case RAM_SAVE_FLAG_EOS
:
3697 if (migrate_multifd() &&
3698 migrate_multifd_flush_after_each_section()) {
3699 multifd_recv_sync_main();
3703 error_report("Unknown combination of migration flags: 0x%x"
3704 " (postcopy mode)", flags
);
3709 /* Got the whole host page, wait for decompress before placing. */
3711 ret
|= wait_for_decompress_done();
3714 /* Detect for any possible file errors */
3715 if (!ret
&& qemu_file_get_error(f
)) {
3716 ret
= qemu_file_get_error(f
);
3719 if (!ret
&& place_needed
) {
3720 if (tmp_page
->all_zero
) {
3721 ret
= postcopy_place_page_zero(mis
, tmp_page
->host_addr
, block
);
3723 ret
= postcopy_place_page(mis
, tmp_page
->host_addr
,
3724 place_source
, block
);
3726 place_needed
= false;
3727 postcopy_temp_page_reset(tmp_page
);
3734 static bool postcopy_is_running(void)
3736 PostcopyState ps
= postcopy_state_get();
3737 return ps
>= POSTCOPY_INCOMING_LISTENING
&& ps
< POSTCOPY_INCOMING_END
;
3741 * Flush content of RAM cache into SVM's memory.
3742 * Only flush the pages that be dirtied by PVM or SVM or both.
3744 void colo_flush_ram_cache(void)
3746 RAMBlock
*block
= NULL
;
3749 unsigned long offset
= 0;
3751 memory_global_dirty_log_sync(false);
3752 qemu_mutex_lock(&ram_state
->bitmap_mutex
);
3753 WITH_RCU_READ_LOCK_GUARD() {
3754 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3755 ramblock_sync_dirty_bitmap(ram_state
, block
);
3759 trace_colo_flush_ram_cache_begin(ram_state
->migration_dirty_pages
);
3760 WITH_RCU_READ_LOCK_GUARD() {
3761 block
= QLIST_FIRST_RCU(&ram_list
.blocks
);
3764 unsigned long num
= 0;
3766 offset
= colo_bitmap_find_dirty(ram_state
, block
, offset
, &num
);
3767 if (!offset_in_ramblock(block
,
3768 ((ram_addr_t
)offset
) << TARGET_PAGE_BITS
)) {
3771 block
= QLIST_NEXT_RCU(block
, next
);
3773 unsigned long i
= 0;
3775 for (i
= 0; i
< num
; i
++) {
3776 migration_bitmap_clear_dirty(ram_state
, block
, offset
+ i
);
3778 dst_host
= block
->host
3779 + (((ram_addr_t
)offset
) << TARGET_PAGE_BITS
);
3780 src_host
= block
->colo_cache
3781 + (((ram_addr_t
)offset
) << TARGET_PAGE_BITS
);
3782 memcpy(dst_host
, src_host
, TARGET_PAGE_SIZE
* num
);
3787 qemu_mutex_unlock(&ram_state
->bitmap_mutex
);
3788 trace_colo_flush_ram_cache_end();
3791 static int parse_ramblock(QEMUFile
*f
, RAMBlock
*block
, ram_addr_t length
)
3794 /* ADVISE is earlier, it shows the source has the postcopy capability on */
3795 bool postcopy_advised
= migration_incoming_postcopy_advised();
3799 if (!qemu_ram_is_migratable(block
)) {
3800 error_report("block %s should not be migrated !", block
->idstr
);
3804 if (length
!= block
->used_length
) {
3805 Error
*local_err
= NULL
;
3807 ret
= qemu_ram_resize(block
, length
, &local_err
);
3809 error_report_err(local_err
);
3813 /* For postcopy we need to check hugepage sizes match */
3814 if (postcopy_advised
&& migrate_postcopy_ram() &&
3815 block
->page_size
!= qemu_host_page_size
) {
3816 uint64_t remote_page_size
= qemu_get_be64(f
);
3817 if (remote_page_size
!= block
->page_size
) {
3818 error_report("Mismatched RAM page size %s "
3819 "(local) %zd != %" PRId64
, block
->idstr
,
3820 block
->page_size
, remote_page_size
);
3824 if (migrate_ignore_shared()) {
3825 hwaddr addr
= qemu_get_be64(f
);
3826 if (migrate_ram_is_ignored(block
) &&
3827 block
->mr
->addr
!= addr
) {
3828 error_report("Mismatched GPAs for block %s "
3829 "%" PRId64
"!= %" PRId64
, block
->idstr
,
3830 (uint64_t)addr
, (uint64_t)block
->mr
->addr
);
3834 ret
= rdma_block_notification_handle(f
, block
->idstr
);
3836 qemu_file_set_error(f
, ret
);
3842 static int parse_ramblocks(QEMUFile
*f
, ram_addr_t total_ram_bytes
)
3846 /* Synchronize RAM block list */
3847 while (!ret
&& total_ram_bytes
) {
3851 int len
= qemu_get_byte(f
);
3853 qemu_get_buffer(f
, (uint8_t *)id
, len
);
3855 length
= qemu_get_be64(f
);
3857 block
= qemu_ram_block_by_name(id
);
3859 ret
= parse_ramblock(f
, block
, length
);
3861 error_report("Unknown ramblock \"%s\", cannot accept "
3865 total_ram_bytes
-= length
;
3872 * ram_load_precopy: load pages in precopy case
3874 * Returns 0 for success or -errno in case of error
3876 * Called in precopy mode by ram_load().
3877 * rcu_read_lock is taken prior to this being called.
3879 * @f: QEMUFile where to send the data
3881 static int ram_load_precopy(QEMUFile
*f
)
3883 MigrationIncomingState
*mis
= migration_incoming_get_current();
3884 int flags
= 0, ret
= 0, invalid_flags
= 0, len
= 0, i
= 0;
3886 if (!migrate_compress()) {
3887 invalid_flags
|= RAM_SAVE_FLAG_COMPRESS_PAGE
;
3890 while (!ret
&& !(flags
& RAM_SAVE_FLAG_EOS
)) {
3892 void *host
= NULL
, *host_bak
= NULL
;
3896 * Yield periodically to let main loop run, but an iteration of
3897 * the main loop is expensive, so do it each some iterations
3899 if ((i
& 32767) == 0 && qemu_in_coroutine()) {
3900 aio_co_schedule(qemu_get_current_aio_context(),
3901 qemu_coroutine_self());
3902 qemu_coroutine_yield();
3906 addr
= qemu_get_be64(f
);
3907 flags
= addr
& ~TARGET_PAGE_MASK
;
3908 addr
&= TARGET_PAGE_MASK
;
3910 if (flags
& invalid_flags
) {
3911 if (flags
& invalid_flags
& RAM_SAVE_FLAG_COMPRESS_PAGE
) {
3912 error_report("Received an unexpected compressed page");
3919 if (flags
& (RAM_SAVE_FLAG_ZERO
| RAM_SAVE_FLAG_PAGE
|
3920 RAM_SAVE_FLAG_COMPRESS_PAGE
| RAM_SAVE_FLAG_XBZRLE
)) {
3921 RAMBlock
*block
= ram_block_from_stream(mis
, f
, flags
,
3922 RAM_CHANNEL_PRECOPY
);
3924 host
= host_from_ram_block_offset(block
, addr
);
3926 * After going into COLO stage, we should not load the page
3927 * into SVM's memory directly, we put them into colo_cache firstly.
3928 * NOTE: We need to keep a copy of SVM's ram in colo_cache.
3929 * Previously, we copied all these memory in preparing stage of COLO
3930 * while we need to stop VM, which is a time-consuming process.
3931 * Here we optimize it by a trick, back-up every page while in
3932 * migration process while COLO is enabled, though it affects the
3933 * speed of the migration, but it obviously reduce the downtime of
3934 * back-up all SVM'S memory in COLO preparing stage.
3936 if (migration_incoming_colo_enabled()) {
3937 if (migration_incoming_in_colo_state()) {
3938 /* In COLO stage, put all pages into cache temporarily */
3939 host
= colo_cache_from_block_offset(block
, addr
, true);
3942 * In migration stage but before COLO stage,
3943 * Put all pages into both cache and SVM's memory.
3945 host_bak
= colo_cache_from_block_offset(block
, addr
, false);
3949 error_report("Illegal RAM offset " RAM_ADDR_FMT
, addr
);
3953 if (!migration_incoming_in_colo_state()) {
3954 ramblock_recv_bitmap_set(block
, host
);
3957 trace_ram_load_loop(block
->idstr
, (uint64_t)addr
, flags
, host
);
3960 switch (flags
& ~RAM_SAVE_FLAG_CONTINUE
) {
3961 case RAM_SAVE_FLAG_MEM_SIZE
:
3962 ret
= parse_ramblocks(f
, addr
);
3965 case RAM_SAVE_FLAG_ZERO
:
3966 ch
= qemu_get_byte(f
);
3968 error_report("Found a zero page with value %d", ch
);
3972 ram_handle_zero(host
, TARGET_PAGE_SIZE
);
3975 case RAM_SAVE_FLAG_PAGE
:
3976 qemu_get_buffer(f
, host
, TARGET_PAGE_SIZE
);
3979 case RAM_SAVE_FLAG_COMPRESS_PAGE
:
3980 len
= qemu_get_be32(f
);
3981 if (len
< 0 || len
> compressBound(TARGET_PAGE_SIZE
)) {
3982 error_report("Invalid compressed data length: %d", len
);
3986 decompress_data_with_multi_threads(f
, host
, len
);
3989 case RAM_SAVE_FLAG_XBZRLE
:
3990 if (load_xbzrle(f
, addr
, host
) < 0) {
3991 error_report("Failed to decompress XBZRLE page at "
3992 RAM_ADDR_FMT
, addr
);
3997 case RAM_SAVE_FLAG_MULTIFD_FLUSH
:
3998 multifd_recv_sync_main();
4000 case RAM_SAVE_FLAG_EOS
:
4002 if (migrate_multifd() &&
4003 migrate_multifd_flush_after_each_section()) {
4004 multifd_recv_sync_main();
4007 case RAM_SAVE_FLAG_HOOK
:
4008 ret
= rdma_registration_handle(f
);
4010 qemu_file_set_error(f
, ret
);
4014 error_report("Unknown combination of migration flags: 0x%x", flags
);
4018 ret
= qemu_file_get_error(f
);
4020 if (!ret
&& host_bak
) {
4021 memcpy(host_bak
, host
, TARGET_PAGE_SIZE
);
4025 ret
|= wait_for_decompress_done();
4029 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
4032 static uint64_t seq_iter
;
4034 * If system is running in postcopy mode, page inserts to host memory must
4037 bool postcopy_running
= postcopy_is_running();
4041 if (version_id
!= 4) {
4046 * This RCU critical section can be very long running.
4047 * When RCU reclaims in the code start to become numerous,
4048 * it will be necessary to reduce the granularity of this
4051 WITH_RCU_READ_LOCK_GUARD() {
4052 if (postcopy_running
) {
4054 * Note! Here RAM_CHANNEL_PRECOPY is the precopy channel of
4055 * postcopy migration, we have another RAM_CHANNEL_POSTCOPY to
4056 * service fast page faults.
4058 ret
= ram_load_postcopy(f
, RAM_CHANNEL_PRECOPY
);
4060 ret
= ram_load_precopy(f
);
4063 trace_ram_load_complete(ret
, seq_iter
);
4068 static bool ram_has_postcopy(void *opaque
)
4071 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
4072 if (ramblock_is_pmem(rb
)) {
4073 info_report("Block: %s, host: %p is a nvdimm memory, postcopy"
4074 "is not supported now!", rb
->idstr
, rb
->host
);
4079 return migrate_postcopy_ram();
4082 /* Sync all the dirty bitmap with destination VM. */
4083 static int ram_dirty_bitmap_sync_all(MigrationState
*s
, RAMState
*rs
)
4086 QEMUFile
*file
= s
->to_dst_file
;
4088 trace_ram_dirty_bitmap_sync_start();
4090 qatomic_set(&rs
->postcopy_bmap_sync_requested
, 0);
4091 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
4092 qemu_savevm_send_recv_bitmap(file
, block
->idstr
);
4093 trace_ram_dirty_bitmap_request(block
->idstr
);
4094 qatomic_inc(&rs
->postcopy_bmap_sync_requested
);
4097 trace_ram_dirty_bitmap_sync_wait();
4099 /* Wait until all the ramblocks' dirty bitmap synced */
4100 while (qatomic_read(&rs
->postcopy_bmap_sync_requested
)) {
4101 if (migration_rp_wait(s
)) {
4106 trace_ram_dirty_bitmap_sync_complete();
4112 * Read the received bitmap, revert it as the initial dirty bitmap.
4113 * This is only used when the postcopy migration is paused but wants
4114 * to resume from a middle point.
4116 * Returns true if succeeded, false for errors.
4118 bool ram_dirty_bitmap_reload(MigrationState
*s
, RAMBlock
*block
, Error
**errp
)
4120 /* from_dst_file is always valid because we're within rp_thread */
4121 QEMUFile
*file
= s
->rp_state
.from_dst_file
;
4122 g_autofree
unsigned long *le_bitmap
= NULL
;
4123 unsigned long nbits
= block
->used_length
>> TARGET_PAGE_BITS
;
4124 uint64_t local_size
= DIV_ROUND_UP(nbits
, 8);
4125 uint64_t size
, end_mark
;
4126 RAMState
*rs
= ram_state
;
4128 trace_ram_dirty_bitmap_reload_begin(block
->idstr
);
4130 if (s
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
4131 error_setg(errp
, "Reload bitmap in incorrect state %s",
4132 MigrationStatus_str(s
->state
));
4137 * Note: see comments in ramblock_recv_bitmap_send() on why we
4138 * need the endianness conversion, and the paddings.
4140 local_size
= ROUND_UP(local_size
, 8);
4143 le_bitmap
= bitmap_new(nbits
+ BITS_PER_LONG
);
4145 size
= qemu_get_be64(file
);
4147 /* The size of the bitmap should match with our ramblock */
4148 if (size
!= local_size
) {
4149 error_setg(errp
, "ramblock '%s' bitmap size mismatch (0x%"PRIx64
4150 " != 0x%"PRIx64
")", block
->idstr
, size
, local_size
);
4154 size
= qemu_get_buffer(file
, (uint8_t *)le_bitmap
, local_size
);
4155 end_mark
= qemu_get_be64(file
);
4157 if (qemu_file_get_error(file
) || size
!= local_size
) {
4158 error_setg(errp
, "read bitmap failed for ramblock '%s': "
4159 "(size 0x%"PRIx64
", got: 0x%"PRIx64
")",
4160 block
->idstr
, local_size
, size
);
4164 if (end_mark
!= RAMBLOCK_RECV_BITMAP_ENDING
) {
4165 error_setg(errp
, "ramblock '%s' end mark incorrect: 0x%"PRIx64
,
4166 block
->idstr
, end_mark
);
4171 * Endianness conversion. We are during postcopy (though paused).
4172 * The dirty bitmap won't change. We can directly modify it.
4174 bitmap_from_le(block
->bmap
, le_bitmap
, nbits
);
4177 * What we received is "received bitmap". Revert it as the initial
4178 * dirty bitmap for this ramblock.
4180 bitmap_complement(block
->bmap
, block
->bmap
, nbits
);
4182 /* Clear dirty bits of discarded ranges that we don't want to migrate. */
4183 ramblock_dirty_bitmap_clear_discarded_pages(block
);
4185 /* We'll recalculate migration_dirty_pages in ram_state_resume_prepare(). */
4186 trace_ram_dirty_bitmap_reload_complete(block
->idstr
);
4188 qatomic_dec(&rs
->postcopy_bmap_sync_requested
);
4191 * We succeeded to sync bitmap for current ramblock. Always kick the
4192 * migration thread to check whether all requested bitmaps are
4193 * reloaded. NOTE: it's racy to only kick when requested==0, because
4194 * we don't know whether the migration thread may still be increasing
4197 migration_rp_kick(s
);
4202 static int ram_resume_prepare(MigrationState
*s
, void *opaque
)
4204 RAMState
*rs
= *(RAMState
**)opaque
;
4207 ret
= ram_dirty_bitmap_sync_all(s
, rs
);
4212 ram_state_resume_prepare(rs
, s
->to_dst_file
);
4217 void postcopy_preempt_shutdown_file(MigrationState
*s
)
4219 qemu_put_be64(s
->postcopy_qemufile_src
, RAM_SAVE_FLAG_EOS
);
4220 qemu_fflush(s
->postcopy_qemufile_src
);
4223 static SaveVMHandlers savevm_ram_handlers
= {
4224 .save_setup
= ram_save_setup
,
4225 .save_live_iterate
= ram_save_iterate
,
4226 .save_live_complete_postcopy
= ram_save_complete
,
4227 .save_live_complete_precopy
= ram_save_complete
,
4228 .has_postcopy
= ram_has_postcopy
,
4229 .state_pending_exact
= ram_state_pending_exact
,
4230 .state_pending_estimate
= ram_state_pending_estimate
,
4231 .load_state
= ram_load
,
4232 .save_cleanup
= ram_save_cleanup
,
4233 .load_setup
= ram_load_setup
,
4234 .load_cleanup
= ram_load_cleanup
,
4235 .resume_prepare
= ram_resume_prepare
,
4238 static void ram_mig_ram_block_resized(RAMBlockNotifier
*n
, void *host
,
4239 size_t old_size
, size_t new_size
)
4241 PostcopyState ps
= postcopy_state_get();
4243 RAMBlock
*rb
= qemu_ram_block_from_host(host
, false, &offset
);
4247 error_report("RAM block not found");
4251 if (migrate_ram_is_ignored(rb
)) {
4255 if (!migration_is_idle()) {
4257 * Precopy code on the source cannot deal with the size of RAM blocks
4258 * changing at random points in time - especially after sending the
4259 * RAM block sizes in the migration stream, they must no longer change.
4260 * Abort and indicate a proper reason.
4262 error_setg(&err
, "RAM block '%s' resized during precopy.", rb
->idstr
);
4263 migration_cancel(err
);
4268 case POSTCOPY_INCOMING_ADVISE
:
4270 * Update what ram_postcopy_incoming_init()->init_range() does at the
4271 * time postcopy was advised. Syncing RAM blocks with the source will
4272 * result in RAM resizes.
4274 if (old_size
< new_size
) {
4275 if (ram_discard_range(rb
->idstr
, old_size
, new_size
- old_size
)) {
4276 error_report("RAM block '%s' discard of resized RAM failed",
4280 rb
->postcopy_length
= new_size
;
4282 case POSTCOPY_INCOMING_NONE
:
4283 case POSTCOPY_INCOMING_RUNNING
:
4284 case POSTCOPY_INCOMING_END
:
4286 * Once our guest is running, postcopy does no longer care about
4287 * resizes. When growing, the new memory was not available on the
4288 * source, no handler needed.
4292 error_report("RAM block '%s' resized during postcopy state: %d",
4298 static RAMBlockNotifier ram_mig_ram_notifier
= {
4299 .ram_block_resized
= ram_mig_ram_block_resized
,
4302 void ram_mig_init(void)
4304 qemu_mutex_init(&XBZRLE
.lock
);
4305 register_savevm_live("ram", 0, 4, &savevm_ram_handlers
, &ram_state
);
4306 ram_block_notifier_add(&ram_mig_ram_notifier
);