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 */
98 * mapped-ram migration supports O_DIRECT, so we need to make sure the
99 * userspace buffer, the IO operation size and the file offset are
100 * aligned according to the underlying device's block size. The first
101 * two are already aligned to page size, but we need to add padding to
102 * the file to align the offset. We cannot read the block size
103 * dynamically because the migration file can be moved between
104 * different systems, so use 1M to cover most block sizes and to keep
105 * the file offset aligned at page size as well.
107 #define MAPPED_RAM_FILE_OFFSET_ALIGNMENT 0x100000
110 * When doing mapped-ram migration, this is the amount we read from
111 * the pages region in the migration file at a time.
113 #define MAPPED_RAM_LOAD_BUF_SIZE 0x100000
115 XBZRLECacheStats xbzrle_counters
;
117 /* used by the search for pages to send */
118 struct PageSearchStatus
{
119 /* The migration channel used for a specific host page */
120 QEMUFile
*pss_channel
;
121 /* Last block from where we have sent data */
122 RAMBlock
*last_sent_block
;
123 /* Current block being searched */
125 /* Current page to search from */
127 /* Set once we wrap around */
129 /* Whether we're sending a host page */
130 bool host_page_sending
;
131 /* The start/end of current host page. Invalid if host_page_sending==false */
132 unsigned long host_page_start
;
133 unsigned long host_page_end
;
135 typedef struct PageSearchStatus PageSearchStatus
;
137 /* struct contains XBZRLE cache and a static page
138 used by the compression */
140 /* buffer used for XBZRLE encoding */
141 uint8_t *encoded_buf
;
142 /* buffer for storing page content */
143 uint8_t *current_buf
;
144 /* Cache for XBZRLE, Protected by lock. */
147 /* it will store a page full of zeros */
148 uint8_t *zero_target_page
;
149 /* buffer used for XBZRLE decoding */
150 uint8_t *decoded_buf
;
153 static void XBZRLE_cache_lock(void)
155 if (migrate_xbzrle()) {
156 qemu_mutex_lock(&XBZRLE
.lock
);
160 static void XBZRLE_cache_unlock(void)
162 if (migrate_xbzrle()) {
163 qemu_mutex_unlock(&XBZRLE
.lock
);
168 * xbzrle_cache_resize: resize the xbzrle cache
170 * This function is called from migrate_params_apply in main
171 * thread, possibly while a migration is in progress. A running
172 * migration may be using the cache and might finish during this call,
173 * hence changes to the cache are protected by XBZRLE.lock().
175 * Returns 0 for success or -1 for error
177 * @new_size: new cache size
178 * @errp: set *errp if the check failed, with reason
180 int xbzrle_cache_resize(uint64_t new_size
, Error
**errp
)
182 PageCache
*new_cache
;
185 /* Check for truncation */
186 if (new_size
!= (size_t)new_size
) {
187 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
188 "exceeding address space");
192 if (new_size
== migrate_xbzrle_cache_size()) {
199 if (XBZRLE
.cache
!= NULL
) {
200 new_cache
= cache_init(new_size
, TARGET_PAGE_SIZE
, errp
);
206 cache_fini(XBZRLE
.cache
);
207 XBZRLE
.cache
= new_cache
;
210 XBZRLE_cache_unlock();
214 static bool postcopy_preempt_active(void)
216 return migrate_postcopy_preempt() && migration_in_postcopy();
219 bool migrate_ram_is_ignored(RAMBlock
*block
)
221 return !qemu_ram_is_migratable(block
) ||
222 (migrate_ignore_shared() && qemu_ram_is_shared(block
)
223 && qemu_ram_is_named_file(block
));
226 #undef RAMBLOCK_FOREACH
228 int foreach_not_ignored_block(RAMBlockIterFunc func
, void *opaque
)
233 RCU_READ_LOCK_GUARD();
235 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
236 ret
= func(block
, opaque
);
244 static void ramblock_recv_map_init(void)
248 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
249 assert(!rb
->receivedmap
);
250 rb
->receivedmap
= bitmap_new(rb
->max_length
>> qemu_target_page_bits());
254 int ramblock_recv_bitmap_test(RAMBlock
*rb
, void *host_addr
)
256 return test_bit(ramblock_recv_bitmap_offset(host_addr
, rb
),
260 bool ramblock_recv_bitmap_test_byte_offset(RAMBlock
*rb
, uint64_t byte_offset
)
262 return test_bit(byte_offset
>> TARGET_PAGE_BITS
, rb
->receivedmap
);
265 void ramblock_recv_bitmap_set(RAMBlock
*rb
, void *host_addr
)
267 set_bit_atomic(ramblock_recv_bitmap_offset(host_addr
, rb
), rb
->receivedmap
);
270 void ramblock_recv_bitmap_set_range(RAMBlock
*rb
, void *host_addr
,
273 bitmap_set_atomic(rb
->receivedmap
,
274 ramblock_recv_bitmap_offset(host_addr
, rb
),
278 #define RAMBLOCK_RECV_BITMAP_ENDING (0x0123456789abcdefULL)
281 * Format: bitmap_size (8 bytes) + whole_bitmap (N bytes).
283 * Returns >0 if success with sent bytes, or <0 if error.
285 int64_t ramblock_recv_bitmap_send(QEMUFile
*file
,
286 const char *block_name
)
288 RAMBlock
*block
= qemu_ram_block_by_name(block_name
);
289 unsigned long *le_bitmap
, nbits
;
293 error_report("%s: invalid block name: %s", __func__
, block_name
);
297 nbits
= block
->postcopy_length
>> TARGET_PAGE_BITS
;
300 * Make sure the tmp bitmap buffer is big enough, e.g., on 32bit
301 * machines we may need 4 more bytes for padding (see below
302 * comment). So extend it a bit before hand.
304 le_bitmap
= bitmap_new(nbits
+ BITS_PER_LONG
);
307 * Always use little endian when sending the bitmap. This is
308 * required that when source and destination VMs are not using the
309 * same endianness. (Note: big endian won't work.)
311 bitmap_to_le(le_bitmap
, block
->receivedmap
, nbits
);
313 /* Size of the bitmap, in bytes */
314 size
= DIV_ROUND_UP(nbits
, 8);
317 * size is always aligned to 8 bytes for 64bit machines, but it
318 * may not be true for 32bit machines. We need this padding to
319 * make sure the migration can survive even between 32bit and
322 size
= ROUND_UP(size
, 8);
324 qemu_put_be64(file
, size
);
325 qemu_put_buffer(file
, (const uint8_t *)le_bitmap
, size
);
328 * Mark as an end, in case the middle part is screwed up due to
329 * some "mysterious" reason.
331 qemu_put_be64(file
, RAMBLOCK_RECV_BITMAP_ENDING
);
332 int ret
= qemu_fflush(file
);
337 return size
+ sizeof(size
);
341 * An outstanding page request, on the source, having been received
344 struct RAMSrcPageRequest
{
349 QSIMPLEQ_ENTRY(RAMSrcPageRequest
) next_req
;
352 /* State of RAM for migration */
355 * PageSearchStatus structures for the channels when send pages.
356 * Protected by the bitmap_mutex.
358 PageSearchStatus pss
[RAM_CHANNEL_MAX
];
359 /* UFFD file descriptor, used in 'write-tracking' migration */
361 /* total ram size in bytes */
362 uint64_t ram_bytes_total
;
363 /* Last block that we have visited searching for dirty pages */
364 RAMBlock
*last_seen_block
;
365 /* Last dirty target page we have sent */
366 ram_addr_t last_page
;
367 /* last ram version we have seen */
368 uint32_t last_version
;
369 /* How many times we have dirty too many pages */
370 int dirty_rate_high_cnt
;
371 /* these variables are used for bitmap sync */
372 /* last time we did a full bitmap_sync */
373 int64_t time_last_bitmap_sync
;
374 /* bytes transferred at start_time */
375 uint64_t bytes_xfer_prev
;
376 /* number of dirty pages since start_time */
377 uint64_t num_dirty_pages_period
;
378 /* xbzrle misses since the beginning of the period */
379 uint64_t xbzrle_cache_miss_prev
;
380 /* Amount of xbzrle pages since the beginning of the period */
381 uint64_t xbzrle_pages_prev
;
382 /* Amount of xbzrle encoded bytes since the beginning of the period */
383 uint64_t xbzrle_bytes_prev
;
384 /* Are we really using XBZRLE (e.g., after the first round). */
386 /* Are we on the last stage of migration */
389 /* total handled target pages at the beginning of period */
390 uint64_t target_page_count_prev
;
391 /* total handled target pages since start */
392 uint64_t target_page_count
;
393 /* number of dirty bits in the bitmap */
394 uint64_t migration_dirty_pages
;
397 * - dirty/clear bitmap
398 * - migration_dirty_pages
401 QemuMutex bitmap_mutex
;
402 /* The RAMBlock used in the last src_page_requests */
403 RAMBlock
*last_req_rb
;
404 /* Queue of outstanding page requests from the destination */
405 QemuMutex src_page_req_mutex
;
406 QSIMPLEQ_HEAD(, RAMSrcPageRequest
) src_page_requests
;
409 * This is only used when postcopy is in recovery phase, to communicate
410 * between the migration thread and the return path thread on dirty
411 * bitmap synchronizations. This field is unused in other stages of
414 unsigned int postcopy_bmap_sync_requested
;
416 typedef struct RAMState RAMState
;
418 static RAMState
*ram_state
;
420 static NotifierWithReturnList precopy_notifier_list
;
422 /* Whether postcopy has queued requests? */
423 static bool postcopy_has_request(RAMState
*rs
)
425 return !QSIMPLEQ_EMPTY_ATOMIC(&rs
->src_page_requests
);
428 void precopy_infrastructure_init(void)
430 notifier_with_return_list_init(&precopy_notifier_list
);
433 void precopy_add_notifier(NotifierWithReturn
*n
)
435 notifier_with_return_list_add(&precopy_notifier_list
, n
);
438 void precopy_remove_notifier(NotifierWithReturn
*n
)
440 notifier_with_return_remove(n
);
443 int precopy_notify(PrecopyNotifyReason reason
, Error
**errp
)
445 PrecopyNotifyData pnd
;
448 return notifier_with_return_list_notify(&precopy_notifier_list
, &pnd
, errp
);
451 uint64_t ram_bytes_remaining(void)
453 return ram_state
? (ram_state
->migration_dirty_pages
* TARGET_PAGE_SIZE
) :
457 void ram_transferred_add(uint64_t bytes
)
459 if (runstate_is_running()) {
460 stat64_add(&mig_stats
.precopy_bytes
, bytes
);
461 } else if (migration_in_postcopy()) {
462 stat64_add(&mig_stats
.postcopy_bytes
, bytes
);
464 stat64_add(&mig_stats
.downtime_bytes
, bytes
);
468 struct MigrationOps
{
469 int (*ram_save_target_page
)(RAMState
*rs
, PageSearchStatus
*pss
);
471 typedef struct MigrationOps MigrationOps
;
473 MigrationOps
*migration_ops
;
475 static int ram_save_host_page_urgent(PageSearchStatus
*pss
);
477 /* NOTE: page is the PFN not real ram_addr_t. */
478 static void pss_init(PageSearchStatus
*pss
, RAMBlock
*rb
, ram_addr_t page
)
482 pss
->complete_round
= false;
486 * Check whether two PSSs are actively sending the same page. Return true
487 * if it is, false otherwise.
489 static bool pss_overlap(PageSearchStatus
*pss1
, PageSearchStatus
*pss2
)
491 return pss1
->host_page_sending
&& pss2
->host_page_sending
&&
492 (pss1
->host_page_start
== pss2
->host_page_start
);
496 * save_page_header: write page header to wire
498 * If this is the 1st block, it also writes the block identification
500 * Returns the number of bytes written
502 * @pss: current PSS channel status
503 * @block: block that contains the page we want to send
504 * @offset: offset inside the block for the page
505 * in the lower bits, it contains flags
507 static size_t save_page_header(PageSearchStatus
*pss
, QEMUFile
*f
,
508 RAMBlock
*block
, ram_addr_t offset
)
511 bool same_block
= (block
== pss
->last_sent_block
);
514 offset
|= RAM_SAVE_FLAG_CONTINUE
;
516 qemu_put_be64(f
, offset
);
520 len
= strlen(block
->idstr
);
521 qemu_put_byte(f
, len
);
522 qemu_put_buffer(f
, (uint8_t *)block
->idstr
, len
);
524 pss
->last_sent_block
= block
;
530 * mig_throttle_guest_down: throttle down the guest
532 * Reduce amount of guest cpu execution to hopefully slow down memory
533 * writes. If guest dirty memory rate is reduced below the rate at
534 * which we can transfer pages to the destination then we should be
535 * able to complete migration. Some workloads dirty memory way too
536 * fast and will not effectively converge, even with auto-converge.
538 static void mig_throttle_guest_down(uint64_t bytes_dirty_period
,
539 uint64_t bytes_dirty_threshold
)
541 uint64_t pct_initial
= migrate_cpu_throttle_initial();
542 uint64_t pct_increment
= migrate_cpu_throttle_increment();
543 bool pct_tailslow
= migrate_cpu_throttle_tailslow();
544 int pct_max
= migrate_max_cpu_throttle();
546 uint64_t throttle_now
= cpu_throttle_get_percentage();
547 uint64_t cpu_now
, cpu_ideal
, throttle_inc
;
549 /* We have not started throttling yet. Let's start it. */
550 if (!cpu_throttle_active()) {
551 cpu_throttle_set(pct_initial
);
553 /* Throttling already on, just increase the rate */
555 throttle_inc
= pct_increment
;
557 /* Compute the ideal CPU percentage used by Guest, which may
558 * make the dirty rate match the dirty rate threshold. */
559 cpu_now
= 100 - throttle_now
;
560 cpu_ideal
= cpu_now
* (bytes_dirty_threshold
* 1.0 /
562 throttle_inc
= MIN(cpu_now
- cpu_ideal
, pct_increment
);
564 cpu_throttle_set(MIN(throttle_now
+ throttle_inc
, pct_max
));
568 void mig_throttle_counter_reset(void)
570 RAMState
*rs
= ram_state
;
572 rs
->time_last_bitmap_sync
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
573 rs
->num_dirty_pages_period
= 0;
574 rs
->bytes_xfer_prev
= migration_transferred_bytes();
578 * xbzrle_cache_zero_page: insert a zero page in the XBZRLE cache
580 * @current_addr: address for the zero page
582 * Update the xbzrle cache to reflect a page that's been sent as all 0.
583 * The important thing is that a stale (not-yet-0'd) page be replaced
585 * As a bonus, if the page wasn't in the cache it gets added so that
586 * when a small write is made into the 0'd page it gets XBZRLE sent.
588 static void xbzrle_cache_zero_page(ram_addr_t current_addr
)
590 /* We don't care if this fails to allocate a new cache page
591 * as long as it updated an old one */
592 cache_insert(XBZRLE
.cache
, current_addr
, XBZRLE
.zero_target_page
,
593 stat64_get(&mig_stats
.dirty_sync_count
));
596 #define ENCODING_FLAG_XBZRLE 0x1
599 * save_xbzrle_page: compress and send current page
601 * Returns: 1 means that we wrote the page
602 * 0 means that page is identical to the one already sent
603 * -1 means that xbzrle would be longer than normal
605 * @rs: current RAM state
606 * @pss: current PSS channel
607 * @current_data: pointer to the address of the page contents
608 * @current_addr: addr of the page
609 * @block: block that contains the page we want to send
610 * @offset: offset inside the block for the page
612 static int save_xbzrle_page(RAMState
*rs
, PageSearchStatus
*pss
,
613 uint8_t **current_data
, ram_addr_t current_addr
,
614 RAMBlock
*block
, ram_addr_t offset
)
616 int encoded_len
= 0, bytes_xbzrle
;
617 uint8_t *prev_cached_page
;
618 QEMUFile
*file
= pss
->pss_channel
;
619 uint64_t generation
= stat64_get(&mig_stats
.dirty_sync_count
);
621 if (!cache_is_cached(XBZRLE
.cache
, current_addr
, generation
)) {
622 xbzrle_counters
.cache_miss
++;
623 if (!rs
->last_stage
) {
624 if (cache_insert(XBZRLE
.cache
, current_addr
, *current_data
,
628 /* update *current_data when the page has been
629 inserted into cache */
630 *current_data
= get_cached_data(XBZRLE
.cache
, current_addr
);
637 * Reaching here means the page has hit the xbzrle cache, no matter what
638 * encoding result it is (normal encoding, overflow or skipping the page),
639 * count the page as encoded. This is used to calculate the encoding rate.
641 * Example: 2 pages (8KB) being encoded, first page encoding generates 2KB,
642 * 2nd page turns out to be skipped (i.e. no new bytes written to the
643 * page), the overall encoding rate will be 8KB / 2KB = 4, which has the
644 * skipped page included. In this way, the encoding rate can tell if the
645 * guest page is good for xbzrle encoding.
647 xbzrle_counters
.pages
++;
648 prev_cached_page
= get_cached_data(XBZRLE
.cache
, current_addr
);
650 /* save current buffer into memory */
651 memcpy(XBZRLE
.current_buf
, *current_data
, TARGET_PAGE_SIZE
);
653 /* XBZRLE encoding (if there is no overflow) */
654 encoded_len
= xbzrle_encode_buffer(prev_cached_page
, XBZRLE
.current_buf
,
655 TARGET_PAGE_SIZE
, XBZRLE
.encoded_buf
,
659 * Update the cache contents, so that it corresponds to the data
660 * sent, in all cases except where we skip the page.
662 if (!rs
->last_stage
&& encoded_len
!= 0) {
663 memcpy(prev_cached_page
, XBZRLE
.current_buf
, TARGET_PAGE_SIZE
);
665 * In the case where we couldn't compress, ensure that the caller
666 * sends the data from the cache, since the guest might have
667 * changed the RAM since we copied it.
669 *current_data
= prev_cached_page
;
672 if (encoded_len
== 0) {
673 trace_save_xbzrle_page_skipping();
675 } else if (encoded_len
== -1) {
676 trace_save_xbzrle_page_overflow();
677 xbzrle_counters
.overflow
++;
678 xbzrle_counters
.bytes
+= TARGET_PAGE_SIZE
;
682 /* Send XBZRLE based compressed page */
683 bytes_xbzrle
= save_page_header(pss
, pss
->pss_channel
, block
,
684 offset
| RAM_SAVE_FLAG_XBZRLE
);
685 qemu_put_byte(file
, ENCODING_FLAG_XBZRLE
);
686 qemu_put_be16(file
, encoded_len
);
687 qemu_put_buffer(file
, XBZRLE
.encoded_buf
, encoded_len
);
688 bytes_xbzrle
+= encoded_len
+ 1 + 2;
690 * Like compressed_size (please see update_compress_thread_counts),
691 * the xbzrle encoded bytes don't count the 8 byte header with
692 * RAM_SAVE_FLAG_CONTINUE.
694 xbzrle_counters
.bytes
+= bytes_xbzrle
- 8;
695 ram_transferred_add(bytes_xbzrle
);
701 * pss_find_next_dirty: find the next dirty page of current ramblock
703 * This function updates pss->page to point to the next dirty page index
704 * within the ramblock to migrate, or the end of ramblock when nothing
705 * found. Note that when pss->host_page_sending==true it means we're
706 * during sending a host page, so we won't look for dirty page that is
707 * outside the host page boundary.
709 * @pss: the current page search status
711 static void pss_find_next_dirty(PageSearchStatus
*pss
)
713 RAMBlock
*rb
= pss
->block
;
714 unsigned long size
= rb
->used_length
>> TARGET_PAGE_BITS
;
715 unsigned long *bitmap
= rb
->bmap
;
717 if (migrate_ram_is_ignored(rb
)) {
718 /* Points directly to the end, so we know no dirty page */
724 * If during sending a host page, only look for dirty pages within the
725 * current host page being send.
727 if (pss
->host_page_sending
) {
728 assert(pss
->host_page_end
);
729 size
= MIN(size
, pss
->host_page_end
);
732 pss
->page
= find_next_bit(bitmap
, size
, pss
->page
);
735 static void migration_clear_memory_region_dirty_bitmap(RAMBlock
*rb
,
741 if (!rb
->clear_bmap
|| !clear_bmap_test_and_clear(rb
, page
)) {
745 shift
= rb
->clear_bmap_shift
;
747 * CLEAR_BITMAP_SHIFT_MIN should always guarantee this... this
748 * can make things easier sometimes since then start address
749 * of the small chunk will always be 64 pages aligned so the
750 * bitmap will always be aligned to unsigned long. We should
751 * even be able to remove this restriction but I'm simply
756 size
= 1ULL << (TARGET_PAGE_BITS
+ shift
);
757 start
= QEMU_ALIGN_DOWN((ram_addr_t
)page
<< TARGET_PAGE_BITS
, size
);
758 trace_migration_bitmap_clear_dirty(rb
->idstr
, start
, size
, page
);
759 memory_region_clear_dirty_bitmap(rb
->mr
, start
, size
);
763 migration_clear_memory_region_dirty_bitmap_range(RAMBlock
*rb
,
765 unsigned long npages
)
767 unsigned long i
, chunk_pages
= 1UL << rb
->clear_bmap_shift
;
768 unsigned long chunk_start
= QEMU_ALIGN_DOWN(start
, chunk_pages
);
769 unsigned long chunk_end
= QEMU_ALIGN_UP(start
+ npages
, chunk_pages
);
772 * Clear pages from start to start + npages - 1, so the end boundary is
775 for (i
= chunk_start
; i
< chunk_end
; i
+= chunk_pages
) {
776 migration_clear_memory_region_dirty_bitmap(rb
, i
);
781 * colo_bitmap_find_diry:find contiguous dirty pages from start
783 * Returns the page offset within memory region of the start of the contiguout
786 * @rs: current RAM state
787 * @rb: RAMBlock where to search for dirty pages
788 * @start: page where we start the search
789 * @num: the number of contiguous dirty pages
792 unsigned long colo_bitmap_find_dirty(RAMState
*rs
, RAMBlock
*rb
,
793 unsigned long start
, unsigned long *num
)
795 unsigned long size
= rb
->used_length
>> TARGET_PAGE_BITS
;
796 unsigned long *bitmap
= rb
->bmap
;
797 unsigned long first
, next
;
801 if (migrate_ram_is_ignored(rb
)) {
805 first
= find_next_bit(bitmap
, size
, start
);
809 next
= find_next_zero_bit(bitmap
, size
, first
+ 1);
810 assert(next
>= first
);
815 static inline bool migration_bitmap_clear_dirty(RAMState
*rs
,
822 * Clear dirty bitmap if needed. This _must_ be called before we
823 * send any of the page in the chunk because we need to make sure
824 * we can capture further page content changes when we sync dirty
825 * log the next time. So as long as we are going to send any of
826 * the page in the chunk we clear the remote dirty bitmap for all.
827 * Clearing it earlier won't be a problem, but too late will.
829 migration_clear_memory_region_dirty_bitmap(rb
, page
);
831 ret
= test_and_clear_bit(page
, rb
->bmap
);
833 rs
->migration_dirty_pages
--;
839 static void dirty_bitmap_clear_section(MemoryRegionSection
*section
,
842 const hwaddr offset
= section
->offset_within_region
;
843 const hwaddr size
= int128_get64(section
->size
);
844 const unsigned long start
= offset
>> TARGET_PAGE_BITS
;
845 const unsigned long npages
= size
>> TARGET_PAGE_BITS
;
846 RAMBlock
*rb
= section
->mr
->ram_block
;
847 uint64_t *cleared_bits
= opaque
;
850 * We don't grab ram_state->bitmap_mutex because we expect to run
851 * only when starting migration or during postcopy recovery where
852 * we don't have concurrent access.
854 if (!migration_in_postcopy() && !migrate_background_snapshot()) {
855 migration_clear_memory_region_dirty_bitmap_range(rb
, start
, npages
);
857 *cleared_bits
+= bitmap_count_one_with_offset(rb
->bmap
, start
, npages
);
858 bitmap_clear(rb
->bmap
, start
, npages
);
862 * Exclude all dirty pages from migration that fall into a discarded range as
863 * managed by a RamDiscardManager responsible for the mapped memory region of
864 * the RAMBlock. Clear the corresponding bits in the dirty bitmaps.
866 * Discarded pages ("logically unplugged") have undefined content and must
867 * not get migrated, because even reading these pages for migration might
868 * result in undesired behavior.
870 * Returns the number of cleared bits in the RAMBlock dirty bitmap.
872 * Note: The result is only stable while migrating (precopy/postcopy).
874 static uint64_t ramblock_dirty_bitmap_clear_discarded_pages(RAMBlock
*rb
)
876 uint64_t cleared_bits
= 0;
878 if (rb
->mr
&& rb
->bmap
&& memory_region_has_ram_discard_manager(rb
->mr
)) {
879 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(rb
->mr
);
880 MemoryRegionSection section
= {
882 .offset_within_region
= 0,
883 .size
= int128_make64(qemu_ram_get_used_length(rb
)),
886 ram_discard_manager_replay_discarded(rdm
, §ion
,
887 dirty_bitmap_clear_section
,
894 * Check if a host-page aligned page falls into a discarded range as managed by
895 * a RamDiscardManager responsible for the mapped memory region of the RAMBlock.
897 * Note: The result is only stable while migrating (precopy/postcopy).
899 bool ramblock_page_is_discarded(RAMBlock
*rb
, ram_addr_t start
)
901 if (rb
->mr
&& memory_region_has_ram_discard_manager(rb
->mr
)) {
902 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(rb
->mr
);
903 MemoryRegionSection section
= {
905 .offset_within_region
= start
,
906 .size
= int128_make64(qemu_ram_pagesize(rb
)),
909 return !ram_discard_manager_is_populated(rdm
, §ion
);
914 /* Called with RCU critical section */
915 static void ramblock_sync_dirty_bitmap(RAMState
*rs
, RAMBlock
*rb
)
917 uint64_t new_dirty_pages
=
918 cpu_physical_memory_sync_dirty_bitmap(rb
, 0, rb
->used_length
);
920 rs
->migration_dirty_pages
+= new_dirty_pages
;
921 rs
->num_dirty_pages_period
+= new_dirty_pages
;
925 * ram_pagesize_summary: calculate all the pagesizes of a VM
927 * Returns a summary bitmap of the page sizes of all RAMBlocks
929 * For VMs with just normal pages this is equivalent to the host page
930 * size. If it's got some huge pages then it's the OR of all the
931 * different page sizes.
933 uint64_t ram_pagesize_summary(void)
936 uint64_t summary
= 0;
938 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
939 summary
|= block
->page_size
;
945 uint64_t ram_get_total_transferred_pages(void)
947 return stat64_get(&mig_stats
.normal_pages
) +
948 stat64_get(&mig_stats
.zero_pages
) +
949 compress_ram_pages() + xbzrle_counters
.pages
;
952 static void migration_update_rates(RAMState
*rs
, int64_t end_time
)
954 uint64_t page_count
= rs
->target_page_count
- rs
->target_page_count_prev
;
956 /* calculate period counters */
957 stat64_set(&mig_stats
.dirty_pages_rate
,
958 rs
->num_dirty_pages_period
* 1000 /
959 (end_time
- rs
->time_last_bitmap_sync
));
965 if (migrate_xbzrle()) {
966 double encoded_size
, unencoded_size
;
968 xbzrle_counters
.cache_miss_rate
= (double)(xbzrle_counters
.cache_miss
-
969 rs
->xbzrle_cache_miss_prev
) / page_count
;
970 rs
->xbzrle_cache_miss_prev
= xbzrle_counters
.cache_miss
;
971 unencoded_size
= (xbzrle_counters
.pages
- rs
->xbzrle_pages_prev
) *
973 encoded_size
= xbzrle_counters
.bytes
- rs
->xbzrle_bytes_prev
;
974 if (xbzrle_counters
.pages
== rs
->xbzrle_pages_prev
|| !encoded_size
) {
975 xbzrle_counters
.encoding_rate
= 0;
977 xbzrle_counters
.encoding_rate
= unencoded_size
/ encoded_size
;
979 rs
->xbzrle_pages_prev
= xbzrle_counters
.pages
;
980 rs
->xbzrle_bytes_prev
= xbzrle_counters
.bytes
;
982 compress_update_rates(page_count
);
986 * Enable dirty-limit to throttle down the guest
988 static void migration_dirty_limit_guest(void)
991 * dirty page rate quota for all vCPUs fetched from
992 * migration parameter 'vcpu_dirty_limit'
994 static int64_t quota_dirtyrate
;
995 MigrationState
*s
= migrate_get_current();
998 * If dirty limit already enabled and migration parameter
999 * vcpu-dirty-limit untouched.
1001 if (dirtylimit_in_service() &&
1002 quota_dirtyrate
== s
->parameters
.vcpu_dirty_limit
) {
1006 quota_dirtyrate
= s
->parameters
.vcpu_dirty_limit
;
1009 * Set all vCPU a quota dirtyrate, note that the second
1010 * parameter will be ignored if setting all vCPU for the vm
1012 qmp_set_vcpu_dirty_limit(false, -1, quota_dirtyrate
, NULL
);
1013 trace_migration_dirty_limit_guest(quota_dirtyrate
);
1016 static void migration_trigger_throttle(RAMState
*rs
)
1018 uint64_t threshold
= migrate_throttle_trigger_threshold();
1019 uint64_t bytes_xfer_period
=
1020 migration_transferred_bytes() - rs
->bytes_xfer_prev
;
1021 uint64_t bytes_dirty_period
= rs
->num_dirty_pages_period
* TARGET_PAGE_SIZE
;
1022 uint64_t bytes_dirty_threshold
= bytes_xfer_period
* threshold
/ 100;
1024 /* During block migration the auto-converge logic incorrectly detects
1025 * that ram migration makes no progress. Avoid this by disabling the
1026 * throttling logic during the bulk phase of block migration. */
1027 if (blk_mig_bulk_active()) {
1032 * The following detection logic can be refined later. For now:
1033 * Check to see if the ratio between dirtied bytes and the approx.
1034 * amount of bytes that just got transferred since the last time
1035 * we were in this routine reaches the threshold. If that happens
1036 * twice, start or increase throttling.
1038 if ((bytes_dirty_period
> bytes_dirty_threshold
) &&
1039 (++rs
->dirty_rate_high_cnt
>= 2)) {
1040 rs
->dirty_rate_high_cnt
= 0;
1041 if (migrate_auto_converge()) {
1042 trace_migration_throttle();
1043 mig_throttle_guest_down(bytes_dirty_period
,
1044 bytes_dirty_threshold
);
1045 } else if (migrate_dirty_limit()) {
1046 migration_dirty_limit_guest();
1051 static void migration_bitmap_sync(RAMState
*rs
, bool last_stage
)
1056 stat64_add(&mig_stats
.dirty_sync_count
, 1);
1058 if (!rs
->time_last_bitmap_sync
) {
1059 rs
->time_last_bitmap_sync
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1062 trace_migration_bitmap_sync_start();
1063 memory_global_dirty_log_sync(last_stage
);
1065 qemu_mutex_lock(&rs
->bitmap_mutex
);
1066 WITH_RCU_READ_LOCK_GUARD() {
1067 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1068 ramblock_sync_dirty_bitmap(rs
, block
);
1070 stat64_set(&mig_stats
.dirty_bytes_last_sync
, ram_bytes_remaining());
1072 qemu_mutex_unlock(&rs
->bitmap_mutex
);
1074 memory_global_after_dirty_log_sync();
1075 trace_migration_bitmap_sync_end(rs
->num_dirty_pages_period
);
1077 end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1079 /* more than 1 second = 1000 millisecons */
1080 if (end_time
> rs
->time_last_bitmap_sync
+ 1000) {
1081 migration_trigger_throttle(rs
);
1083 migration_update_rates(rs
, end_time
);
1085 rs
->target_page_count_prev
= rs
->target_page_count
;
1087 /* reset period counters */
1088 rs
->time_last_bitmap_sync
= end_time
;
1089 rs
->num_dirty_pages_period
= 0;
1090 rs
->bytes_xfer_prev
= migration_transferred_bytes();
1092 if (migrate_events()) {
1093 uint64_t generation
= stat64_get(&mig_stats
.dirty_sync_count
);
1094 qapi_event_send_migration_pass(generation
);
1098 static void migration_bitmap_sync_precopy(RAMState
*rs
, bool last_stage
)
1100 Error
*local_err
= NULL
;
1103 * The current notifier usage is just an optimization to migration, so we
1104 * don't stop the normal migration process in the error case.
1106 if (precopy_notify(PRECOPY_NOTIFY_BEFORE_BITMAP_SYNC
, &local_err
)) {
1107 error_report_err(local_err
);
1111 migration_bitmap_sync(rs
, last_stage
);
1113 if (precopy_notify(PRECOPY_NOTIFY_AFTER_BITMAP_SYNC
, &local_err
)) {
1114 error_report_err(local_err
);
1118 void ram_release_page(const char *rbname
, uint64_t offset
)
1120 if (!migrate_release_ram() || !migration_in_postcopy()) {
1124 ram_discard_range(rbname
, offset
, TARGET_PAGE_SIZE
);
1128 * save_zero_page: send the zero page to the stream
1130 * Returns the number of pages written.
1132 * @rs: current RAM state
1133 * @pss: current PSS channel
1134 * @offset: offset inside the block for the page
1136 static int save_zero_page(RAMState
*rs
, PageSearchStatus
*pss
,
1139 uint8_t *p
= pss
->block
->host
+ offset
;
1140 QEMUFile
*file
= pss
->pss_channel
;
1143 if (!buffer_is_zero(p
, TARGET_PAGE_SIZE
)) {
1147 stat64_add(&mig_stats
.zero_pages
, 1);
1149 if (migrate_mapped_ram()) {
1150 /* zero pages are not transferred with mapped-ram */
1151 clear_bit_atomic(offset
>> TARGET_PAGE_BITS
, pss
->block
->file_bmap
);
1155 len
+= save_page_header(pss
, file
, pss
->block
, offset
| RAM_SAVE_FLAG_ZERO
);
1156 qemu_put_byte(file
, 0);
1158 ram_release_page(pss
->block
->idstr
, offset
);
1159 ram_transferred_add(len
);
1162 * Must let xbzrle know, otherwise a previous (now 0'd) cached
1163 * page would be stale.
1165 if (rs
->xbzrle_started
) {
1166 XBZRLE_cache_lock();
1167 xbzrle_cache_zero_page(pss
->block
->offset
+ offset
);
1168 XBZRLE_cache_unlock();
1175 * @pages: the number of pages written by the control path,
1177 * > 0 - number of pages written
1179 * Return true if the pages has been saved, otherwise false is returned.
1181 static bool control_save_page(PageSearchStatus
*pss
,
1182 ram_addr_t offset
, int *pages
)
1186 ret
= rdma_control_save_page(pss
->pss_channel
, pss
->block
->offset
, offset
,
1188 if (ret
== RAM_SAVE_CONTROL_NOT_SUPP
) {
1192 if (ret
== RAM_SAVE_CONTROL_DELAYED
) {
1201 * directly send the page to the stream
1203 * Returns the number of pages written.
1205 * @pss: current PSS channel
1206 * @block: block that contains the page we want to send
1207 * @offset: offset inside the block for the page
1208 * @buf: the page to be sent
1209 * @async: send to page asyncly
1211 static int save_normal_page(PageSearchStatus
*pss
, RAMBlock
*block
,
1212 ram_addr_t offset
, uint8_t *buf
, bool async
)
1214 QEMUFile
*file
= pss
->pss_channel
;
1216 if (migrate_mapped_ram()) {
1217 qemu_put_buffer_at(file
, buf
, TARGET_PAGE_SIZE
,
1218 block
->pages_offset
+ offset
);
1219 set_bit(offset
>> TARGET_PAGE_BITS
, block
->file_bmap
);
1221 ram_transferred_add(save_page_header(pss
, pss
->pss_channel
, block
,
1222 offset
| RAM_SAVE_FLAG_PAGE
));
1224 qemu_put_buffer_async(file
, buf
, TARGET_PAGE_SIZE
,
1225 migrate_release_ram() &&
1226 migration_in_postcopy());
1228 qemu_put_buffer(file
, buf
, TARGET_PAGE_SIZE
);
1231 ram_transferred_add(TARGET_PAGE_SIZE
);
1232 stat64_add(&mig_stats
.normal_pages
, 1);
1237 * ram_save_page: send the given page to the stream
1239 * Returns the number of pages written.
1241 * >=0 - Number of pages written - this might legally be 0
1242 * if xbzrle noticed the page was the same.
1244 * @rs: current RAM state
1245 * @block: block that contains the page we want to send
1246 * @offset: offset inside the block for the page
1248 static int ram_save_page(RAMState
*rs
, PageSearchStatus
*pss
)
1252 bool send_async
= true;
1253 RAMBlock
*block
= pss
->block
;
1254 ram_addr_t offset
= ((ram_addr_t
)pss
->page
) << TARGET_PAGE_BITS
;
1255 ram_addr_t current_addr
= block
->offset
+ offset
;
1257 p
= block
->host
+ offset
;
1258 trace_ram_save_page(block
->idstr
, (uint64_t)offset
, p
);
1260 XBZRLE_cache_lock();
1261 if (rs
->xbzrle_started
&& !migration_in_postcopy()) {
1262 pages
= save_xbzrle_page(rs
, pss
, &p
, current_addr
,
1264 if (!rs
->last_stage
) {
1265 /* Can't send this cached data async, since the cache page
1266 * might get updated before it gets to the wire
1272 /* XBZRLE overflow or normal page */
1274 pages
= save_normal_page(pss
, block
, offset
, p
, send_async
);
1277 XBZRLE_cache_unlock();
1282 static int ram_save_multifd_page(RAMBlock
*block
, ram_addr_t offset
)
1284 if (!multifd_queue_page(block
, offset
)) {
1287 stat64_add(&mig_stats
.normal_pages
, 1);
1292 int compress_send_queued_data(CompressParam
*param
)
1294 PageSearchStatus
*pss
= &ram_state
->pss
[RAM_CHANNEL_PRECOPY
];
1295 MigrationState
*ms
= migrate_get_current();
1296 QEMUFile
*file
= ms
->to_dst_file
;
1299 RAMBlock
*block
= param
->block
;
1300 ram_addr_t offset
= param
->offset
;
1302 if (param
->result
== RES_NONE
) {
1306 assert(block
== pss
->last_sent_block
);
1308 if (param
->result
== RES_ZEROPAGE
) {
1309 assert(qemu_file_buffer_empty(param
->file
));
1310 len
+= save_page_header(pss
, file
, block
, offset
| RAM_SAVE_FLAG_ZERO
);
1311 qemu_put_byte(file
, 0);
1313 ram_release_page(block
->idstr
, offset
);
1314 } else if (param
->result
== RES_COMPRESS
) {
1315 assert(!qemu_file_buffer_empty(param
->file
));
1316 len
+= save_page_header(pss
, file
, block
,
1317 offset
| RAM_SAVE_FLAG_COMPRESS_PAGE
);
1318 len
+= qemu_put_qemu_file(file
, param
->file
);
1323 update_compress_thread_counts(param
, len
);
1328 #define PAGE_ALL_CLEAN 0
1329 #define PAGE_TRY_AGAIN 1
1330 #define PAGE_DIRTY_FOUND 2
1332 * find_dirty_block: find the next dirty page and update any state
1333 * associated with the search process.
1336 * <0: An error happened
1337 * PAGE_ALL_CLEAN: no dirty page found, give up
1338 * PAGE_TRY_AGAIN: no dirty page found, retry for next block
1339 * PAGE_DIRTY_FOUND: dirty page found
1341 * @rs: current RAM state
1342 * @pss: data about the state of the current dirty page scan
1343 * @again: set to false if the search has scanned the whole of RAM
1345 static int find_dirty_block(RAMState
*rs
, PageSearchStatus
*pss
)
1347 /* Update pss->page for the next dirty bit in ramblock */
1348 pss_find_next_dirty(pss
);
1350 if (pss
->complete_round
&& pss
->block
== rs
->last_seen_block
&&
1351 pss
->page
>= rs
->last_page
) {
1353 * We've been once around the RAM and haven't found anything.
1356 return PAGE_ALL_CLEAN
;
1358 if (!offset_in_ramblock(pss
->block
,
1359 ((ram_addr_t
)pss
->page
) << TARGET_PAGE_BITS
)) {
1360 /* Didn't find anything in this RAM Block */
1362 pss
->block
= QLIST_NEXT_RCU(pss
->block
, next
);
1364 if (migrate_multifd() &&
1365 (!migrate_multifd_flush_after_each_section() ||
1366 migrate_mapped_ram())) {
1367 QEMUFile
*f
= rs
->pss
[RAM_CHANNEL_PRECOPY
].pss_channel
;
1368 int ret
= multifd_send_sync_main();
1373 if (!migrate_mapped_ram()) {
1374 qemu_put_be64(f
, RAM_SAVE_FLAG_MULTIFD_FLUSH
);
1379 * If memory migration starts over, we will meet a dirtied page
1380 * which may still exists in compression threads's ring, so we
1381 * should flush the compressed data to make sure the new page
1382 * is not overwritten by the old one in the destination.
1384 * Also If xbzrle is on, stop using the data compression at this
1385 * point. In theory, xbzrle can do better than compression.
1387 compress_flush_data();
1389 /* Hit the end of the list */
1390 pss
->block
= QLIST_FIRST_RCU(&ram_list
.blocks
);
1391 /* Flag that we've looped */
1392 pss
->complete_round
= true;
1393 /* After the first round, enable XBZRLE. */
1394 if (migrate_xbzrle()) {
1395 rs
->xbzrle_started
= true;
1398 /* Didn't find anything this time, but try again on the new block */
1399 return PAGE_TRY_AGAIN
;
1401 /* We've found something */
1402 return PAGE_DIRTY_FOUND
;
1407 * unqueue_page: gets a page of the queue
1409 * Helper for 'get_queued_page' - gets a page off the queue
1411 * Returns the block of the page (or NULL if none available)
1413 * @rs: current RAM state
1414 * @offset: used to return the offset within the RAMBlock
1416 static RAMBlock
*unqueue_page(RAMState
*rs
, ram_addr_t
*offset
)
1418 struct RAMSrcPageRequest
*entry
;
1419 RAMBlock
*block
= NULL
;
1421 if (!postcopy_has_request(rs
)) {
1425 QEMU_LOCK_GUARD(&rs
->src_page_req_mutex
);
1428 * This should _never_ change even after we take the lock, because no one
1429 * should be taking anything off the request list other than us.
1431 assert(postcopy_has_request(rs
));
1433 entry
= QSIMPLEQ_FIRST(&rs
->src_page_requests
);
1435 *offset
= entry
->offset
;
1437 if (entry
->len
> TARGET_PAGE_SIZE
) {
1438 entry
->len
-= TARGET_PAGE_SIZE
;
1439 entry
->offset
+= TARGET_PAGE_SIZE
;
1441 memory_region_unref(block
->mr
);
1442 QSIMPLEQ_REMOVE_HEAD(&rs
->src_page_requests
, next_req
);
1444 migration_consume_urgent_request();
1450 #if defined(__linux__)
1452 * poll_fault_page: try to get next UFFD write fault page and, if pending fault
1453 * is found, return RAM block pointer and page offset
1455 * Returns pointer to the RAMBlock containing faulting page,
1456 * NULL if no write faults are pending
1458 * @rs: current RAM state
1459 * @offset: page offset from the beginning of the block
1461 static RAMBlock
*poll_fault_page(RAMState
*rs
, ram_addr_t
*offset
)
1463 struct uffd_msg uffd_msg
;
1468 if (!migrate_background_snapshot()) {
1472 res
= uffd_read_events(rs
->uffdio_fd
, &uffd_msg
, 1);
1477 page_address
= (void *)(uintptr_t) uffd_msg
.arg
.pagefault
.address
;
1478 block
= qemu_ram_block_from_host(page_address
, false, offset
);
1479 assert(block
&& (block
->flags
& RAM_UF_WRITEPROTECT
) != 0);
1484 * ram_save_release_protection: release UFFD write protection after
1485 * a range of pages has been saved
1487 * @rs: current RAM state
1488 * @pss: page-search-status structure
1489 * @start_page: index of the first page in the range relative to pss->block
1491 * Returns 0 on success, negative value in case of an error
1493 static int ram_save_release_protection(RAMState
*rs
, PageSearchStatus
*pss
,
1494 unsigned long start_page
)
1498 /* Check if page is from UFFD-managed region. */
1499 if (pss
->block
->flags
& RAM_UF_WRITEPROTECT
) {
1500 void *page_address
= pss
->block
->host
+ (start_page
<< TARGET_PAGE_BITS
);
1501 uint64_t run_length
= (pss
->page
- start_page
) << TARGET_PAGE_BITS
;
1503 /* Flush async buffers before un-protect. */
1504 qemu_fflush(pss
->pss_channel
);
1505 /* Un-protect memory range. */
1506 res
= uffd_change_protection(rs
->uffdio_fd
, page_address
, run_length
,
1513 /* ram_write_tracking_available: check if kernel supports required UFFD features
1515 * Returns true if supports, false otherwise
1517 bool ram_write_tracking_available(void)
1519 uint64_t uffd_features
;
1522 res
= uffd_query_features(&uffd_features
);
1524 (uffd_features
& UFFD_FEATURE_PAGEFAULT_FLAG_WP
) != 0);
1527 /* ram_write_tracking_compatible: check if guest configuration is
1528 * compatible with 'write-tracking'
1530 * Returns true if compatible, false otherwise
1532 bool ram_write_tracking_compatible(void)
1534 const uint64_t uffd_ioctls_mask
= BIT(_UFFDIO_WRITEPROTECT
);
1539 /* Open UFFD file descriptor */
1540 uffd_fd
= uffd_create_fd(UFFD_FEATURE_PAGEFAULT_FLAG_WP
, false);
1545 RCU_READ_LOCK_GUARD();
1547 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1548 uint64_t uffd_ioctls
;
1550 /* Nothing to do with read-only and MMIO-writable regions */
1551 if (block
->mr
->readonly
|| block
->mr
->rom_device
) {
1554 /* Try to register block memory via UFFD-IO to track writes */
1555 if (uffd_register_memory(uffd_fd
, block
->host
, block
->max_length
,
1556 UFFDIO_REGISTER_MODE_WP
, &uffd_ioctls
)) {
1559 if ((uffd_ioctls
& uffd_ioctls_mask
) != uffd_ioctls_mask
) {
1566 uffd_close_fd(uffd_fd
);
1570 static inline void populate_read_range(RAMBlock
*block
, ram_addr_t offset
,
1573 const ram_addr_t end
= offset
+ size
;
1576 * We read one byte of each page; this will preallocate page tables if
1577 * required and populate the shared zeropage on MAP_PRIVATE anonymous memory
1578 * where no page was populated yet. This might require adaption when
1579 * supporting other mappings, like shmem.
1581 for (; offset
< end
; offset
+= block
->page_size
) {
1582 char tmp
= *((char *)block
->host
+ offset
);
1584 /* Don't optimize the read out */
1585 asm volatile("" : "+r" (tmp
));
1589 static inline int populate_read_section(MemoryRegionSection
*section
,
1592 const hwaddr size
= int128_get64(section
->size
);
1593 hwaddr offset
= section
->offset_within_region
;
1594 RAMBlock
*block
= section
->mr
->ram_block
;
1596 populate_read_range(block
, offset
, size
);
1601 * ram_block_populate_read: preallocate page tables and populate pages in the
1602 * RAM block by reading a byte of each page.
1604 * Since it's solely used for userfault_fd WP feature, here we just
1605 * hardcode page size to qemu_real_host_page_size.
1607 * @block: RAM block to populate
1609 static void ram_block_populate_read(RAMBlock
*rb
)
1612 * Skip populating all pages that fall into a discarded range as managed by
1613 * a RamDiscardManager responsible for the mapped memory region of the
1614 * RAMBlock. Such discarded ("logically unplugged") parts of a RAMBlock
1615 * must not get populated automatically. We don't have to track
1616 * modifications via userfaultfd WP reliably, because these pages will
1617 * not be part of the migration stream either way -- see
1618 * ramblock_dirty_bitmap_exclude_discarded_pages().
1620 * Note: The result is only stable while migrating (precopy/postcopy).
1622 if (rb
->mr
&& memory_region_has_ram_discard_manager(rb
->mr
)) {
1623 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(rb
->mr
);
1624 MemoryRegionSection section
= {
1626 .offset_within_region
= 0,
1627 .size
= rb
->mr
->size
,
1630 ram_discard_manager_replay_populated(rdm
, §ion
,
1631 populate_read_section
, NULL
);
1633 populate_read_range(rb
, 0, rb
->used_length
);
1638 * ram_write_tracking_prepare: prepare for UFFD-WP memory tracking
1640 void ram_write_tracking_prepare(void)
1644 RCU_READ_LOCK_GUARD();
1646 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1647 /* Nothing to do with read-only and MMIO-writable regions */
1648 if (block
->mr
->readonly
|| block
->mr
->rom_device
) {
1653 * Populate pages of the RAM block before enabling userfault_fd
1656 * This stage is required since ioctl(UFFDIO_WRITEPROTECT) with
1657 * UFFDIO_WRITEPROTECT_MODE_WP mode setting would silently skip
1658 * pages with pte_none() entries in page table.
1660 ram_block_populate_read(block
);
1664 static inline int uffd_protect_section(MemoryRegionSection
*section
,
1667 const hwaddr size
= int128_get64(section
->size
);
1668 const hwaddr offset
= section
->offset_within_region
;
1669 RAMBlock
*rb
= section
->mr
->ram_block
;
1670 int uffd_fd
= (uintptr_t)opaque
;
1672 return uffd_change_protection(uffd_fd
, rb
->host
+ offset
, size
, true,
1676 static int ram_block_uffd_protect(RAMBlock
*rb
, int uffd_fd
)
1678 assert(rb
->flags
& RAM_UF_WRITEPROTECT
);
1680 /* See ram_block_populate_read() */
1681 if (rb
->mr
&& memory_region_has_ram_discard_manager(rb
->mr
)) {
1682 RamDiscardManager
*rdm
= memory_region_get_ram_discard_manager(rb
->mr
);
1683 MemoryRegionSection section
= {
1685 .offset_within_region
= 0,
1686 .size
= rb
->mr
->size
,
1689 return ram_discard_manager_replay_populated(rdm
, §ion
,
1690 uffd_protect_section
,
1691 (void *)(uintptr_t)uffd_fd
);
1693 return uffd_change_protection(uffd_fd
, rb
->host
,
1694 rb
->used_length
, true, false);
1698 * ram_write_tracking_start: start UFFD-WP memory tracking
1700 * Returns 0 for success or negative value in case of error
1702 int ram_write_tracking_start(void)
1705 RAMState
*rs
= ram_state
;
1708 /* Open UFFD file descriptor */
1709 uffd_fd
= uffd_create_fd(UFFD_FEATURE_PAGEFAULT_FLAG_WP
, true);
1713 rs
->uffdio_fd
= uffd_fd
;
1715 RCU_READ_LOCK_GUARD();
1717 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1718 /* Nothing to do with read-only and MMIO-writable regions */
1719 if (block
->mr
->readonly
|| block
->mr
->rom_device
) {
1723 /* Register block memory with UFFD to track writes */
1724 if (uffd_register_memory(rs
->uffdio_fd
, block
->host
,
1725 block
->max_length
, UFFDIO_REGISTER_MODE_WP
, NULL
)) {
1728 block
->flags
|= RAM_UF_WRITEPROTECT
;
1729 memory_region_ref(block
->mr
);
1731 /* Apply UFFD write protection to the block memory range */
1732 if (ram_block_uffd_protect(block
, uffd_fd
)) {
1736 trace_ram_write_tracking_ramblock_start(block
->idstr
, block
->page_size
,
1737 block
->host
, block
->max_length
);
1743 error_report("ram_write_tracking_start() failed: restoring initial memory state");
1745 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1746 if ((block
->flags
& RAM_UF_WRITEPROTECT
) == 0) {
1749 uffd_unregister_memory(rs
->uffdio_fd
, block
->host
, block
->max_length
);
1750 /* Cleanup flags and remove reference */
1751 block
->flags
&= ~RAM_UF_WRITEPROTECT
;
1752 memory_region_unref(block
->mr
);
1755 uffd_close_fd(uffd_fd
);
1761 * ram_write_tracking_stop: stop UFFD-WP memory tracking and remove protection
1763 void ram_write_tracking_stop(void)
1765 RAMState
*rs
= ram_state
;
1768 RCU_READ_LOCK_GUARD();
1770 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
1771 if ((block
->flags
& RAM_UF_WRITEPROTECT
) == 0) {
1774 uffd_unregister_memory(rs
->uffdio_fd
, block
->host
, block
->max_length
);
1776 trace_ram_write_tracking_ramblock_stop(block
->idstr
, block
->page_size
,
1777 block
->host
, block
->max_length
);
1779 /* Cleanup flags and remove reference */
1780 block
->flags
&= ~RAM_UF_WRITEPROTECT
;
1781 memory_region_unref(block
->mr
);
1784 /* Finally close UFFD file descriptor */
1785 uffd_close_fd(rs
->uffdio_fd
);
1790 /* No target OS support, stubs just fail or ignore */
1792 static RAMBlock
*poll_fault_page(RAMState
*rs
, ram_addr_t
*offset
)
1800 static int ram_save_release_protection(RAMState
*rs
, PageSearchStatus
*pss
,
1801 unsigned long start_page
)
1810 bool ram_write_tracking_available(void)
1815 bool ram_write_tracking_compatible(void)
1821 int ram_write_tracking_start(void)
1827 void ram_write_tracking_stop(void)
1831 #endif /* defined(__linux__) */
1834 * get_queued_page: unqueue a page from the postcopy requests
1836 * Skips pages that are already sent (!dirty)
1838 * Returns true if a queued page is found
1840 * @rs: current RAM state
1841 * @pss: data about the state of the current dirty page scan
1843 static bool get_queued_page(RAMState
*rs
, PageSearchStatus
*pss
)
1850 block
= unqueue_page(rs
, &offset
);
1852 * We're sending this page, and since it's postcopy nothing else
1853 * will dirty it, and we must make sure it doesn't get sent again
1854 * even if this queue request was received after the background
1855 * search already sent it.
1860 page
= offset
>> TARGET_PAGE_BITS
;
1861 dirty
= test_bit(page
, block
->bmap
);
1863 trace_get_queued_page_not_dirty(block
->idstr
, (uint64_t)offset
,
1866 trace_get_queued_page(block
->idstr
, (uint64_t)offset
, page
);
1870 } while (block
&& !dirty
);
1874 * Poll write faults too if background snapshot is enabled; that's
1875 * when we have vcpus got blocked by the write protected pages.
1877 block
= poll_fault_page(rs
, &offset
);
1882 * We want the background search to continue from the queued page
1883 * since the guest is likely to want other pages near to the page
1884 * it just requested.
1887 pss
->page
= offset
>> TARGET_PAGE_BITS
;
1890 * This unqueued page would break the "one round" check, even is
1893 pss
->complete_round
= false;
1900 * migration_page_queue_free: drop any remaining pages in the ram
1903 * It should be empty at the end anyway, but in error cases there may
1904 * be some left. in case that there is any page left, we drop it.
1907 static void migration_page_queue_free(RAMState
*rs
)
1909 struct RAMSrcPageRequest
*mspr
, *next_mspr
;
1910 /* This queue generally should be empty - but in the case of a failed
1911 * migration might have some droppings in.
1913 RCU_READ_LOCK_GUARD();
1914 QSIMPLEQ_FOREACH_SAFE(mspr
, &rs
->src_page_requests
, next_req
, next_mspr
) {
1915 memory_region_unref(mspr
->rb
->mr
);
1916 QSIMPLEQ_REMOVE_HEAD(&rs
->src_page_requests
, next_req
);
1922 * ram_save_queue_pages: queue the page for transmission
1924 * A request from postcopy destination for example.
1926 * Returns zero on success or negative on error
1928 * @rbname: Name of the RAMBLock of the request. NULL means the
1929 * same that last one.
1930 * @start: starting address from the start of the RAMBlock
1931 * @len: length (in bytes) to send
1933 int ram_save_queue_pages(const char *rbname
, ram_addr_t start
, ram_addr_t len
,
1937 RAMState
*rs
= ram_state
;
1939 stat64_add(&mig_stats
.postcopy_requests
, 1);
1940 RCU_READ_LOCK_GUARD();
1943 /* Reuse last RAMBlock */
1944 ramblock
= rs
->last_req_rb
;
1948 * Shouldn't happen, we can't reuse the last RAMBlock if
1949 * it's the 1st request.
1951 error_setg(errp
, "MIG_RP_MSG_REQ_PAGES has no previous block");
1955 ramblock
= qemu_ram_block_by_name(rbname
);
1958 /* We shouldn't be asked for a non-existent RAMBlock */
1959 error_setg(errp
, "MIG_RP_MSG_REQ_PAGES has no block '%s'", rbname
);
1962 rs
->last_req_rb
= ramblock
;
1964 trace_ram_save_queue_pages(ramblock
->idstr
, start
, len
);
1965 if (!offset_in_ramblock(ramblock
, start
+ len
- 1)) {
1966 error_setg(errp
, "MIG_RP_MSG_REQ_PAGES request overrun, "
1967 "start=" RAM_ADDR_FMT
" len="
1968 RAM_ADDR_FMT
" blocklen=" RAM_ADDR_FMT
,
1969 start
, len
, ramblock
->used_length
);
1974 * When with postcopy preempt, we send back the page directly in the
1977 if (postcopy_preempt_active()) {
1978 ram_addr_t page_start
= start
>> TARGET_PAGE_BITS
;
1979 size_t page_size
= qemu_ram_pagesize(ramblock
);
1980 PageSearchStatus
*pss
= &ram_state
->pss
[RAM_CHANNEL_POSTCOPY
];
1983 qemu_mutex_lock(&rs
->bitmap_mutex
);
1985 pss_init(pss
, ramblock
, page_start
);
1987 * Always use the preempt channel, and make sure it's there. It's
1988 * safe to access without lock, because when rp-thread is running
1989 * we should be the only one who operates on the qemufile
1991 pss
->pss_channel
= migrate_get_current()->postcopy_qemufile_src
;
1992 assert(pss
->pss_channel
);
1995 * It must be either one or multiple of host page size. Just
1996 * assert; if something wrong we're mostly split brain anyway.
1998 assert(len
% page_size
== 0);
2000 if (ram_save_host_page_urgent(pss
)) {
2001 error_setg(errp
, "ram_save_host_page_urgent() failed: "
2002 "ramblock=%s, start_addr=0x"RAM_ADDR_FMT
,
2003 ramblock
->idstr
, start
);
2008 * NOTE: after ram_save_host_page_urgent() succeeded, pss->page
2009 * will automatically be moved and point to the next host page
2010 * we're going to send, so no need to update here.
2012 * Normally QEMU never sends >1 host page in requests, so
2013 * logically we don't even need that as the loop should only
2014 * run once, but just to be consistent.
2018 qemu_mutex_unlock(&rs
->bitmap_mutex
);
2023 struct RAMSrcPageRequest
*new_entry
=
2024 g_new0(struct RAMSrcPageRequest
, 1);
2025 new_entry
->rb
= ramblock
;
2026 new_entry
->offset
= start
;
2027 new_entry
->len
= len
;
2029 memory_region_ref(ramblock
->mr
);
2030 qemu_mutex_lock(&rs
->src_page_req_mutex
);
2031 QSIMPLEQ_INSERT_TAIL(&rs
->src_page_requests
, new_entry
, next_req
);
2032 migration_make_urgent_request();
2033 qemu_mutex_unlock(&rs
->src_page_req_mutex
);
2039 * try to compress the page before posting it out, return true if the page
2040 * has been properly handled by compression, otherwise needs other
2041 * paths to handle it
2043 static bool save_compress_page(RAMState
*rs
, PageSearchStatus
*pss
,
2046 if (!migrate_compress()) {
2051 * When starting the process of a new block, the first page of
2052 * the block should be sent out before other pages in the same
2053 * block, and all the pages in last block should have been sent
2054 * out, keeping this order is important, because the 'cont' flag
2055 * is used to avoid resending the block name.
2057 * We post the fist page as normal page as compression will take
2058 * much CPU resource.
2060 if (pss
->block
!= pss
->last_sent_block
) {
2061 compress_flush_data();
2065 return compress_page_with_multi_thread(pss
->block
, offset
,
2066 compress_send_queued_data
);
2070 * ram_save_target_page_legacy: save one target page
2072 * Returns the number of pages written
2074 * @rs: current RAM state
2075 * @pss: data about the page we want to send
2077 static int ram_save_target_page_legacy(RAMState
*rs
, PageSearchStatus
*pss
)
2079 RAMBlock
*block
= pss
->block
;
2080 ram_addr_t offset
= ((ram_addr_t
)pss
->page
) << TARGET_PAGE_BITS
;
2083 if (control_save_page(pss
, offset
, &res
)) {
2087 if (save_compress_page(rs
, pss
, offset
)) {
2091 if (save_zero_page(rs
, pss
, offset
)) {
2096 * Do not use multifd in postcopy as one whole host page should be
2097 * placed. Meanwhile postcopy requires atomic update of pages, so even
2098 * if host page size == guest page size the dest guest during run may
2099 * still see partially copied pages which is data corruption.
2101 if (migrate_multifd() && !migration_in_postcopy()) {
2102 return ram_save_multifd_page(block
, offset
);
2105 return ram_save_page(rs
, pss
);
2108 /* Should be called before sending a host page */
2109 static void pss_host_page_prepare(PageSearchStatus
*pss
)
2111 /* How many guest pages are there in one host page? */
2112 size_t guest_pfns
= qemu_ram_pagesize(pss
->block
) >> TARGET_PAGE_BITS
;
2114 pss
->host_page_sending
= true;
2115 if (guest_pfns
<= 1) {
2117 * This covers both when guest psize == host psize, or when guest
2118 * has larger psize than the host (guest_pfns==0).
2120 * For the latter, we always send one whole guest page per
2121 * iteration of the host page (example: an Alpha VM on x86 host
2122 * will have guest psize 8K while host psize 4K).
2124 pss
->host_page_start
= pss
->page
;
2125 pss
->host_page_end
= pss
->page
+ 1;
2128 * The host page spans over multiple guest pages, we send them
2129 * within the same host page iteration.
2131 pss
->host_page_start
= ROUND_DOWN(pss
->page
, guest_pfns
);
2132 pss
->host_page_end
= ROUND_UP(pss
->page
+ 1, guest_pfns
);
2137 * Whether the page pointed by PSS is within the host page being sent.
2138 * Must be called after a previous pss_host_page_prepare().
2140 static bool pss_within_range(PageSearchStatus
*pss
)
2142 ram_addr_t ram_addr
;
2144 assert(pss
->host_page_sending
);
2146 /* Over host-page boundary? */
2147 if (pss
->page
>= pss
->host_page_end
) {
2151 ram_addr
= ((ram_addr_t
)pss
->page
) << TARGET_PAGE_BITS
;
2153 return offset_in_ramblock(pss
->block
, ram_addr
);
2156 static void pss_host_page_finish(PageSearchStatus
*pss
)
2158 pss
->host_page_sending
= false;
2159 /* This is not needed, but just to reset it */
2160 pss
->host_page_start
= pss
->host_page_end
= 0;
2164 * Send an urgent host page specified by `pss'. Need to be called with
2165 * bitmap_mutex held.
2167 * Returns 0 if save host page succeeded, false otherwise.
2169 static int ram_save_host_page_urgent(PageSearchStatus
*pss
)
2171 bool page_dirty
, sent
= false;
2172 RAMState
*rs
= ram_state
;
2175 trace_postcopy_preempt_send_host_page(pss
->block
->idstr
, pss
->page
);
2176 pss_host_page_prepare(pss
);
2179 * If precopy is sending the same page, let it be done in precopy, or
2180 * we could send the same page in two channels and none of them will
2181 * receive the whole page.
2183 if (pss_overlap(pss
, &ram_state
->pss
[RAM_CHANNEL_PRECOPY
])) {
2184 trace_postcopy_preempt_hit(pss
->block
->idstr
,
2185 pss
->page
<< TARGET_PAGE_BITS
);
2190 page_dirty
= migration_bitmap_clear_dirty(rs
, pss
->block
, pss
->page
);
2193 /* Be strict to return code; it must be 1, or what else? */
2194 if (migration_ops
->ram_save_target_page(rs
, pss
) != 1) {
2195 error_report_once("%s: ram_save_target_page failed", __func__
);
2201 pss_find_next_dirty(pss
);
2202 } while (pss_within_range(pss
));
2204 pss_host_page_finish(pss
);
2205 /* For urgent requests, flush immediately if sent */
2207 qemu_fflush(pss
->pss_channel
);
2213 * ram_save_host_page: save a whole host page
2215 * Starting at *offset send pages up to the end of the current host
2216 * page. It's valid for the initial offset to point into the middle of
2217 * a host page in which case the remainder of the hostpage is sent.
2218 * Only dirty target pages are sent. Note that the host page size may
2219 * be a huge page for this block.
2221 * The saving stops at the boundary of the used_length of the block
2222 * if the RAMBlock isn't a multiple of the host page size.
2224 * The caller must be with ram_state.bitmap_mutex held to call this
2225 * function. Note that this function can temporarily release the lock, but
2226 * when the function is returned it'll make sure the lock is still held.
2228 * Returns the number of pages written or negative on error
2230 * @rs: current RAM state
2231 * @pss: data about the page we want to send
2233 static int ram_save_host_page(RAMState
*rs
, PageSearchStatus
*pss
)
2235 bool page_dirty
, preempt_active
= postcopy_preempt_active();
2236 int tmppages
, pages
= 0;
2237 size_t pagesize_bits
=
2238 qemu_ram_pagesize(pss
->block
) >> TARGET_PAGE_BITS
;
2239 unsigned long start_page
= pss
->page
;
2242 if (migrate_ram_is_ignored(pss
->block
)) {
2243 error_report("block %s should not be migrated !", pss
->block
->idstr
);
2247 /* Update host page boundary information */
2248 pss_host_page_prepare(pss
);
2251 page_dirty
= migration_bitmap_clear_dirty(rs
, pss
->block
, pss
->page
);
2253 /* Check the pages is dirty and if it is send it */
2256 * Properly yield the lock only in postcopy preempt mode
2257 * because both migration thread and rp-return thread can
2258 * operate on the bitmaps.
2260 if (preempt_active
) {
2261 qemu_mutex_unlock(&rs
->bitmap_mutex
);
2263 tmppages
= migration_ops
->ram_save_target_page(rs
, pss
);
2264 if (tmppages
>= 0) {
2267 * Allow rate limiting to happen in the middle of huge pages if
2268 * something is sent in the current iteration.
2270 if (pagesize_bits
> 1 && tmppages
> 0) {
2271 migration_rate_limit();
2274 if (preempt_active
) {
2275 qemu_mutex_lock(&rs
->bitmap_mutex
);
2282 pss_host_page_finish(pss
);
2286 pss_find_next_dirty(pss
);
2287 } while (pss_within_range(pss
));
2289 pss_host_page_finish(pss
);
2291 res
= ram_save_release_protection(rs
, pss
, start_page
);
2292 return (res
< 0 ? res
: pages
);
2296 * ram_find_and_save_block: finds a dirty page and sends it to f
2298 * Called within an RCU critical section.
2300 * Returns the number of pages written where zero means no dirty pages,
2301 * or negative on error
2303 * @rs: current RAM state
2305 * On systems where host-page-size > target-page-size it will send all the
2306 * pages in a host page that are dirty.
2308 static int ram_find_and_save_block(RAMState
*rs
)
2310 PageSearchStatus
*pss
= &rs
->pss
[RAM_CHANNEL_PRECOPY
];
2313 /* No dirty page as there is zero RAM */
2314 if (!rs
->ram_bytes_total
) {
2319 * Always keep last_seen_block/last_page valid during this procedure,
2320 * because find_dirty_block() relies on these values (e.g., we compare
2321 * last_seen_block with pss.block to see whether we searched all the
2322 * ramblocks) to detect the completion of migration. Having NULL value
2323 * of last_seen_block can conditionally cause below loop to run forever.
2325 if (!rs
->last_seen_block
) {
2326 rs
->last_seen_block
= QLIST_FIRST_RCU(&ram_list
.blocks
);
2330 pss_init(pss
, rs
->last_seen_block
, rs
->last_page
);
2333 if (!get_queued_page(rs
, pss
)) {
2334 /* priority queue empty, so just search for something dirty */
2335 int res
= find_dirty_block(rs
, pss
);
2336 if (res
!= PAGE_DIRTY_FOUND
) {
2337 if (res
== PAGE_ALL_CLEAN
) {
2339 } else if (res
== PAGE_TRY_AGAIN
) {
2341 } else if (res
< 0) {
2347 pages
= ram_save_host_page(rs
, pss
);
2353 rs
->last_seen_block
= pss
->block
;
2354 rs
->last_page
= pss
->page
;
2359 static uint64_t ram_bytes_total_with_ignored(void)
2364 RCU_READ_LOCK_GUARD();
2366 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
2367 total
+= block
->used_length
;
2372 uint64_t ram_bytes_total(void)
2377 RCU_READ_LOCK_GUARD();
2379 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2380 total
+= block
->used_length
;
2385 static void xbzrle_load_setup(void)
2387 XBZRLE
.decoded_buf
= g_malloc(TARGET_PAGE_SIZE
);
2390 static void xbzrle_load_cleanup(void)
2392 g_free(XBZRLE
.decoded_buf
);
2393 XBZRLE
.decoded_buf
= NULL
;
2396 static void ram_state_cleanup(RAMState
**rsp
)
2399 migration_page_queue_free(*rsp
);
2400 qemu_mutex_destroy(&(*rsp
)->bitmap_mutex
);
2401 qemu_mutex_destroy(&(*rsp
)->src_page_req_mutex
);
2407 static void xbzrle_cleanup(void)
2409 XBZRLE_cache_lock();
2411 cache_fini(XBZRLE
.cache
);
2412 g_free(XBZRLE
.encoded_buf
);
2413 g_free(XBZRLE
.current_buf
);
2414 g_free(XBZRLE
.zero_target_page
);
2415 XBZRLE
.cache
= NULL
;
2416 XBZRLE
.encoded_buf
= NULL
;
2417 XBZRLE
.current_buf
= NULL
;
2418 XBZRLE
.zero_target_page
= NULL
;
2420 XBZRLE_cache_unlock();
2423 static void ram_save_cleanup(void *opaque
)
2425 RAMState
**rsp
= opaque
;
2428 /* We don't use dirty log with background snapshots */
2429 if (!migrate_background_snapshot()) {
2430 /* caller have hold BQL or is in a bh, so there is
2431 * no writing race against the migration bitmap
2433 if (global_dirty_tracking
& GLOBAL_DIRTY_MIGRATION
) {
2435 * do not stop dirty log without starting it, since
2436 * memory_global_dirty_log_stop will assert that
2437 * memory_global_dirty_log_start/stop used in pairs
2439 memory_global_dirty_log_stop(GLOBAL_DIRTY_MIGRATION
);
2443 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2444 g_free(block
->clear_bmap
);
2445 block
->clear_bmap
= NULL
;
2446 g_free(block
->bmap
);
2451 compress_threads_save_cleanup();
2452 ram_state_cleanup(rsp
);
2453 g_free(migration_ops
);
2454 migration_ops
= NULL
;
2457 static void ram_state_reset(RAMState
*rs
)
2461 for (i
= 0; i
< RAM_CHANNEL_MAX
; i
++) {
2462 rs
->pss
[i
].last_sent_block
= NULL
;
2465 rs
->last_seen_block
= NULL
;
2467 rs
->last_version
= ram_list
.version
;
2468 rs
->xbzrle_started
= false;
2471 #define MAX_WAIT 50 /* ms, half buffered_file limit */
2473 /* **** functions for postcopy ***** */
2475 void ram_postcopy_migrated_memory_release(MigrationState
*ms
)
2477 struct RAMBlock
*block
;
2479 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2480 unsigned long *bitmap
= block
->bmap
;
2481 unsigned long range
= block
->used_length
>> TARGET_PAGE_BITS
;
2482 unsigned long run_start
= find_next_zero_bit(bitmap
, range
, 0);
2484 while (run_start
< range
) {
2485 unsigned long run_end
= find_next_bit(bitmap
, range
, run_start
+ 1);
2486 ram_discard_range(block
->idstr
,
2487 ((ram_addr_t
)run_start
) << TARGET_PAGE_BITS
,
2488 ((ram_addr_t
)(run_end
- run_start
))
2489 << TARGET_PAGE_BITS
);
2490 run_start
= find_next_zero_bit(bitmap
, range
, run_end
+ 1);
2496 * postcopy_send_discard_bm_ram: discard a RAMBlock
2498 * Callback from postcopy_each_ram_send_discard for each RAMBlock
2500 * @ms: current migration state
2501 * @block: RAMBlock to discard
2503 static void postcopy_send_discard_bm_ram(MigrationState
*ms
, RAMBlock
*block
)
2505 unsigned long end
= block
->used_length
>> TARGET_PAGE_BITS
;
2506 unsigned long current
;
2507 unsigned long *bitmap
= block
->bmap
;
2509 for (current
= 0; current
< end
; ) {
2510 unsigned long one
= find_next_bit(bitmap
, end
, current
);
2511 unsigned long zero
, discard_length
;
2517 zero
= find_next_zero_bit(bitmap
, end
, one
+ 1);
2520 discard_length
= end
- one
;
2522 discard_length
= zero
- one
;
2524 postcopy_discard_send_range(ms
, one
, discard_length
);
2525 current
= one
+ discard_length
;
2529 static void postcopy_chunk_hostpages_pass(MigrationState
*ms
, RAMBlock
*block
);
2532 * postcopy_each_ram_send_discard: discard all RAMBlocks
2534 * Utility for the outgoing postcopy code.
2535 * Calls postcopy_send_discard_bm_ram for each RAMBlock
2536 * passing it bitmap indexes and name.
2537 * (qemu_ram_foreach_block ends up passing unscaled lengths
2538 * which would mean postcopy code would have to deal with target page)
2540 * @ms: current migration state
2542 static void postcopy_each_ram_send_discard(MigrationState
*ms
)
2544 struct RAMBlock
*block
;
2546 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2547 postcopy_discard_send_init(ms
, block
->idstr
);
2550 * Deal with TPS != HPS and huge pages. It discard any partially sent
2551 * host-page size chunks, mark any partially dirty host-page size
2552 * chunks as all dirty. In this case the host-page is the host-page
2553 * for the particular RAMBlock, i.e. it might be a huge page.
2555 postcopy_chunk_hostpages_pass(ms
, block
);
2558 * Postcopy sends chunks of bitmap over the wire, but it
2559 * just needs indexes at this point, avoids it having
2560 * target page specific code.
2562 postcopy_send_discard_bm_ram(ms
, block
);
2563 postcopy_discard_send_finish(ms
);
2568 * postcopy_chunk_hostpages_pass: canonicalize bitmap in hostpages
2570 * Helper for postcopy_chunk_hostpages; it's called twice to
2571 * canonicalize the two bitmaps, that are similar, but one is
2574 * Postcopy requires that all target pages in a hostpage are dirty or
2575 * clean, not a mix. This function canonicalizes the bitmaps.
2577 * @ms: current migration state
2578 * @block: block that contains the page we want to canonicalize
2580 static void postcopy_chunk_hostpages_pass(MigrationState
*ms
, RAMBlock
*block
)
2582 RAMState
*rs
= ram_state
;
2583 unsigned long *bitmap
= block
->bmap
;
2584 unsigned int host_ratio
= block
->page_size
/ TARGET_PAGE_SIZE
;
2585 unsigned long pages
= block
->used_length
>> TARGET_PAGE_BITS
;
2586 unsigned long run_start
;
2588 if (block
->page_size
== TARGET_PAGE_SIZE
) {
2589 /* Easy case - TPS==HPS for a non-huge page RAMBlock */
2593 /* Find a dirty page */
2594 run_start
= find_next_bit(bitmap
, pages
, 0);
2596 while (run_start
< pages
) {
2599 * If the start of this run of pages is in the middle of a host
2600 * page, then we need to fixup this host page.
2602 if (QEMU_IS_ALIGNED(run_start
, host_ratio
)) {
2603 /* Find the end of this run */
2604 run_start
= find_next_zero_bit(bitmap
, pages
, run_start
+ 1);
2606 * If the end isn't at the start of a host page, then the
2607 * run doesn't finish at the end of a host page
2608 * and we need to discard.
2612 if (!QEMU_IS_ALIGNED(run_start
, host_ratio
)) {
2614 unsigned long fixup_start_addr
= QEMU_ALIGN_DOWN(run_start
,
2616 run_start
= QEMU_ALIGN_UP(run_start
, host_ratio
);
2618 /* Clean up the bitmap */
2619 for (page
= fixup_start_addr
;
2620 page
< fixup_start_addr
+ host_ratio
; page
++) {
2622 * Remark them as dirty, updating the count for any pages
2623 * that weren't previously dirty.
2625 rs
->migration_dirty_pages
+= !test_and_set_bit(page
, bitmap
);
2629 /* Find the next dirty page for the next iteration */
2630 run_start
= find_next_bit(bitmap
, pages
, run_start
);
2635 * ram_postcopy_send_discard_bitmap: transmit the discard bitmap
2637 * Transmit the set of pages to be discarded after precopy to the target
2638 * these are pages that:
2639 * a) Have been previously transmitted but are now dirty again
2640 * b) Pages that have never been transmitted, this ensures that
2641 * any pages on the destination that have been mapped by background
2642 * tasks get discarded (transparent huge pages is the specific concern)
2643 * Hopefully this is pretty sparse
2645 * @ms: current migration state
2647 void ram_postcopy_send_discard_bitmap(MigrationState
*ms
)
2649 RAMState
*rs
= ram_state
;
2651 RCU_READ_LOCK_GUARD();
2653 /* This should be our last sync, the src is now paused */
2654 migration_bitmap_sync(rs
, false);
2656 /* Easiest way to make sure we don't resume in the middle of a host-page */
2657 rs
->pss
[RAM_CHANNEL_PRECOPY
].last_sent_block
= NULL
;
2658 rs
->last_seen_block
= NULL
;
2661 postcopy_each_ram_send_discard(ms
);
2663 trace_ram_postcopy_send_discard_bitmap();
2667 * ram_discard_range: discard dirtied pages at the beginning of postcopy
2669 * Returns zero on success
2671 * @rbname: name of the RAMBlock of the request. NULL means the
2672 * same that last one.
2673 * @start: RAMBlock starting page
2674 * @length: RAMBlock size
2676 int ram_discard_range(const char *rbname
, uint64_t start
, size_t length
)
2678 trace_ram_discard_range(rbname
, start
, length
);
2680 RCU_READ_LOCK_GUARD();
2681 RAMBlock
*rb
= qemu_ram_block_by_name(rbname
);
2684 error_report("ram_discard_range: Failed to find block '%s'", rbname
);
2689 * On source VM, we don't need to update the received bitmap since
2690 * we don't even have one.
2692 if (rb
->receivedmap
) {
2693 bitmap_clear(rb
->receivedmap
, start
>> qemu_target_page_bits(),
2694 length
>> qemu_target_page_bits());
2697 return ram_block_discard_range(rb
, start
, length
);
2701 * For every allocation, we will try not to crash the VM if the
2702 * allocation failed.
2704 static int xbzrle_init(void)
2706 Error
*local_err
= NULL
;
2708 if (!migrate_xbzrle()) {
2712 XBZRLE_cache_lock();
2714 XBZRLE
.zero_target_page
= g_try_malloc0(TARGET_PAGE_SIZE
);
2715 if (!XBZRLE
.zero_target_page
) {
2716 error_report("%s: Error allocating zero page", __func__
);
2720 XBZRLE
.cache
= cache_init(migrate_xbzrle_cache_size(),
2721 TARGET_PAGE_SIZE
, &local_err
);
2722 if (!XBZRLE
.cache
) {
2723 error_report_err(local_err
);
2724 goto free_zero_page
;
2727 XBZRLE
.encoded_buf
= g_try_malloc0(TARGET_PAGE_SIZE
);
2728 if (!XBZRLE
.encoded_buf
) {
2729 error_report("%s: Error allocating encoded_buf", __func__
);
2733 XBZRLE
.current_buf
= g_try_malloc(TARGET_PAGE_SIZE
);
2734 if (!XBZRLE
.current_buf
) {
2735 error_report("%s: Error allocating current_buf", __func__
);
2736 goto free_encoded_buf
;
2739 /* We are all good */
2740 XBZRLE_cache_unlock();
2744 g_free(XBZRLE
.encoded_buf
);
2745 XBZRLE
.encoded_buf
= NULL
;
2747 cache_fini(XBZRLE
.cache
);
2748 XBZRLE
.cache
= NULL
;
2750 g_free(XBZRLE
.zero_target_page
);
2751 XBZRLE
.zero_target_page
= NULL
;
2753 XBZRLE_cache_unlock();
2757 static int ram_state_init(RAMState
**rsp
)
2759 *rsp
= g_try_new0(RAMState
, 1);
2762 error_report("%s: Init ramstate fail", __func__
);
2766 qemu_mutex_init(&(*rsp
)->bitmap_mutex
);
2767 qemu_mutex_init(&(*rsp
)->src_page_req_mutex
);
2768 QSIMPLEQ_INIT(&(*rsp
)->src_page_requests
);
2769 (*rsp
)->ram_bytes_total
= ram_bytes_total();
2772 * Count the total number of pages used by ram blocks not including any
2773 * gaps due to alignment or unplugs.
2774 * This must match with the initial values of dirty bitmap.
2776 (*rsp
)->migration_dirty_pages
= (*rsp
)->ram_bytes_total
>> TARGET_PAGE_BITS
;
2777 ram_state_reset(*rsp
);
2782 static void ram_list_init_bitmaps(void)
2784 MigrationState
*ms
= migrate_get_current();
2786 unsigned long pages
;
2789 /* Skip setting bitmap if there is no RAM */
2790 if (ram_bytes_total()) {
2791 shift
= ms
->clear_bitmap_shift
;
2792 if (shift
> CLEAR_BITMAP_SHIFT_MAX
) {
2793 error_report("clear_bitmap_shift (%u) too big, using "
2794 "max value (%u)", shift
, CLEAR_BITMAP_SHIFT_MAX
);
2795 shift
= CLEAR_BITMAP_SHIFT_MAX
;
2796 } else if (shift
< CLEAR_BITMAP_SHIFT_MIN
) {
2797 error_report("clear_bitmap_shift (%u) too small, using "
2798 "min value (%u)", shift
, CLEAR_BITMAP_SHIFT_MIN
);
2799 shift
= CLEAR_BITMAP_SHIFT_MIN
;
2802 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2803 pages
= block
->max_length
>> TARGET_PAGE_BITS
;
2805 * The initial dirty bitmap for migration must be set with all
2806 * ones to make sure we'll migrate every guest RAM page to
2808 * Here we set RAMBlock.bmap all to 1 because when rebegin a
2809 * new migration after a failed migration, ram_list.
2810 * dirty_memory[DIRTY_MEMORY_MIGRATION] don't include the whole
2813 block
->bmap
= bitmap_new(pages
);
2814 bitmap_set(block
->bmap
, 0, pages
);
2815 if (migrate_mapped_ram()) {
2816 block
->file_bmap
= bitmap_new(pages
);
2818 block
->clear_bmap_shift
= shift
;
2819 block
->clear_bmap
= bitmap_new(clear_bmap_size(pages
, shift
));
2824 static void migration_bitmap_clear_discarded_pages(RAMState
*rs
)
2826 unsigned long pages
;
2829 RCU_READ_LOCK_GUARD();
2831 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
2832 pages
= ramblock_dirty_bitmap_clear_discarded_pages(rb
);
2833 rs
->migration_dirty_pages
-= pages
;
2837 static void ram_init_bitmaps(RAMState
*rs
)
2839 qemu_mutex_lock_ramlist();
2841 WITH_RCU_READ_LOCK_GUARD() {
2842 ram_list_init_bitmaps();
2843 /* We don't use dirty log with background snapshots */
2844 if (!migrate_background_snapshot()) {
2845 memory_global_dirty_log_start(GLOBAL_DIRTY_MIGRATION
);
2846 migration_bitmap_sync_precopy(rs
, false);
2849 qemu_mutex_unlock_ramlist();
2852 * After an eventual first bitmap sync, fixup the initial bitmap
2853 * containing all 1s to exclude any discarded pages from migration.
2855 migration_bitmap_clear_discarded_pages(rs
);
2858 static int ram_init_all(RAMState
**rsp
)
2860 if (ram_state_init(rsp
)) {
2864 if (xbzrle_init()) {
2865 ram_state_cleanup(rsp
);
2869 ram_init_bitmaps(*rsp
);
2874 static void ram_state_resume_prepare(RAMState
*rs
, QEMUFile
*out
)
2880 * Postcopy is not using xbzrle/compression, so no need for that.
2881 * Also, since source are already halted, we don't need to care
2882 * about dirty page logging as well.
2885 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
2886 pages
+= bitmap_count_one(block
->bmap
,
2887 block
->used_length
>> TARGET_PAGE_BITS
);
2890 /* This may not be aligned with current bitmaps. Recalculate. */
2891 rs
->migration_dirty_pages
= pages
;
2893 ram_state_reset(rs
);
2895 /* Update RAMState cache of output QEMUFile */
2896 rs
->pss
[RAM_CHANNEL_PRECOPY
].pss_channel
= out
;
2898 trace_ram_state_resume_prepare(pages
);
2902 * This function clears bits of the free pages reported by the caller from the
2903 * migration dirty bitmap. @addr is the host address corresponding to the
2904 * start of the continuous guest free pages, and @len is the total bytes of
2907 void qemu_guest_free_page_hint(void *addr
, size_t len
)
2911 size_t used_len
, start
, npages
;
2912 MigrationState
*s
= migrate_get_current();
2914 /* This function is currently expected to be used during live migration */
2915 if (!migration_is_setup_or_active(s
->state
)) {
2919 for (; len
> 0; len
-= used_len
, addr
+= used_len
) {
2920 block
= qemu_ram_block_from_host(addr
, false, &offset
);
2921 if (unlikely(!block
|| offset
>= block
->used_length
)) {
2923 * The implementation might not support RAMBlock resize during
2924 * live migration, but it could happen in theory with future
2925 * updates. So we add a check here to capture that case.
2927 error_report_once("%s unexpected error", __func__
);
2931 if (len
<= block
->used_length
- offset
) {
2934 used_len
= block
->used_length
- offset
;
2937 start
= offset
>> TARGET_PAGE_BITS
;
2938 npages
= used_len
>> TARGET_PAGE_BITS
;
2940 qemu_mutex_lock(&ram_state
->bitmap_mutex
);
2942 * The skipped free pages are equavalent to be sent from clear_bmap's
2943 * perspective, so clear the bits from the memory region bitmap which
2944 * are initially set. Otherwise those skipped pages will be sent in
2945 * the next round after syncing from the memory region bitmap.
2947 migration_clear_memory_region_dirty_bitmap_range(block
, start
, npages
);
2948 ram_state
->migration_dirty_pages
-=
2949 bitmap_count_one_with_offset(block
->bmap
, start
, npages
);
2950 bitmap_clear(block
->bmap
, start
, npages
);
2951 qemu_mutex_unlock(&ram_state
->bitmap_mutex
);
2955 #define MAPPED_RAM_HDR_VERSION 1
2956 struct MappedRamHeader
{
2959 * The target's page size, so we know how many pages are in the
2964 * The offset in the migration file where the pages bitmap is
2967 uint64_t bitmap_offset
;
2969 * The offset in the migration file where the actual pages (data)
2972 uint64_t pages_offset
;
2974 typedef struct MappedRamHeader MappedRamHeader
;
2976 static void mapped_ram_setup_ramblock(QEMUFile
*file
, RAMBlock
*block
)
2978 g_autofree MappedRamHeader
*header
= NULL
;
2979 size_t header_size
, bitmap_size
;
2982 header
= g_new0(MappedRamHeader
, 1);
2983 header_size
= sizeof(MappedRamHeader
);
2985 num_pages
= block
->used_length
>> TARGET_PAGE_BITS
;
2986 bitmap_size
= BITS_TO_LONGS(num_pages
) * sizeof(unsigned long);
2989 * Save the file offsets of where the bitmap and the pages should
2990 * go as they are written at the end of migration and during the
2991 * iterative phase, respectively.
2993 block
->bitmap_offset
= qemu_get_offset(file
) + header_size
;
2994 block
->pages_offset
= ROUND_UP(block
->bitmap_offset
+
2996 MAPPED_RAM_FILE_OFFSET_ALIGNMENT
);
2998 header
->version
= cpu_to_be32(MAPPED_RAM_HDR_VERSION
);
2999 header
->page_size
= cpu_to_be64(TARGET_PAGE_SIZE
);
3000 header
->bitmap_offset
= cpu_to_be64(block
->bitmap_offset
);
3001 header
->pages_offset
= cpu_to_be64(block
->pages_offset
);
3003 qemu_put_buffer(file
, (uint8_t *) header
, header_size
);
3005 /* prepare offset for next ramblock */
3006 qemu_set_offset(file
, block
->pages_offset
+ block
->used_length
, SEEK_SET
);
3009 static bool mapped_ram_read_header(QEMUFile
*file
, MappedRamHeader
*header
,
3012 size_t ret
, header_size
= sizeof(MappedRamHeader
);
3014 ret
= qemu_get_buffer(file
, (uint8_t *)header
, header_size
);
3015 if (ret
!= header_size
) {
3016 error_setg(errp
, "Could not read whole mapped-ram migration header "
3017 "(expected %zd, got %zd bytes)", header_size
, ret
);
3021 /* migration stream is big-endian */
3022 header
->version
= be32_to_cpu(header
->version
);
3024 if (header
->version
> MAPPED_RAM_HDR_VERSION
) {
3025 error_setg(errp
, "Migration mapped-ram capability version not "
3026 "supported (expected <= %d, got %d)", MAPPED_RAM_HDR_VERSION
,
3031 header
->page_size
= be64_to_cpu(header
->page_size
);
3032 header
->bitmap_offset
= be64_to_cpu(header
->bitmap_offset
);
3033 header
->pages_offset
= be64_to_cpu(header
->pages_offset
);
3039 * Each of ram_save_setup, ram_save_iterate and ram_save_complete has
3040 * long-running RCU critical section. When rcu-reclaims in the code
3041 * start to become numerous it will be necessary to reduce the
3042 * granularity of these critical sections.
3046 * ram_save_setup: Setup RAM for migration
3048 * Returns zero to indicate success and negative for error
3050 * @f: QEMUFile where to send the data
3051 * @opaque: RAMState pointer
3053 static int ram_save_setup(QEMUFile
*f
, void *opaque
)
3055 RAMState
**rsp
= opaque
;
3057 int ret
, max_hg_page_size
;
3059 if (compress_threads_save_setup()) {
3063 /* migration has already setup the bitmap, reuse it. */
3064 if (!migration_in_colo_state()) {
3065 if (ram_init_all(rsp
) != 0) {
3066 compress_threads_save_cleanup();
3070 (*rsp
)->pss
[RAM_CHANNEL_PRECOPY
].pss_channel
= f
;
3073 * ??? Mirrors the previous value of qemu_host_page_size,
3074 * but is this really what was intended for the migration?
3076 max_hg_page_size
= MAX(qemu_real_host_page_size(), TARGET_PAGE_SIZE
);
3078 WITH_RCU_READ_LOCK_GUARD() {
3079 qemu_put_be64(f
, ram_bytes_total_with_ignored()
3080 | RAM_SAVE_FLAG_MEM_SIZE
);
3082 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
3083 qemu_put_byte(f
, strlen(block
->idstr
));
3084 qemu_put_buffer(f
, (uint8_t *)block
->idstr
, strlen(block
->idstr
));
3085 qemu_put_be64(f
, block
->used_length
);
3086 if (migrate_postcopy_ram() &&
3087 block
->page_size
!= max_hg_page_size
) {
3088 qemu_put_be64(f
, block
->page_size
);
3090 if (migrate_ignore_shared()) {
3091 qemu_put_be64(f
, block
->mr
->addr
);
3094 if (migrate_mapped_ram()) {
3095 mapped_ram_setup_ramblock(f
, block
);
3100 ret
= rdma_registration_start(f
, RAM_CONTROL_SETUP
);
3102 qemu_file_set_error(f
, ret
);
3106 ret
= rdma_registration_stop(f
, RAM_CONTROL_SETUP
);
3108 qemu_file_set_error(f
, ret
);
3112 migration_ops
= g_malloc0(sizeof(MigrationOps
));
3113 migration_ops
->ram_save_target_page
= ram_save_target_page_legacy
;
3116 ret
= multifd_send_sync_main();
3122 if (migrate_multifd() && !migrate_multifd_flush_after_each_section()
3123 && !migrate_mapped_ram()) {
3124 qemu_put_be64(f
, RAM_SAVE_FLAG_MULTIFD_FLUSH
);
3127 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3128 return qemu_fflush(f
);
3131 static void ram_save_file_bmap(QEMUFile
*f
)
3135 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
3136 long num_pages
= block
->used_length
>> TARGET_PAGE_BITS
;
3137 long bitmap_size
= BITS_TO_LONGS(num_pages
) * sizeof(unsigned long);
3139 qemu_put_buffer_at(f
, (uint8_t *)block
->file_bmap
, bitmap_size
,
3140 block
->bitmap_offset
);
3141 ram_transferred_add(bitmap_size
);
3144 * Free the bitmap here to catch any synchronization issues
3145 * with multifd channels. No channels should be sending pages
3146 * after we've written the bitmap to file.
3148 g_free(block
->file_bmap
);
3149 block
->file_bmap
= NULL
;
3153 void ramblock_set_file_bmap_atomic(RAMBlock
*block
, ram_addr_t offset
)
3155 set_bit_atomic(offset
>> TARGET_PAGE_BITS
, block
->file_bmap
);
3159 * ram_save_iterate: iterative stage for migration
3161 * Returns zero to indicate success and negative for error
3163 * @f: QEMUFile where to send the data
3164 * @opaque: RAMState pointer
3166 static int ram_save_iterate(QEMUFile
*f
, void *opaque
)
3168 RAMState
**temp
= opaque
;
3169 RAMState
*rs
= *temp
;
3175 if (blk_mig_bulk_active()) {
3176 /* Avoid transferring ram during bulk phase of block migration as
3177 * the bulk phase will usually take a long time and transferring
3178 * ram updates during that time is pointless. */
3183 * We'll take this lock a little bit long, but it's okay for two reasons.
3184 * Firstly, the only possible other thread to take it is who calls
3185 * qemu_guest_free_page_hint(), which should be rare; secondly, see
3186 * MAX_WAIT (if curious, further see commit 4508bd9ed8053ce) below, which
3187 * guarantees that we'll at least released it in a regular basis.
3189 WITH_QEMU_LOCK_GUARD(&rs
->bitmap_mutex
) {
3190 WITH_RCU_READ_LOCK_GUARD() {
3191 if (ram_list
.version
!= rs
->last_version
) {
3192 ram_state_reset(rs
);
3195 /* Read version before ram_list.blocks */
3198 ret
= rdma_registration_start(f
, RAM_CONTROL_ROUND
);
3200 qemu_file_set_error(f
, ret
);
3204 t0
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
3206 while ((ret
= migration_rate_exceeded(f
)) == 0 ||
3207 postcopy_has_request(rs
)) {
3210 if (qemu_file_get_error(f
)) {
3214 pages
= ram_find_and_save_block(rs
);
3215 /* no more pages to sent */
3222 qemu_file_set_error(f
, pages
);
3226 rs
->target_page_count
+= pages
;
3229 * During postcopy, it is necessary to make sure one whole host
3230 * page is sent in one chunk.
3232 if (migrate_postcopy_ram()) {
3233 compress_flush_data();
3237 * we want to check in the 1st loop, just in case it was the 1st
3238 * time and we had to sync the dirty bitmap.
3239 * qemu_clock_get_ns() is a bit expensive, so we only check each
3242 if ((i
& 63) == 0) {
3243 uint64_t t1
= (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) - t0
) /
3245 if (t1
> MAX_WAIT
) {
3246 trace_ram_save_iterate_big_wait(t1
, i
);
3256 * Must occur before EOS (or any QEMUFile operation)
3257 * because of RDMA protocol.
3259 ret
= rdma_registration_stop(f
, RAM_CONTROL_ROUND
);
3261 qemu_file_set_error(f
, ret
);
3266 && migration_is_setup_or_active(migrate_get_current()->state
)) {
3267 if (migrate_multifd() && migrate_multifd_flush_after_each_section() &&
3268 !migrate_mapped_ram()) {
3269 ret
= multifd_send_sync_main();
3275 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3276 ram_transferred_add(8);
3277 ret
= qemu_fflush(f
);
3287 * ram_save_complete: function called to send the remaining amount of ram
3289 * Returns zero to indicate success or negative on error
3291 * Called with the BQL
3293 * @f: QEMUFile where to send the data
3294 * @opaque: RAMState pointer
3296 static int ram_save_complete(QEMUFile
*f
, void *opaque
)
3298 RAMState
**temp
= opaque
;
3299 RAMState
*rs
= *temp
;
3302 rs
->last_stage
= !migration_in_colo_state();
3304 WITH_RCU_READ_LOCK_GUARD() {
3305 if (!migration_in_postcopy()) {
3306 migration_bitmap_sync_precopy(rs
, true);
3309 ret
= rdma_registration_start(f
, RAM_CONTROL_FINISH
);
3311 qemu_file_set_error(f
, ret
);
3315 /* try transferring iterative blocks of memory */
3317 /* flush all remaining blocks regardless of rate limiting */
3318 qemu_mutex_lock(&rs
->bitmap_mutex
);
3322 pages
= ram_find_and_save_block(rs
);
3323 /* no more blocks to sent */
3328 qemu_mutex_unlock(&rs
->bitmap_mutex
);
3332 qemu_mutex_unlock(&rs
->bitmap_mutex
);
3334 compress_flush_data();
3336 ret
= rdma_registration_stop(f
, RAM_CONTROL_FINISH
);
3338 qemu_file_set_error(f
, ret
);
3343 ret
= multifd_send_sync_main();
3348 if (migrate_mapped_ram()) {
3349 ram_save_file_bmap(f
);
3351 if (qemu_file_get_error(f
)) {
3352 Error
*local_err
= NULL
;
3353 int err
= qemu_file_get_error_obj(f
, &local_err
);
3355 error_reportf_err(local_err
, "Failed to write bitmap to file: ");
3360 if (migrate_multifd() && !migrate_multifd_flush_after_each_section() &&
3361 !migrate_mapped_ram()) {
3362 qemu_put_be64(f
, RAM_SAVE_FLAG_MULTIFD_FLUSH
);
3364 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3365 return qemu_fflush(f
);
3368 static void ram_state_pending_estimate(void *opaque
, uint64_t *must_precopy
,
3369 uint64_t *can_postcopy
)
3371 RAMState
**temp
= opaque
;
3372 RAMState
*rs
= *temp
;
3374 uint64_t remaining_size
= rs
->migration_dirty_pages
* TARGET_PAGE_SIZE
;
3376 if (migrate_postcopy_ram()) {
3377 /* We can do postcopy, and all the data is postcopiable */
3378 *can_postcopy
+= remaining_size
;
3380 *must_precopy
+= remaining_size
;
3384 static void ram_state_pending_exact(void *opaque
, uint64_t *must_precopy
,
3385 uint64_t *can_postcopy
)
3387 RAMState
**temp
= opaque
;
3388 RAMState
*rs
= *temp
;
3389 uint64_t remaining_size
;
3391 if (!migration_in_postcopy()) {
3393 WITH_RCU_READ_LOCK_GUARD() {
3394 migration_bitmap_sync_precopy(rs
, false);
3399 remaining_size
= rs
->migration_dirty_pages
* TARGET_PAGE_SIZE
;
3401 if (migrate_postcopy_ram()) {
3402 /* We can do postcopy, and all the data is postcopiable */
3403 *can_postcopy
+= remaining_size
;
3405 *must_precopy
+= remaining_size
;
3409 static int load_xbzrle(QEMUFile
*f
, ram_addr_t addr
, void *host
)
3411 unsigned int xh_len
;
3413 uint8_t *loaded_data
;
3415 /* extract RLE header */
3416 xh_flags
= qemu_get_byte(f
);
3417 xh_len
= qemu_get_be16(f
);
3419 if (xh_flags
!= ENCODING_FLAG_XBZRLE
) {
3420 error_report("Failed to load XBZRLE page - wrong compression!");
3424 if (xh_len
> TARGET_PAGE_SIZE
) {
3425 error_report("Failed to load XBZRLE page - len overflow!");
3428 loaded_data
= XBZRLE
.decoded_buf
;
3429 /* load data and decode */
3430 /* it can change loaded_data to point to an internal buffer */
3431 qemu_get_buffer_in_place(f
, &loaded_data
, xh_len
);
3434 if (xbzrle_decode_buffer(loaded_data
, xh_len
, host
,
3435 TARGET_PAGE_SIZE
) == -1) {
3436 error_report("Failed to load XBZRLE page - decode error!");
3444 * ram_block_from_stream: read a RAMBlock id from the migration stream
3446 * Must be called from within a rcu critical section.
3448 * Returns a pointer from within the RCU-protected ram_list.
3450 * @mis: the migration incoming state pointer
3451 * @f: QEMUFile where to read the data from
3452 * @flags: Page flags (mostly to see if it's a continuation of previous block)
3453 * @channel: the channel we're using
3455 static inline RAMBlock
*ram_block_from_stream(MigrationIncomingState
*mis
,
3456 QEMUFile
*f
, int flags
,
3459 RAMBlock
*block
= mis
->last_recv_block
[channel
];
3463 if (flags
& RAM_SAVE_FLAG_CONTINUE
) {
3465 error_report("Ack, bad migration stream!");
3471 len
= qemu_get_byte(f
);
3472 qemu_get_buffer(f
, (uint8_t *)id
, len
);
3475 block
= qemu_ram_block_by_name(id
);
3477 error_report("Can't find block %s", id
);
3481 if (migrate_ram_is_ignored(block
)) {
3482 error_report("block %s should not be migrated !", id
);
3486 mis
->last_recv_block
[channel
] = block
;
3491 static inline void *host_from_ram_block_offset(RAMBlock
*block
,
3494 if (!offset_in_ramblock(block
, offset
)) {
3498 return block
->host
+ offset
;
3501 static void *host_page_from_ram_block_offset(RAMBlock
*block
,
3504 /* Note: Explicitly no check against offset_in_ramblock(). */
3505 return (void *)QEMU_ALIGN_DOWN((uintptr_t)(block
->host
+ offset
),
3509 static ram_addr_t
host_page_offset_from_ram_block_offset(RAMBlock
*block
,
3512 return ((uintptr_t)block
->host
+ offset
) & (block
->page_size
- 1);
3515 void colo_record_bitmap(RAMBlock
*block
, ram_addr_t
*normal
, uint32_t pages
)
3517 qemu_mutex_lock(&ram_state
->bitmap_mutex
);
3518 for (int i
= 0; i
< pages
; i
++) {
3519 ram_addr_t offset
= normal
[i
];
3520 ram_state
->migration_dirty_pages
+= !test_and_set_bit(
3521 offset
>> TARGET_PAGE_BITS
,
3524 qemu_mutex_unlock(&ram_state
->bitmap_mutex
);
3527 static inline void *colo_cache_from_block_offset(RAMBlock
*block
,
3528 ram_addr_t offset
, bool record_bitmap
)
3530 if (!offset_in_ramblock(block
, offset
)) {
3533 if (!block
->colo_cache
) {
3534 error_report("%s: colo_cache is NULL in block :%s",
3535 __func__
, block
->idstr
);
3540 * During colo checkpoint, we need bitmap of these migrated pages.
3541 * It help us to decide which pages in ram cache should be flushed
3542 * into VM's RAM later.
3544 if (record_bitmap
) {
3545 colo_record_bitmap(block
, &offset
, 1);
3547 return block
->colo_cache
+ offset
;
3551 * ram_handle_zero: handle the zero page case
3553 * If a page (or a whole RDMA chunk) has been
3554 * determined to be zero, then zap it.
3556 * @host: host address for the zero page
3557 * @ch: what the page is filled from. We only support zero
3558 * @size: size of the zero page
3560 void ram_handle_zero(void *host
, uint64_t size
)
3562 if (!buffer_is_zero(host
, size
)) {
3563 memset(host
, 0, size
);
3567 static void colo_init_ram_state(void)
3569 ram_state_init(&ram_state
);
3573 * colo cache: this is for secondary VM, we cache the whole
3574 * memory of the secondary VM, it is need to hold the global lock
3575 * to call this helper.
3577 int colo_init_ram_cache(void)
3581 WITH_RCU_READ_LOCK_GUARD() {
3582 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3583 block
->colo_cache
= qemu_anon_ram_alloc(block
->used_length
,
3584 NULL
, false, false);
3585 if (!block
->colo_cache
) {
3586 error_report("%s: Can't alloc memory for COLO cache of block %s,"
3587 "size 0x" RAM_ADDR_FMT
, __func__
, block
->idstr
,
3588 block
->used_length
);
3589 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3590 if (block
->colo_cache
) {
3591 qemu_anon_ram_free(block
->colo_cache
, block
->used_length
);
3592 block
->colo_cache
= NULL
;
3597 if (!machine_dump_guest_core(current_machine
)) {
3598 qemu_madvise(block
->colo_cache
, block
->used_length
,
3599 QEMU_MADV_DONTDUMP
);
3605 * Record the dirty pages that sent by PVM, we use this dirty bitmap together
3606 * with to decide which page in cache should be flushed into SVM's RAM. Here
3607 * we use the same name 'ram_bitmap' as for migration.
3609 if (ram_bytes_total()) {
3610 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3611 unsigned long pages
= block
->max_length
>> TARGET_PAGE_BITS
;
3612 block
->bmap
= bitmap_new(pages
);
3616 colo_init_ram_state();
3620 /* TODO: duplicated with ram_init_bitmaps */
3621 void colo_incoming_start_dirty_log(void)
3623 RAMBlock
*block
= NULL
;
3624 /* For memory_global_dirty_log_start below. */
3626 qemu_mutex_lock_ramlist();
3628 memory_global_dirty_log_sync(false);
3629 WITH_RCU_READ_LOCK_GUARD() {
3630 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3631 ramblock_sync_dirty_bitmap(ram_state
, block
);
3632 /* Discard this dirty bitmap record */
3633 bitmap_zero(block
->bmap
, block
->max_length
>> TARGET_PAGE_BITS
);
3635 memory_global_dirty_log_start(GLOBAL_DIRTY_MIGRATION
);
3637 ram_state
->migration_dirty_pages
= 0;
3638 qemu_mutex_unlock_ramlist();
3642 /* It is need to hold the global lock to call this helper */
3643 void colo_release_ram_cache(void)
3647 memory_global_dirty_log_stop(GLOBAL_DIRTY_MIGRATION
);
3648 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3649 g_free(block
->bmap
);
3653 WITH_RCU_READ_LOCK_GUARD() {
3654 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3655 if (block
->colo_cache
) {
3656 qemu_anon_ram_free(block
->colo_cache
, block
->used_length
);
3657 block
->colo_cache
= NULL
;
3661 ram_state_cleanup(&ram_state
);
3665 * ram_load_setup: Setup RAM for migration incoming side
3667 * Returns zero to indicate success and negative for error
3669 * @f: QEMUFile where to receive the data
3670 * @opaque: RAMState pointer
3672 static int ram_load_setup(QEMUFile
*f
, void *opaque
)
3674 xbzrle_load_setup();
3675 ramblock_recv_map_init();
3680 static int ram_load_cleanup(void *opaque
)
3684 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
3685 qemu_ram_block_writeback(rb
);
3688 xbzrle_load_cleanup();
3690 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
3691 g_free(rb
->receivedmap
);
3692 rb
->receivedmap
= NULL
;
3699 * ram_postcopy_incoming_init: allocate postcopy data structures
3701 * Returns 0 for success and negative if there was one error
3703 * @mis: current migration incoming state
3705 * Allocate data structures etc needed by incoming migration with
3706 * postcopy-ram. postcopy-ram's similarly names
3707 * postcopy_ram_incoming_init does the work.
3709 int ram_postcopy_incoming_init(MigrationIncomingState
*mis
)
3711 return postcopy_ram_incoming_init(mis
);
3715 * ram_load_postcopy: load a page in postcopy case
3717 * Returns 0 for success or -errno in case of error
3719 * Called in postcopy mode by ram_load().
3720 * rcu_read_lock is taken prior to this being called.
3722 * @f: QEMUFile where to send the data
3723 * @channel: the channel to use for loading
3725 int ram_load_postcopy(QEMUFile
*f
, int channel
)
3727 int flags
= 0, ret
= 0;
3728 bool place_needed
= false;
3729 bool matches_target_page_size
= false;
3730 MigrationIncomingState
*mis
= migration_incoming_get_current();
3731 PostcopyTmpPage
*tmp_page
= &mis
->postcopy_tmp_pages
[channel
];
3733 while (!ret
&& !(flags
& RAM_SAVE_FLAG_EOS
)) {
3735 void *page_buffer
= NULL
;
3736 void *place_source
= NULL
;
3737 RAMBlock
*block
= NULL
;
3741 addr
= qemu_get_be64(f
);
3744 * If qemu file error, we should stop here, and then "addr"
3747 ret
= qemu_file_get_error(f
);
3752 flags
= addr
& ~TARGET_PAGE_MASK
;
3753 addr
&= TARGET_PAGE_MASK
;
3755 trace_ram_load_postcopy_loop(channel
, (uint64_t)addr
, flags
);
3756 if (flags
& (RAM_SAVE_FLAG_ZERO
| RAM_SAVE_FLAG_PAGE
|
3757 RAM_SAVE_FLAG_COMPRESS_PAGE
)) {
3758 block
= ram_block_from_stream(mis
, f
, flags
, channel
);
3765 * Relying on used_length is racy and can result in false positives.
3766 * We might place pages beyond used_length in case RAM was shrunk
3767 * while in postcopy, which is fine - trying to place via
3768 * UFFDIO_COPY/UFFDIO_ZEROPAGE will never segfault.
3770 if (!block
->host
|| addr
>= block
->postcopy_length
) {
3771 error_report("Illegal RAM offset " RAM_ADDR_FMT
, addr
);
3775 tmp_page
->target_pages
++;
3776 matches_target_page_size
= block
->page_size
== TARGET_PAGE_SIZE
;
3778 * Postcopy requires that we place whole host pages atomically;
3779 * these may be huge pages for RAMBlocks that are backed by
3781 * To make it atomic, the data is read into a temporary page
3782 * that's moved into place later.
3783 * The migration protocol uses, possibly smaller, target-pages
3784 * however the source ensures it always sends all the components
3785 * of a host page in one chunk.
3787 page_buffer
= tmp_page
->tmp_huge_page
+
3788 host_page_offset_from_ram_block_offset(block
, addr
);
3789 /* If all TP are zero then we can optimise the place */
3790 if (tmp_page
->target_pages
== 1) {
3791 tmp_page
->host_addr
=
3792 host_page_from_ram_block_offset(block
, addr
);
3793 } else if (tmp_page
->host_addr
!=
3794 host_page_from_ram_block_offset(block
, addr
)) {
3795 /* not the 1st TP within the HP */
3796 error_report("Non-same host page detected on channel %d: "
3797 "Target host page %p, received host page %p "
3798 "(rb %s offset 0x"RAM_ADDR_FMT
" target_pages %d)",
3799 channel
, tmp_page
->host_addr
,
3800 host_page_from_ram_block_offset(block
, addr
),
3801 block
->idstr
, addr
, tmp_page
->target_pages
);
3807 * If it's the last part of a host page then we place the host
3810 if (tmp_page
->target_pages
==
3811 (block
->page_size
/ TARGET_PAGE_SIZE
)) {
3812 place_needed
= true;
3814 place_source
= tmp_page
->tmp_huge_page
;
3817 switch (flags
& ~RAM_SAVE_FLAG_CONTINUE
) {
3818 case RAM_SAVE_FLAG_ZERO
:
3819 ch
= qemu_get_byte(f
);
3821 error_report("Found a zero page with value %d", ch
);
3826 * Can skip to set page_buffer when
3827 * this is a zero page and (block->page_size == TARGET_PAGE_SIZE).
3829 if (!matches_target_page_size
) {
3830 memset(page_buffer
, ch
, TARGET_PAGE_SIZE
);
3834 case RAM_SAVE_FLAG_PAGE
:
3835 tmp_page
->all_zero
= false;
3836 if (!matches_target_page_size
) {
3837 /* For huge pages, we always use temporary buffer */
3838 qemu_get_buffer(f
, page_buffer
, TARGET_PAGE_SIZE
);
3841 * For small pages that matches target page size, we
3842 * avoid the qemu_file copy. Instead we directly use
3843 * the buffer of QEMUFile to place the page. Note: we
3844 * cannot do any QEMUFile operation before using that
3845 * buffer to make sure the buffer is valid when
3848 qemu_get_buffer_in_place(f
, (uint8_t **)&place_source
,
3852 case RAM_SAVE_FLAG_COMPRESS_PAGE
:
3853 tmp_page
->all_zero
= false;
3854 len
= qemu_get_be32(f
);
3855 if (len
< 0 || len
> compressBound(TARGET_PAGE_SIZE
)) {
3856 error_report("Invalid compressed data length: %d", len
);
3860 decompress_data_with_multi_threads(f
, page_buffer
, len
);
3862 case RAM_SAVE_FLAG_MULTIFD_FLUSH
:
3863 multifd_recv_sync_main();
3865 case RAM_SAVE_FLAG_EOS
:
3867 if (migrate_multifd() &&
3868 migrate_multifd_flush_after_each_section()) {
3869 multifd_recv_sync_main();
3873 error_report("Unknown combination of migration flags: 0x%x"
3874 " (postcopy mode)", flags
);
3879 /* Got the whole host page, wait for decompress before placing. */
3881 ret
|= wait_for_decompress_done();
3884 /* Detect for any possible file errors */
3885 if (!ret
&& qemu_file_get_error(f
)) {
3886 ret
= qemu_file_get_error(f
);
3889 if (!ret
&& place_needed
) {
3890 if (tmp_page
->all_zero
) {
3891 ret
= postcopy_place_page_zero(mis
, tmp_page
->host_addr
, block
);
3893 ret
= postcopy_place_page(mis
, tmp_page
->host_addr
,
3894 place_source
, block
);
3896 place_needed
= false;
3897 postcopy_temp_page_reset(tmp_page
);
3904 static bool postcopy_is_running(void)
3906 PostcopyState ps
= postcopy_state_get();
3907 return ps
>= POSTCOPY_INCOMING_LISTENING
&& ps
< POSTCOPY_INCOMING_END
;
3911 * Flush content of RAM cache into SVM's memory.
3912 * Only flush the pages that be dirtied by PVM or SVM or both.
3914 void colo_flush_ram_cache(void)
3916 RAMBlock
*block
= NULL
;
3919 unsigned long offset
= 0;
3921 memory_global_dirty_log_sync(false);
3922 qemu_mutex_lock(&ram_state
->bitmap_mutex
);
3923 WITH_RCU_READ_LOCK_GUARD() {
3924 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
3925 ramblock_sync_dirty_bitmap(ram_state
, block
);
3929 trace_colo_flush_ram_cache_begin(ram_state
->migration_dirty_pages
);
3930 WITH_RCU_READ_LOCK_GUARD() {
3931 block
= QLIST_FIRST_RCU(&ram_list
.blocks
);
3934 unsigned long num
= 0;
3936 offset
= colo_bitmap_find_dirty(ram_state
, block
, offset
, &num
);
3937 if (!offset_in_ramblock(block
,
3938 ((ram_addr_t
)offset
) << TARGET_PAGE_BITS
)) {
3941 block
= QLIST_NEXT_RCU(block
, next
);
3943 unsigned long i
= 0;
3945 for (i
= 0; i
< num
; i
++) {
3946 migration_bitmap_clear_dirty(ram_state
, block
, offset
+ i
);
3948 dst_host
= block
->host
3949 + (((ram_addr_t
)offset
) << TARGET_PAGE_BITS
);
3950 src_host
= block
->colo_cache
3951 + (((ram_addr_t
)offset
) << TARGET_PAGE_BITS
);
3952 memcpy(dst_host
, src_host
, TARGET_PAGE_SIZE
* num
);
3957 qemu_mutex_unlock(&ram_state
->bitmap_mutex
);
3958 trace_colo_flush_ram_cache_end();
3961 static size_t ram_load_multifd_pages(void *host_addr
, size_t size
,
3964 MultiFDRecvData
*data
= multifd_get_recv_data();
3966 data
->opaque
= host_addr
;
3967 data
->file_offset
= offset
;
3970 if (!multifd_recv()) {
3977 static bool read_ramblock_mapped_ram(QEMUFile
*f
, RAMBlock
*block
,
3978 long num_pages
, unsigned long *bitmap
,
3982 unsigned long set_bit_idx
, clear_bit_idx
;
3985 size_t read
, unread
, size
;
3987 for (set_bit_idx
= find_first_bit(bitmap
, num_pages
);
3988 set_bit_idx
< num_pages
;
3989 set_bit_idx
= find_next_bit(bitmap
, num_pages
, clear_bit_idx
+ 1)) {
3991 clear_bit_idx
= find_next_zero_bit(bitmap
, num_pages
, set_bit_idx
+ 1);
3993 unread
= TARGET_PAGE_SIZE
* (clear_bit_idx
- set_bit_idx
);
3994 offset
= set_bit_idx
<< TARGET_PAGE_BITS
;
3996 while (unread
> 0) {
3997 host
= host_from_ram_block_offset(block
, offset
);
3999 error_setg(errp
, "page outside of ramblock %s range",
4004 size
= MIN(unread
, MAPPED_RAM_LOAD_BUF_SIZE
);
4006 if (migrate_multifd()) {
4007 read
= ram_load_multifd_pages(host
, size
,
4008 block
->pages_offset
+ offset
);
4010 read
= qemu_get_buffer_at(f
, host
, size
,
4011 block
->pages_offset
+ offset
);
4025 qemu_file_get_error_obj(f
, errp
);
4026 error_prepend(errp
, "(%s) failed to read page " RAM_ADDR_FMT
4027 "from file offset %" PRIx64
": ", block
->idstr
, offset
,
4028 block
->pages_offset
+ offset
);
4032 static void parse_ramblock_mapped_ram(QEMUFile
*f
, RAMBlock
*block
,
4033 ram_addr_t length
, Error
**errp
)
4035 g_autofree
unsigned long *bitmap
= NULL
;
4036 MappedRamHeader header
;
4040 if (!mapped_ram_read_header(f
, &header
, errp
)) {
4044 block
->pages_offset
= header
.pages_offset
;
4047 * Check the alignment of the file region that contains pages. We
4048 * don't enforce MAPPED_RAM_FILE_OFFSET_ALIGNMENT to allow that
4049 * value to change in the future. Do only a sanity check with page
4052 if (!QEMU_IS_ALIGNED(block
->pages_offset
, TARGET_PAGE_SIZE
)) {
4054 "Error reading ramblock %s pages, region has bad alignment",
4059 num_pages
= length
/ header
.page_size
;
4060 bitmap_size
= BITS_TO_LONGS(num_pages
) * sizeof(unsigned long);
4062 bitmap
= g_malloc0(bitmap_size
);
4063 if (qemu_get_buffer_at(f
, (uint8_t *)bitmap
, bitmap_size
,
4064 header
.bitmap_offset
) != bitmap_size
) {
4065 error_setg(errp
, "Error reading dirty bitmap");
4069 if (!read_ramblock_mapped_ram(f
, block
, num_pages
, bitmap
, errp
)) {
4073 /* Skip pages array */
4074 qemu_set_offset(f
, block
->pages_offset
+ length
, SEEK_SET
);
4079 static int parse_ramblock(QEMUFile
*f
, RAMBlock
*block
, ram_addr_t length
)
4082 /* ADVISE is earlier, it shows the source has the postcopy capability on */
4083 bool postcopy_advised
= migration_incoming_postcopy_advised();
4084 int max_hg_page_size
;
4085 Error
*local_err
= NULL
;
4089 if (migrate_mapped_ram()) {
4090 parse_ramblock_mapped_ram(f
, block
, length
, &local_err
);
4092 error_report_err(local_err
);
4098 if (!qemu_ram_is_migratable(block
)) {
4099 error_report("block %s should not be migrated !", block
->idstr
);
4103 if (length
!= block
->used_length
) {
4104 ret
= qemu_ram_resize(block
, length
, &local_err
);
4106 error_report_err(local_err
);
4112 * ??? Mirrors the previous value of qemu_host_page_size,
4113 * but is this really what was intended for the migration?
4115 max_hg_page_size
= MAX(qemu_real_host_page_size(), TARGET_PAGE_SIZE
);
4117 /* For postcopy we need to check hugepage sizes match */
4118 if (postcopy_advised
&& migrate_postcopy_ram() &&
4119 block
->page_size
!= max_hg_page_size
) {
4120 uint64_t remote_page_size
= qemu_get_be64(f
);
4121 if (remote_page_size
!= block
->page_size
) {
4122 error_report("Mismatched RAM page size %s "
4123 "(local) %zd != %" PRId64
, block
->idstr
,
4124 block
->page_size
, remote_page_size
);
4128 if (migrate_ignore_shared()) {
4129 hwaddr addr
= qemu_get_be64(f
);
4130 if (migrate_ram_is_ignored(block
) &&
4131 block
->mr
->addr
!= addr
) {
4132 error_report("Mismatched GPAs for block %s "
4133 "%" PRId64
"!= %" PRId64
, block
->idstr
,
4134 (uint64_t)addr
, (uint64_t)block
->mr
->addr
);
4138 ret
= rdma_block_notification_handle(f
, block
->idstr
);
4140 qemu_file_set_error(f
, ret
);
4146 static int parse_ramblocks(QEMUFile
*f
, ram_addr_t total_ram_bytes
)
4150 /* Synchronize RAM block list */
4151 while (!ret
&& total_ram_bytes
) {
4155 int len
= qemu_get_byte(f
);
4157 qemu_get_buffer(f
, (uint8_t *)id
, len
);
4159 length
= qemu_get_be64(f
);
4161 block
= qemu_ram_block_by_name(id
);
4163 ret
= parse_ramblock(f
, block
, length
);
4165 error_report("Unknown ramblock \"%s\", cannot accept "
4169 total_ram_bytes
-= length
;
4176 * ram_load_precopy: load pages in precopy case
4178 * Returns 0 for success or -errno in case of error
4180 * Called in precopy mode by ram_load().
4181 * rcu_read_lock is taken prior to this being called.
4183 * @f: QEMUFile where to send the data
4185 static int ram_load_precopy(QEMUFile
*f
)
4187 MigrationIncomingState
*mis
= migration_incoming_get_current();
4188 int flags
= 0, ret
= 0, invalid_flags
= 0, len
= 0, i
= 0;
4190 if (!migrate_compress()) {
4191 invalid_flags
|= RAM_SAVE_FLAG_COMPRESS_PAGE
;
4194 if (migrate_mapped_ram()) {
4195 invalid_flags
|= (RAM_SAVE_FLAG_HOOK
| RAM_SAVE_FLAG_MULTIFD_FLUSH
|
4196 RAM_SAVE_FLAG_PAGE
| RAM_SAVE_FLAG_XBZRLE
|
4197 RAM_SAVE_FLAG_ZERO
);
4200 while (!ret
&& !(flags
& RAM_SAVE_FLAG_EOS
)) {
4202 void *host
= NULL
, *host_bak
= NULL
;
4206 * Yield periodically to let main loop run, but an iteration of
4207 * the main loop is expensive, so do it each some iterations
4209 if ((i
& 32767) == 0 && qemu_in_coroutine()) {
4210 aio_co_schedule(qemu_get_current_aio_context(),
4211 qemu_coroutine_self());
4212 qemu_coroutine_yield();
4216 addr
= qemu_get_be64(f
);
4217 flags
= addr
& ~TARGET_PAGE_MASK
;
4218 addr
&= TARGET_PAGE_MASK
;
4220 if (flags
& invalid_flags
) {
4221 error_report("Unexpected RAM flags: %d", flags
& invalid_flags
);
4223 if (flags
& invalid_flags
& RAM_SAVE_FLAG_COMPRESS_PAGE
) {
4224 error_report("Received an unexpected compressed page");
4231 if (flags
& (RAM_SAVE_FLAG_ZERO
| RAM_SAVE_FLAG_PAGE
|
4232 RAM_SAVE_FLAG_COMPRESS_PAGE
| RAM_SAVE_FLAG_XBZRLE
)) {
4233 RAMBlock
*block
= ram_block_from_stream(mis
, f
, flags
,
4234 RAM_CHANNEL_PRECOPY
);
4236 host
= host_from_ram_block_offset(block
, addr
);
4238 * After going into COLO stage, we should not load the page
4239 * into SVM's memory directly, we put them into colo_cache firstly.
4240 * NOTE: We need to keep a copy of SVM's ram in colo_cache.
4241 * Previously, we copied all these memory in preparing stage of COLO
4242 * while we need to stop VM, which is a time-consuming process.
4243 * Here we optimize it by a trick, back-up every page while in
4244 * migration process while COLO is enabled, though it affects the
4245 * speed of the migration, but it obviously reduce the downtime of
4246 * back-up all SVM'S memory in COLO preparing stage.
4248 if (migration_incoming_colo_enabled()) {
4249 if (migration_incoming_in_colo_state()) {
4250 /* In COLO stage, put all pages into cache temporarily */
4251 host
= colo_cache_from_block_offset(block
, addr
, true);
4254 * In migration stage but before COLO stage,
4255 * Put all pages into both cache and SVM's memory.
4257 host_bak
= colo_cache_from_block_offset(block
, addr
, false);
4261 error_report("Illegal RAM offset " RAM_ADDR_FMT
, addr
);
4265 if (!migration_incoming_in_colo_state()) {
4266 ramblock_recv_bitmap_set(block
, host
);
4269 trace_ram_load_loop(block
->idstr
, (uint64_t)addr
, flags
, host
);
4272 switch (flags
& ~RAM_SAVE_FLAG_CONTINUE
) {
4273 case RAM_SAVE_FLAG_MEM_SIZE
:
4274 ret
= parse_ramblocks(f
, addr
);
4276 * For mapped-ram migration (to a file) using multifd, we sync
4277 * once and for all here to make sure all tasks we queued to
4278 * multifd threads are completed, so that all the ramblocks
4279 * (including all the guest memory pages within) are fully
4280 * loaded after this sync returns.
4282 if (migrate_mapped_ram()) {
4283 multifd_recv_sync_main();
4287 case RAM_SAVE_FLAG_ZERO
:
4288 ch
= qemu_get_byte(f
);
4290 error_report("Found a zero page with value %d", ch
);
4294 ram_handle_zero(host
, TARGET_PAGE_SIZE
);
4297 case RAM_SAVE_FLAG_PAGE
:
4298 qemu_get_buffer(f
, host
, TARGET_PAGE_SIZE
);
4301 case RAM_SAVE_FLAG_COMPRESS_PAGE
:
4302 len
= qemu_get_be32(f
);
4303 if (len
< 0 || len
> compressBound(TARGET_PAGE_SIZE
)) {
4304 error_report("Invalid compressed data length: %d", len
);
4308 decompress_data_with_multi_threads(f
, host
, len
);
4311 case RAM_SAVE_FLAG_XBZRLE
:
4312 if (load_xbzrle(f
, addr
, host
) < 0) {
4313 error_report("Failed to decompress XBZRLE page at "
4314 RAM_ADDR_FMT
, addr
);
4319 case RAM_SAVE_FLAG_MULTIFD_FLUSH
:
4320 multifd_recv_sync_main();
4322 case RAM_SAVE_FLAG_EOS
:
4324 if (migrate_multifd() &&
4325 migrate_multifd_flush_after_each_section() &&
4327 * Mapped-ram migration flushes once and for all after
4328 * parsing ramblocks. Always ignore EOS for it.
4330 !migrate_mapped_ram()) {
4331 multifd_recv_sync_main();
4334 case RAM_SAVE_FLAG_HOOK
:
4335 ret
= rdma_registration_handle(f
);
4337 qemu_file_set_error(f
, ret
);
4341 error_report("Unknown combination of migration flags: 0x%x", flags
);
4345 ret
= qemu_file_get_error(f
);
4347 if (!ret
&& host_bak
) {
4348 memcpy(host_bak
, host
, TARGET_PAGE_SIZE
);
4352 ret
|= wait_for_decompress_done();
4356 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
4359 static uint64_t seq_iter
;
4361 * If system is running in postcopy mode, page inserts to host memory must
4364 bool postcopy_running
= postcopy_is_running();
4368 if (version_id
!= 4) {
4373 * This RCU critical section can be very long running.
4374 * When RCU reclaims in the code start to become numerous,
4375 * it will be necessary to reduce the granularity of this
4378 WITH_RCU_READ_LOCK_GUARD() {
4379 if (postcopy_running
) {
4381 * Note! Here RAM_CHANNEL_PRECOPY is the precopy channel of
4382 * postcopy migration, we have another RAM_CHANNEL_POSTCOPY to
4383 * service fast page faults.
4385 ret
= ram_load_postcopy(f
, RAM_CHANNEL_PRECOPY
);
4387 ret
= ram_load_precopy(f
);
4390 trace_ram_load_complete(ret
, seq_iter
);
4395 static bool ram_has_postcopy(void *opaque
)
4398 RAMBLOCK_FOREACH_NOT_IGNORED(rb
) {
4399 if (ramblock_is_pmem(rb
)) {
4400 info_report("Block: %s, host: %p is a nvdimm memory, postcopy"
4401 "is not supported now!", rb
->idstr
, rb
->host
);
4406 return migrate_postcopy_ram();
4409 /* Sync all the dirty bitmap with destination VM. */
4410 static int ram_dirty_bitmap_sync_all(MigrationState
*s
, RAMState
*rs
)
4413 QEMUFile
*file
= s
->to_dst_file
;
4415 trace_ram_dirty_bitmap_sync_start();
4417 qatomic_set(&rs
->postcopy_bmap_sync_requested
, 0);
4418 RAMBLOCK_FOREACH_NOT_IGNORED(block
) {
4419 qemu_savevm_send_recv_bitmap(file
, block
->idstr
);
4420 trace_ram_dirty_bitmap_request(block
->idstr
);
4421 qatomic_inc(&rs
->postcopy_bmap_sync_requested
);
4424 trace_ram_dirty_bitmap_sync_wait();
4426 /* Wait until all the ramblocks' dirty bitmap synced */
4427 while (qatomic_read(&rs
->postcopy_bmap_sync_requested
)) {
4428 if (migration_rp_wait(s
)) {
4433 trace_ram_dirty_bitmap_sync_complete();
4439 * Read the received bitmap, revert it as the initial dirty bitmap.
4440 * This is only used when the postcopy migration is paused but wants
4441 * to resume from a middle point.
4443 * Returns true if succeeded, false for errors.
4445 bool ram_dirty_bitmap_reload(MigrationState
*s
, RAMBlock
*block
, Error
**errp
)
4447 /* from_dst_file is always valid because we're within rp_thread */
4448 QEMUFile
*file
= s
->rp_state
.from_dst_file
;
4449 g_autofree
unsigned long *le_bitmap
= NULL
;
4450 unsigned long nbits
= block
->used_length
>> TARGET_PAGE_BITS
;
4451 uint64_t local_size
= DIV_ROUND_UP(nbits
, 8);
4452 uint64_t size
, end_mark
;
4453 RAMState
*rs
= ram_state
;
4455 trace_ram_dirty_bitmap_reload_begin(block
->idstr
);
4457 if (s
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
4458 error_setg(errp
, "Reload bitmap in incorrect state %s",
4459 MigrationStatus_str(s
->state
));
4464 * Note: see comments in ramblock_recv_bitmap_send() on why we
4465 * need the endianness conversion, and the paddings.
4467 local_size
= ROUND_UP(local_size
, 8);
4470 le_bitmap
= bitmap_new(nbits
+ BITS_PER_LONG
);
4472 size
= qemu_get_be64(file
);
4474 /* The size of the bitmap should match with our ramblock */
4475 if (size
!= local_size
) {
4476 error_setg(errp
, "ramblock '%s' bitmap size mismatch (0x%"PRIx64
4477 " != 0x%"PRIx64
")", block
->idstr
, size
, local_size
);
4481 size
= qemu_get_buffer(file
, (uint8_t *)le_bitmap
, local_size
);
4482 end_mark
= qemu_get_be64(file
);
4484 if (qemu_file_get_error(file
) || size
!= local_size
) {
4485 error_setg(errp
, "read bitmap failed for ramblock '%s': "
4486 "(size 0x%"PRIx64
", got: 0x%"PRIx64
")",
4487 block
->idstr
, local_size
, size
);
4491 if (end_mark
!= RAMBLOCK_RECV_BITMAP_ENDING
) {
4492 error_setg(errp
, "ramblock '%s' end mark incorrect: 0x%"PRIx64
,
4493 block
->idstr
, end_mark
);
4498 * Endianness conversion. We are during postcopy (though paused).
4499 * The dirty bitmap won't change. We can directly modify it.
4501 bitmap_from_le(block
->bmap
, le_bitmap
, nbits
);
4504 * What we received is "received bitmap". Revert it as the initial
4505 * dirty bitmap for this ramblock.
4507 bitmap_complement(block
->bmap
, block
->bmap
, nbits
);
4509 /* Clear dirty bits of discarded ranges that we don't want to migrate. */
4510 ramblock_dirty_bitmap_clear_discarded_pages(block
);
4512 /* We'll recalculate migration_dirty_pages in ram_state_resume_prepare(). */
4513 trace_ram_dirty_bitmap_reload_complete(block
->idstr
);
4515 qatomic_dec(&rs
->postcopy_bmap_sync_requested
);
4518 * We succeeded to sync bitmap for current ramblock. Always kick the
4519 * migration thread to check whether all requested bitmaps are
4520 * reloaded. NOTE: it's racy to only kick when requested==0, because
4521 * we don't know whether the migration thread may still be increasing
4524 migration_rp_kick(s
);
4529 static int ram_resume_prepare(MigrationState
*s
, void *opaque
)
4531 RAMState
*rs
= *(RAMState
**)opaque
;
4534 ret
= ram_dirty_bitmap_sync_all(s
, rs
);
4539 ram_state_resume_prepare(rs
, s
->to_dst_file
);
4544 void postcopy_preempt_shutdown_file(MigrationState
*s
)
4546 qemu_put_be64(s
->postcopy_qemufile_src
, RAM_SAVE_FLAG_EOS
);
4547 qemu_fflush(s
->postcopy_qemufile_src
);
4550 static SaveVMHandlers savevm_ram_handlers
= {
4551 .save_setup
= ram_save_setup
,
4552 .save_live_iterate
= ram_save_iterate
,
4553 .save_live_complete_postcopy
= ram_save_complete
,
4554 .save_live_complete_precopy
= ram_save_complete
,
4555 .has_postcopy
= ram_has_postcopy
,
4556 .state_pending_exact
= ram_state_pending_exact
,
4557 .state_pending_estimate
= ram_state_pending_estimate
,
4558 .load_state
= ram_load
,
4559 .save_cleanup
= ram_save_cleanup
,
4560 .load_setup
= ram_load_setup
,
4561 .load_cleanup
= ram_load_cleanup
,
4562 .resume_prepare
= ram_resume_prepare
,
4565 static void ram_mig_ram_block_resized(RAMBlockNotifier
*n
, void *host
,
4566 size_t old_size
, size_t new_size
)
4568 PostcopyState ps
= postcopy_state_get();
4570 RAMBlock
*rb
= qemu_ram_block_from_host(host
, false, &offset
);
4574 error_report("RAM block not found");
4578 if (migrate_ram_is_ignored(rb
)) {
4582 if (!migration_is_idle()) {
4584 * Precopy code on the source cannot deal with the size of RAM blocks
4585 * changing at random points in time - especially after sending the
4586 * RAM block sizes in the migration stream, they must no longer change.
4587 * Abort and indicate a proper reason.
4589 error_setg(&err
, "RAM block '%s' resized during precopy.", rb
->idstr
);
4590 migration_cancel(err
);
4595 case POSTCOPY_INCOMING_ADVISE
:
4597 * Update what ram_postcopy_incoming_init()->init_range() does at the
4598 * time postcopy was advised. Syncing RAM blocks with the source will
4599 * result in RAM resizes.
4601 if (old_size
< new_size
) {
4602 if (ram_discard_range(rb
->idstr
, old_size
, new_size
- old_size
)) {
4603 error_report("RAM block '%s' discard of resized RAM failed",
4607 rb
->postcopy_length
= new_size
;
4609 case POSTCOPY_INCOMING_NONE
:
4610 case POSTCOPY_INCOMING_RUNNING
:
4611 case POSTCOPY_INCOMING_END
:
4613 * Once our guest is running, postcopy does no longer care about
4614 * resizes. When growing, the new memory was not available on the
4615 * source, no handler needed.
4619 error_report("RAM block '%s' resized during postcopy state: %d",
4625 static RAMBlockNotifier ram_mig_ram_notifier
= {
4626 .ram_block_resized
= ram_mig_ram_block_resized
,
4629 void ram_mig_init(void)
4631 qemu_mutex_init(&XBZRLE
.lock
);
4632 register_savevm_live("ram", 0, 4, &savevm_ram_handlers
, &ram_state
);
4633 ram_block_notifier_add(&ram_mig_ram_notifier
);