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"
32 #include "qemu/cutils.h"
33 #include "qemu/bitops.h"
34 #include "qemu/bitmap.h"
35 #include "qemu/main-loop.h"
36 #include "qemu/pmem.h"
39 #include "migration.h"
41 #include "migration/register.h"
42 #include "migration/misc.h"
43 #include "qemu-file.h"
44 #include "postcopy-ram.h"
45 #include "page_cache.h"
46 #include "qemu/error-report.h"
47 #include "qapi/error.h"
48 #include "qapi/qapi-events-migration.h"
49 #include "qapi/qmp/qerror.h"
51 #include "exec/ram_addr.h"
52 #include "exec/target_page.h"
53 #include "qemu/rcu_queue.h"
54 #include "migration/colo.h"
56 #include "sysemu/sysemu.h"
57 #include "qemu/uuid.h"
61 /***********************************************************/
62 /* ram save/restore */
64 /* RAM_SAVE_FLAG_ZERO used to be named RAM_SAVE_FLAG_COMPRESS, it
65 * worked for pages that where filled with the same char. We switched
66 * it to only search for the zero value. And to avoid confusion with
67 * RAM_SSAVE_FLAG_COMPRESS_PAGE just rename it.
70 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
71 #define RAM_SAVE_FLAG_ZERO 0x02
72 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
73 #define RAM_SAVE_FLAG_PAGE 0x08
74 #define RAM_SAVE_FLAG_EOS 0x10
75 #define RAM_SAVE_FLAG_CONTINUE 0x20
76 #define RAM_SAVE_FLAG_XBZRLE 0x40
77 /* 0x80 is reserved in migration.h start with 0x100 next */
78 #define RAM_SAVE_FLAG_COMPRESS_PAGE 0x100
80 static inline bool is_zero_range(uint8_t *p
, uint64_t size
)
82 return buffer_is_zero(p
, size
);
85 XBZRLECacheStats xbzrle_counters
;
87 /* struct contains XBZRLE cache and a static page
88 used by the compression */
90 /* buffer used for XBZRLE encoding */
92 /* buffer for storing page content */
94 /* Cache for XBZRLE, Protected by lock. */
97 /* it will store a page full of zeros */
98 uint8_t *zero_target_page
;
99 /* buffer used for XBZRLE decoding */
100 uint8_t *decoded_buf
;
103 static void XBZRLE_cache_lock(void)
105 if (migrate_use_xbzrle())
106 qemu_mutex_lock(&XBZRLE
.lock
);
109 static void XBZRLE_cache_unlock(void)
111 if (migrate_use_xbzrle())
112 qemu_mutex_unlock(&XBZRLE
.lock
);
116 * xbzrle_cache_resize: resize the xbzrle cache
118 * This function is called from qmp_migrate_set_cache_size in main
119 * thread, possibly while a migration is in progress. A running
120 * migration may be using the cache and might finish during this call,
121 * hence changes to the cache are protected by XBZRLE.lock().
123 * Returns 0 for success or -1 for error
125 * @new_size: new cache size
126 * @errp: set *errp if the check failed, with reason
128 int xbzrle_cache_resize(int64_t new_size
, Error
**errp
)
130 PageCache
*new_cache
;
133 /* Check for truncation */
134 if (new_size
!= (size_t)new_size
) {
135 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
136 "exceeding address space");
140 if (new_size
== migrate_xbzrle_cache_size()) {
147 if (XBZRLE
.cache
!= NULL
) {
148 new_cache
= cache_init(new_size
, TARGET_PAGE_SIZE
, errp
);
154 cache_fini(XBZRLE
.cache
);
155 XBZRLE
.cache
= new_cache
;
158 XBZRLE_cache_unlock();
162 /* Should be holding either ram_list.mutex, or the RCU lock. */
163 #define RAMBLOCK_FOREACH_MIGRATABLE(block) \
164 INTERNAL_RAMBLOCK_FOREACH(block) \
165 if (!qemu_ram_is_migratable(block)) {} else
167 #undef RAMBLOCK_FOREACH
169 static void ramblock_recv_map_init(void)
173 RAMBLOCK_FOREACH_MIGRATABLE(rb
) {
174 assert(!rb
->receivedmap
);
175 rb
->receivedmap
= bitmap_new(rb
->max_length
>> qemu_target_page_bits());
179 int ramblock_recv_bitmap_test(RAMBlock
*rb
, void *host_addr
)
181 return test_bit(ramblock_recv_bitmap_offset(host_addr
, rb
),
185 bool ramblock_recv_bitmap_test_byte_offset(RAMBlock
*rb
, uint64_t byte_offset
)
187 return test_bit(byte_offset
>> TARGET_PAGE_BITS
, rb
->receivedmap
);
190 void ramblock_recv_bitmap_set(RAMBlock
*rb
, void *host_addr
)
192 set_bit_atomic(ramblock_recv_bitmap_offset(host_addr
, rb
), rb
->receivedmap
);
195 void ramblock_recv_bitmap_set_range(RAMBlock
*rb
, void *host_addr
,
198 bitmap_set_atomic(rb
->receivedmap
,
199 ramblock_recv_bitmap_offset(host_addr
, rb
),
203 #define RAMBLOCK_RECV_BITMAP_ENDING (0x0123456789abcdefULL)
206 * Format: bitmap_size (8 bytes) + whole_bitmap (N bytes).
208 * Returns >0 if success with sent bytes, or <0 if error.
210 int64_t ramblock_recv_bitmap_send(QEMUFile
*file
,
211 const char *block_name
)
213 RAMBlock
*block
= qemu_ram_block_by_name(block_name
);
214 unsigned long *le_bitmap
, nbits
;
218 error_report("%s: invalid block name: %s", __func__
, block_name
);
222 nbits
= block
->used_length
>> TARGET_PAGE_BITS
;
225 * Make sure the tmp bitmap buffer is big enough, e.g., on 32bit
226 * machines we may need 4 more bytes for padding (see below
227 * comment). So extend it a bit before hand.
229 le_bitmap
= bitmap_new(nbits
+ BITS_PER_LONG
);
232 * Always use little endian when sending the bitmap. This is
233 * required that when source and destination VMs are not using the
234 * same endianess. (Note: big endian won't work.)
236 bitmap_to_le(le_bitmap
, block
->receivedmap
, nbits
);
238 /* Size of the bitmap, in bytes */
239 size
= DIV_ROUND_UP(nbits
, 8);
242 * size is always aligned to 8 bytes for 64bit machines, but it
243 * may not be true for 32bit machines. We need this padding to
244 * make sure the migration can survive even between 32bit and
247 size
= ROUND_UP(size
, 8);
249 qemu_put_be64(file
, size
);
250 qemu_put_buffer(file
, (const uint8_t *)le_bitmap
, size
);
252 * Mark as an end, in case the middle part is screwed up due to
253 * some "misterious" reason.
255 qemu_put_be64(file
, RAMBLOCK_RECV_BITMAP_ENDING
);
260 if (qemu_file_get_error(file
)) {
261 return qemu_file_get_error(file
);
264 return size
+ sizeof(size
);
268 * An outstanding page request, on the source, having been received
271 struct RAMSrcPageRequest
{
276 QSIMPLEQ_ENTRY(RAMSrcPageRequest
) next_req
;
279 /* State of RAM for migration */
281 /* QEMUFile used for this migration */
283 /* Last block that we have visited searching for dirty pages */
284 RAMBlock
*last_seen_block
;
285 /* Last block from where we have sent data */
286 RAMBlock
*last_sent_block
;
287 /* Last dirty target page we have sent */
288 ram_addr_t last_page
;
289 /* last ram version we have seen */
290 uint32_t last_version
;
291 /* We are in the first round */
293 /* How many times we have dirty too many pages */
294 int dirty_rate_high_cnt
;
295 /* these variables are used for bitmap sync */
296 /* last time we did a full bitmap_sync */
297 int64_t time_last_bitmap_sync
;
298 /* bytes transferred at start_time */
299 uint64_t bytes_xfer_prev
;
300 /* number of dirty pages since start_time */
301 uint64_t num_dirty_pages_period
;
302 /* xbzrle misses since the beginning of the period */
303 uint64_t xbzrle_cache_miss_prev
;
305 /* compression statistics since the beginning of the period */
306 /* amount of count that no free thread to compress data */
307 uint64_t compress_thread_busy_prev
;
308 /* amount bytes after compression */
309 uint64_t compressed_size_prev
;
310 /* amount of compressed pages */
311 uint64_t compress_pages_prev
;
313 /* total handled target pages at the beginning of period */
314 uint64_t target_page_count_prev
;
315 /* total handled target pages since start */
316 uint64_t target_page_count
;
317 /* number of dirty bits in the bitmap */
318 uint64_t migration_dirty_pages
;
319 /* protects modification of the bitmap */
320 QemuMutex bitmap_mutex
;
321 /* The RAMBlock used in the last src_page_requests */
322 RAMBlock
*last_req_rb
;
323 /* Queue of outstanding page requests from the destination */
324 QemuMutex src_page_req_mutex
;
325 QSIMPLEQ_HEAD(, RAMSrcPageRequest
) src_page_requests
;
327 typedef struct RAMState RAMState
;
329 static RAMState
*ram_state
;
331 uint64_t ram_bytes_remaining(void)
333 return ram_state
? (ram_state
->migration_dirty_pages
* TARGET_PAGE_SIZE
) :
337 MigrationStats ram_counters
;
339 /* used by the search for pages to send */
340 struct PageSearchStatus
{
341 /* Current block being searched */
343 /* Current page to search from */
345 /* Set once we wrap around */
348 typedef struct PageSearchStatus PageSearchStatus
;
350 CompressionStats compression_counters
;
352 struct CompressParam
{
362 /* internally used fields */
366 typedef struct CompressParam CompressParam
;
368 struct DecompressParam
{
378 typedef struct DecompressParam DecompressParam
;
380 static CompressParam
*comp_param
;
381 static QemuThread
*compress_threads
;
382 /* comp_done_cond is used to wake up the migration thread when
383 * one of the compression threads has finished the compression.
384 * comp_done_lock is used to co-work with comp_done_cond.
386 static QemuMutex comp_done_lock
;
387 static QemuCond comp_done_cond
;
388 /* The empty QEMUFileOps will be used by file in CompressParam */
389 static const QEMUFileOps empty_ops
= { };
391 static QEMUFile
*decomp_file
;
392 static DecompressParam
*decomp_param
;
393 static QemuThread
*decompress_threads
;
394 static QemuMutex decomp_done_lock
;
395 static QemuCond decomp_done_cond
;
397 static bool do_compress_ram_page(QEMUFile
*f
, z_stream
*stream
, RAMBlock
*block
,
398 ram_addr_t offset
, uint8_t *source_buf
);
400 static void *do_data_compress(void *opaque
)
402 CompressParam
*param
= opaque
;
407 qemu_mutex_lock(¶m
->mutex
);
408 while (!param
->quit
) {
410 block
= param
->block
;
411 offset
= param
->offset
;
413 qemu_mutex_unlock(¶m
->mutex
);
415 zero_page
= do_compress_ram_page(param
->file
, ¶m
->stream
,
416 block
, offset
, param
->originbuf
);
418 qemu_mutex_lock(&comp_done_lock
);
420 param
->zero_page
= zero_page
;
421 qemu_cond_signal(&comp_done_cond
);
422 qemu_mutex_unlock(&comp_done_lock
);
424 qemu_mutex_lock(¶m
->mutex
);
426 qemu_cond_wait(¶m
->cond
, ¶m
->mutex
);
429 qemu_mutex_unlock(¶m
->mutex
);
434 static void compress_threads_save_cleanup(void)
438 if (!migrate_use_compression() || !comp_param
) {
442 thread_count
= migrate_compress_threads();
443 for (i
= 0; i
< thread_count
; i
++) {
445 * we use it as a indicator which shows if the thread is
446 * properly init'd or not
448 if (!comp_param
[i
].file
) {
452 qemu_mutex_lock(&comp_param
[i
].mutex
);
453 comp_param
[i
].quit
= true;
454 qemu_cond_signal(&comp_param
[i
].cond
);
455 qemu_mutex_unlock(&comp_param
[i
].mutex
);
457 qemu_thread_join(compress_threads
+ i
);
458 qemu_mutex_destroy(&comp_param
[i
].mutex
);
459 qemu_cond_destroy(&comp_param
[i
].cond
);
460 deflateEnd(&comp_param
[i
].stream
);
461 g_free(comp_param
[i
].originbuf
);
462 qemu_fclose(comp_param
[i
].file
);
463 comp_param
[i
].file
= NULL
;
465 qemu_mutex_destroy(&comp_done_lock
);
466 qemu_cond_destroy(&comp_done_cond
);
467 g_free(compress_threads
);
469 compress_threads
= NULL
;
473 static int compress_threads_save_setup(void)
477 if (!migrate_use_compression()) {
480 thread_count
= migrate_compress_threads();
481 compress_threads
= g_new0(QemuThread
, thread_count
);
482 comp_param
= g_new0(CompressParam
, thread_count
);
483 qemu_cond_init(&comp_done_cond
);
484 qemu_mutex_init(&comp_done_lock
);
485 for (i
= 0; i
< thread_count
; i
++) {
486 comp_param
[i
].originbuf
= g_try_malloc(TARGET_PAGE_SIZE
);
487 if (!comp_param
[i
].originbuf
) {
491 if (deflateInit(&comp_param
[i
].stream
,
492 migrate_compress_level()) != Z_OK
) {
493 g_free(comp_param
[i
].originbuf
);
497 /* comp_param[i].file is just used as a dummy buffer to save data,
498 * set its ops to empty.
500 comp_param
[i
].file
= qemu_fopen_ops(NULL
, &empty_ops
);
501 comp_param
[i
].done
= true;
502 comp_param
[i
].quit
= false;
503 qemu_mutex_init(&comp_param
[i
].mutex
);
504 qemu_cond_init(&comp_param
[i
].cond
);
505 qemu_thread_create(compress_threads
+ i
, "compress",
506 do_data_compress
, comp_param
+ i
,
507 QEMU_THREAD_JOINABLE
);
512 compress_threads_save_cleanup();
518 #define MULTIFD_MAGIC 0x11223344U
519 #define MULTIFD_VERSION 1
521 #define MULTIFD_FLAG_SYNC (1 << 0)
526 unsigned char uuid
[16]; /* QemuUUID */
528 } __attribute__((packed
)) MultiFDInit_t
;
539 } __attribute__((packed
)) MultiFDPacket_t
;
542 /* number of used pages */
544 /* number of allocated pages */
546 /* global number of generated multifd packets */
548 /* offset of each page */
550 /* pointer to each page */
556 /* this fields are not changed once the thread is created */
559 /* channel thread name */
561 /* channel thread id */
563 /* communication channel */
565 /* sem where to wait for more work */
567 /* this mutex protects the following parameters */
569 /* is this channel thread running */
571 /* should this thread finish */
573 /* thread has work to do */
575 /* array of pages to sent */
576 MultiFDPages_t
*pages
;
577 /* packet allocated len */
579 /* pointer to the packet */
580 MultiFDPacket_t
*packet
;
581 /* multifd flags for each packet */
583 /* global number of generated multifd packets */
585 /* thread local variables */
586 /* packets sent through this channel */
587 uint64_t num_packets
;
588 /* pages sent through this channel */
590 /* syncs main thread and channels */
591 QemuSemaphore sem_sync
;
595 /* this fields are not changed once the thread is created */
598 /* channel thread name */
600 /* channel thread id */
602 /* communication channel */
604 /* this mutex protects the following parameters */
606 /* is this channel thread running */
608 /* array of pages to receive */
609 MultiFDPages_t
*pages
;
610 /* packet allocated len */
612 /* pointer to the packet */
613 MultiFDPacket_t
*packet
;
614 /* multifd flags for each packet */
616 /* global number of generated multifd packets */
618 /* thread local variables */
619 /* packets sent through this channel */
620 uint64_t num_packets
;
621 /* pages sent through this channel */
623 /* syncs main thread and channels */
624 QemuSemaphore sem_sync
;
627 static int multifd_send_initial_packet(MultiFDSendParams
*p
, Error
**errp
)
632 msg
.magic
= cpu_to_be32(MULTIFD_MAGIC
);
633 msg
.version
= cpu_to_be32(MULTIFD_VERSION
);
635 memcpy(msg
.uuid
, &qemu_uuid
.data
, sizeof(msg
.uuid
));
637 ret
= qio_channel_write_all(p
->c
, (char *)&msg
, sizeof(msg
), errp
);
644 static int multifd_recv_initial_packet(QIOChannel
*c
, Error
**errp
)
649 ret
= qio_channel_read_all(c
, (char *)&msg
, sizeof(msg
), errp
);
654 msg
.magic
= be32_to_cpu(msg
.magic
);
655 msg
.version
= be32_to_cpu(msg
.version
);
657 if (msg
.magic
!= MULTIFD_MAGIC
) {
658 error_setg(errp
, "multifd: received packet magic %x "
659 "expected %x", msg
.magic
, MULTIFD_MAGIC
);
663 if (msg
.version
!= MULTIFD_VERSION
) {
664 error_setg(errp
, "multifd: received packet version %d "
665 "expected %d", msg
.version
, MULTIFD_VERSION
);
669 if (memcmp(msg
.uuid
, &qemu_uuid
, sizeof(qemu_uuid
))) {
670 char *uuid
= qemu_uuid_unparse_strdup(&qemu_uuid
);
671 char *msg_uuid
= qemu_uuid_unparse_strdup((const QemuUUID
*)msg
.uuid
);
673 error_setg(errp
, "multifd: received uuid '%s' and expected "
674 "uuid '%s' for channel %hhd", msg_uuid
, uuid
, msg
.id
);
680 if (msg
.id
> migrate_multifd_channels()) {
681 error_setg(errp
, "multifd: received channel version %d "
682 "expected %d", msg
.version
, MULTIFD_VERSION
);
689 static MultiFDPages_t
*multifd_pages_init(size_t size
)
691 MultiFDPages_t
*pages
= g_new0(MultiFDPages_t
, 1);
693 pages
->allocated
= size
;
694 pages
->iov
= g_new0(struct iovec
, size
);
695 pages
->offset
= g_new0(ram_addr_t
, size
);
700 static void multifd_pages_clear(MultiFDPages_t
*pages
)
703 pages
->allocated
= 0;
704 pages
->packet_num
= 0;
708 g_free(pages
->offset
);
709 pages
->offset
= NULL
;
713 static void multifd_send_fill_packet(MultiFDSendParams
*p
)
715 MultiFDPacket_t
*packet
= p
->packet
;
718 packet
->magic
= cpu_to_be32(MULTIFD_MAGIC
);
719 packet
->version
= cpu_to_be32(MULTIFD_VERSION
);
720 packet
->flags
= cpu_to_be32(p
->flags
);
721 packet
->size
= cpu_to_be32(migrate_multifd_page_count());
722 packet
->used
= cpu_to_be32(p
->pages
->used
);
723 packet
->packet_num
= cpu_to_be64(p
->packet_num
);
725 if (p
->pages
->block
) {
726 strncpy(packet
->ramblock
, p
->pages
->block
->idstr
, 256);
729 for (i
= 0; i
< p
->pages
->used
; i
++) {
730 packet
->offset
[i
] = cpu_to_be64(p
->pages
->offset
[i
]);
734 static int multifd_recv_unfill_packet(MultiFDRecvParams
*p
, Error
**errp
)
736 MultiFDPacket_t
*packet
= p
->packet
;
740 packet
->magic
= be32_to_cpu(packet
->magic
);
741 if (packet
->magic
!= MULTIFD_MAGIC
) {
742 error_setg(errp
, "multifd: received packet "
743 "magic %x and expected magic %x",
744 packet
->magic
, MULTIFD_MAGIC
);
748 packet
->version
= be32_to_cpu(packet
->version
);
749 if (packet
->version
!= MULTIFD_VERSION
) {
750 error_setg(errp
, "multifd: received packet "
751 "version %d and expected version %d",
752 packet
->version
, MULTIFD_VERSION
);
756 p
->flags
= be32_to_cpu(packet
->flags
);
758 packet
->size
= be32_to_cpu(packet
->size
);
759 if (packet
->size
> migrate_multifd_page_count()) {
760 error_setg(errp
, "multifd: received packet "
761 "with size %d and expected maximum size %d",
762 packet
->size
, migrate_multifd_page_count()) ;
766 p
->pages
->used
= be32_to_cpu(packet
->used
);
767 if (p
->pages
->used
> packet
->size
) {
768 error_setg(errp
, "multifd: received packet "
769 "with size %d and expected maximum size %d",
770 p
->pages
->used
, packet
->size
) ;
774 p
->packet_num
= be64_to_cpu(packet
->packet_num
);
776 if (p
->pages
->used
) {
777 /* make sure that ramblock is 0 terminated */
778 packet
->ramblock
[255] = 0;
779 block
= qemu_ram_block_by_name(packet
->ramblock
);
781 error_setg(errp
, "multifd: unknown ram block %s",
787 for (i
= 0; i
< p
->pages
->used
; i
++) {
788 ram_addr_t offset
= be64_to_cpu(packet
->offset
[i
]);
790 if (offset
> (block
->used_length
- TARGET_PAGE_SIZE
)) {
791 error_setg(errp
, "multifd: offset too long " RAM_ADDR_FMT
792 " (max " RAM_ADDR_FMT
")",
793 offset
, block
->max_length
);
796 p
->pages
->iov
[i
].iov_base
= block
->host
+ offset
;
797 p
->pages
->iov
[i
].iov_len
= TARGET_PAGE_SIZE
;
804 MultiFDSendParams
*params
;
805 /* number of created threads */
807 /* array of pages to sent */
808 MultiFDPages_t
*pages
;
809 /* syncs main thread and channels */
810 QemuSemaphore sem_sync
;
811 /* global number of generated multifd packets */
813 /* send channels ready */
814 QemuSemaphore channels_ready
;
815 } *multifd_send_state
;
818 * How we use multifd_send_state->pages and channel->pages?
820 * We create a pages for each channel, and a main one. Each time that
821 * we need to send a batch of pages we interchange the ones between
822 * multifd_send_state and the channel that is sending it. There are
823 * two reasons for that:
824 * - to not have to do so many mallocs during migration
825 * - to make easier to know what to free at the end of migration
827 * This way we always know who is the owner of each "pages" struct,
828 * and we don't need any loocking. It belongs to the migration thread
829 * or to the channel thread. Switching is safe because the migration
830 * thread is using the channel mutex when changing it, and the channel
831 * have to had finish with its own, otherwise pending_job can't be
835 static void multifd_send_pages(void)
838 static int next_channel
;
839 MultiFDSendParams
*p
= NULL
; /* make happy gcc */
840 MultiFDPages_t
*pages
= multifd_send_state
->pages
;
841 uint64_t transferred
;
843 qemu_sem_wait(&multifd_send_state
->channels_ready
);
844 for (i
= next_channel
;; i
= (i
+ 1) % migrate_multifd_channels()) {
845 p
= &multifd_send_state
->params
[i
];
847 qemu_mutex_lock(&p
->mutex
);
848 if (!p
->pending_job
) {
850 next_channel
= (i
+ 1) % migrate_multifd_channels();
853 qemu_mutex_unlock(&p
->mutex
);
857 p
->packet_num
= multifd_send_state
->packet_num
++;
858 p
->pages
->block
= NULL
;
859 multifd_send_state
->pages
= p
->pages
;
861 transferred
= ((uint64_t) pages
->used
) * TARGET_PAGE_SIZE
+ p
->packet_len
;
862 ram_counters
.multifd_bytes
+= transferred
;
863 ram_counters
.transferred
+= transferred
;;
864 qemu_mutex_unlock(&p
->mutex
);
865 qemu_sem_post(&p
->sem
);
868 static void multifd_queue_page(RAMBlock
*block
, ram_addr_t offset
)
870 MultiFDPages_t
*pages
= multifd_send_state
->pages
;
873 pages
->block
= block
;
876 if (pages
->block
== block
) {
877 pages
->offset
[pages
->used
] = offset
;
878 pages
->iov
[pages
->used
].iov_base
= block
->host
+ offset
;
879 pages
->iov
[pages
->used
].iov_len
= TARGET_PAGE_SIZE
;
882 if (pages
->used
< pages
->allocated
) {
887 multifd_send_pages();
889 if (pages
->block
!= block
) {
890 multifd_queue_page(block
, offset
);
894 static void multifd_send_terminate_threads(Error
*err
)
899 MigrationState
*s
= migrate_get_current();
900 migrate_set_error(s
, err
);
901 if (s
->state
== MIGRATION_STATUS_SETUP
||
902 s
->state
== MIGRATION_STATUS_PRE_SWITCHOVER
||
903 s
->state
== MIGRATION_STATUS_DEVICE
||
904 s
->state
== MIGRATION_STATUS_ACTIVE
) {
905 migrate_set_state(&s
->state
, s
->state
,
906 MIGRATION_STATUS_FAILED
);
910 for (i
= 0; i
< migrate_multifd_channels(); i
++) {
911 MultiFDSendParams
*p
= &multifd_send_state
->params
[i
];
913 qemu_mutex_lock(&p
->mutex
);
915 qemu_sem_post(&p
->sem
);
916 qemu_mutex_unlock(&p
->mutex
);
920 void multifd_save_cleanup(void)
924 if (!migrate_use_multifd()) {
927 multifd_send_terminate_threads(NULL
);
928 for (i
= 0; i
< migrate_multifd_channels(); i
++) {
929 MultiFDSendParams
*p
= &multifd_send_state
->params
[i
];
932 qemu_thread_join(&p
->thread
);
934 socket_send_channel_destroy(p
->c
);
936 qemu_mutex_destroy(&p
->mutex
);
937 qemu_sem_destroy(&p
->sem
);
938 qemu_sem_destroy(&p
->sem_sync
);
941 multifd_pages_clear(p
->pages
);
947 qemu_sem_destroy(&multifd_send_state
->channels_ready
);
948 qemu_sem_destroy(&multifd_send_state
->sem_sync
);
949 g_free(multifd_send_state
->params
);
950 multifd_send_state
->params
= NULL
;
951 multifd_pages_clear(multifd_send_state
->pages
);
952 multifd_send_state
->pages
= NULL
;
953 g_free(multifd_send_state
);
954 multifd_send_state
= NULL
;
957 static void multifd_send_sync_main(void)
961 if (!migrate_use_multifd()) {
964 if (multifd_send_state
->pages
->used
) {
965 multifd_send_pages();
967 for (i
= 0; i
< migrate_multifd_channels(); i
++) {
968 MultiFDSendParams
*p
= &multifd_send_state
->params
[i
];
970 trace_multifd_send_sync_main_signal(p
->id
);
972 qemu_mutex_lock(&p
->mutex
);
974 p
->packet_num
= multifd_send_state
->packet_num
++;
975 p
->flags
|= MULTIFD_FLAG_SYNC
;
977 qemu_mutex_unlock(&p
->mutex
);
978 qemu_sem_post(&p
->sem
);
980 for (i
= 0; i
< migrate_multifd_channels(); i
++) {
981 MultiFDSendParams
*p
= &multifd_send_state
->params
[i
];
983 trace_multifd_send_sync_main_wait(p
->id
);
984 qemu_sem_wait(&multifd_send_state
->sem_sync
);
986 trace_multifd_send_sync_main(multifd_send_state
->packet_num
);
989 static void *multifd_send_thread(void *opaque
)
991 MultiFDSendParams
*p
= opaque
;
992 Error
*local_err
= NULL
;
995 trace_multifd_send_thread_start(p
->id
);
996 rcu_register_thread();
998 if (multifd_send_initial_packet(p
, &local_err
) < 0) {
1001 /* initial packet */
1005 qemu_sem_wait(&p
->sem
);
1006 qemu_mutex_lock(&p
->mutex
);
1008 if (p
->pending_job
) {
1009 uint32_t used
= p
->pages
->used
;
1010 uint64_t packet_num
= p
->packet_num
;
1011 uint32_t flags
= p
->flags
;
1013 multifd_send_fill_packet(p
);
1016 p
->num_pages
+= used
;
1018 qemu_mutex_unlock(&p
->mutex
);
1020 trace_multifd_send(p
->id
, packet_num
, used
, flags
);
1022 ret
= qio_channel_write_all(p
->c
, (void *)p
->packet
,
1023 p
->packet_len
, &local_err
);
1028 ret
= qio_channel_writev_all(p
->c
, p
->pages
->iov
, used
, &local_err
);
1033 qemu_mutex_lock(&p
->mutex
);
1035 qemu_mutex_unlock(&p
->mutex
);
1037 if (flags
& MULTIFD_FLAG_SYNC
) {
1038 qemu_sem_post(&multifd_send_state
->sem_sync
);
1040 qemu_sem_post(&multifd_send_state
->channels_ready
);
1041 } else if (p
->quit
) {
1042 qemu_mutex_unlock(&p
->mutex
);
1045 qemu_mutex_unlock(&p
->mutex
);
1046 /* sometimes there are spurious wakeups */
1052 multifd_send_terminate_threads(local_err
);
1055 qemu_mutex_lock(&p
->mutex
);
1057 qemu_mutex_unlock(&p
->mutex
);
1059 rcu_unregister_thread();
1060 trace_multifd_send_thread_end(p
->id
, p
->num_packets
, p
->num_pages
);
1065 static void multifd_new_send_channel_async(QIOTask
*task
, gpointer opaque
)
1067 MultiFDSendParams
*p
= opaque
;
1068 QIOChannel
*sioc
= QIO_CHANNEL(qio_task_get_source(task
));
1069 Error
*local_err
= NULL
;
1071 if (qio_task_propagate_error(task
, &local_err
)) {
1072 migrate_set_error(migrate_get_current(), local_err
);
1073 multifd_save_cleanup();
1075 p
->c
= QIO_CHANNEL(sioc
);
1076 qio_channel_set_delay(p
->c
, false);
1078 qemu_thread_create(&p
->thread
, p
->name
, multifd_send_thread
, p
,
1079 QEMU_THREAD_JOINABLE
);
1081 atomic_inc(&multifd_send_state
->count
);
1085 int multifd_save_setup(void)
1088 uint32_t page_count
= migrate_multifd_page_count();
1091 if (!migrate_use_multifd()) {
1094 thread_count
= migrate_multifd_channels();
1095 multifd_send_state
= g_malloc0(sizeof(*multifd_send_state
));
1096 multifd_send_state
->params
= g_new0(MultiFDSendParams
, thread_count
);
1097 atomic_set(&multifd_send_state
->count
, 0);
1098 multifd_send_state
->pages
= multifd_pages_init(page_count
);
1099 qemu_sem_init(&multifd_send_state
->sem_sync
, 0);
1100 qemu_sem_init(&multifd_send_state
->channels_ready
, 0);
1102 for (i
= 0; i
< thread_count
; i
++) {
1103 MultiFDSendParams
*p
= &multifd_send_state
->params
[i
];
1105 qemu_mutex_init(&p
->mutex
);
1106 qemu_sem_init(&p
->sem
, 0);
1107 qemu_sem_init(&p
->sem_sync
, 0);
1111 p
->pages
= multifd_pages_init(page_count
);
1112 p
->packet_len
= sizeof(MultiFDPacket_t
)
1113 + sizeof(ram_addr_t
) * page_count
;
1114 p
->packet
= g_malloc0(p
->packet_len
);
1115 p
->name
= g_strdup_printf("multifdsend_%d", i
);
1116 socket_send_channel_create(multifd_new_send_channel_async
, p
);
1122 MultiFDRecvParams
*params
;
1123 /* number of created threads */
1125 /* syncs main thread and channels */
1126 QemuSemaphore sem_sync
;
1127 /* global number of generated multifd packets */
1128 uint64_t packet_num
;
1129 } *multifd_recv_state
;
1131 static void multifd_recv_terminate_threads(Error
*err
)
1136 MigrationState
*s
= migrate_get_current();
1137 migrate_set_error(s
, err
);
1138 if (s
->state
== MIGRATION_STATUS_SETUP
||
1139 s
->state
== MIGRATION_STATUS_ACTIVE
) {
1140 migrate_set_state(&s
->state
, s
->state
,
1141 MIGRATION_STATUS_FAILED
);
1145 for (i
= 0; i
< migrate_multifd_channels(); i
++) {
1146 MultiFDRecvParams
*p
= &multifd_recv_state
->params
[i
];
1148 qemu_mutex_lock(&p
->mutex
);
1149 /* We could arrive here for two reasons:
1150 - normal quit, i.e. everything went fine, just finished
1151 - error quit: We close the channels so the channel threads
1152 finish the qio_channel_read_all_eof() */
1153 qio_channel_shutdown(p
->c
, QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
);
1154 qemu_mutex_unlock(&p
->mutex
);
1158 int multifd_load_cleanup(Error
**errp
)
1163 if (!migrate_use_multifd()) {
1166 multifd_recv_terminate_threads(NULL
);
1167 for (i
= 0; i
< migrate_multifd_channels(); i
++) {
1168 MultiFDRecvParams
*p
= &multifd_recv_state
->params
[i
];
1171 qemu_thread_join(&p
->thread
);
1173 object_unref(OBJECT(p
->c
));
1175 qemu_mutex_destroy(&p
->mutex
);
1176 qemu_sem_destroy(&p
->sem_sync
);
1179 multifd_pages_clear(p
->pages
);
1185 qemu_sem_destroy(&multifd_recv_state
->sem_sync
);
1186 g_free(multifd_recv_state
->params
);
1187 multifd_recv_state
->params
= NULL
;
1188 g_free(multifd_recv_state
);
1189 multifd_recv_state
= NULL
;
1194 static void multifd_recv_sync_main(void)
1198 if (!migrate_use_multifd()) {
1201 for (i
= 0; i
< migrate_multifd_channels(); i
++) {
1202 MultiFDRecvParams
*p
= &multifd_recv_state
->params
[i
];
1204 trace_multifd_recv_sync_main_wait(p
->id
);
1205 qemu_sem_wait(&multifd_recv_state
->sem_sync
);
1206 qemu_mutex_lock(&p
->mutex
);
1207 if (multifd_recv_state
->packet_num
< p
->packet_num
) {
1208 multifd_recv_state
->packet_num
= p
->packet_num
;
1210 qemu_mutex_unlock(&p
->mutex
);
1212 for (i
= 0; i
< migrate_multifd_channels(); i
++) {
1213 MultiFDRecvParams
*p
= &multifd_recv_state
->params
[i
];
1215 trace_multifd_recv_sync_main_signal(p
->id
);
1216 qemu_sem_post(&p
->sem_sync
);
1218 trace_multifd_recv_sync_main(multifd_recv_state
->packet_num
);
1221 static void *multifd_recv_thread(void *opaque
)
1223 MultiFDRecvParams
*p
= opaque
;
1224 Error
*local_err
= NULL
;
1227 trace_multifd_recv_thread_start(p
->id
);
1228 rcu_register_thread();
1234 ret
= qio_channel_read_all_eof(p
->c
, (void *)p
->packet
,
1235 p
->packet_len
, &local_err
);
1236 if (ret
== 0) { /* EOF */
1239 if (ret
== -1) { /* Error */
1243 qemu_mutex_lock(&p
->mutex
);
1244 ret
= multifd_recv_unfill_packet(p
, &local_err
);
1246 qemu_mutex_unlock(&p
->mutex
);
1250 used
= p
->pages
->used
;
1252 trace_multifd_recv(p
->id
, p
->packet_num
, used
, flags
);
1254 p
->num_pages
+= used
;
1255 qemu_mutex_unlock(&p
->mutex
);
1257 ret
= qio_channel_readv_all(p
->c
, p
->pages
->iov
, used
, &local_err
);
1262 if (flags
& MULTIFD_FLAG_SYNC
) {
1263 qemu_sem_post(&multifd_recv_state
->sem_sync
);
1264 qemu_sem_wait(&p
->sem_sync
);
1269 multifd_recv_terminate_threads(local_err
);
1271 qemu_mutex_lock(&p
->mutex
);
1273 qemu_mutex_unlock(&p
->mutex
);
1275 rcu_unregister_thread();
1276 trace_multifd_recv_thread_end(p
->id
, p
->num_packets
, p
->num_pages
);
1281 int multifd_load_setup(void)
1284 uint32_t page_count
= migrate_multifd_page_count();
1287 if (!migrate_use_multifd()) {
1290 thread_count
= migrate_multifd_channels();
1291 multifd_recv_state
= g_malloc0(sizeof(*multifd_recv_state
));
1292 multifd_recv_state
->params
= g_new0(MultiFDRecvParams
, thread_count
);
1293 atomic_set(&multifd_recv_state
->count
, 0);
1294 qemu_sem_init(&multifd_recv_state
->sem_sync
, 0);
1296 for (i
= 0; i
< thread_count
; i
++) {
1297 MultiFDRecvParams
*p
= &multifd_recv_state
->params
[i
];
1299 qemu_mutex_init(&p
->mutex
);
1300 qemu_sem_init(&p
->sem_sync
, 0);
1302 p
->pages
= multifd_pages_init(page_count
);
1303 p
->packet_len
= sizeof(MultiFDPacket_t
)
1304 + sizeof(ram_addr_t
) * page_count
;
1305 p
->packet
= g_malloc0(p
->packet_len
);
1306 p
->name
= g_strdup_printf("multifdrecv_%d", i
);
1311 bool multifd_recv_all_channels_created(void)
1313 int thread_count
= migrate_multifd_channels();
1315 if (!migrate_use_multifd()) {
1319 return thread_count
== atomic_read(&multifd_recv_state
->count
);
1323 * Try to receive all multifd channels to get ready for the migration.
1324 * - Return true and do not set @errp when correctly receving all channels;
1325 * - Return false and do not set @errp when correctly receiving the current one;
1326 * - Return false and set @errp when failing to receive the current channel.
1328 bool multifd_recv_new_channel(QIOChannel
*ioc
, Error
**errp
)
1330 MultiFDRecvParams
*p
;
1331 Error
*local_err
= NULL
;
1334 id
= multifd_recv_initial_packet(ioc
, &local_err
);
1336 multifd_recv_terminate_threads(local_err
);
1337 error_propagate_prepend(errp
, local_err
,
1338 "failed to receive packet"
1339 " via multifd channel %d: ",
1340 atomic_read(&multifd_recv_state
->count
));
1344 p
= &multifd_recv_state
->params
[id
];
1346 error_setg(&local_err
, "multifd: received id '%d' already setup'",
1348 multifd_recv_terminate_threads(local_err
);
1349 error_propagate(errp
, local_err
);
1353 object_ref(OBJECT(ioc
));
1354 /* initial packet */
1358 qemu_thread_create(&p
->thread
, p
->name
, multifd_recv_thread
, p
,
1359 QEMU_THREAD_JOINABLE
);
1360 atomic_inc(&multifd_recv_state
->count
);
1361 return atomic_read(&multifd_recv_state
->count
) ==
1362 migrate_multifd_channels();
1366 * save_page_header: write page header to wire
1368 * If this is the 1st block, it also writes the block identification
1370 * Returns the number of bytes written
1372 * @f: QEMUFile where to send the data
1373 * @block: block that contains the page we want to send
1374 * @offset: offset inside the block for the page
1375 * in the lower bits, it contains flags
1377 static size_t save_page_header(RAMState
*rs
, QEMUFile
*f
, RAMBlock
*block
,
1382 if (block
== rs
->last_sent_block
) {
1383 offset
|= RAM_SAVE_FLAG_CONTINUE
;
1385 qemu_put_be64(f
, offset
);
1388 if (!(offset
& RAM_SAVE_FLAG_CONTINUE
)) {
1389 len
= strlen(block
->idstr
);
1390 qemu_put_byte(f
, len
);
1391 qemu_put_buffer(f
, (uint8_t *)block
->idstr
, len
);
1393 rs
->last_sent_block
= block
;
1399 * mig_throttle_guest_down: throotle down the guest
1401 * Reduce amount of guest cpu execution to hopefully slow down memory
1402 * writes. If guest dirty memory rate is reduced below the rate at
1403 * which we can transfer pages to the destination then we should be
1404 * able to complete migration. Some workloads dirty memory way too
1405 * fast and will not effectively converge, even with auto-converge.
1407 static void mig_throttle_guest_down(void)
1409 MigrationState
*s
= migrate_get_current();
1410 uint64_t pct_initial
= s
->parameters
.cpu_throttle_initial
;
1411 uint64_t pct_icrement
= s
->parameters
.cpu_throttle_increment
;
1412 int pct_max
= s
->parameters
.max_cpu_throttle
;
1414 /* We have not started throttling yet. Let's start it. */
1415 if (!cpu_throttle_active()) {
1416 cpu_throttle_set(pct_initial
);
1418 /* Throttling already on, just increase the rate */
1419 cpu_throttle_set(MIN(cpu_throttle_get_percentage() + pct_icrement
,
1425 * xbzrle_cache_zero_page: insert a zero page in the XBZRLE cache
1427 * @rs: current RAM state
1428 * @current_addr: address for the zero page
1430 * Update the xbzrle cache to reflect a page that's been sent as all 0.
1431 * The important thing is that a stale (not-yet-0'd) page be replaced
1433 * As a bonus, if the page wasn't in the cache it gets added so that
1434 * when a small write is made into the 0'd page it gets XBZRLE sent.
1436 static void xbzrle_cache_zero_page(RAMState
*rs
, ram_addr_t current_addr
)
1438 if (rs
->ram_bulk_stage
|| !migrate_use_xbzrle()) {
1442 /* We don't care if this fails to allocate a new cache page
1443 * as long as it updated an old one */
1444 cache_insert(XBZRLE
.cache
, current_addr
, XBZRLE
.zero_target_page
,
1445 ram_counters
.dirty_sync_count
);
1448 #define ENCODING_FLAG_XBZRLE 0x1
1451 * save_xbzrle_page: compress and send current page
1453 * Returns: 1 means that we wrote the page
1454 * 0 means that page is identical to the one already sent
1455 * -1 means that xbzrle would be longer than normal
1457 * @rs: current RAM state
1458 * @current_data: pointer to the address of the page contents
1459 * @current_addr: addr of the page
1460 * @block: block that contains the page we want to send
1461 * @offset: offset inside the block for the page
1462 * @last_stage: if we are at the completion stage
1464 static int save_xbzrle_page(RAMState
*rs
, uint8_t **current_data
,
1465 ram_addr_t current_addr
, RAMBlock
*block
,
1466 ram_addr_t offset
, bool last_stage
)
1468 int encoded_len
= 0, bytes_xbzrle
;
1469 uint8_t *prev_cached_page
;
1471 if (!cache_is_cached(XBZRLE
.cache
, current_addr
,
1472 ram_counters
.dirty_sync_count
)) {
1473 xbzrle_counters
.cache_miss
++;
1475 if (cache_insert(XBZRLE
.cache
, current_addr
, *current_data
,
1476 ram_counters
.dirty_sync_count
) == -1) {
1479 /* update *current_data when the page has been
1480 inserted into cache */
1481 *current_data
= get_cached_data(XBZRLE
.cache
, current_addr
);
1487 prev_cached_page
= get_cached_data(XBZRLE
.cache
, current_addr
);
1489 /* save current buffer into memory */
1490 memcpy(XBZRLE
.current_buf
, *current_data
, TARGET_PAGE_SIZE
);
1492 /* XBZRLE encoding (if there is no overflow) */
1493 encoded_len
= xbzrle_encode_buffer(prev_cached_page
, XBZRLE
.current_buf
,
1494 TARGET_PAGE_SIZE
, XBZRLE
.encoded_buf
,
1496 if (encoded_len
== 0) {
1497 trace_save_xbzrle_page_skipping();
1499 } else if (encoded_len
== -1) {
1500 trace_save_xbzrle_page_overflow();
1501 xbzrle_counters
.overflow
++;
1502 /* update data in the cache */
1504 memcpy(prev_cached_page
, *current_data
, TARGET_PAGE_SIZE
);
1505 *current_data
= prev_cached_page
;
1510 /* we need to update the data in the cache, in order to get the same data */
1512 memcpy(prev_cached_page
, XBZRLE
.current_buf
, TARGET_PAGE_SIZE
);
1515 /* Send XBZRLE based compressed page */
1516 bytes_xbzrle
= save_page_header(rs
, rs
->f
, block
,
1517 offset
| RAM_SAVE_FLAG_XBZRLE
);
1518 qemu_put_byte(rs
->f
, ENCODING_FLAG_XBZRLE
);
1519 qemu_put_be16(rs
->f
, encoded_len
);
1520 qemu_put_buffer(rs
->f
, XBZRLE
.encoded_buf
, encoded_len
);
1521 bytes_xbzrle
+= encoded_len
+ 1 + 2;
1522 xbzrle_counters
.pages
++;
1523 xbzrle_counters
.bytes
+= bytes_xbzrle
;
1524 ram_counters
.transferred
+= bytes_xbzrle
;
1530 * migration_bitmap_find_dirty: find the next dirty page from start
1532 * Called with rcu_read_lock() to protect migration_bitmap
1534 * Returns the byte offset within memory region of the start of a dirty page
1536 * @rs: current RAM state
1537 * @rb: RAMBlock where to search for dirty pages
1538 * @start: page where we start the search
1541 unsigned long migration_bitmap_find_dirty(RAMState
*rs
, RAMBlock
*rb
,
1542 unsigned long start
)
1544 unsigned long size
= rb
->used_length
>> TARGET_PAGE_BITS
;
1545 unsigned long *bitmap
= rb
->bmap
;
1548 if (!qemu_ram_is_migratable(rb
)) {
1552 if (rs
->ram_bulk_stage
&& start
> 0) {
1555 next
= find_next_bit(bitmap
, size
, start
);
1561 static inline bool migration_bitmap_clear_dirty(RAMState
*rs
,
1567 ret
= test_and_clear_bit(page
, rb
->bmap
);
1570 rs
->migration_dirty_pages
--;
1575 static void migration_bitmap_sync_range(RAMState
*rs
, RAMBlock
*rb
,
1576 ram_addr_t start
, ram_addr_t length
)
1578 rs
->migration_dirty_pages
+=
1579 cpu_physical_memory_sync_dirty_bitmap(rb
, start
, length
,
1580 &rs
->num_dirty_pages_period
);
1584 * ram_pagesize_summary: calculate all the pagesizes of a VM
1586 * Returns a summary bitmap of the page sizes of all RAMBlocks
1588 * For VMs with just normal pages this is equivalent to the host page
1589 * size. If it's got some huge pages then it's the OR of all the
1590 * different page sizes.
1592 uint64_t ram_pagesize_summary(void)
1595 uint64_t summary
= 0;
1597 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
1598 summary
|= block
->page_size
;
1604 uint64_t ram_get_total_transferred_pages(void)
1606 return ram_counters
.normal
+ ram_counters
.duplicate
+
1607 compression_counters
.pages
+ xbzrle_counters
.pages
;
1610 static void migration_update_rates(RAMState
*rs
, int64_t end_time
)
1612 uint64_t page_count
= rs
->target_page_count
- rs
->target_page_count_prev
;
1613 double compressed_size
;
1615 /* calculate period counters */
1616 ram_counters
.dirty_pages_rate
= rs
->num_dirty_pages_period
* 1000
1617 / (end_time
- rs
->time_last_bitmap_sync
);
1623 if (migrate_use_xbzrle()) {
1624 xbzrle_counters
.cache_miss_rate
= (double)(xbzrle_counters
.cache_miss
-
1625 rs
->xbzrle_cache_miss_prev
) / page_count
;
1626 rs
->xbzrle_cache_miss_prev
= xbzrle_counters
.cache_miss
;
1629 if (migrate_use_compression()) {
1630 compression_counters
.busy_rate
= (double)(compression_counters
.busy
-
1631 rs
->compress_thread_busy_prev
) / page_count
;
1632 rs
->compress_thread_busy_prev
= compression_counters
.busy
;
1634 compressed_size
= compression_counters
.compressed_size
-
1635 rs
->compressed_size_prev
;
1636 if (compressed_size
) {
1637 double uncompressed_size
= (compression_counters
.pages
-
1638 rs
->compress_pages_prev
) * TARGET_PAGE_SIZE
;
1640 /* Compression-Ratio = Uncompressed-size / Compressed-size */
1641 compression_counters
.compression_rate
=
1642 uncompressed_size
/ compressed_size
;
1644 rs
->compress_pages_prev
= compression_counters
.pages
;
1645 rs
->compressed_size_prev
= compression_counters
.compressed_size
;
1650 static void migration_bitmap_sync(RAMState
*rs
)
1654 uint64_t bytes_xfer_now
;
1656 ram_counters
.dirty_sync_count
++;
1658 if (!rs
->time_last_bitmap_sync
) {
1659 rs
->time_last_bitmap_sync
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1662 trace_migration_bitmap_sync_start();
1663 memory_global_dirty_log_sync();
1665 qemu_mutex_lock(&rs
->bitmap_mutex
);
1667 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
1668 migration_bitmap_sync_range(rs
, block
, 0, block
->used_length
);
1670 ram_counters
.remaining
= ram_bytes_remaining();
1672 qemu_mutex_unlock(&rs
->bitmap_mutex
);
1674 trace_migration_bitmap_sync_end(rs
->num_dirty_pages_period
);
1676 end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1678 /* more than 1 second = 1000 millisecons */
1679 if (end_time
> rs
->time_last_bitmap_sync
+ 1000) {
1680 bytes_xfer_now
= ram_counters
.transferred
;
1682 /* During block migration the auto-converge logic incorrectly detects
1683 * that ram migration makes no progress. Avoid this by disabling the
1684 * throttling logic during the bulk phase of block migration. */
1685 if (migrate_auto_converge() && !blk_mig_bulk_active()) {
1686 /* The following detection logic can be refined later. For now:
1687 Check to see if the dirtied bytes is 50% more than the approx.
1688 amount of bytes that just got transferred since the last time we
1689 were in this routine. If that happens twice, start or increase
1692 if ((rs
->num_dirty_pages_period
* TARGET_PAGE_SIZE
>
1693 (bytes_xfer_now
- rs
->bytes_xfer_prev
) / 2) &&
1694 (++rs
->dirty_rate_high_cnt
>= 2)) {
1695 trace_migration_throttle();
1696 rs
->dirty_rate_high_cnt
= 0;
1697 mig_throttle_guest_down();
1701 migration_update_rates(rs
, end_time
);
1703 rs
->target_page_count_prev
= rs
->target_page_count
;
1705 /* reset period counters */
1706 rs
->time_last_bitmap_sync
= end_time
;
1707 rs
->num_dirty_pages_period
= 0;
1708 rs
->bytes_xfer_prev
= bytes_xfer_now
;
1710 if (migrate_use_events()) {
1711 qapi_event_send_migration_pass(ram_counters
.dirty_sync_count
);
1716 * save_zero_page_to_file: send the zero page to the file
1718 * Returns the size of data written to the file, 0 means the page is not
1721 * @rs: current RAM state
1722 * @file: the file where the data is saved
1723 * @block: block that contains the page we want to send
1724 * @offset: offset inside the block for the page
1726 static int save_zero_page_to_file(RAMState
*rs
, QEMUFile
*file
,
1727 RAMBlock
*block
, ram_addr_t offset
)
1729 uint8_t *p
= block
->host
+ offset
;
1732 if (is_zero_range(p
, TARGET_PAGE_SIZE
)) {
1733 len
+= save_page_header(rs
, file
, block
, offset
| RAM_SAVE_FLAG_ZERO
);
1734 qemu_put_byte(file
, 0);
1741 * save_zero_page: send the zero page to the stream
1743 * Returns the number of pages written.
1745 * @rs: current RAM state
1746 * @block: block that contains the page we want to send
1747 * @offset: offset inside the block for the page
1749 static int save_zero_page(RAMState
*rs
, RAMBlock
*block
, ram_addr_t offset
)
1751 int len
= save_zero_page_to_file(rs
, rs
->f
, block
, offset
);
1754 ram_counters
.duplicate
++;
1755 ram_counters
.transferred
+= len
;
1761 static void ram_release_pages(const char *rbname
, uint64_t offset
, int pages
)
1763 if (!migrate_release_ram() || !migration_in_postcopy()) {
1767 ram_discard_range(rbname
, offset
, pages
<< TARGET_PAGE_BITS
);
1771 * @pages: the number of pages written by the control path,
1773 * > 0 - number of pages written
1775 * Return true if the pages has been saved, otherwise false is returned.
1777 static bool control_save_page(RAMState
*rs
, RAMBlock
*block
, ram_addr_t offset
,
1780 uint64_t bytes_xmit
= 0;
1784 ret
= ram_control_save_page(rs
->f
, block
->offset
, offset
, TARGET_PAGE_SIZE
,
1786 if (ret
== RAM_SAVE_CONTROL_NOT_SUPP
) {
1791 ram_counters
.transferred
+= bytes_xmit
;
1795 if (ret
== RAM_SAVE_CONTROL_DELAYED
) {
1799 if (bytes_xmit
> 0) {
1800 ram_counters
.normal
++;
1801 } else if (bytes_xmit
== 0) {
1802 ram_counters
.duplicate
++;
1809 * directly send the page to the stream
1811 * Returns the number of pages written.
1813 * @rs: current RAM state
1814 * @block: block that contains the page we want to send
1815 * @offset: offset inside the block for the page
1816 * @buf: the page to be sent
1817 * @async: send to page asyncly
1819 static int save_normal_page(RAMState
*rs
, RAMBlock
*block
, ram_addr_t offset
,
1820 uint8_t *buf
, bool async
)
1822 ram_counters
.transferred
+= save_page_header(rs
, rs
->f
, block
,
1823 offset
| RAM_SAVE_FLAG_PAGE
);
1825 qemu_put_buffer_async(rs
->f
, buf
, TARGET_PAGE_SIZE
,
1826 migrate_release_ram() &
1827 migration_in_postcopy());
1829 qemu_put_buffer(rs
->f
, buf
, TARGET_PAGE_SIZE
);
1831 ram_counters
.transferred
+= TARGET_PAGE_SIZE
;
1832 ram_counters
.normal
++;
1837 * ram_save_page: send the given page to the stream
1839 * Returns the number of pages written.
1841 * >=0 - Number of pages written - this might legally be 0
1842 * if xbzrle noticed the page was the same.
1844 * @rs: current RAM state
1845 * @block: block that contains the page we want to send
1846 * @offset: offset inside the block for the page
1847 * @last_stage: if we are at the completion stage
1849 static int ram_save_page(RAMState
*rs
, PageSearchStatus
*pss
, bool last_stage
)
1853 bool send_async
= true;
1854 RAMBlock
*block
= pss
->block
;
1855 ram_addr_t offset
= pss
->page
<< TARGET_PAGE_BITS
;
1856 ram_addr_t current_addr
= block
->offset
+ offset
;
1858 p
= block
->host
+ offset
;
1859 trace_ram_save_page(block
->idstr
, (uint64_t)offset
, p
);
1861 XBZRLE_cache_lock();
1862 if (!rs
->ram_bulk_stage
&& !migration_in_postcopy() &&
1863 migrate_use_xbzrle()) {
1864 pages
= save_xbzrle_page(rs
, &p
, current_addr
, block
,
1865 offset
, last_stage
);
1867 /* Can't send this cached data async, since the cache page
1868 * might get updated before it gets to the wire
1874 /* XBZRLE overflow or normal page */
1876 pages
= save_normal_page(rs
, block
, offset
, p
, send_async
);
1879 XBZRLE_cache_unlock();
1884 static int ram_save_multifd_page(RAMState
*rs
, RAMBlock
*block
,
1887 multifd_queue_page(block
, offset
);
1888 ram_counters
.normal
++;
1893 static bool do_compress_ram_page(QEMUFile
*f
, z_stream
*stream
, RAMBlock
*block
,
1894 ram_addr_t offset
, uint8_t *source_buf
)
1896 RAMState
*rs
= ram_state
;
1897 uint8_t *p
= block
->host
+ (offset
& TARGET_PAGE_MASK
);
1898 bool zero_page
= false;
1901 if (save_zero_page_to_file(rs
, f
, block
, offset
)) {
1906 save_page_header(rs
, f
, block
, offset
| RAM_SAVE_FLAG_COMPRESS_PAGE
);
1909 * copy it to a internal buffer to avoid it being modified by VM
1910 * so that we can catch up the error during compression and
1913 memcpy(source_buf
, p
, TARGET_PAGE_SIZE
);
1914 ret
= qemu_put_compression_data(f
, stream
, source_buf
, TARGET_PAGE_SIZE
);
1916 qemu_file_set_error(migrate_get_current()->to_dst_file
, ret
);
1917 error_report("compressed data failed!");
1922 ram_release_pages(block
->idstr
, offset
& TARGET_PAGE_MASK
, 1);
1927 update_compress_thread_counts(const CompressParam
*param
, int bytes_xmit
)
1929 ram_counters
.transferred
+= bytes_xmit
;
1931 if (param
->zero_page
) {
1932 ram_counters
.duplicate
++;
1936 /* 8 means a header with RAM_SAVE_FLAG_CONTINUE. */
1937 compression_counters
.compressed_size
+= bytes_xmit
- 8;
1938 compression_counters
.pages
++;
1941 static bool save_page_use_compression(RAMState
*rs
);
1943 static void flush_compressed_data(RAMState
*rs
)
1945 int idx
, len
, thread_count
;
1947 if (!save_page_use_compression(rs
)) {
1950 thread_count
= migrate_compress_threads();
1952 qemu_mutex_lock(&comp_done_lock
);
1953 for (idx
= 0; idx
< thread_count
; idx
++) {
1954 while (!comp_param
[idx
].done
) {
1955 qemu_cond_wait(&comp_done_cond
, &comp_done_lock
);
1958 qemu_mutex_unlock(&comp_done_lock
);
1960 for (idx
= 0; idx
< thread_count
; idx
++) {
1961 qemu_mutex_lock(&comp_param
[idx
].mutex
);
1962 if (!comp_param
[idx
].quit
) {
1963 len
= qemu_put_qemu_file(rs
->f
, comp_param
[idx
].file
);
1965 * it's safe to fetch zero_page without holding comp_done_lock
1966 * as there is no further request submitted to the thread,
1967 * i.e, the thread should be waiting for a request at this point.
1969 update_compress_thread_counts(&comp_param
[idx
], len
);
1971 qemu_mutex_unlock(&comp_param
[idx
].mutex
);
1975 static inline void set_compress_params(CompressParam
*param
, RAMBlock
*block
,
1978 param
->block
= block
;
1979 param
->offset
= offset
;
1982 static int compress_page_with_multi_thread(RAMState
*rs
, RAMBlock
*block
,
1985 int idx
, thread_count
, bytes_xmit
= -1, pages
= -1;
1986 bool wait
= migrate_compress_wait_thread();
1988 thread_count
= migrate_compress_threads();
1989 qemu_mutex_lock(&comp_done_lock
);
1991 for (idx
= 0; idx
< thread_count
; idx
++) {
1992 if (comp_param
[idx
].done
) {
1993 comp_param
[idx
].done
= false;
1994 bytes_xmit
= qemu_put_qemu_file(rs
->f
, comp_param
[idx
].file
);
1995 qemu_mutex_lock(&comp_param
[idx
].mutex
);
1996 set_compress_params(&comp_param
[idx
], block
, offset
);
1997 qemu_cond_signal(&comp_param
[idx
].cond
);
1998 qemu_mutex_unlock(&comp_param
[idx
].mutex
);
2000 update_compress_thread_counts(&comp_param
[idx
], bytes_xmit
);
2006 * wait for the free thread if the user specifies 'compress-wait-thread',
2007 * otherwise we will post the page out in the main thread as normal page.
2009 if (pages
< 0 && wait
) {
2010 qemu_cond_wait(&comp_done_cond
, &comp_done_lock
);
2013 qemu_mutex_unlock(&comp_done_lock
);
2019 * find_dirty_block: find the next dirty page and update any state
2020 * associated with the search process.
2022 * Returns if a page is found
2024 * @rs: current RAM state
2025 * @pss: data about the state of the current dirty page scan
2026 * @again: set to false if the search has scanned the whole of RAM
2028 static bool find_dirty_block(RAMState
*rs
, PageSearchStatus
*pss
, bool *again
)
2030 pss
->page
= migration_bitmap_find_dirty(rs
, pss
->block
, pss
->page
);
2031 if (pss
->complete_round
&& pss
->block
== rs
->last_seen_block
&&
2032 pss
->page
>= rs
->last_page
) {
2034 * We've been once around the RAM and haven't found anything.
2040 if ((pss
->page
<< TARGET_PAGE_BITS
) >= pss
->block
->used_length
) {
2041 /* Didn't find anything in this RAM Block */
2043 pss
->block
= QLIST_NEXT_RCU(pss
->block
, next
);
2046 * If memory migration starts over, we will meet a dirtied page
2047 * which may still exists in compression threads's ring, so we
2048 * should flush the compressed data to make sure the new page
2049 * is not overwritten by the old one in the destination.
2051 * Also If xbzrle is on, stop using the data compression at this
2052 * point. In theory, xbzrle can do better than compression.
2054 flush_compressed_data(rs
);
2056 /* Hit the end of the list */
2057 pss
->block
= QLIST_FIRST_RCU(&ram_list
.blocks
);
2058 /* Flag that we've looped */
2059 pss
->complete_round
= true;
2060 rs
->ram_bulk_stage
= false;
2062 /* Didn't find anything this time, but try again on the new block */
2066 /* Can go around again, but... */
2068 /* We've found something so probably don't need to */
2074 * unqueue_page: gets a page of the queue
2076 * Helper for 'get_queued_page' - gets a page off the queue
2078 * Returns the block of the page (or NULL if none available)
2080 * @rs: current RAM state
2081 * @offset: used to return the offset within the RAMBlock
2083 static RAMBlock
*unqueue_page(RAMState
*rs
, ram_addr_t
*offset
)
2085 RAMBlock
*block
= NULL
;
2087 if (QSIMPLEQ_EMPTY_ATOMIC(&rs
->src_page_requests
)) {
2091 qemu_mutex_lock(&rs
->src_page_req_mutex
);
2092 if (!QSIMPLEQ_EMPTY(&rs
->src_page_requests
)) {
2093 struct RAMSrcPageRequest
*entry
=
2094 QSIMPLEQ_FIRST(&rs
->src_page_requests
);
2096 *offset
= entry
->offset
;
2098 if (entry
->len
> TARGET_PAGE_SIZE
) {
2099 entry
->len
-= TARGET_PAGE_SIZE
;
2100 entry
->offset
+= TARGET_PAGE_SIZE
;
2102 memory_region_unref(block
->mr
);
2103 QSIMPLEQ_REMOVE_HEAD(&rs
->src_page_requests
, next_req
);
2105 migration_consume_urgent_request();
2108 qemu_mutex_unlock(&rs
->src_page_req_mutex
);
2114 * get_queued_page: unqueue a page from the postocpy requests
2116 * Skips pages that are already sent (!dirty)
2118 * Returns if a queued page is found
2120 * @rs: current RAM state
2121 * @pss: data about the state of the current dirty page scan
2123 static bool get_queued_page(RAMState
*rs
, PageSearchStatus
*pss
)
2130 block
= unqueue_page(rs
, &offset
);
2132 * We're sending this page, and since it's postcopy nothing else
2133 * will dirty it, and we must make sure it doesn't get sent again
2134 * even if this queue request was received after the background
2135 * search already sent it.
2140 page
= offset
>> TARGET_PAGE_BITS
;
2141 dirty
= test_bit(page
, block
->bmap
);
2143 trace_get_queued_page_not_dirty(block
->idstr
, (uint64_t)offset
,
2144 page
, test_bit(page
, block
->unsentmap
));
2146 trace_get_queued_page(block
->idstr
, (uint64_t)offset
, page
);
2150 } while (block
&& !dirty
);
2154 * As soon as we start servicing pages out of order, then we have
2155 * to kill the bulk stage, since the bulk stage assumes
2156 * in (migration_bitmap_find_and_reset_dirty) that every page is
2157 * dirty, that's no longer true.
2159 rs
->ram_bulk_stage
= false;
2162 * We want the background search to continue from the queued page
2163 * since the guest is likely to want other pages near to the page
2164 * it just requested.
2167 pss
->page
= offset
>> TARGET_PAGE_BITS
;
2174 * migration_page_queue_free: drop any remaining pages in the ram
2177 * It should be empty at the end anyway, but in error cases there may
2178 * be some left. in case that there is any page left, we drop it.
2181 static void migration_page_queue_free(RAMState
*rs
)
2183 struct RAMSrcPageRequest
*mspr
, *next_mspr
;
2184 /* This queue generally should be empty - but in the case of a failed
2185 * migration might have some droppings in.
2188 QSIMPLEQ_FOREACH_SAFE(mspr
, &rs
->src_page_requests
, next_req
, next_mspr
) {
2189 memory_region_unref(mspr
->rb
->mr
);
2190 QSIMPLEQ_REMOVE_HEAD(&rs
->src_page_requests
, next_req
);
2197 * ram_save_queue_pages: queue the page for transmission
2199 * A request from postcopy destination for example.
2201 * Returns zero on success or negative on error
2203 * @rbname: Name of the RAMBLock of the request. NULL means the
2204 * same that last one.
2205 * @start: starting address from the start of the RAMBlock
2206 * @len: length (in bytes) to send
2208 int ram_save_queue_pages(const char *rbname
, ram_addr_t start
, ram_addr_t len
)
2211 RAMState
*rs
= ram_state
;
2213 ram_counters
.postcopy_requests
++;
2216 /* Reuse last RAMBlock */
2217 ramblock
= rs
->last_req_rb
;
2221 * Shouldn't happen, we can't reuse the last RAMBlock if
2222 * it's the 1st request.
2224 error_report("ram_save_queue_pages no previous block");
2228 ramblock
= qemu_ram_block_by_name(rbname
);
2231 /* We shouldn't be asked for a non-existent RAMBlock */
2232 error_report("ram_save_queue_pages no block '%s'", rbname
);
2235 rs
->last_req_rb
= ramblock
;
2237 trace_ram_save_queue_pages(ramblock
->idstr
, start
, len
);
2238 if (start
+len
> ramblock
->used_length
) {
2239 error_report("%s request overrun start=" RAM_ADDR_FMT
" len="
2240 RAM_ADDR_FMT
" blocklen=" RAM_ADDR_FMT
,
2241 __func__
, start
, len
, ramblock
->used_length
);
2245 struct RAMSrcPageRequest
*new_entry
=
2246 g_malloc0(sizeof(struct RAMSrcPageRequest
));
2247 new_entry
->rb
= ramblock
;
2248 new_entry
->offset
= start
;
2249 new_entry
->len
= len
;
2251 memory_region_ref(ramblock
->mr
);
2252 qemu_mutex_lock(&rs
->src_page_req_mutex
);
2253 QSIMPLEQ_INSERT_TAIL(&rs
->src_page_requests
, new_entry
, next_req
);
2254 migration_make_urgent_request();
2255 qemu_mutex_unlock(&rs
->src_page_req_mutex
);
2265 static bool save_page_use_compression(RAMState
*rs
)
2267 if (!migrate_use_compression()) {
2272 * If xbzrle is on, stop using the data compression after first
2273 * round of migration even if compression is enabled. In theory,
2274 * xbzrle can do better than compression.
2276 if (rs
->ram_bulk_stage
|| !migrate_use_xbzrle()) {
2284 * try to compress the page before posting it out, return true if the page
2285 * has been properly handled by compression, otherwise needs other
2286 * paths to handle it
2288 static bool save_compress_page(RAMState
*rs
, RAMBlock
*block
, ram_addr_t offset
)
2290 if (!save_page_use_compression(rs
)) {
2295 * When starting the process of a new block, the first page of
2296 * the block should be sent out before other pages in the same
2297 * block, and all the pages in last block should have been sent
2298 * out, keeping this order is important, because the 'cont' flag
2299 * is used to avoid resending the block name.
2301 * We post the fist page as normal page as compression will take
2302 * much CPU resource.
2304 if (block
!= rs
->last_sent_block
) {
2305 flush_compressed_data(rs
);
2309 if (compress_page_with_multi_thread(rs
, block
, offset
) > 0) {
2313 compression_counters
.busy
++;
2318 * ram_save_target_page: save one target page
2320 * Returns the number of pages written
2322 * @rs: current RAM state
2323 * @pss: data about the page we want to send
2324 * @last_stage: if we are at the completion stage
2326 static int ram_save_target_page(RAMState
*rs
, PageSearchStatus
*pss
,
2329 RAMBlock
*block
= pss
->block
;
2330 ram_addr_t offset
= pss
->page
<< TARGET_PAGE_BITS
;
2333 if (control_save_page(rs
, block
, offset
, &res
)) {
2337 if (save_compress_page(rs
, block
, offset
)) {
2341 res
= save_zero_page(rs
, block
, offset
);
2343 /* Must let xbzrle know, otherwise a previous (now 0'd) cached
2344 * page would be stale
2346 if (!save_page_use_compression(rs
)) {
2347 XBZRLE_cache_lock();
2348 xbzrle_cache_zero_page(rs
, block
->offset
+ offset
);
2349 XBZRLE_cache_unlock();
2351 ram_release_pages(block
->idstr
, offset
, res
);
2356 * do not use multifd for compression as the first page in the new
2357 * block should be posted out before sending the compressed page
2359 if (!save_page_use_compression(rs
) && migrate_use_multifd()) {
2360 return ram_save_multifd_page(rs
, block
, offset
);
2363 return ram_save_page(rs
, pss
, last_stage
);
2367 * ram_save_host_page: save a whole host page
2369 * Starting at *offset send pages up to the end of the current host
2370 * page. It's valid for the initial offset to point into the middle of
2371 * a host page in which case the remainder of the hostpage is sent.
2372 * Only dirty target pages are sent. Note that the host page size may
2373 * be a huge page for this block.
2374 * The saving stops at the boundary of the used_length of the block
2375 * if the RAMBlock isn't a multiple of the host page size.
2377 * Returns the number of pages written or negative on error
2379 * @rs: current RAM state
2380 * @ms: current migration state
2381 * @pss: data about the page we want to send
2382 * @last_stage: if we are at the completion stage
2384 static int ram_save_host_page(RAMState
*rs
, PageSearchStatus
*pss
,
2387 int tmppages
, pages
= 0;
2388 size_t pagesize_bits
=
2389 qemu_ram_pagesize(pss
->block
) >> TARGET_PAGE_BITS
;
2391 if (!qemu_ram_is_migratable(pss
->block
)) {
2392 error_report("block %s should not be migrated !", pss
->block
->idstr
);
2397 /* Check the pages is dirty and if it is send it */
2398 if (!migration_bitmap_clear_dirty(rs
, pss
->block
, pss
->page
)) {
2403 tmppages
= ram_save_target_page(rs
, pss
, last_stage
);
2409 if (pss
->block
->unsentmap
) {
2410 clear_bit(pss
->page
, pss
->block
->unsentmap
);
2414 } while ((pss
->page
& (pagesize_bits
- 1)) &&
2415 offset_in_ramblock(pss
->block
, pss
->page
<< TARGET_PAGE_BITS
));
2417 /* The offset we leave with is the last one we looked at */
2423 * ram_find_and_save_block: finds a dirty page and sends it to f
2425 * Called within an RCU critical section.
2427 * Returns the number of pages written where zero means no dirty pages,
2428 * or negative on error
2430 * @rs: current RAM state
2431 * @last_stage: if we are at the completion stage
2433 * On systems where host-page-size > target-page-size it will send all the
2434 * pages in a host page that are dirty.
2437 static int ram_find_and_save_block(RAMState
*rs
, bool last_stage
)
2439 PageSearchStatus pss
;
2443 /* No dirty page as there is zero RAM */
2444 if (!ram_bytes_total()) {
2448 pss
.block
= rs
->last_seen_block
;
2449 pss
.page
= rs
->last_page
;
2450 pss
.complete_round
= false;
2453 pss
.block
= QLIST_FIRST_RCU(&ram_list
.blocks
);
2458 found
= get_queued_page(rs
, &pss
);
2461 /* priority queue empty, so just search for something dirty */
2462 found
= find_dirty_block(rs
, &pss
, &again
);
2466 pages
= ram_save_host_page(rs
, &pss
, last_stage
);
2468 } while (!pages
&& again
);
2470 rs
->last_seen_block
= pss
.block
;
2471 rs
->last_page
= pss
.page
;
2476 void acct_update_position(QEMUFile
*f
, size_t size
, bool zero
)
2478 uint64_t pages
= size
/ TARGET_PAGE_SIZE
;
2481 ram_counters
.duplicate
+= pages
;
2483 ram_counters
.normal
+= pages
;
2484 ram_counters
.transferred
+= size
;
2485 qemu_update_position(f
, size
);
2489 uint64_t ram_bytes_total(void)
2495 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
2496 total
+= block
->used_length
;
2502 static void xbzrle_load_setup(void)
2504 XBZRLE
.decoded_buf
= g_malloc(TARGET_PAGE_SIZE
);
2507 static void xbzrle_load_cleanup(void)
2509 g_free(XBZRLE
.decoded_buf
);
2510 XBZRLE
.decoded_buf
= NULL
;
2513 static void ram_state_cleanup(RAMState
**rsp
)
2516 migration_page_queue_free(*rsp
);
2517 qemu_mutex_destroy(&(*rsp
)->bitmap_mutex
);
2518 qemu_mutex_destroy(&(*rsp
)->src_page_req_mutex
);
2524 static void xbzrle_cleanup(void)
2526 XBZRLE_cache_lock();
2528 cache_fini(XBZRLE
.cache
);
2529 g_free(XBZRLE
.encoded_buf
);
2530 g_free(XBZRLE
.current_buf
);
2531 g_free(XBZRLE
.zero_target_page
);
2532 XBZRLE
.cache
= NULL
;
2533 XBZRLE
.encoded_buf
= NULL
;
2534 XBZRLE
.current_buf
= NULL
;
2535 XBZRLE
.zero_target_page
= NULL
;
2537 XBZRLE_cache_unlock();
2540 static void ram_save_cleanup(void *opaque
)
2542 RAMState
**rsp
= opaque
;
2545 /* caller have hold iothread lock or is in a bh, so there is
2546 * no writing race against this migration_bitmap
2548 memory_global_dirty_log_stop();
2550 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
2551 g_free(block
->bmap
);
2553 g_free(block
->unsentmap
);
2554 block
->unsentmap
= NULL
;
2558 compress_threads_save_cleanup();
2559 ram_state_cleanup(rsp
);
2562 static void ram_state_reset(RAMState
*rs
)
2564 rs
->last_seen_block
= NULL
;
2565 rs
->last_sent_block
= NULL
;
2567 rs
->last_version
= ram_list
.version
;
2568 rs
->ram_bulk_stage
= true;
2571 #define MAX_WAIT 50 /* ms, half buffered_file limit */
2574 * 'expected' is the value you expect the bitmap mostly to be full
2575 * of; it won't bother printing lines that are all this value.
2576 * If 'todump' is null the migration bitmap is dumped.
2578 void ram_debug_dump_bitmap(unsigned long *todump
, bool expected
,
2579 unsigned long pages
)
2582 int64_t linelen
= 128;
2585 for (cur
= 0; cur
< pages
; cur
+= linelen
) {
2589 * Last line; catch the case where the line length
2590 * is longer than remaining ram
2592 if (cur
+ linelen
> pages
) {
2593 linelen
= pages
- cur
;
2595 for (curb
= 0; curb
< linelen
; curb
++) {
2596 bool thisbit
= test_bit(cur
+ curb
, todump
);
2597 linebuf
[curb
] = thisbit
? '1' : '.';
2598 found
= found
|| (thisbit
!= expected
);
2601 linebuf
[curb
] = '\0';
2602 fprintf(stderr
, "0x%08" PRIx64
" : %s\n", cur
, linebuf
);
2607 /* **** functions for postcopy ***** */
2609 void ram_postcopy_migrated_memory_release(MigrationState
*ms
)
2611 struct RAMBlock
*block
;
2613 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
2614 unsigned long *bitmap
= block
->bmap
;
2615 unsigned long range
= block
->used_length
>> TARGET_PAGE_BITS
;
2616 unsigned long run_start
= find_next_zero_bit(bitmap
, range
, 0);
2618 while (run_start
< range
) {
2619 unsigned long run_end
= find_next_bit(bitmap
, range
, run_start
+ 1);
2620 ram_discard_range(block
->idstr
, run_start
<< TARGET_PAGE_BITS
,
2621 (run_end
- run_start
) << TARGET_PAGE_BITS
);
2622 run_start
= find_next_zero_bit(bitmap
, range
, run_end
+ 1);
2628 * postcopy_send_discard_bm_ram: discard a RAMBlock
2630 * Returns zero on success
2632 * Callback from postcopy_each_ram_send_discard for each RAMBlock
2633 * Note: At this point the 'unsentmap' is the processed bitmap combined
2634 * with the dirtymap; so a '1' means it's either dirty or unsent.
2636 * @ms: current migration state
2637 * @pds: state for postcopy
2638 * @start: RAMBlock starting page
2639 * @length: RAMBlock size
2641 static int postcopy_send_discard_bm_ram(MigrationState
*ms
,
2642 PostcopyDiscardState
*pds
,
2645 unsigned long end
= block
->used_length
>> TARGET_PAGE_BITS
;
2646 unsigned long current
;
2647 unsigned long *unsentmap
= block
->unsentmap
;
2649 for (current
= 0; current
< end
; ) {
2650 unsigned long one
= find_next_bit(unsentmap
, end
, current
);
2653 unsigned long zero
= find_next_zero_bit(unsentmap
, end
, one
+ 1);
2654 unsigned long discard_length
;
2657 discard_length
= end
- one
;
2659 discard_length
= zero
- one
;
2661 if (discard_length
) {
2662 postcopy_discard_send_range(ms
, pds
, one
, discard_length
);
2664 current
= one
+ discard_length
;
2674 * postcopy_each_ram_send_discard: discard all RAMBlocks
2676 * Returns 0 for success or negative for error
2678 * Utility for the outgoing postcopy code.
2679 * Calls postcopy_send_discard_bm_ram for each RAMBlock
2680 * passing it bitmap indexes and name.
2681 * (qemu_ram_foreach_block ends up passing unscaled lengths
2682 * which would mean postcopy code would have to deal with target page)
2684 * @ms: current migration state
2686 static int postcopy_each_ram_send_discard(MigrationState
*ms
)
2688 struct RAMBlock
*block
;
2691 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
2692 PostcopyDiscardState
*pds
=
2693 postcopy_discard_send_init(ms
, block
->idstr
);
2696 * Postcopy sends chunks of bitmap over the wire, but it
2697 * just needs indexes at this point, avoids it having
2698 * target page specific code.
2700 ret
= postcopy_send_discard_bm_ram(ms
, pds
, block
);
2701 postcopy_discard_send_finish(ms
, pds
);
2711 * postcopy_chunk_hostpages_pass: canocalize bitmap in hostpages
2713 * Helper for postcopy_chunk_hostpages; it's called twice to
2714 * canonicalize the two bitmaps, that are similar, but one is
2717 * Postcopy requires that all target pages in a hostpage are dirty or
2718 * clean, not a mix. This function canonicalizes the bitmaps.
2720 * @ms: current migration state
2721 * @unsent_pass: if true we need to canonicalize partially unsent host pages
2722 * otherwise we need to canonicalize partially dirty host pages
2723 * @block: block that contains the page we want to canonicalize
2724 * @pds: state for postcopy
2726 static void postcopy_chunk_hostpages_pass(MigrationState
*ms
, bool unsent_pass
,
2728 PostcopyDiscardState
*pds
)
2730 RAMState
*rs
= ram_state
;
2731 unsigned long *bitmap
= block
->bmap
;
2732 unsigned long *unsentmap
= block
->unsentmap
;
2733 unsigned int host_ratio
= block
->page_size
/ TARGET_PAGE_SIZE
;
2734 unsigned long pages
= block
->used_length
>> TARGET_PAGE_BITS
;
2735 unsigned long run_start
;
2737 if (block
->page_size
== TARGET_PAGE_SIZE
) {
2738 /* Easy case - TPS==HPS for a non-huge page RAMBlock */
2743 /* Find a sent page */
2744 run_start
= find_next_zero_bit(unsentmap
, pages
, 0);
2746 /* Find a dirty page */
2747 run_start
= find_next_bit(bitmap
, pages
, 0);
2750 while (run_start
< pages
) {
2751 bool do_fixup
= false;
2752 unsigned long fixup_start_addr
;
2753 unsigned long host_offset
;
2756 * If the start of this run of pages is in the middle of a host
2757 * page, then we need to fixup this host page.
2759 host_offset
= run_start
% host_ratio
;
2762 run_start
-= host_offset
;
2763 fixup_start_addr
= run_start
;
2764 /* For the next pass */
2765 run_start
= run_start
+ host_ratio
;
2767 /* Find the end of this run */
2768 unsigned long run_end
;
2770 run_end
= find_next_bit(unsentmap
, pages
, run_start
+ 1);
2772 run_end
= find_next_zero_bit(bitmap
, pages
, run_start
+ 1);
2775 * If the end isn't at the start of a host page, then the
2776 * run doesn't finish at the end of a host page
2777 * and we need to discard.
2779 host_offset
= run_end
% host_ratio
;
2782 fixup_start_addr
= run_end
- host_offset
;
2784 * This host page has gone, the next loop iteration starts
2785 * from after the fixup
2787 run_start
= fixup_start_addr
+ host_ratio
;
2790 * No discards on this iteration, next loop starts from
2791 * next sent/dirty page
2793 run_start
= run_end
+ 1;
2800 /* Tell the destination to discard this page */
2801 if (unsent_pass
|| !test_bit(fixup_start_addr
, unsentmap
)) {
2802 /* For the unsent_pass we:
2803 * discard partially sent pages
2804 * For the !unsent_pass (dirty) we:
2805 * discard partially dirty pages that were sent
2806 * (any partially sent pages were already discarded
2807 * by the previous unsent_pass)
2809 postcopy_discard_send_range(ms
, pds
, fixup_start_addr
,
2813 /* Clean up the bitmap */
2814 for (page
= fixup_start_addr
;
2815 page
< fixup_start_addr
+ host_ratio
; page
++) {
2816 /* All pages in this host page are now not sent */
2817 set_bit(page
, unsentmap
);
2820 * Remark them as dirty, updating the count for any pages
2821 * that weren't previously dirty.
2823 rs
->migration_dirty_pages
+= !test_and_set_bit(page
, bitmap
);
2828 /* Find the next sent page for the next iteration */
2829 run_start
= find_next_zero_bit(unsentmap
, pages
, run_start
);
2831 /* Find the next dirty page for the next iteration */
2832 run_start
= find_next_bit(bitmap
, pages
, run_start
);
2838 * postcopy_chuck_hostpages: discrad any partially sent host page
2840 * Utility for the outgoing postcopy code.
2842 * Discard any partially sent host-page size chunks, mark any partially
2843 * dirty host-page size chunks as all dirty. In this case the host-page
2844 * is the host-page for the particular RAMBlock, i.e. it might be a huge page
2846 * Returns zero on success
2848 * @ms: current migration state
2849 * @block: block we want to work with
2851 static int postcopy_chunk_hostpages(MigrationState
*ms
, RAMBlock
*block
)
2853 PostcopyDiscardState
*pds
=
2854 postcopy_discard_send_init(ms
, block
->idstr
);
2856 /* First pass: Discard all partially sent host pages */
2857 postcopy_chunk_hostpages_pass(ms
, true, block
, pds
);
2859 * Second pass: Ensure that all partially dirty host pages are made
2862 postcopy_chunk_hostpages_pass(ms
, false, block
, pds
);
2864 postcopy_discard_send_finish(ms
, pds
);
2869 * ram_postcopy_send_discard_bitmap: transmit the discard bitmap
2871 * Returns zero on success
2873 * Transmit the set of pages to be discarded after precopy to the target
2874 * these are pages that:
2875 * a) Have been previously transmitted but are now dirty again
2876 * b) Pages that have never been transmitted, this ensures that
2877 * any pages on the destination that have been mapped by background
2878 * tasks get discarded (transparent huge pages is the specific concern)
2879 * Hopefully this is pretty sparse
2881 * @ms: current migration state
2883 int ram_postcopy_send_discard_bitmap(MigrationState
*ms
)
2885 RAMState
*rs
= ram_state
;
2891 /* This should be our last sync, the src is now paused */
2892 migration_bitmap_sync(rs
);
2894 /* Easiest way to make sure we don't resume in the middle of a host-page */
2895 rs
->last_seen_block
= NULL
;
2896 rs
->last_sent_block
= NULL
;
2899 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
2900 unsigned long pages
= block
->used_length
>> TARGET_PAGE_BITS
;
2901 unsigned long *bitmap
= block
->bmap
;
2902 unsigned long *unsentmap
= block
->unsentmap
;
2905 /* We don't have a safe way to resize the sentmap, so
2906 * if the bitmap was resized it will be NULL at this
2909 error_report("migration ram resized during precopy phase");
2913 /* Deal with TPS != HPS and huge pages */
2914 ret
= postcopy_chunk_hostpages(ms
, block
);
2921 * Update the unsentmap to be unsentmap = unsentmap | dirty
2923 bitmap_or(unsentmap
, unsentmap
, bitmap
, pages
);
2924 #ifdef DEBUG_POSTCOPY
2925 ram_debug_dump_bitmap(unsentmap
, true, pages
);
2928 trace_ram_postcopy_send_discard_bitmap();
2930 ret
= postcopy_each_ram_send_discard(ms
);
2937 * ram_discard_range: discard dirtied pages at the beginning of postcopy
2939 * Returns zero on success
2941 * @rbname: name of the RAMBlock of the request. NULL means the
2942 * same that last one.
2943 * @start: RAMBlock starting page
2944 * @length: RAMBlock size
2946 int ram_discard_range(const char *rbname
, uint64_t start
, size_t length
)
2950 trace_ram_discard_range(rbname
, start
, length
);
2953 RAMBlock
*rb
= qemu_ram_block_by_name(rbname
);
2956 error_report("ram_discard_range: Failed to find block '%s'", rbname
);
2961 * On source VM, we don't need to update the received bitmap since
2962 * we don't even have one.
2964 if (rb
->receivedmap
) {
2965 bitmap_clear(rb
->receivedmap
, start
>> qemu_target_page_bits(),
2966 length
>> qemu_target_page_bits());
2969 ret
= ram_block_discard_range(rb
, start
, length
);
2978 * For every allocation, we will try not to crash the VM if the
2979 * allocation failed.
2981 static int xbzrle_init(void)
2983 Error
*local_err
= NULL
;
2985 if (!migrate_use_xbzrle()) {
2989 XBZRLE_cache_lock();
2991 XBZRLE
.zero_target_page
= g_try_malloc0(TARGET_PAGE_SIZE
);
2992 if (!XBZRLE
.zero_target_page
) {
2993 error_report("%s: Error allocating zero page", __func__
);
2997 XBZRLE
.cache
= cache_init(migrate_xbzrle_cache_size(),
2998 TARGET_PAGE_SIZE
, &local_err
);
2999 if (!XBZRLE
.cache
) {
3000 error_report_err(local_err
);
3001 goto free_zero_page
;
3004 XBZRLE
.encoded_buf
= g_try_malloc0(TARGET_PAGE_SIZE
);
3005 if (!XBZRLE
.encoded_buf
) {
3006 error_report("%s: Error allocating encoded_buf", __func__
);
3010 XBZRLE
.current_buf
= g_try_malloc(TARGET_PAGE_SIZE
);
3011 if (!XBZRLE
.current_buf
) {
3012 error_report("%s: Error allocating current_buf", __func__
);
3013 goto free_encoded_buf
;
3016 /* We are all good */
3017 XBZRLE_cache_unlock();
3021 g_free(XBZRLE
.encoded_buf
);
3022 XBZRLE
.encoded_buf
= NULL
;
3024 cache_fini(XBZRLE
.cache
);
3025 XBZRLE
.cache
= NULL
;
3027 g_free(XBZRLE
.zero_target_page
);
3028 XBZRLE
.zero_target_page
= NULL
;
3030 XBZRLE_cache_unlock();
3034 static int ram_state_init(RAMState
**rsp
)
3036 *rsp
= g_try_new0(RAMState
, 1);
3039 error_report("%s: Init ramstate fail", __func__
);
3043 qemu_mutex_init(&(*rsp
)->bitmap_mutex
);
3044 qemu_mutex_init(&(*rsp
)->src_page_req_mutex
);
3045 QSIMPLEQ_INIT(&(*rsp
)->src_page_requests
);
3048 * Count the total number of pages used by ram blocks not including any
3049 * gaps due to alignment or unplugs.
3051 (*rsp
)->migration_dirty_pages
= ram_bytes_total() >> TARGET_PAGE_BITS
;
3053 ram_state_reset(*rsp
);
3058 static void ram_list_init_bitmaps(void)
3061 unsigned long pages
;
3063 /* Skip setting bitmap if there is no RAM */
3064 if (ram_bytes_total()) {
3065 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
3066 pages
= block
->max_length
>> TARGET_PAGE_BITS
;
3067 block
->bmap
= bitmap_new(pages
);
3068 bitmap_set(block
->bmap
, 0, pages
);
3069 if (migrate_postcopy_ram()) {
3070 block
->unsentmap
= bitmap_new(pages
);
3071 bitmap_set(block
->unsentmap
, 0, pages
);
3077 static void ram_init_bitmaps(RAMState
*rs
)
3079 /* For memory_global_dirty_log_start below. */
3080 qemu_mutex_lock_iothread();
3081 qemu_mutex_lock_ramlist();
3084 ram_list_init_bitmaps();
3085 memory_global_dirty_log_start();
3086 migration_bitmap_sync(rs
);
3089 qemu_mutex_unlock_ramlist();
3090 qemu_mutex_unlock_iothread();
3093 static int ram_init_all(RAMState
**rsp
)
3095 if (ram_state_init(rsp
)) {
3099 if (xbzrle_init()) {
3100 ram_state_cleanup(rsp
);
3104 ram_init_bitmaps(*rsp
);
3109 static void ram_state_resume_prepare(RAMState
*rs
, QEMUFile
*out
)
3115 * Postcopy is not using xbzrle/compression, so no need for that.
3116 * Also, since source are already halted, we don't need to care
3117 * about dirty page logging as well.
3120 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
3121 pages
+= bitmap_count_one(block
->bmap
,
3122 block
->used_length
>> TARGET_PAGE_BITS
);
3125 /* This may not be aligned with current bitmaps. Recalculate. */
3126 rs
->migration_dirty_pages
= pages
;
3128 rs
->last_seen_block
= NULL
;
3129 rs
->last_sent_block
= NULL
;
3131 rs
->last_version
= ram_list
.version
;
3133 * Disable the bulk stage, otherwise we'll resend the whole RAM no
3134 * matter what we have sent.
3136 rs
->ram_bulk_stage
= false;
3138 /* Update RAMState cache of output QEMUFile */
3141 trace_ram_state_resume_prepare(pages
);
3145 * Each of ram_save_setup, ram_save_iterate and ram_save_complete has
3146 * long-running RCU critical section. When rcu-reclaims in the code
3147 * start to become numerous it will be necessary to reduce the
3148 * granularity of these critical sections.
3152 * ram_save_setup: Setup RAM for migration
3154 * Returns zero to indicate success and negative for error
3156 * @f: QEMUFile where to send the data
3157 * @opaque: RAMState pointer
3159 static int ram_save_setup(QEMUFile
*f
, void *opaque
)
3161 RAMState
**rsp
= opaque
;
3164 if (compress_threads_save_setup()) {
3168 /* migration has already setup the bitmap, reuse it. */
3169 if (!migration_in_colo_state()) {
3170 if (ram_init_all(rsp
) != 0) {
3171 compress_threads_save_cleanup();
3179 qemu_put_be64(f
, ram_bytes_total() | RAM_SAVE_FLAG_MEM_SIZE
);
3181 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
3182 qemu_put_byte(f
, strlen(block
->idstr
));
3183 qemu_put_buffer(f
, (uint8_t *)block
->idstr
, strlen(block
->idstr
));
3184 qemu_put_be64(f
, block
->used_length
);
3185 if (migrate_postcopy_ram() && block
->page_size
!= qemu_host_page_size
) {
3186 qemu_put_be64(f
, block
->page_size
);
3192 ram_control_before_iterate(f
, RAM_CONTROL_SETUP
);
3193 ram_control_after_iterate(f
, RAM_CONTROL_SETUP
);
3195 multifd_send_sync_main();
3196 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3203 * ram_save_iterate: iterative stage for migration
3205 * Returns zero to indicate success and negative for error
3207 * @f: QEMUFile where to send the data
3208 * @opaque: RAMState pointer
3210 static int ram_save_iterate(QEMUFile
*f
, void *opaque
)
3212 RAMState
**temp
= opaque
;
3213 RAMState
*rs
= *temp
;
3219 if (blk_mig_bulk_active()) {
3220 /* Avoid transferring ram during bulk phase of block migration as
3221 * the bulk phase will usually take a long time and transferring
3222 * ram updates during that time is pointless. */
3227 if (ram_list
.version
!= rs
->last_version
) {
3228 ram_state_reset(rs
);
3231 /* Read version before ram_list.blocks */
3234 ram_control_before_iterate(f
, RAM_CONTROL_ROUND
);
3236 t0
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
3238 while ((ret
= qemu_file_rate_limit(f
)) == 0 ||
3239 !QSIMPLEQ_EMPTY(&rs
->src_page_requests
)) {
3242 if (qemu_file_get_error(f
)) {
3246 pages
= ram_find_and_save_block(rs
, false);
3247 /* no more pages to sent */
3254 qemu_file_set_error(f
, pages
);
3258 rs
->target_page_count
+= pages
;
3260 /* we want to check in the 1st loop, just in case it was the 1st time
3261 and we had to sync the dirty bitmap.
3262 qemu_get_clock_ns() is a bit expensive, so we only check each some
3265 if ((i
& 63) == 0) {
3266 uint64_t t1
= (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) - t0
) / 1000000;
3267 if (t1
> MAX_WAIT
) {
3268 trace_ram_save_iterate_big_wait(t1
, i
);
3277 * Must occur before EOS (or any QEMUFile operation)
3278 * because of RDMA protocol.
3280 ram_control_after_iterate(f
, RAM_CONTROL_ROUND
);
3282 multifd_send_sync_main();
3284 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3286 ram_counters
.transferred
+= 8;
3288 ret
= qemu_file_get_error(f
);
3297 * ram_save_complete: function called to send the remaining amount of ram
3299 * Returns zero to indicate success or negative on error
3301 * Called with iothread lock
3303 * @f: QEMUFile where to send the data
3304 * @opaque: RAMState pointer
3306 static int ram_save_complete(QEMUFile
*f
, void *opaque
)
3308 RAMState
**temp
= opaque
;
3309 RAMState
*rs
= *temp
;
3314 if (!migration_in_postcopy()) {
3315 migration_bitmap_sync(rs
);
3318 ram_control_before_iterate(f
, RAM_CONTROL_FINISH
);
3320 /* try transferring iterative blocks of memory */
3322 /* flush all remaining blocks regardless of rate limiting */
3326 pages
= ram_find_and_save_block(rs
, !migration_in_colo_state());
3327 /* no more blocks to sent */
3337 flush_compressed_data(rs
);
3338 ram_control_after_iterate(f
, RAM_CONTROL_FINISH
);
3342 multifd_send_sync_main();
3343 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
3349 static void ram_save_pending(QEMUFile
*f
, void *opaque
, uint64_t max_size
,
3350 uint64_t *res_precopy_only
,
3351 uint64_t *res_compatible
,
3352 uint64_t *res_postcopy_only
)
3354 RAMState
**temp
= opaque
;
3355 RAMState
*rs
= *temp
;
3356 uint64_t remaining_size
;
3358 remaining_size
= rs
->migration_dirty_pages
* TARGET_PAGE_SIZE
;
3360 if (!migration_in_postcopy() &&
3361 remaining_size
< max_size
) {
3362 qemu_mutex_lock_iothread();
3364 migration_bitmap_sync(rs
);
3366 qemu_mutex_unlock_iothread();
3367 remaining_size
= rs
->migration_dirty_pages
* TARGET_PAGE_SIZE
;
3370 if (migrate_postcopy_ram()) {
3371 /* We can do postcopy, and all the data is postcopiable */
3372 *res_compatible
+= remaining_size
;
3374 *res_precopy_only
+= remaining_size
;
3378 static int load_xbzrle(QEMUFile
*f
, ram_addr_t addr
, void *host
)
3380 unsigned int xh_len
;
3382 uint8_t *loaded_data
;
3384 /* extract RLE header */
3385 xh_flags
= qemu_get_byte(f
);
3386 xh_len
= qemu_get_be16(f
);
3388 if (xh_flags
!= ENCODING_FLAG_XBZRLE
) {
3389 error_report("Failed to load XBZRLE page - wrong compression!");
3393 if (xh_len
> TARGET_PAGE_SIZE
) {
3394 error_report("Failed to load XBZRLE page - len overflow!");
3397 loaded_data
= XBZRLE
.decoded_buf
;
3398 /* load data and decode */
3399 /* it can change loaded_data to point to an internal buffer */
3400 qemu_get_buffer_in_place(f
, &loaded_data
, xh_len
);
3403 if (xbzrle_decode_buffer(loaded_data
, xh_len
, host
,
3404 TARGET_PAGE_SIZE
) == -1) {
3405 error_report("Failed to load XBZRLE page - decode error!");
3413 * ram_block_from_stream: read a RAMBlock id from the migration stream
3415 * Must be called from within a rcu critical section.
3417 * Returns a pointer from within the RCU-protected ram_list.
3419 * @f: QEMUFile where to read the data from
3420 * @flags: Page flags (mostly to see if it's a continuation of previous block)
3422 static inline RAMBlock
*ram_block_from_stream(QEMUFile
*f
, int flags
)
3424 static RAMBlock
*block
= NULL
;
3428 if (flags
& RAM_SAVE_FLAG_CONTINUE
) {
3430 error_report("Ack, bad migration stream!");
3436 len
= qemu_get_byte(f
);
3437 qemu_get_buffer(f
, (uint8_t *)id
, len
);
3440 block
= qemu_ram_block_by_name(id
);
3442 error_report("Can't find block %s", id
);
3446 if (!qemu_ram_is_migratable(block
)) {
3447 error_report("block %s should not be migrated !", id
);
3454 static inline void *host_from_ram_block_offset(RAMBlock
*block
,
3457 if (!offset_in_ramblock(block
, offset
)) {
3461 return block
->host
+ offset
;
3464 static inline void *colo_cache_from_block_offset(RAMBlock
*block
,
3467 if (!offset_in_ramblock(block
, offset
)) {
3470 if (!block
->colo_cache
) {
3471 error_report("%s: colo_cache is NULL in block :%s",
3472 __func__
, block
->idstr
);
3477 * During colo checkpoint, we need bitmap of these migrated pages.
3478 * It help us to decide which pages in ram cache should be flushed
3479 * into VM's RAM later.
3481 if (!test_and_set_bit(offset
>> TARGET_PAGE_BITS
, block
->bmap
)) {
3482 ram_state
->migration_dirty_pages
++;
3484 return block
->colo_cache
+ offset
;
3488 * ram_handle_compressed: handle the zero page case
3490 * If a page (or a whole RDMA chunk) has been
3491 * determined to be zero, then zap it.
3493 * @host: host address for the zero page
3494 * @ch: what the page is filled from. We only support zero
3495 * @size: size of the zero page
3497 void ram_handle_compressed(void *host
, uint8_t ch
, uint64_t size
)
3499 if (ch
!= 0 || !is_zero_range(host
, size
)) {
3500 memset(host
, ch
, size
);
3504 /* return the size after decompression, or negative value on error */
3506 qemu_uncompress_data(z_stream
*stream
, uint8_t *dest
, size_t dest_len
,
3507 const uint8_t *source
, size_t source_len
)
3511 err
= inflateReset(stream
);
3516 stream
->avail_in
= source_len
;
3517 stream
->next_in
= (uint8_t *)source
;
3518 stream
->avail_out
= dest_len
;
3519 stream
->next_out
= dest
;
3521 err
= inflate(stream
, Z_NO_FLUSH
);
3522 if (err
!= Z_STREAM_END
) {
3526 return stream
->total_out
;
3529 static void *do_data_decompress(void *opaque
)
3531 DecompressParam
*param
= opaque
;
3532 unsigned long pagesize
;
3536 qemu_mutex_lock(¶m
->mutex
);
3537 while (!param
->quit
) {
3542 qemu_mutex_unlock(¶m
->mutex
);
3544 pagesize
= TARGET_PAGE_SIZE
;
3546 ret
= qemu_uncompress_data(¶m
->stream
, des
, pagesize
,
3547 param
->compbuf
, len
);
3548 if (ret
< 0 && migrate_get_current()->decompress_error_check
) {
3549 error_report("decompress data failed");
3550 qemu_file_set_error(decomp_file
, ret
);
3553 qemu_mutex_lock(&decomp_done_lock
);
3555 qemu_cond_signal(&decomp_done_cond
);
3556 qemu_mutex_unlock(&decomp_done_lock
);
3558 qemu_mutex_lock(¶m
->mutex
);
3560 qemu_cond_wait(¶m
->cond
, ¶m
->mutex
);
3563 qemu_mutex_unlock(¶m
->mutex
);
3568 static int wait_for_decompress_done(void)
3570 int idx
, thread_count
;
3572 if (!migrate_use_compression()) {
3576 thread_count
= migrate_decompress_threads();
3577 qemu_mutex_lock(&decomp_done_lock
);
3578 for (idx
= 0; idx
< thread_count
; idx
++) {
3579 while (!decomp_param
[idx
].done
) {
3580 qemu_cond_wait(&decomp_done_cond
, &decomp_done_lock
);
3583 qemu_mutex_unlock(&decomp_done_lock
);
3584 return qemu_file_get_error(decomp_file
);
3587 static void compress_threads_load_cleanup(void)
3589 int i
, thread_count
;
3591 if (!migrate_use_compression()) {
3594 thread_count
= migrate_decompress_threads();
3595 for (i
= 0; i
< thread_count
; i
++) {
3597 * we use it as a indicator which shows if the thread is
3598 * properly init'd or not
3600 if (!decomp_param
[i
].compbuf
) {
3604 qemu_mutex_lock(&decomp_param
[i
].mutex
);
3605 decomp_param
[i
].quit
= true;
3606 qemu_cond_signal(&decomp_param
[i
].cond
);
3607 qemu_mutex_unlock(&decomp_param
[i
].mutex
);
3609 for (i
= 0; i
< thread_count
; i
++) {
3610 if (!decomp_param
[i
].compbuf
) {
3614 qemu_thread_join(decompress_threads
+ i
);
3615 qemu_mutex_destroy(&decomp_param
[i
].mutex
);
3616 qemu_cond_destroy(&decomp_param
[i
].cond
);
3617 inflateEnd(&decomp_param
[i
].stream
);
3618 g_free(decomp_param
[i
].compbuf
);
3619 decomp_param
[i
].compbuf
= NULL
;
3621 g_free(decompress_threads
);
3622 g_free(decomp_param
);
3623 decompress_threads
= NULL
;
3624 decomp_param
= NULL
;
3628 static int compress_threads_load_setup(QEMUFile
*f
)
3630 int i
, thread_count
;
3632 if (!migrate_use_compression()) {
3636 thread_count
= migrate_decompress_threads();
3637 decompress_threads
= g_new0(QemuThread
, thread_count
);
3638 decomp_param
= g_new0(DecompressParam
, thread_count
);
3639 qemu_mutex_init(&decomp_done_lock
);
3640 qemu_cond_init(&decomp_done_cond
);
3642 for (i
= 0; i
< thread_count
; i
++) {
3643 if (inflateInit(&decomp_param
[i
].stream
) != Z_OK
) {
3647 decomp_param
[i
].compbuf
= g_malloc0(compressBound(TARGET_PAGE_SIZE
));
3648 qemu_mutex_init(&decomp_param
[i
].mutex
);
3649 qemu_cond_init(&decomp_param
[i
].cond
);
3650 decomp_param
[i
].done
= true;
3651 decomp_param
[i
].quit
= false;
3652 qemu_thread_create(decompress_threads
+ i
, "decompress",
3653 do_data_decompress
, decomp_param
+ i
,
3654 QEMU_THREAD_JOINABLE
);
3658 compress_threads_load_cleanup();
3662 static void decompress_data_with_multi_threads(QEMUFile
*f
,
3663 void *host
, int len
)
3665 int idx
, thread_count
;
3667 thread_count
= migrate_decompress_threads();
3668 qemu_mutex_lock(&decomp_done_lock
);
3670 for (idx
= 0; idx
< thread_count
; idx
++) {
3671 if (decomp_param
[idx
].done
) {
3672 decomp_param
[idx
].done
= false;
3673 qemu_mutex_lock(&decomp_param
[idx
].mutex
);
3674 qemu_get_buffer(f
, decomp_param
[idx
].compbuf
, len
);
3675 decomp_param
[idx
].des
= host
;
3676 decomp_param
[idx
].len
= len
;
3677 qemu_cond_signal(&decomp_param
[idx
].cond
);
3678 qemu_mutex_unlock(&decomp_param
[idx
].mutex
);
3682 if (idx
< thread_count
) {
3685 qemu_cond_wait(&decomp_done_cond
, &decomp_done_lock
);
3688 qemu_mutex_unlock(&decomp_done_lock
);
3692 * colo cache: this is for secondary VM, we cache the whole
3693 * memory of the secondary VM, it is need to hold the global lock
3694 * to call this helper.
3696 int colo_init_ram_cache(void)
3701 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
3702 block
->colo_cache
= qemu_anon_ram_alloc(block
->used_length
,
3705 if (!block
->colo_cache
) {
3706 error_report("%s: Can't alloc memory for COLO cache of block %s,"
3707 "size 0x" RAM_ADDR_FMT
, __func__
, block
->idstr
,
3708 block
->used_length
);
3711 memcpy(block
->colo_cache
, block
->host
, block
->used_length
);
3715 * Record the dirty pages that sent by PVM, we use this dirty bitmap together
3716 * with to decide which page in cache should be flushed into SVM's RAM. Here
3717 * we use the same name 'ram_bitmap' as for migration.
3719 if (ram_bytes_total()) {
3722 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
3723 unsigned long pages
= block
->max_length
>> TARGET_PAGE_BITS
;
3725 block
->bmap
= bitmap_new(pages
);
3726 bitmap_set(block
->bmap
, 0, pages
);
3729 ram_state
= g_new0(RAMState
, 1);
3730 ram_state
->migration_dirty_pages
= 0;
3731 memory_global_dirty_log_start();
3737 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
3738 if (block
->colo_cache
) {
3739 qemu_anon_ram_free(block
->colo_cache
, block
->used_length
);
3740 block
->colo_cache
= NULL
;
3748 /* It is need to hold the global lock to call this helper */
3749 void colo_release_ram_cache(void)
3753 memory_global_dirty_log_stop();
3754 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
3755 g_free(block
->bmap
);
3761 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
3762 if (block
->colo_cache
) {
3763 qemu_anon_ram_free(block
->colo_cache
, block
->used_length
);
3764 block
->colo_cache
= NULL
;
3774 * ram_load_setup: Setup RAM for migration incoming side
3776 * Returns zero to indicate success and negative for error
3778 * @f: QEMUFile where to receive the data
3779 * @opaque: RAMState pointer
3781 static int ram_load_setup(QEMUFile
*f
, void *opaque
)
3783 if (compress_threads_load_setup(f
)) {
3787 xbzrle_load_setup();
3788 ramblock_recv_map_init();
3793 static int ram_load_cleanup(void *opaque
)
3797 RAMBLOCK_FOREACH_MIGRATABLE(rb
) {
3798 if (ramblock_is_pmem(rb
)) {
3799 pmem_persist(rb
->host
, rb
->used_length
);
3803 xbzrle_load_cleanup();
3804 compress_threads_load_cleanup();
3806 RAMBLOCK_FOREACH_MIGRATABLE(rb
) {
3807 g_free(rb
->receivedmap
);
3808 rb
->receivedmap
= NULL
;
3815 * ram_postcopy_incoming_init: allocate postcopy data structures
3817 * Returns 0 for success and negative if there was one error
3819 * @mis: current migration incoming state
3821 * Allocate data structures etc needed by incoming migration with
3822 * postcopy-ram. postcopy-ram's similarly names
3823 * postcopy_ram_incoming_init does the work.
3825 int ram_postcopy_incoming_init(MigrationIncomingState
*mis
)
3827 return postcopy_ram_incoming_init(mis
);
3831 * ram_load_postcopy: load a page in postcopy case
3833 * Returns 0 for success or -errno in case of error
3835 * Called in postcopy mode by ram_load().
3836 * rcu_read_lock is taken prior to this being called.
3838 * @f: QEMUFile where to send the data
3840 static int ram_load_postcopy(QEMUFile
*f
)
3842 int flags
= 0, ret
= 0;
3843 bool place_needed
= false;
3844 bool matches_target_page_size
= false;
3845 MigrationIncomingState
*mis
= migration_incoming_get_current();
3846 /* Temporary page that is later 'placed' */
3847 void *postcopy_host_page
= postcopy_get_tmp_page(mis
);
3848 void *last_host
= NULL
;
3849 bool all_zero
= false;
3851 while (!ret
&& !(flags
& RAM_SAVE_FLAG_EOS
)) {
3854 void *page_buffer
= NULL
;
3855 void *place_source
= NULL
;
3856 RAMBlock
*block
= NULL
;
3859 addr
= qemu_get_be64(f
);
3862 * If qemu file error, we should stop here, and then "addr"
3865 ret
= qemu_file_get_error(f
);
3870 flags
= addr
& ~TARGET_PAGE_MASK
;
3871 addr
&= TARGET_PAGE_MASK
;
3873 trace_ram_load_postcopy_loop((uint64_t)addr
, flags
);
3874 place_needed
= false;
3875 if (flags
& (RAM_SAVE_FLAG_ZERO
| RAM_SAVE_FLAG_PAGE
)) {
3876 block
= ram_block_from_stream(f
, flags
);
3878 host
= host_from_ram_block_offset(block
, addr
);
3880 error_report("Illegal RAM offset " RAM_ADDR_FMT
, addr
);
3884 matches_target_page_size
= block
->page_size
== TARGET_PAGE_SIZE
;
3886 * Postcopy requires that we place whole host pages atomically;
3887 * these may be huge pages for RAMBlocks that are backed by
3889 * To make it atomic, the data is read into a temporary page
3890 * that's moved into place later.
3891 * The migration protocol uses, possibly smaller, target-pages
3892 * however the source ensures it always sends all the components
3893 * of a host page in order.
3895 page_buffer
= postcopy_host_page
+
3896 ((uintptr_t)host
& (block
->page_size
- 1));
3897 /* If all TP are zero then we can optimise the place */
3898 if (!((uintptr_t)host
& (block
->page_size
- 1))) {
3901 /* not the 1st TP within the HP */
3902 if (host
!= (last_host
+ TARGET_PAGE_SIZE
)) {
3903 error_report("Non-sequential target page %p/%p",
3912 * If it's the last part of a host page then we place the host
3915 place_needed
= (((uintptr_t)host
+ TARGET_PAGE_SIZE
) &
3916 (block
->page_size
- 1)) == 0;
3917 place_source
= postcopy_host_page
;
3921 switch (flags
& ~RAM_SAVE_FLAG_CONTINUE
) {
3922 case RAM_SAVE_FLAG_ZERO
:
3923 ch
= qemu_get_byte(f
);
3924 memset(page_buffer
, ch
, TARGET_PAGE_SIZE
);
3930 case RAM_SAVE_FLAG_PAGE
:
3932 if (!matches_target_page_size
) {
3933 /* For huge pages, we always use temporary buffer */
3934 qemu_get_buffer(f
, page_buffer
, TARGET_PAGE_SIZE
);
3937 * For small pages that matches target page size, we
3938 * avoid the qemu_file copy. Instead we directly use
3939 * the buffer of QEMUFile to place the page. Note: we
3940 * cannot do any QEMUFile operation before using that
3941 * buffer to make sure the buffer is valid when
3944 qemu_get_buffer_in_place(f
, (uint8_t **)&place_source
,
3948 case RAM_SAVE_FLAG_EOS
:
3950 multifd_recv_sync_main();
3953 error_report("Unknown combination of migration flags: %#x"
3954 " (postcopy mode)", flags
);
3959 /* Detect for any possible file errors */
3960 if (!ret
&& qemu_file_get_error(f
)) {
3961 ret
= qemu_file_get_error(f
);
3964 if (!ret
&& place_needed
) {
3965 /* This gets called at the last target page in the host page */
3966 void *place_dest
= host
+ TARGET_PAGE_SIZE
- block
->page_size
;
3969 ret
= postcopy_place_page_zero(mis
, place_dest
,
3972 ret
= postcopy_place_page(mis
, place_dest
,
3973 place_source
, block
);
3981 static bool postcopy_is_advised(void)
3983 PostcopyState ps
= postcopy_state_get();
3984 return ps
>= POSTCOPY_INCOMING_ADVISE
&& ps
< POSTCOPY_INCOMING_END
;
3987 static bool postcopy_is_running(void)
3989 PostcopyState ps
= postcopy_state_get();
3990 return ps
>= POSTCOPY_INCOMING_LISTENING
&& ps
< POSTCOPY_INCOMING_END
;
3994 * Flush content of RAM cache into SVM's memory.
3995 * Only flush the pages that be dirtied by PVM or SVM or both.
3997 static void colo_flush_ram_cache(void)
3999 RAMBlock
*block
= NULL
;
4002 unsigned long offset
= 0;
4004 memory_global_dirty_log_sync();
4006 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
4007 migration_bitmap_sync_range(ram_state
, block
, 0, block
->used_length
);
4011 trace_colo_flush_ram_cache_begin(ram_state
->migration_dirty_pages
);
4013 block
= QLIST_FIRST_RCU(&ram_list
.blocks
);
4016 offset
= migration_bitmap_find_dirty(ram_state
, block
, offset
);
4018 if (offset
<< TARGET_PAGE_BITS
>= block
->used_length
) {
4020 block
= QLIST_NEXT_RCU(block
, next
);
4022 migration_bitmap_clear_dirty(ram_state
, block
, offset
);
4023 dst_host
= block
->host
+ (offset
<< TARGET_PAGE_BITS
);
4024 src_host
= block
->colo_cache
+ (offset
<< TARGET_PAGE_BITS
);
4025 memcpy(dst_host
, src_host
, TARGET_PAGE_SIZE
);
4030 trace_colo_flush_ram_cache_end();
4033 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
4035 int flags
= 0, ret
= 0, invalid_flags
= 0;
4036 static uint64_t seq_iter
;
4039 * If system is running in postcopy mode, page inserts to host memory must
4042 bool postcopy_running
= postcopy_is_running();
4043 /* ADVISE is earlier, it shows the source has the postcopy capability on */
4044 bool postcopy_advised
= postcopy_is_advised();
4048 if (version_id
!= 4) {
4052 if (!migrate_use_compression()) {
4053 invalid_flags
|= RAM_SAVE_FLAG_COMPRESS_PAGE
;
4055 /* This RCU critical section can be very long running.
4056 * When RCU reclaims in the code start to become numerous,
4057 * it will be necessary to reduce the granularity of this
4062 if (postcopy_running
) {
4063 ret
= ram_load_postcopy(f
);
4066 while (!postcopy_running
&& !ret
&& !(flags
& RAM_SAVE_FLAG_EOS
)) {
4067 ram_addr_t addr
, total_ram_bytes
;
4071 addr
= qemu_get_be64(f
);
4072 flags
= addr
& ~TARGET_PAGE_MASK
;
4073 addr
&= TARGET_PAGE_MASK
;
4075 if (flags
& invalid_flags
) {
4076 if (flags
& invalid_flags
& RAM_SAVE_FLAG_COMPRESS_PAGE
) {
4077 error_report("Received an unexpected compressed page");
4084 if (flags
& (RAM_SAVE_FLAG_ZERO
| RAM_SAVE_FLAG_PAGE
|
4085 RAM_SAVE_FLAG_COMPRESS_PAGE
| RAM_SAVE_FLAG_XBZRLE
)) {
4086 RAMBlock
*block
= ram_block_from_stream(f
, flags
);
4089 * After going into COLO, we should load the Page into colo_cache.
4091 if (migration_incoming_in_colo_state()) {
4092 host
= colo_cache_from_block_offset(block
, addr
);
4094 host
= host_from_ram_block_offset(block
, addr
);
4097 error_report("Illegal RAM offset " RAM_ADDR_FMT
, addr
);
4102 if (!migration_incoming_in_colo_state()) {
4103 ramblock_recv_bitmap_set(block
, host
);
4106 trace_ram_load_loop(block
->idstr
, (uint64_t)addr
, flags
, host
);
4109 switch (flags
& ~RAM_SAVE_FLAG_CONTINUE
) {
4110 case RAM_SAVE_FLAG_MEM_SIZE
:
4111 /* Synchronize RAM block list */
4112 total_ram_bytes
= addr
;
4113 while (!ret
&& total_ram_bytes
) {
4118 len
= qemu_get_byte(f
);
4119 qemu_get_buffer(f
, (uint8_t *)id
, len
);
4121 length
= qemu_get_be64(f
);
4123 block
= qemu_ram_block_by_name(id
);
4124 if (block
&& !qemu_ram_is_migratable(block
)) {
4125 error_report("block %s should not be migrated !", id
);
4128 if (length
!= block
->used_length
) {
4129 Error
*local_err
= NULL
;
4131 ret
= qemu_ram_resize(block
, length
,
4134 error_report_err(local_err
);
4137 /* For postcopy we need to check hugepage sizes match */
4138 if (postcopy_advised
&&
4139 block
->page_size
!= qemu_host_page_size
) {
4140 uint64_t remote_page_size
= qemu_get_be64(f
);
4141 if (remote_page_size
!= block
->page_size
) {
4142 error_report("Mismatched RAM page size %s "
4143 "(local) %zd != %" PRId64
,
4144 id
, block
->page_size
,
4149 ram_control_load_hook(f
, RAM_CONTROL_BLOCK_REG
,
4152 error_report("Unknown ramblock \"%s\", cannot "
4153 "accept migration", id
);
4157 total_ram_bytes
-= length
;
4161 case RAM_SAVE_FLAG_ZERO
:
4162 ch
= qemu_get_byte(f
);
4163 ram_handle_compressed(host
, ch
, TARGET_PAGE_SIZE
);
4166 case RAM_SAVE_FLAG_PAGE
:
4167 qemu_get_buffer(f
, host
, TARGET_PAGE_SIZE
);
4170 case RAM_SAVE_FLAG_COMPRESS_PAGE
:
4171 len
= qemu_get_be32(f
);
4172 if (len
< 0 || len
> compressBound(TARGET_PAGE_SIZE
)) {
4173 error_report("Invalid compressed data length: %d", len
);
4177 decompress_data_with_multi_threads(f
, host
, len
);
4180 case RAM_SAVE_FLAG_XBZRLE
:
4181 if (load_xbzrle(f
, addr
, host
) < 0) {
4182 error_report("Failed to decompress XBZRLE page at "
4183 RAM_ADDR_FMT
, addr
);
4188 case RAM_SAVE_FLAG_EOS
:
4190 multifd_recv_sync_main();
4193 if (flags
& RAM_SAVE_FLAG_HOOK
) {
4194 ram_control_load_hook(f
, RAM_CONTROL_HOOK
, NULL
);
4196 error_report("Unknown combination of migration flags: %#x",
4202 ret
= qemu_file_get_error(f
);
4206 ret
|= wait_for_decompress_done();
4208 trace_ram_load_complete(ret
, seq_iter
);
4210 if (!ret
&& migration_incoming_in_colo_state()) {
4211 colo_flush_ram_cache();
4216 static bool ram_has_postcopy(void *opaque
)
4219 RAMBLOCK_FOREACH_MIGRATABLE(rb
) {
4220 if (ramblock_is_pmem(rb
)) {
4221 info_report("Block: %s, host: %p is a nvdimm memory, postcopy"
4222 "is not supported now!", rb
->idstr
, rb
->host
);
4227 return migrate_postcopy_ram();
4230 /* Sync all the dirty bitmap with destination VM. */
4231 static int ram_dirty_bitmap_sync_all(MigrationState
*s
, RAMState
*rs
)
4234 QEMUFile
*file
= s
->to_dst_file
;
4235 int ramblock_count
= 0;
4237 trace_ram_dirty_bitmap_sync_start();
4239 RAMBLOCK_FOREACH_MIGRATABLE(block
) {
4240 qemu_savevm_send_recv_bitmap(file
, block
->idstr
);
4241 trace_ram_dirty_bitmap_request(block
->idstr
);
4245 trace_ram_dirty_bitmap_sync_wait();
4247 /* Wait until all the ramblocks' dirty bitmap synced */
4248 while (ramblock_count
--) {
4249 qemu_sem_wait(&s
->rp_state
.rp_sem
);
4252 trace_ram_dirty_bitmap_sync_complete();
4257 static void ram_dirty_bitmap_reload_notify(MigrationState
*s
)
4259 qemu_sem_post(&s
->rp_state
.rp_sem
);
4263 * Read the received bitmap, revert it as the initial dirty bitmap.
4264 * This is only used when the postcopy migration is paused but wants
4265 * to resume from a middle point.
4267 int ram_dirty_bitmap_reload(MigrationState
*s
, RAMBlock
*block
)
4270 QEMUFile
*file
= s
->rp_state
.from_dst_file
;
4271 unsigned long *le_bitmap
, nbits
= block
->used_length
>> TARGET_PAGE_BITS
;
4272 uint64_t local_size
= DIV_ROUND_UP(nbits
, 8);
4273 uint64_t size
, end_mark
;
4275 trace_ram_dirty_bitmap_reload_begin(block
->idstr
);
4277 if (s
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
4278 error_report("%s: incorrect state %s", __func__
,
4279 MigrationStatus_str(s
->state
));
4284 * Note: see comments in ramblock_recv_bitmap_send() on why we
4285 * need the endianess convertion, and the paddings.
4287 local_size
= ROUND_UP(local_size
, 8);
4290 le_bitmap
= bitmap_new(nbits
+ BITS_PER_LONG
);
4292 size
= qemu_get_be64(file
);
4294 /* The size of the bitmap should match with our ramblock */
4295 if (size
!= local_size
) {
4296 error_report("%s: ramblock '%s' bitmap size mismatch "
4297 "(0x%"PRIx64
" != 0x%"PRIx64
")", __func__
,
4298 block
->idstr
, size
, local_size
);
4303 size
= qemu_get_buffer(file
, (uint8_t *)le_bitmap
, local_size
);
4304 end_mark
= qemu_get_be64(file
);
4306 ret
= qemu_file_get_error(file
);
4307 if (ret
|| size
!= local_size
) {
4308 error_report("%s: read bitmap failed for ramblock '%s': %d"
4309 " (size 0x%"PRIx64
", got: 0x%"PRIx64
")",
4310 __func__
, block
->idstr
, ret
, local_size
, size
);
4315 if (end_mark
!= RAMBLOCK_RECV_BITMAP_ENDING
) {
4316 error_report("%s: ramblock '%s' end mark incorrect: 0x%"PRIu64
,
4317 __func__
, block
->idstr
, end_mark
);
4323 * Endianess convertion. We are during postcopy (though paused).
4324 * The dirty bitmap won't change. We can directly modify it.
4326 bitmap_from_le(block
->bmap
, le_bitmap
, nbits
);
4329 * What we received is "received bitmap". Revert it as the initial
4330 * dirty bitmap for this ramblock.
4332 bitmap_complement(block
->bmap
, block
->bmap
, nbits
);
4334 trace_ram_dirty_bitmap_reload_complete(block
->idstr
);
4337 * We succeeded to sync bitmap for current ramblock. If this is
4338 * the last one to sync, we need to notify the main send thread.
4340 ram_dirty_bitmap_reload_notify(s
);
4348 static int ram_resume_prepare(MigrationState
*s
, void *opaque
)
4350 RAMState
*rs
= *(RAMState
**)opaque
;
4353 ret
= ram_dirty_bitmap_sync_all(s
, rs
);
4358 ram_state_resume_prepare(rs
, s
->to_dst_file
);
4363 static SaveVMHandlers savevm_ram_handlers
= {
4364 .save_setup
= ram_save_setup
,
4365 .save_live_iterate
= ram_save_iterate
,
4366 .save_live_complete_postcopy
= ram_save_complete
,
4367 .save_live_complete_precopy
= ram_save_complete
,
4368 .has_postcopy
= ram_has_postcopy
,
4369 .save_live_pending
= ram_save_pending
,
4370 .load_state
= ram_load
,
4371 .save_cleanup
= ram_save_cleanup
,
4372 .load_setup
= ram_load_setup
,
4373 .load_cleanup
= ram_load_cleanup
,
4374 .resume_prepare
= ram_resume_prepare
,
4377 void ram_mig_init(void)
4379 qemu_mutex_init(&XBZRLE
.lock
);
4380 register_savevm_live(NULL
, "ram", 0, 4, &savevm_ram_handlers
, &ram_state
);