]> git.proxmox.com Git - mirror_qemu.git/blame - migration/ram.c
migration/ram: Reduce unnecessary rate limiting
[mirror_qemu.git] / migration / ram.c
CommitLineData
56e93d26
JQ
1/*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
76cc7b58
JQ
5 * Copyright (c) 2011-2015 Red Hat Inc
6 *
7 * Authors:
8 * Juan Quintela <quintela@redhat.com>
56e93d26
JQ
9 *
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:
16 *
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
19 *
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
26 * THE SOFTWARE.
27 */
e688df6b 28
1393a485 29#include "qemu/osdep.h"
f348b6d1 30#include "qemu/cutils.h"
56e93d26
JQ
31#include "qemu/bitops.h"
32#include "qemu/bitmap.h"
7205c9ec 33#include "qemu/main-loop.h"
709e3fe8 34#include "xbzrle.h"
7b1e1a22 35#include "ram.h"
6666c96a 36#include "migration.h"
f2a8f0a6 37#include "migration/register.h"
7b1e1a22 38#include "migration/misc.h"
08a0aee1 39#include "qemu-file.h"
be07b0ac 40#include "postcopy-ram.h"
53d37d36 41#include "page_cache.h"
56e93d26 42#include "qemu/error-report.h"
e688df6b 43#include "qapi/error.h"
ab7cbb0b 44#include "qapi/qapi-types-migration.h"
9af23989 45#include "qapi/qapi-events-migration.h"
8acabf69 46#include "qapi/qmp/qerror.h"
56e93d26 47#include "trace.h"
56e93d26 48#include "exec/ram_addr.h"
f9494614 49#include "exec/target_page.h"
56e93d26 50#include "qemu/rcu_queue.h"
a91246c9 51#include "migration/colo.h"
53d37d36 52#include "block.h"
b0c3cf94 53#include "sysemu/cpu-throttle.h"
edd090c7 54#include "savevm.h"
b9ee2f7d 55#include "qemu/iov.h"
d32ca5ad 56#include "multifd.h"
278e2f55
AG
57#include "sysemu/runstate.h"
58
59#if defined(__linux__)
60#include "qemu/userfaultfd.h"
61#endif /* defined(__linux__) */
56e93d26 62
56e93d26
JQ
63/***********************************************************/
64/* ram save/restore */
65
bb890ed5
JQ
66/* RAM_SAVE_FLAG_ZERO used to be named RAM_SAVE_FLAG_COMPRESS, it
67 * worked for pages that where filled with the same char. We switched
68 * it to only search for the zero value. And to avoid confusion with
69 * RAM_SSAVE_FLAG_COMPRESS_PAGE just rename it.
70 */
71
56e93d26 72#define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
bb890ed5 73#define RAM_SAVE_FLAG_ZERO 0x02
56e93d26
JQ
74#define RAM_SAVE_FLAG_MEM_SIZE 0x04
75#define RAM_SAVE_FLAG_PAGE 0x08
76#define RAM_SAVE_FLAG_EOS 0x10
77#define RAM_SAVE_FLAG_CONTINUE 0x20
78#define RAM_SAVE_FLAG_XBZRLE 0x40
79/* 0x80 is reserved in migration.h start with 0x100 next */
80#define RAM_SAVE_FLAG_COMPRESS_PAGE 0x100
81
56e93d26
JQ
82static inline bool is_zero_range(uint8_t *p, uint64_t size)
83{
a1febc49 84 return buffer_is_zero(p, size);
56e93d26
JQ
85}
86
9360447d
JQ
87XBZRLECacheStats xbzrle_counters;
88
56e93d26
JQ
89/* struct contains XBZRLE cache and a static page
90 used by the compression */
91static struct {
92 /* buffer used for XBZRLE encoding */
93 uint8_t *encoded_buf;
94 /* buffer for storing page content */
95 uint8_t *current_buf;
96 /* Cache for XBZRLE, Protected by lock. */
97 PageCache *cache;
98 QemuMutex lock;
c00e0928
JQ
99 /* it will store a page full of zeros */
100 uint8_t *zero_target_page;
f265e0e4
JQ
101 /* buffer used for XBZRLE decoding */
102 uint8_t *decoded_buf;
56e93d26
JQ
103} XBZRLE;
104
56e93d26
JQ
105static void XBZRLE_cache_lock(void)
106{
f4c51a6b 107 if (migrate_use_xbzrle()) {
56e93d26 108 qemu_mutex_lock(&XBZRLE.lock);
f4c51a6b 109 }
56e93d26
JQ
110}
111
112static void XBZRLE_cache_unlock(void)
113{
f4c51a6b 114 if (migrate_use_xbzrle()) {
56e93d26 115 qemu_mutex_unlock(&XBZRLE.lock);
f4c51a6b 116 }
56e93d26
JQ
117}
118
3d0684b2
JQ
119/**
120 * xbzrle_cache_resize: resize the xbzrle cache
121 *
cbde7be9 122 * This function is called from migrate_params_apply in main
3d0684b2
JQ
123 * thread, possibly while a migration is in progress. A running
124 * migration may be using the cache and might finish during this call,
125 * hence changes to the cache are protected by XBZRLE.lock().
126 *
c9dede2d 127 * Returns 0 for success or -1 for error
3d0684b2
JQ
128 *
129 * @new_size: new cache size
8acabf69 130 * @errp: set *errp if the check failed, with reason
56e93d26 131 */
8b9407a0 132int xbzrle_cache_resize(uint64_t new_size, Error **errp)
56e93d26
JQ
133{
134 PageCache *new_cache;
c9dede2d 135 int64_t ret = 0;
56e93d26 136
8acabf69
JQ
137 /* Check for truncation */
138 if (new_size != (size_t)new_size) {
139 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
140 "exceeding address space");
141 return -1;
142 }
143
2a313e5c
JQ
144 if (new_size == migrate_xbzrle_cache_size()) {
145 /* nothing to do */
c9dede2d 146 return 0;
2a313e5c
JQ
147 }
148
56e93d26
JQ
149 XBZRLE_cache_lock();
150
151 if (XBZRLE.cache != NULL) {
80f8dfde 152 new_cache = cache_init(new_size, TARGET_PAGE_SIZE, errp);
56e93d26 153 if (!new_cache) {
56e93d26
JQ
154 ret = -1;
155 goto out;
156 }
157
158 cache_fini(XBZRLE.cache);
159 XBZRLE.cache = new_cache;
160 }
56e93d26
JQ
161out:
162 XBZRLE_cache_unlock();
163 return ret;
164}
165
3ded54b1 166bool ramblock_is_ignored(RAMBlock *block)
fbd162e6
YK
167{
168 return !qemu_ram_is_migratable(block) ||
169 (migrate_ignore_shared() && qemu_ram_is_shared(block));
170}
171
343f632c
DDAG
172#undef RAMBLOCK_FOREACH
173
fbd162e6
YK
174int foreach_not_ignored_block(RAMBlockIterFunc func, void *opaque)
175{
176 RAMBlock *block;
177 int ret = 0;
178
89ac5a1d
DDAG
179 RCU_READ_LOCK_GUARD();
180
fbd162e6
YK
181 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
182 ret = func(block, opaque);
183 if (ret) {
184 break;
185 }
186 }
fbd162e6
YK
187 return ret;
188}
189
f9494614
AP
190static void ramblock_recv_map_init(void)
191{
192 RAMBlock *rb;
193
fbd162e6 194 RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
f9494614
AP
195 assert(!rb->receivedmap);
196 rb->receivedmap = bitmap_new(rb->max_length >> qemu_target_page_bits());
197 }
198}
199
200int ramblock_recv_bitmap_test(RAMBlock *rb, void *host_addr)
201{
202 return test_bit(ramblock_recv_bitmap_offset(host_addr, rb),
203 rb->receivedmap);
204}
205
1cba9f6e
DDAG
206bool ramblock_recv_bitmap_test_byte_offset(RAMBlock *rb, uint64_t byte_offset)
207{
208 return test_bit(byte_offset >> TARGET_PAGE_BITS, rb->receivedmap);
209}
210
f9494614
AP
211void ramblock_recv_bitmap_set(RAMBlock *rb, void *host_addr)
212{
213 set_bit_atomic(ramblock_recv_bitmap_offset(host_addr, rb), rb->receivedmap);
214}
215
216void ramblock_recv_bitmap_set_range(RAMBlock *rb, void *host_addr,
217 size_t nr)
218{
219 bitmap_set_atomic(rb->receivedmap,
220 ramblock_recv_bitmap_offset(host_addr, rb),
221 nr);
222}
223
a335debb
PX
224#define RAMBLOCK_RECV_BITMAP_ENDING (0x0123456789abcdefULL)
225
226/*
227 * Format: bitmap_size (8 bytes) + whole_bitmap (N bytes).
228 *
229 * Returns >0 if success with sent bytes, or <0 if error.
230 */
231int64_t ramblock_recv_bitmap_send(QEMUFile *file,
232 const char *block_name)
233{
234 RAMBlock *block = qemu_ram_block_by_name(block_name);
235 unsigned long *le_bitmap, nbits;
236 uint64_t size;
237
238 if (!block) {
239 error_report("%s: invalid block name: %s", __func__, block_name);
240 return -1;
241 }
242
243 nbits = block->used_length >> TARGET_PAGE_BITS;
244
245 /*
246 * Make sure the tmp bitmap buffer is big enough, e.g., on 32bit
247 * machines we may need 4 more bytes for padding (see below
248 * comment). So extend it a bit before hand.
249 */
250 le_bitmap = bitmap_new(nbits + BITS_PER_LONG);
251
252 /*
253 * Always use little endian when sending the bitmap. This is
254 * required that when source and destination VMs are not using the
3a4452d8 255 * same endianness. (Note: big endian won't work.)
a335debb
PX
256 */
257 bitmap_to_le(le_bitmap, block->receivedmap, nbits);
258
259 /* Size of the bitmap, in bytes */
a725ef9f 260 size = DIV_ROUND_UP(nbits, 8);
a335debb
PX
261
262 /*
263 * size is always aligned to 8 bytes for 64bit machines, but it
264 * may not be true for 32bit machines. We need this padding to
265 * make sure the migration can survive even between 32bit and
266 * 64bit machines.
267 */
268 size = ROUND_UP(size, 8);
269
270 qemu_put_be64(file, size);
271 qemu_put_buffer(file, (const uint8_t *)le_bitmap, size);
272 /*
273 * Mark as an end, in case the middle part is screwed up due to
3a4452d8 274 * some "mysterious" reason.
a335debb
PX
275 */
276 qemu_put_be64(file, RAMBLOCK_RECV_BITMAP_ENDING);
277 qemu_fflush(file);
278
bf269906 279 g_free(le_bitmap);
a335debb
PX
280
281 if (qemu_file_get_error(file)) {
282 return qemu_file_get_error(file);
283 }
284
285 return size + sizeof(size);
286}
287
ec481c6c
JQ
288/*
289 * An outstanding page request, on the source, having been received
290 * and queued
291 */
292struct RAMSrcPageRequest {
293 RAMBlock *rb;
294 hwaddr offset;
295 hwaddr len;
296
297 QSIMPLEQ_ENTRY(RAMSrcPageRequest) next_req;
298};
299
6f37bb8b
JQ
300/* State of RAM for migration */
301struct RAMState {
204b88b8
JQ
302 /* QEMUFile used for this migration */
303 QEMUFile *f;
278e2f55
AG
304 /* UFFD file descriptor, used in 'write-tracking' migration */
305 int uffdio_fd;
6f37bb8b
JQ
306 /* Last block that we have visited searching for dirty pages */
307 RAMBlock *last_seen_block;
308 /* Last block from where we have sent data */
309 RAMBlock *last_sent_block;
269ace29
JQ
310 /* Last dirty target page we have sent */
311 ram_addr_t last_page;
6f37bb8b
JQ
312 /* last ram version we have seen */
313 uint32_t last_version;
8d820d6f
JQ
314 /* How many times we have dirty too many pages */
315 int dirty_rate_high_cnt;
f664da80
JQ
316 /* these variables are used for bitmap sync */
317 /* last time we did a full bitmap_sync */
318 int64_t time_last_bitmap_sync;
eac74159 319 /* bytes transferred at start_time */
c4bdf0cf 320 uint64_t bytes_xfer_prev;
a66cd90c 321 /* number of dirty pages since start_time */
68908ed6 322 uint64_t num_dirty_pages_period;
b5833fde
JQ
323 /* xbzrle misses since the beginning of the period */
324 uint64_t xbzrle_cache_miss_prev;
e460a4b1
WW
325 /* Amount of xbzrle pages since the beginning of the period */
326 uint64_t xbzrle_pages_prev;
327 /* Amount of xbzrle encoded bytes since the beginning of the period */
328 uint64_t xbzrle_bytes_prev;
1a373522
DH
329 /* Start using XBZRLE (e.g., after the first round). */
330 bool xbzrle_enabled;
76e03000
XG
331
332 /* compression statistics since the beginning of the period */
333 /* amount of count that no free thread to compress data */
334 uint64_t compress_thread_busy_prev;
335 /* amount bytes after compression */
336 uint64_t compressed_size_prev;
337 /* amount of compressed pages */
338 uint64_t compress_pages_prev;
339
be8b02ed
XG
340 /* total handled target pages at the beginning of period */
341 uint64_t target_page_count_prev;
342 /* total handled target pages since start */
343 uint64_t target_page_count;
9360447d 344 /* number of dirty bits in the bitmap */
2dfaf12e 345 uint64_t migration_dirty_pages;
386a907b 346 /* Protects modification of the bitmap and migration dirty pages */
108cfae0 347 QemuMutex bitmap_mutex;
68a098f3
JQ
348 /* The RAMBlock used in the last src_page_requests */
349 RAMBlock *last_req_rb;
ec481c6c
JQ
350 /* Queue of outstanding page requests from the destination */
351 QemuMutex src_page_req_mutex;
b58deb34 352 QSIMPLEQ_HEAD(, RAMSrcPageRequest) src_page_requests;
6f37bb8b
JQ
353};
354typedef struct RAMState RAMState;
355
53518d94 356static RAMState *ram_state;
6f37bb8b 357
bd227060
WW
358static NotifierWithReturnList precopy_notifier_list;
359
360void precopy_infrastructure_init(void)
361{
362 notifier_with_return_list_init(&precopy_notifier_list);
363}
364
365void precopy_add_notifier(NotifierWithReturn *n)
366{
367 notifier_with_return_list_add(&precopy_notifier_list, n);
368}
369
370void precopy_remove_notifier(NotifierWithReturn *n)
371{
372 notifier_with_return_remove(n);
373}
374
375int precopy_notify(PrecopyNotifyReason reason, Error **errp)
376{
377 PrecopyNotifyData pnd;
378 pnd.reason = reason;
379 pnd.errp = errp;
380
381 return notifier_with_return_list_notify(&precopy_notifier_list, &pnd);
382}
383
9edabd4d 384uint64_t ram_bytes_remaining(void)
2f4fde93 385{
bae416e5
DDAG
386 return ram_state ? (ram_state->migration_dirty_pages * TARGET_PAGE_SIZE) :
387 0;
2f4fde93
JQ
388}
389
9360447d 390MigrationStats ram_counters;
96506894 391
b8fb8cb7
DDAG
392/* used by the search for pages to send */
393struct PageSearchStatus {
394 /* Current block being searched */
395 RAMBlock *block;
a935e30f
JQ
396 /* Current page to search from */
397 unsigned long page;
b8fb8cb7
DDAG
398 /* Set once we wrap around */
399 bool complete_round;
400};
401typedef struct PageSearchStatus PageSearchStatus;
402
76e03000
XG
403CompressionStats compression_counters;
404
56e93d26 405struct CompressParam {
56e93d26 406 bool done;
90e56fb4 407 bool quit;
5e5fdcff 408 bool zero_page;
56e93d26
JQ
409 QEMUFile *file;
410 QemuMutex mutex;
411 QemuCond cond;
412 RAMBlock *block;
413 ram_addr_t offset;
34ab9e97
XG
414
415 /* internally used fields */
dcaf446e 416 z_stream stream;
34ab9e97 417 uint8_t *originbuf;
56e93d26
JQ
418};
419typedef struct CompressParam CompressParam;
420
421struct DecompressParam {
73a8912b 422 bool done;
90e56fb4 423 bool quit;
56e93d26
JQ
424 QemuMutex mutex;
425 QemuCond cond;
426 void *des;
d341d9f3 427 uint8_t *compbuf;
56e93d26 428 int len;
797ca154 429 z_stream stream;
56e93d26
JQ
430};
431typedef struct DecompressParam DecompressParam;
432
433static CompressParam *comp_param;
434static QemuThread *compress_threads;
435/* comp_done_cond is used to wake up the migration thread when
436 * one of the compression threads has finished the compression.
437 * comp_done_lock is used to co-work with comp_done_cond.
438 */
0d9f9a5c
LL
439static QemuMutex comp_done_lock;
440static QemuCond comp_done_cond;
56e93d26
JQ
441/* The empty QEMUFileOps will be used by file in CompressParam */
442static const QEMUFileOps empty_ops = { };
443
34ab9e97 444static QEMUFile *decomp_file;
56e93d26
JQ
445static DecompressParam *decomp_param;
446static QemuThread *decompress_threads;
73a8912b
LL
447static QemuMutex decomp_done_lock;
448static QemuCond decomp_done_cond;
56e93d26 449
5e5fdcff 450static bool do_compress_ram_page(QEMUFile *f, z_stream *stream, RAMBlock *block,
6ef3771c 451 ram_addr_t offset, uint8_t *source_buf);
56e93d26
JQ
452
453static void *do_data_compress(void *opaque)
454{
455 CompressParam *param = opaque;
a7a9a88f
LL
456 RAMBlock *block;
457 ram_addr_t offset;
5e5fdcff 458 bool zero_page;
56e93d26 459
a7a9a88f 460 qemu_mutex_lock(&param->mutex);
90e56fb4 461 while (!param->quit) {
a7a9a88f
LL
462 if (param->block) {
463 block = param->block;
464 offset = param->offset;
465 param->block = NULL;
466 qemu_mutex_unlock(&param->mutex);
467
5e5fdcff
XG
468 zero_page = do_compress_ram_page(param->file, &param->stream,
469 block, offset, param->originbuf);
a7a9a88f 470
0d9f9a5c 471 qemu_mutex_lock(&comp_done_lock);
a7a9a88f 472 param->done = true;
5e5fdcff 473 param->zero_page = zero_page;
0d9f9a5c
LL
474 qemu_cond_signal(&comp_done_cond);
475 qemu_mutex_unlock(&comp_done_lock);
a7a9a88f
LL
476
477 qemu_mutex_lock(&param->mutex);
478 } else {
56e93d26
JQ
479 qemu_cond_wait(&param->cond, &param->mutex);
480 }
56e93d26 481 }
a7a9a88f 482 qemu_mutex_unlock(&param->mutex);
56e93d26
JQ
483
484 return NULL;
485}
486
f0afa331 487static void compress_threads_save_cleanup(void)
56e93d26
JQ
488{
489 int i, thread_count;
490
05306935 491 if (!migrate_use_compression() || !comp_param) {
56e93d26
JQ
492 return;
493 }
05306935 494
56e93d26
JQ
495 thread_count = migrate_compress_threads();
496 for (i = 0; i < thread_count; i++) {
dcaf446e
XG
497 /*
498 * we use it as a indicator which shows if the thread is
499 * properly init'd or not
500 */
501 if (!comp_param[i].file) {
502 break;
503 }
05306935
FL
504
505 qemu_mutex_lock(&comp_param[i].mutex);
506 comp_param[i].quit = true;
507 qemu_cond_signal(&comp_param[i].cond);
508 qemu_mutex_unlock(&comp_param[i].mutex);
509
56e93d26 510 qemu_thread_join(compress_threads + i);
56e93d26
JQ
511 qemu_mutex_destroy(&comp_param[i].mutex);
512 qemu_cond_destroy(&comp_param[i].cond);
dcaf446e 513 deflateEnd(&comp_param[i].stream);
34ab9e97 514 g_free(comp_param[i].originbuf);
dcaf446e
XG
515 qemu_fclose(comp_param[i].file);
516 comp_param[i].file = NULL;
56e93d26 517 }
0d9f9a5c
LL
518 qemu_mutex_destroy(&comp_done_lock);
519 qemu_cond_destroy(&comp_done_cond);
56e93d26
JQ
520 g_free(compress_threads);
521 g_free(comp_param);
56e93d26
JQ
522 compress_threads = NULL;
523 comp_param = NULL;
56e93d26
JQ
524}
525
dcaf446e 526static int compress_threads_save_setup(void)
56e93d26
JQ
527{
528 int i, thread_count;
529
530 if (!migrate_use_compression()) {
dcaf446e 531 return 0;
56e93d26 532 }
56e93d26
JQ
533 thread_count = migrate_compress_threads();
534 compress_threads = g_new0(QemuThread, thread_count);
535 comp_param = g_new0(CompressParam, thread_count);
0d9f9a5c
LL
536 qemu_cond_init(&comp_done_cond);
537 qemu_mutex_init(&comp_done_lock);
56e93d26 538 for (i = 0; i < thread_count; i++) {
34ab9e97
XG
539 comp_param[i].originbuf = g_try_malloc(TARGET_PAGE_SIZE);
540 if (!comp_param[i].originbuf) {
541 goto exit;
542 }
543
dcaf446e
XG
544 if (deflateInit(&comp_param[i].stream,
545 migrate_compress_level()) != Z_OK) {
34ab9e97 546 g_free(comp_param[i].originbuf);
dcaf446e
XG
547 goto exit;
548 }
549
e110aa91
C
550 /* comp_param[i].file is just used as a dummy buffer to save data,
551 * set its ops to empty.
56e93d26
JQ
552 */
553 comp_param[i].file = qemu_fopen_ops(NULL, &empty_ops);
554 comp_param[i].done = true;
90e56fb4 555 comp_param[i].quit = false;
56e93d26
JQ
556 qemu_mutex_init(&comp_param[i].mutex);
557 qemu_cond_init(&comp_param[i].cond);
558 qemu_thread_create(compress_threads + i, "compress",
559 do_data_compress, comp_param + i,
560 QEMU_THREAD_JOINABLE);
561 }
dcaf446e
XG
562 return 0;
563
564exit:
565 compress_threads_save_cleanup();
566 return -1;
56e93d26
JQ
567}
568
569/**
3d0684b2 570 * save_page_header: write page header to wire
56e93d26
JQ
571 *
572 * If this is the 1st block, it also writes the block identification
573 *
3d0684b2 574 * Returns the number of bytes written
56e93d26
JQ
575 *
576 * @f: QEMUFile where to send the data
577 * @block: block that contains the page we want to send
578 * @offset: offset inside the block for the page
579 * in the lower bits, it contains flags
580 */
2bf3aa85
JQ
581static size_t save_page_header(RAMState *rs, QEMUFile *f, RAMBlock *block,
582 ram_addr_t offset)
56e93d26 583{
9f5f380b 584 size_t size, len;
56e93d26 585
24795694
JQ
586 if (block == rs->last_sent_block) {
587 offset |= RAM_SAVE_FLAG_CONTINUE;
588 }
2bf3aa85 589 qemu_put_be64(f, offset);
56e93d26
JQ
590 size = 8;
591
592 if (!(offset & RAM_SAVE_FLAG_CONTINUE)) {
9f5f380b 593 len = strlen(block->idstr);
2bf3aa85
JQ
594 qemu_put_byte(f, len);
595 qemu_put_buffer(f, (uint8_t *)block->idstr, len);
9f5f380b 596 size += 1 + len;
24795694 597 rs->last_sent_block = block;
56e93d26
JQ
598 }
599 return size;
600}
601
3d0684b2
JQ
602/**
603 * mig_throttle_guest_down: throotle down the guest
604 *
605 * Reduce amount of guest cpu execution to hopefully slow down memory
606 * writes. If guest dirty memory rate is reduced below the rate at
607 * which we can transfer pages to the destination then we should be
608 * able to complete migration. Some workloads dirty memory way too
609 * fast and will not effectively converge, even with auto-converge.
070afca2 610 */
cbbf8182
KZ
611static void mig_throttle_guest_down(uint64_t bytes_dirty_period,
612 uint64_t bytes_dirty_threshold)
070afca2
JH
613{
614 MigrationState *s = migrate_get_current();
2594f56d 615 uint64_t pct_initial = s->parameters.cpu_throttle_initial;
cbbf8182
KZ
616 uint64_t pct_increment = s->parameters.cpu_throttle_increment;
617 bool pct_tailslow = s->parameters.cpu_throttle_tailslow;
4cbc9c7f 618 int pct_max = s->parameters.max_cpu_throttle;
070afca2 619
cbbf8182
KZ
620 uint64_t throttle_now = cpu_throttle_get_percentage();
621 uint64_t cpu_now, cpu_ideal, throttle_inc;
622
070afca2
JH
623 /* We have not started throttling yet. Let's start it. */
624 if (!cpu_throttle_active()) {
625 cpu_throttle_set(pct_initial);
626 } else {
627 /* Throttling already on, just increase the rate */
cbbf8182
KZ
628 if (!pct_tailslow) {
629 throttle_inc = pct_increment;
630 } else {
631 /* Compute the ideal CPU percentage used by Guest, which may
632 * make the dirty rate match the dirty rate threshold. */
633 cpu_now = 100 - throttle_now;
634 cpu_ideal = cpu_now * (bytes_dirty_threshold * 1.0 /
635 bytes_dirty_period);
636 throttle_inc = MIN(cpu_now - cpu_ideal, pct_increment);
637 }
638 cpu_throttle_set(MIN(throttle_now + throttle_inc, pct_max));
070afca2
JH
639 }
640}
641
3d0684b2
JQ
642/**
643 * xbzrle_cache_zero_page: insert a zero page in the XBZRLE cache
644 *
6f37bb8b 645 * @rs: current RAM state
3d0684b2
JQ
646 * @current_addr: address for the zero page
647 *
648 * Update the xbzrle cache to reflect a page that's been sent as all 0.
56e93d26
JQ
649 * The important thing is that a stale (not-yet-0'd) page be replaced
650 * by the new data.
651 * As a bonus, if the page wasn't in the cache it gets added so that
3d0684b2 652 * when a small write is made into the 0'd page it gets XBZRLE sent.
56e93d26 653 */
6f37bb8b 654static void xbzrle_cache_zero_page(RAMState *rs, ram_addr_t current_addr)
56e93d26 655{
1a373522 656 if (!rs->xbzrle_enabled) {
56e93d26
JQ
657 return;
658 }
659
660 /* We don't care if this fails to allocate a new cache page
661 * as long as it updated an old one */
c00e0928 662 cache_insert(XBZRLE.cache, current_addr, XBZRLE.zero_target_page,
9360447d 663 ram_counters.dirty_sync_count);
56e93d26
JQ
664}
665
666#define ENCODING_FLAG_XBZRLE 0x1
667
668/**
669 * save_xbzrle_page: compress and send current page
670 *
671 * Returns: 1 means that we wrote the page
672 * 0 means that page is identical to the one already sent
673 * -1 means that xbzrle would be longer than normal
674 *
5a987738 675 * @rs: current RAM state
3d0684b2
JQ
676 * @current_data: pointer to the address of the page contents
677 * @current_addr: addr of the page
56e93d26
JQ
678 * @block: block that contains the page we want to send
679 * @offset: offset inside the block for the page
680 * @last_stage: if we are at the completion stage
56e93d26 681 */
204b88b8 682static int save_xbzrle_page(RAMState *rs, uint8_t **current_data,
56e93d26 683 ram_addr_t current_addr, RAMBlock *block,
072c2511 684 ram_addr_t offset, bool last_stage)
56e93d26
JQ
685{
686 int encoded_len = 0, bytes_xbzrle;
687 uint8_t *prev_cached_page;
688
9360447d
JQ
689 if (!cache_is_cached(XBZRLE.cache, current_addr,
690 ram_counters.dirty_sync_count)) {
691 xbzrle_counters.cache_miss++;
56e93d26
JQ
692 if (!last_stage) {
693 if (cache_insert(XBZRLE.cache, current_addr, *current_data,
9360447d 694 ram_counters.dirty_sync_count) == -1) {
56e93d26
JQ
695 return -1;
696 } else {
697 /* update *current_data when the page has been
698 inserted into cache */
699 *current_data = get_cached_data(XBZRLE.cache, current_addr);
700 }
701 }
702 return -1;
703 }
704
e460a4b1
WW
705 /*
706 * Reaching here means the page has hit the xbzrle cache, no matter what
707 * encoding result it is (normal encoding, overflow or skipping the page),
3a4452d8 708 * count the page as encoded. This is used to calculate the encoding rate.
e460a4b1
WW
709 *
710 * Example: 2 pages (8KB) being encoded, first page encoding generates 2KB,
711 * 2nd page turns out to be skipped (i.e. no new bytes written to the
712 * page), the overall encoding rate will be 8KB / 2KB = 4, which has the
713 * skipped page included. In this way, the encoding rate can tell if the
714 * guest page is good for xbzrle encoding.
715 */
716 xbzrle_counters.pages++;
56e93d26
JQ
717 prev_cached_page = get_cached_data(XBZRLE.cache, current_addr);
718
719 /* save current buffer into memory */
720 memcpy(XBZRLE.current_buf, *current_data, TARGET_PAGE_SIZE);
721
722 /* XBZRLE encoding (if there is no overflow) */
723 encoded_len = xbzrle_encode_buffer(prev_cached_page, XBZRLE.current_buf,
724 TARGET_PAGE_SIZE, XBZRLE.encoded_buf,
725 TARGET_PAGE_SIZE);
ca353803
WY
726
727 /*
728 * Update the cache contents, so that it corresponds to the data
729 * sent, in all cases except where we skip the page.
730 */
731 if (!last_stage && encoded_len != 0) {
732 memcpy(prev_cached_page, XBZRLE.current_buf, TARGET_PAGE_SIZE);
733 /*
734 * In the case where we couldn't compress, ensure that the caller
735 * sends the data from the cache, since the guest might have
736 * changed the RAM since we copied it.
737 */
738 *current_data = prev_cached_page;
739 }
740
56e93d26 741 if (encoded_len == 0) {
55c4446b 742 trace_save_xbzrle_page_skipping();
56e93d26
JQ
743 return 0;
744 } else if (encoded_len == -1) {
55c4446b 745 trace_save_xbzrle_page_overflow();
9360447d 746 xbzrle_counters.overflow++;
e460a4b1 747 xbzrle_counters.bytes += TARGET_PAGE_SIZE;
56e93d26
JQ
748 return -1;
749 }
750
56e93d26 751 /* Send XBZRLE based compressed page */
2bf3aa85 752 bytes_xbzrle = save_page_header(rs, rs->f, block,
204b88b8
JQ
753 offset | RAM_SAVE_FLAG_XBZRLE);
754 qemu_put_byte(rs->f, ENCODING_FLAG_XBZRLE);
755 qemu_put_be16(rs->f, encoded_len);
756 qemu_put_buffer(rs->f, XBZRLE.encoded_buf, encoded_len);
56e93d26 757 bytes_xbzrle += encoded_len + 1 + 2;
e460a4b1
WW
758 /*
759 * Like compressed_size (please see update_compress_thread_counts),
760 * the xbzrle encoded bytes don't count the 8 byte header with
761 * RAM_SAVE_FLAG_CONTINUE.
762 */
763 xbzrle_counters.bytes += bytes_xbzrle - 8;
9360447d 764 ram_counters.transferred += bytes_xbzrle;
56e93d26
JQ
765
766 return 1;
767}
768
3d0684b2
JQ
769/**
770 * migration_bitmap_find_dirty: find the next dirty page from start
f3f491fc 771 *
a5f7b1a6 772 * Returns the page offset within memory region of the start of a dirty page
3d0684b2 773 *
6f37bb8b 774 * @rs: current RAM state
3d0684b2 775 * @rb: RAMBlock where to search for dirty pages
a935e30f 776 * @start: page where we start the search
f3f491fc 777 */
56e93d26 778static inline
a935e30f 779unsigned long migration_bitmap_find_dirty(RAMState *rs, RAMBlock *rb,
f20e2865 780 unsigned long start)
56e93d26 781{
6b6712ef
JQ
782 unsigned long size = rb->used_length >> TARGET_PAGE_BITS;
783 unsigned long *bitmap = rb->bmap;
56e93d26 784
fbd162e6 785 if (ramblock_is_ignored(rb)) {
b895de50
CLG
786 return size;
787 }
788
1a373522 789 return find_next_bit(bitmap, size, start);
56e93d26
JQ
790}
791
06b10688 792static inline bool migration_bitmap_clear_dirty(RAMState *rs,
f20e2865
JQ
793 RAMBlock *rb,
794 unsigned long page)
a82d593b
DDAG
795{
796 bool ret;
a82d593b 797
37396950 798 QEMU_LOCK_GUARD(&rs->bitmap_mutex);
002cad6b
PX
799
800 /*
801 * Clear dirty bitmap if needed. This _must_ be called before we
802 * send any of the page in the chunk because we need to make sure
803 * we can capture further page content changes when we sync dirty
804 * log the next time. So as long as we are going to send any of
805 * the page in the chunk we clear the remote dirty bitmap for all.
806 * Clearing it earlier won't be a problem, but too late will.
807 */
808 if (rb->clear_bmap && clear_bmap_test_and_clear(rb, page)) {
809 uint8_t shift = rb->clear_bmap_shift;
810 hwaddr size = 1ULL << (TARGET_PAGE_BITS + shift);
8bba004c 811 hwaddr start = (((ram_addr_t)page) << TARGET_PAGE_BITS) & (-size);
002cad6b
PX
812
813 /*
814 * CLEAR_BITMAP_SHIFT_MIN should always guarantee this... this
815 * can make things easier sometimes since then start address
816 * of the small chunk will always be 64 pages aligned so the
817 * bitmap will always be aligned to unsigned long. We should
818 * even be able to remove this restriction but I'm simply
819 * keeping it.
820 */
821 assert(shift >= 6);
822 trace_migration_bitmap_clear_dirty(rb->idstr, start, size, page);
823 memory_region_clear_dirty_bitmap(rb->mr, start, size);
824 }
825
6b6712ef 826 ret = test_and_clear_bit(page, rb->bmap);
a82d593b
DDAG
827
828 if (ret) {
0d8ec885 829 rs->migration_dirty_pages--;
a82d593b 830 }
386a907b 831
a82d593b
DDAG
832 return ret;
833}
834
267691b6 835/* Called with RCU critical section */
7a3e9571 836static void ramblock_sync_dirty_bitmap(RAMState *rs, RAMBlock *rb)
56e93d26 837{
fb613580
KZ
838 uint64_t new_dirty_pages =
839 cpu_physical_memory_sync_dirty_bitmap(rb, 0, rb->used_length);
840
841 rs->migration_dirty_pages += new_dirty_pages;
842 rs->num_dirty_pages_period += new_dirty_pages;
56e93d26
JQ
843}
844
3d0684b2
JQ
845/**
846 * ram_pagesize_summary: calculate all the pagesizes of a VM
847 *
848 * Returns a summary bitmap of the page sizes of all RAMBlocks
849 *
850 * For VMs with just normal pages this is equivalent to the host page
851 * size. If it's got some huge pages then it's the OR of all the
852 * different page sizes.
e8ca1db2
DDAG
853 */
854uint64_t ram_pagesize_summary(void)
855{
856 RAMBlock *block;
857 uint64_t summary = 0;
858
fbd162e6 859 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
e8ca1db2
DDAG
860 summary |= block->page_size;
861 }
862
863 return summary;
864}
865
aecbfe9c
XG
866uint64_t ram_get_total_transferred_pages(void)
867{
868 return ram_counters.normal + ram_counters.duplicate +
869 compression_counters.pages + xbzrle_counters.pages;
870}
871
b734035b
XG
872static void migration_update_rates(RAMState *rs, int64_t end_time)
873{
be8b02ed 874 uint64_t page_count = rs->target_page_count - rs->target_page_count_prev;
76e03000 875 double compressed_size;
b734035b
XG
876
877 /* calculate period counters */
878 ram_counters.dirty_pages_rate = rs->num_dirty_pages_period * 1000
879 / (end_time - rs->time_last_bitmap_sync);
880
be8b02ed 881 if (!page_count) {
b734035b
XG
882 return;
883 }
884
885 if (migrate_use_xbzrle()) {
e460a4b1
WW
886 double encoded_size, unencoded_size;
887
b734035b 888 xbzrle_counters.cache_miss_rate = (double)(xbzrle_counters.cache_miss -
be8b02ed 889 rs->xbzrle_cache_miss_prev) / page_count;
b734035b 890 rs->xbzrle_cache_miss_prev = xbzrle_counters.cache_miss;
e460a4b1
WW
891 unencoded_size = (xbzrle_counters.pages - rs->xbzrle_pages_prev) *
892 TARGET_PAGE_SIZE;
893 encoded_size = xbzrle_counters.bytes - rs->xbzrle_bytes_prev;
92271402 894 if (xbzrle_counters.pages == rs->xbzrle_pages_prev || !encoded_size) {
e460a4b1 895 xbzrle_counters.encoding_rate = 0;
e460a4b1
WW
896 } else {
897 xbzrle_counters.encoding_rate = unencoded_size / encoded_size;
898 }
899 rs->xbzrle_pages_prev = xbzrle_counters.pages;
900 rs->xbzrle_bytes_prev = xbzrle_counters.bytes;
b734035b 901 }
76e03000
XG
902
903 if (migrate_use_compression()) {
904 compression_counters.busy_rate = (double)(compression_counters.busy -
905 rs->compress_thread_busy_prev) / page_count;
906 rs->compress_thread_busy_prev = compression_counters.busy;
907
908 compressed_size = compression_counters.compressed_size -
909 rs->compressed_size_prev;
910 if (compressed_size) {
911 double uncompressed_size = (compression_counters.pages -
912 rs->compress_pages_prev) * TARGET_PAGE_SIZE;
913
914 /* Compression-Ratio = Uncompressed-size / Compressed-size */
915 compression_counters.compression_rate =
916 uncompressed_size / compressed_size;
917
918 rs->compress_pages_prev = compression_counters.pages;
919 rs->compressed_size_prev = compression_counters.compressed_size;
920 }
921 }
b734035b
XG
922}
923
dc14a470
KZ
924static void migration_trigger_throttle(RAMState *rs)
925{
926 MigrationState *s = migrate_get_current();
927 uint64_t threshold = s->parameters.throttle_trigger_threshold;
928
929 uint64_t bytes_xfer_period = ram_counters.transferred - rs->bytes_xfer_prev;
930 uint64_t bytes_dirty_period = rs->num_dirty_pages_period * TARGET_PAGE_SIZE;
931 uint64_t bytes_dirty_threshold = bytes_xfer_period * threshold / 100;
932
933 /* During block migration the auto-converge logic incorrectly detects
934 * that ram migration makes no progress. Avoid this by disabling the
935 * throttling logic during the bulk phase of block migration. */
936 if (migrate_auto_converge() && !blk_mig_bulk_active()) {
937 /* The following detection logic can be refined later. For now:
938 Check to see if the ratio between dirtied bytes and the approx.
939 amount of bytes that just got transferred since the last time
940 we were in this routine reaches the threshold. If that happens
941 twice, start or increase throttling. */
942
943 if ((bytes_dirty_period > bytes_dirty_threshold) &&
944 (++rs->dirty_rate_high_cnt >= 2)) {
945 trace_migration_throttle();
946 rs->dirty_rate_high_cnt = 0;
cbbf8182
KZ
947 mig_throttle_guest_down(bytes_dirty_period,
948 bytes_dirty_threshold);
dc14a470
KZ
949 }
950 }
951}
952
8d820d6f 953static void migration_bitmap_sync(RAMState *rs)
56e93d26
JQ
954{
955 RAMBlock *block;
56e93d26 956 int64_t end_time;
56e93d26 957
9360447d 958 ram_counters.dirty_sync_count++;
56e93d26 959
f664da80
JQ
960 if (!rs->time_last_bitmap_sync) {
961 rs->time_last_bitmap_sync = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
56e93d26
JQ
962 }
963
964 trace_migration_bitmap_sync_start();
9c1f8f44 965 memory_global_dirty_log_sync();
56e93d26 966
108cfae0 967 qemu_mutex_lock(&rs->bitmap_mutex);
89ac5a1d
DDAG
968 WITH_RCU_READ_LOCK_GUARD() {
969 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
970 ramblock_sync_dirty_bitmap(rs, block);
971 }
972 ram_counters.remaining = ram_bytes_remaining();
56e93d26 973 }
108cfae0 974 qemu_mutex_unlock(&rs->bitmap_mutex);
56e93d26 975
9458a9a1 976 memory_global_after_dirty_log_sync();
a66cd90c 977 trace_migration_bitmap_sync_end(rs->num_dirty_pages_period);
1ffb5dfd 978
56e93d26
JQ
979 end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
980
981 /* more than 1 second = 1000 millisecons */
f664da80 982 if (end_time > rs->time_last_bitmap_sync + 1000) {
dc14a470 983 migration_trigger_throttle(rs);
070afca2 984
b734035b
XG
985 migration_update_rates(rs, end_time);
986
be8b02ed 987 rs->target_page_count_prev = rs->target_page_count;
d693c6f1
FF
988
989 /* reset period counters */
f664da80 990 rs->time_last_bitmap_sync = end_time;
a66cd90c 991 rs->num_dirty_pages_period = 0;
dc14a470 992 rs->bytes_xfer_prev = ram_counters.transferred;
56e93d26 993 }
4addcd4f 994 if (migrate_use_events()) {
3ab72385 995 qapi_event_send_migration_pass(ram_counters.dirty_sync_count);
4addcd4f 996 }
56e93d26
JQ
997}
998
bd227060
WW
999static void migration_bitmap_sync_precopy(RAMState *rs)
1000{
1001 Error *local_err = NULL;
1002
1003 /*
1004 * The current notifier usage is just an optimization to migration, so we
1005 * don't stop the normal migration process in the error case.
1006 */
1007 if (precopy_notify(PRECOPY_NOTIFY_BEFORE_BITMAP_SYNC, &local_err)) {
1008 error_report_err(local_err);
b4a1733c 1009 local_err = NULL;
bd227060
WW
1010 }
1011
1012 migration_bitmap_sync(rs);
1013
1014 if (precopy_notify(PRECOPY_NOTIFY_AFTER_BITMAP_SYNC, &local_err)) {
1015 error_report_err(local_err);
1016 }
1017}
1018
6c97ec5f
XG
1019/**
1020 * save_zero_page_to_file: send the zero page to the file
1021 *
1022 * Returns the size of data written to the file, 0 means the page is not
1023 * a zero page
1024 *
1025 * @rs: current RAM state
1026 * @file: the file where the data is saved
1027 * @block: block that contains the page we want to send
1028 * @offset: offset inside the block for the page
1029 */
1030static int save_zero_page_to_file(RAMState *rs, QEMUFile *file,
1031 RAMBlock *block, ram_addr_t offset)
1032{
1033 uint8_t *p = block->host + offset;
1034 int len = 0;
1035
1036 if (is_zero_range(p, TARGET_PAGE_SIZE)) {
1037 len += save_page_header(rs, file, block, offset | RAM_SAVE_FLAG_ZERO);
1038 qemu_put_byte(file, 0);
1039 len += 1;
1040 }
1041 return len;
1042}
1043
56e93d26 1044/**
3d0684b2 1045 * save_zero_page: send the zero page to the stream
56e93d26 1046 *
3d0684b2 1047 * Returns the number of pages written.
56e93d26 1048 *
f7ccd61b 1049 * @rs: current RAM state
56e93d26
JQ
1050 * @block: block that contains the page we want to send
1051 * @offset: offset inside the block for the page
56e93d26 1052 */
7faccdc3 1053static int save_zero_page(RAMState *rs, RAMBlock *block, ram_addr_t offset)
56e93d26 1054{
6c97ec5f 1055 int len = save_zero_page_to_file(rs, rs->f, block, offset);
56e93d26 1056
6c97ec5f 1057 if (len) {
9360447d 1058 ram_counters.duplicate++;
6c97ec5f
XG
1059 ram_counters.transferred += len;
1060 return 1;
56e93d26 1061 }
6c97ec5f 1062 return -1;
56e93d26
JQ
1063}
1064
5727309d 1065static void ram_release_pages(const char *rbname, uint64_t offset, int pages)
53f09a10 1066{
5727309d 1067 if (!migrate_release_ram() || !migration_in_postcopy()) {
53f09a10
PB
1068 return;
1069 }
1070
8bba004c 1071 ram_discard_range(rbname, offset, ((ram_addr_t)pages) << TARGET_PAGE_BITS);
53f09a10
PB
1072}
1073
059ff0fb
XG
1074/*
1075 * @pages: the number of pages written by the control path,
1076 * < 0 - error
1077 * > 0 - number of pages written
1078 *
1079 * Return true if the pages has been saved, otherwise false is returned.
1080 */
1081static bool control_save_page(RAMState *rs, RAMBlock *block, ram_addr_t offset,
1082 int *pages)
1083{
1084 uint64_t bytes_xmit = 0;
1085 int ret;
1086
1087 *pages = -1;
1088 ret = ram_control_save_page(rs->f, block->offset, offset, TARGET_PAGE_SIZE,
1089 &bytes_xmit);
1090 if (ret == RAM_SAVE_CONTROL_NOT_SUPP) {
1091 return false;
1092 }
1093
1094 if (bytes_xmit) {
1095 ram_counters.transferred += bytes_xmit;
1096 *pages = 1;
1097 }
1098
1099 if (ret == RAM_SAVE_CONTROL_DELAYED) {
1100 return true;
1101 }
1102
1103 if (bytes_xmit > 0) {
1104 ram_counters.normal++;
1105 } else if (bytes_xmit == 0) {
1106 ram_counters.duplicate++;
1107 }
1108
1109 return true;
1110}
1111
65dacaa0
XG
1112/*
1113 * directly send the page to the stream
1114 *
1115 * Returns the number of pages written.
1116 *
1117 * @rs: current RAM state
1118 * @block: block that contains the page we want to send
1119 * @offset: offset inside the block for the page
1120 * @buf: the page to be sent
1121 * @async: send to page asyncly
1122 */
1123static int save_normal_page(RAMState *rs, RAMBlock *block, ram_addr_t offset,
1124 uint8_t *buf, bool async)
1125{
1126 ram_counters.transferred += save_page_header(rs, rs->f, block,
1127 offset | RAM_SAVE_FLAG_PAGE);
1128 if (async) {
1129 qemu_put_buffer_async(rs->f, buf, TARGET_PAGE_SIZE,
1130 migrate_release_ram() &
1131 migration_in_postcopy());
1132 } else {
1133 qemu_put_buffer(rs->f, buf, TARGET_PAGE_SIZE);
1134 }
1135 ram_counters.transferred += TARGET_PAGE_SIZE;
1136 ram_counters.normal++;
1137 return 1;
1138}
1139
56e93d26 1140/**
3d0684b2 1141 * ram_save_page: send the given page to the stream
56e93d26 1142 *
3d0684b2 1143 * Returns the number of pages written.
3fd3c4b3
DDAG
1144 * < 0 - error
1145 * >=0 - Number of pages written - this might legally be 0
1146 * if xbzrle noticed the page was the same.
56e93d26 1147 *
6f37bb8b 1148 * @rs: current RAM state
56e93d26
JQ
1149 * @block: block that contains the page we want to send
1150 * @offset: offset inside the block for the page
1151 * @last_stage: if we are at the completion stage
56e93d26 1152 */
a0a8aa14 1153static int ram_save_page(RAMState *rs, PageSearchStatus *pss, bool last_stage)
56e93d26
JQ
1154{
1155 int pages = -1;
56e93d26 1156 uint8_t *p;
56e93d26 1157 bool send_async = true;
a08f6890 1158 RAMBlock *block = pss->block;
8bba004c 1159 ram_addr_t offset = ((ram_addr_t)pss->page) << TARGET_PAGE_BITS;
059ff0fb 1160 ram_addr_t current_addr = block->offset + offset;
56e93d26 1161
2f68e399 1162 p = block->host + offset;
1db9d8e5 1163 trace_ram_save_page(block->idstr, (uint64_t)offset, p);
56e93d26 1164
56e93d26 1165 XBZRLE_cache_lock();
1a373522 1166 if (rs->xbzrle_enabled && !migration_in_postcopy()) {
059ff0fb
XG
1167 pages = save_xbzrle_page(rs, &p, current_addr, block,
1168 offset, last_stage);
1169 if (!last_stage) {
1170 /* Can't send this cached data async, since the cache page
1171 * might get updated before it gets to the wire
56e93d26 1172 */
059ff0fb 1173 send_async = false;
56e93d26
JQ
1174 }
1175 }
1176
1177 /* XBZRLE overflow or normal page */
1178 if (pages == -1) {
65dacaa0 1179 pages = save_normal_page(rs, block, offset, p, send_async);
56e93d26
JQ
1180 }
1181
1182 XBZRLE_cache_unlock();
1183
1184 return pages;
1185}
1186
b9ee2f7d
JQ
1187static int ram_save_multifd_page(RAMState *rs, RAMBlock *block,
1188 ram_addr_t offset)
1189{
67a4c891 1190 if (multifd_queue_page(rs->f, block, offset) < 0) {
713f762a
IR
1191 return -1;
1192 }
b9ee2f7d
JQ
1193 ram_counters.normal++;
1194
1195 return 1;
1196}
1197
5e5fdcff 1198static bool do_compress_ram_page(QEMUFile *f, z_stream *stream, RAMBlock *block,
6ef3771c 1199 ram_addr_t offset, uint8_t *source_buf)
56e93d26 1200{
53518d94 1201 RAMState *rs = ram_state;
a7a9a88f 1202 uint8_t *p = block->host + (offset & TARGET_PAGE_MASK);
5e5fdcff 1203 bool zero_page = false;
6ef3771c 1204 int ret;
56e93d26 1205
5e5fdcff
XG
1206 if (save_zero_page_to_file(rs, f, block, offset)) {
1207 zero_page = true;
1208 goto exit;
1209 }
1210
6ef3771c 1211 save_page_header(rs, f, block, offset | RAM_SAVE_FLAG_COMPRESS_PAGE);
34ab9e97
XG
1212
1213 /*
1214 * copy it to a internal buffer to avoid it being modified by VM
1215 * so that we can catch up the error during compression and
1216 * decompression
1217 */
1218 memcpy(source_buf, p, TARGET_PAGE_SIZE);
6ef3771c
XG
1219 ret = qemu_put_compression_data(f, stream, source_buf, TARGET_PAGE_SIZE);
1220 if (ret < 0) {
1221 qemu_file_set_error(migrate_get_current()->to_dst_file, ret);
b3be2896 1222 error_report("compressed data failed!");
5e5fdcff 1223 return false;
b3be2896 1224 }
56e93d26 1225
5e5fdcff 1226exit:
6ef3771c 1227 ram_release_pages(block->idstr, offset & TARGET_PAGE_MASK, 1);
5e5fdcff
XG
1228 return zero_page;
1229}
1230
1231static void
1232update_compress_thread_counts(const CompressParam *param, int bytes_xmit)
1233{
76e03000
XG
1234 ram_counters.transferred += bytes_xmit;
1235
5e5fdcff
XG
1236 if (param->zero_page) {
1237 ram_counters.duplicate++;
76e03000 1238 return;
5e5fdcff 1239 }
76e03000
XG
1240
1241 /* 8 means a header with RAM_SAVE_FLAG_CONTINUE. */
1242 compression_counters.compressed_size += bytes_xmit - 8;
1243 compression_counters.pages++;
56e93d26
JQ
1244}
1245
32b05495
XG
1246static bool save_page_use_compression(RAMState *rs);
1247
ce25d337 1248static void flush_compressed_data(RAMState *rs)
56e93d26
JQ
1249{
1250 int idx, len, thread_count;
1251
32b05495 1252 if (!save_page_use_compression(rs)) {
56e93d26
JQ
1253 return;
1254 }
1255 thread_count = migrate_compress_threads();
a7a9a88f 1256
0d9f9a5c 1257 qemu_mutex_lock(&comp_done_lock);
56e93d26 1258 for (idx = 0; idx < thread_count; idx++) {
a7a9a88f 1259 while (!comp_param[idx].done) {
0d9f9a5c 1260 qemu_cond_wait(&comp_done_cond, &comp_done_lock);
56e93d26 1261 }
a7a9a88f 1262 }
0d9f9a5c 1263 qemu_mutex_unlock(&comp_done_lock);
a7a9a88f
LL
1264
1265 for (idx = 0; idx < thread_count; idx++) {
1266 qemu_mutex_lock(&comp_param[idx].mutex);
90e56fb4 1267 if (!comp_param[idx].quit) {
ce25d337 1268 len = qemu_put_qemu_file(rs->f, comp_param[idx].file);
5e5fdcff
XG
1269 /*
1270 * it's safe to fetch zero_page without holding comp_done_lock
1271 * as there is no further request submitted to the thread,
1272 * i.e, the thread should be waiting for a request at this point.
1273 */
1274 update_compress_thread_counts(&comp_param[idx], len);
56e93d26 1275 }
a7a9a88f 1276 qemu_mutex_unlock(&comp_param[idx].mutex);
56e93d26
JQ
1277 }
1278}
1279
1280static inline void set_compress_params(CompressParam *param, RAMBlock *block,
1281 ram_addr_t offset)
1282{
1283 param->block = block;
1284 param->offset = offset;
1285}
1286
ce25d337
JQ
1287static int compress_page_with_multi_thread(RAMState *rs, RAMBlock *block,
1288 ram_addr_t offset)
56e93d26
JQ
1289{
1290 int idx, thread_count, bytes_xmit = -1, pages = -1;
1d58872a 1291 bool wait = migrate_compress_wait_thread();
56e93d26
JQ
1292
1293 thread_count = migrate_compress_threads();
0d9f9a5c 1294 qemu_mutex_lock(&comp_done_lock);
1d58872a
XG
1295retry:
1296 for (idx = 0; idx < thread_count; idx++) {
1297 if (comp_param[idx].done) {
1298 comp_param[idx].done = false;
1299 bytes_xmit = qemu_put_qemu_file(rs->f, comp_param[idx].file);
1300 qemu_mutex_lock(&comp_param[idx].mutex);
1301 set_compress_params(&comp_param[idx], block, offset);
1302 qemu_cond_signal(&comp_param[idx].cond);
1303 qemu_mutex_unlock(&comp_param[idx].mutex);
1304 pages = 1;
5e5fdcff 1305 update_compress_thread_counts(&comp_param[idx], bytes_xmit);
56e93d26 1306 break;
56e93d26
JQ
1307 }
1308 }
1d58872a
XG
1309
1310 /*
1311 * wait for the free thread if the user specifies 'compress-wait-thread',
1312 * otherwise we will post the page out in the main thread as normal page.
1313 */
1314 if (pages < 0 && wait) {
1315 qemu_cond_wait(&comp_done_cond, &comp_done_lock);
1316 goto retry;
1317 }
0d9f9a5c 1318 qemu_mutex_unlock(&comp_done_lock);
56e93d26
JQ
1319
1320 return pages;
1321}
1322
3d0684b2
JQ
1323/**
1324 * find_dirty_block: find the next dirty page and update any state
1325 * associated with the search process.
b9e60928 1326 *
a5f7b1a6 1327 * Returns true if a page is found
b9e60928 1328 *
6f37bb8b 1329 * @rs: current RAM state
3d0684b2
JQ
1330 * @pss: data about the state of the current dirty page scan
1331 * @again: set to false if the search has scanned the whole of RAM
b9e60928 1332 */
f20e2865 1333static bool find_dirty_block(RAMState *rs, PageSearchStatus *pss, bool *again)
b9e60928 1334{
f20e2865 1335 pss->page = migration_bitmap_find_dirty(rs, pss->block, pss->page);
6f37bb8b 1336 if (pss->complete_round && pss->block == rs->last_seen_block &&
a935e30f 1337 pss->page >= rs->last_page) {
b9e60928
DDAG
1338 /*
1339 * We've been once around the RAM and haven't found anything.
1340 * Give up.
1341 */
1342 *again = false;
1343 return false;
1344 }
8bba004c
AR
1345 if ((((ram_addr_t)pss->page) << TARGET_PAGE_BITS)
1346 >= pss->block->used_length) {
b9e60928 1347 /* Didn't find anything in this RAM Block */
a935e30f 1348 pss->page = 0;
b9e60928
DDAG
1349 pss->block = QLIST_NEXT_RCU(pss->block, next);
1350 if (!pss->block) {
48df9d80
XG
1351 /*
1352 * If memory migration starts over, we will meet a dirtied page
1353 * which may still exists in compression threads's ring, so we
1354 * should flush the compressed data to make sure the new page
1355 * is not overwritten by the old one in the destination.
1356 *
1357 * Also If xbzrle is on, stop using the data compression at this
1358 * point. In theory, xbzrle can do better than compression.
1359 */
1360 flush_compressed_data(rs);
1361
b9e60928
DDAG
1362 /* Hit the end of the list */
1363 pss->block = QLIST_FIRST_RCU(&ram_list.blocks);
1364 /* Flag that we've looped */
1365 pss->complete_round = true;
1a373522
DH
1366 /* After the first round, enable XBZRLE. */
1367 if (migrate_use_xbzrle()) {
1368 rs->xbzrle_enabled = true;
1369 }
b9e60928
DDAG
1370 }
1371 /* Didn't find anything this time, but try again on the new block */
1372 *again = true;
1373 return false;
1374 } else {
1375 /* Can go around again, but... */
1376 *again = true;
1377 /* We've found something so probably don't need to */
1378 return true;
1379 }
1380}
1381
3d0684b2
JQ
1382/**
1383 * unqueue_page: gets a page of the queue
1384 *
a82d593b 1385 * Helper for 'get_queued_page' - gets a page off the queue
a82d593b 1386 *
3d0684b2
JQ
1387 * Returns the block of the page (or NULL if none available)
1388 *
ec481c6c 1389 * @rs: current RAM state
3d0684b2 1390 * @offset: used to return the offset within the RAMBlock
a82d593b 1391 */
f20e2865 1392static RAMBlock *unqueue_page(RAMState *rs, ram_addr_t *offset)
a82d593b
DDAG
1393{
1394 RAMBlock *block = NULL;
1395
ae526e32
XG
1396 if (QSIMPLEQ_EMPTY_ATOMIC(&rs->src_page_requests)) {
1397 return NULL;
1398 }
1399
6e8a355d 1400 QEMU_LOCK_GUARD(&rs->src_page_req_mutex);
ec481c6c
JQ
1401 if (!QSIMPLEQ_EMPTY(&rs->src_page_requests)) {
1402 struct RAMSrcPageRequest *entry =
1403 QSIMPLEQ_FIRST(&rs->src_page_requests);
a82d593b
DDAG
1404 block = entry->rb;
1405 *offset = entry->offset;
a82d593b
DDAG
1406
1407 if (entry->len > TARGET_PAGE_SIZE) {
1408 entry->len -= TARGET_PAGE_SIZE;
1409 entry->offset += TARGET_PAGE_SIZE;
1410 } else {
1411 memory_region_unref(block->mr);
ec481c6c 1412 QSIMPLEQ_REMOVE_HEAD(&rs->src_page_requests, next_req);
a82d593b 1413 g_free(entry);
e03a34f8 1414 migration_consume_urgent_request();
a82d593b
DDAG
1415 }
1416 }
a82d593b
DDAG
1417
1418 return block;
1419}
1420
278e2f55
AG
1421#if defined(__linux__)
1422/**
1423 * poll_fault_page: try to get next UFFD write fault page and, if pending fault
1424 * is found, return RAM block pointer and page offset
1425 *
1426 * Returns pointer to the RAMBlock containing faulting page,
1427 * NULL if no write faults are pending
1428 *
1429 * @rs: current RAM state
1430 * @offset: page offset from the beginning of the block
1431 */
1432static RAMBlock *poll_fault_page(RAMState *rs, ram_addr_t *offset)
1433{
1434 struct uffd_msg uffd_msg;
1435 void *page_address;
82ea3e3b 1436 RAMBlock *block;
278e2f55
AG
1437 int res;
1438
1439 if (!migrate_background_snapshot()) {
1440 return NULL;
1441 }
1442
1443 res = uffd_read_events(rs->uffdio_fd, &uffd_msg, 1);
1444 if (res <= 0) {
1445 return NULL;
1446 }
1447
1448 page_address = (void *)(uintptr_t) uffd_msg.arg.pagefault.address;
82ea3e3b
AG
1449 block = qemu_ram_block_from_host(page_address, false, offset);
1450 assert(block && (block->flags & RAM_UF_WRITEPROTECT) != 0);
1451 return block;
278e2f55
AG
1452}
1453
1454/**
1455 * ram_save_release_protection: release UFFD write protection after
1456 * a range of pages has been saved
1457 *
1458 * @rs: current RAM state
1459 * @pss: page-search-status structure
1460 * @start_page: index of the first page in the range relative to pss->block
1461 *
1462 * Returns 0 on success, negative value in case of an error
1463*/
1464static int ram_save_release_protection(RAMState *rs, PageSearchStatus *pss,
1465 unsigned long start_page)
1466{
1467 int res = 0;
1468
1469 /* Check if page is from UFFD-managed region. */
1470 if (pss->block->flags & RAM_UF_WRITEPROTECT) {
1471 void *page_address = pss->block->host + (start_page << TARGET_PAGE_BITS);
1472 uint64_t run_length = (pss->page - start_page + 1) << TARGET_PAGE_BITS;
1473
1474 /* Flush async buffers before un-protect. */
1475 qemu_fflush(rs->f);
1476 /* Un-protect memory range. */
1477 res = uffd_change_protection(rs->uffdio_fd, page_address, run_length,
1478 false, false);
1479 }
1480
1481 return res;
1482}
1483
1484/* ram_write_tracking_available: check if kernel supports required UFFD features
1485 *
1486 * Returns true if supports, false otherwise
1487 */
1488bool ram_write_tracking_available(void)
1489{
1490 uint64_t uffd_features;
1491 int res;
1492
1493 res = uffd_query_features(&uffd_features);
1494 return (res == 0 &&
1495 (uffd_features & UFFD_FEATURE_PAGEFAULT_FLAG_WP) != 0);
1496}
1497
1498/* ram_write_tracking_compatible: check if guest configuration is
1499 * compatible with 'write-tracking'
1500 *
1501 * Returns true if compatible, false otherwise
1502 */
1503bool ram_write_tracking_compatible(void)
1504{
1505 const uint64_t uffd_ioctls_mask = BIT(_UFFDIO_WRITEPROTECT);
1506 int uffd_fd;
82ea3e3b 1507 RAMBlock *block;
278e2f55
AG
1508 bool ret = false;
1509
1510 /* Open UFFD file descriptor */
1511 uffd_fd = uffd_create_fd(UFFD_FEATURE_PAGEFAULT_FLAG_WP, false);
1512 if (uffd_fd < 0) {
1513 return false;
1514 }
1515
1516 RCU_READ_LOCK_GUARD();
1517
82ea3e3b 1518 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
278e2f55
AG
1519 uint64_t uffd_ioctls;
1520
1521 /* Nothing to do with read-only and MMIO-writable regions */
82ea3e3b 1522 if (block->mr->readonly || block->mr->rom_device) {
278e2f55
AG
1523 continue;
1524 }
1525 /* Try to register block memory via UFFD-IO to track writes */
82ea3e3b 1526 if (uffd_register_memory(uffd_fd, block->host, block->max_length,
278e2f55
AG
1527 UFFDIO_REGISTER_MODE_WP, &uffd_ioctls)) {
1528 goto out;
1529 }
1530 if ((uffd_ioctls & uffd_ioctls_mask) != uffd_ioctls_mask) {
1531 goto out;
1532 }
1533 }
1534 ret = true;
1535
1536out:
1537 uffd_close_fd(uffd_fd);
1538 return ret;
1539}
1540
eeccb99c
AG
1541/*
1542 * ram_block_populate_pages: populate memory in the RAM block by reading
1543 * an integer from the beginning of each page.
1544 *
1545 * Since it's solely used for userfault_fd WP feature, here we just
1546 * hardcode page size to qemu_real_host_page_size.
1547 *
82ea3e3b 1548 * @block: RAM block to populate
eeccb99c 1549 */
82ea3e3b 1550static void ram_block_populate_pages(RAMBlock *block)
eeccb99c 1551{
82ea3e3b 1552 char *ptr = (char *) block->host;
eeccb99c 1553
82ea3e3b 1554 for (ram_addr_t offset = 0; offset < block->used_length;
eeccb99c
AG
1555 offset += qemu_real_host_page_size) {
1556 char tmp = *(ptr + offset);
1557
1558 /* Don't optimize the read out */
1559 asm volatile("" : "+r" (tmp));
1560 }
1561}
1562
1563/*
1564 * ram_write_tracking_prepare: prepare for UFFD-WP memory tracking
1565 */
1566void ram_write_tracking_prepare(void)
1567{
82ea3e3b 1568 RAMBlock *block;
eeccb99c
AG
1569
1570 RCU_READ_LOCK_GUARD();
1571
82ea3e3b 1572 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
eeccb99c 1573 /* Nothing to do with read-only and MMIO-writable regions */
82ea3e3b 1574 if (block->mr->readonly || block->mr->rom_device) {
eeccb99c
AG
1575 continue;
1576 }
1577
1578 /*
1579 * Populate pages of the RAM block before enabling userfault_fd
1580 * write protection.
1581 *
1582 * This stage is required since ioctl(UFFDIO_WRITEPROTECT) with
1583 * UFFDIO_WRITEPROTECT_MODE_WP mode setting would silently skip
1584 * pages with pte_none() entries in page table.
1585 */
82ea3e3b 1586 ram_block_populate_pages(block);
eeccb99c
AG
1587 }
1588}
1589
278e2f55
AG
1590/*
1591 * ram_write_tracking_start: start UFFD-WP memory tracking
1592 *
1593 * Returns 0 for success or negative value in case of error
1594 */
1595int ram_write_tracking_start(void)
1596{
1597 int uffd_fd;
1598 RAMState *rs = ram_state;
82ea3e3b 1599 RAMBlock *block;
278e2f55
AG
1600
1601 /* Open UFFD file descriptor */
1602 uffd_fd = uffd_create_fd(UFFD_FEATURE_PAGEFAULT_FLAG_WP, true);
1603 if (uffd_fd < 0) {
1604 return uffd_fd;
1605 }
1606 rs->uffdio_fd = uffd_fd;
1607
1608 RCU_READ_LOCK_GUARD();
1609
82ea3e3b 1610 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
278e2f55 1611 /* Nothing to do with read-only and MMIO-writable regions */
82ea3e3b 1612 if (block->mr->readonly || block->mr->rom_device) {
278e2f55
AG
1613 continue;
1614 }
1615
1616 /* Register block memory with UFFD to track writes */
82ea3e3b
AG
1617 if (uffd_register_memory(rs->uffdio_fd, block->host,
1618 block->max_length, UFFDIO_REGISTER_MODE_WP, NULL)) {
278e2f55
AG
1619 goto fail;
1620 }
1621 /* Apply UFFD write protection to the block memory range */
82ea3e3b
AG
1622 if (uffd_change_protection(rs->uffdio_fd, block->host,
1623 block->max_length, true, false)) {
278e2f55
AG
1624 goto fail;
1625 }
82ea3e3b
AG
1626 block->flags |= RAM_UF_WRITEPROTECT;
1627 memory_region_ref(block->mr);
278e2f55 1628
82ea3e3b
AG
1629 trace_ram_write_tracking_ramblock_start(block->idstr, block->page_size,
1630 block->host, block->max_length);
278e2f55
AG
1631 }
1632
1633 return 0;
1634
1635fail:
1636 error_report("ram_write_tracking_start() failed: restoring initial memory state");
1637
82ea3e3b
AG
1638 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
1639 if ((block->flags & RAM_UF_WRITEPROTECT) == 0) {
278e2f55
AG
1640 continue;
1641 }
1642 /*
1643 * In case some memory block failed to be write-protected
1644 * remove protection and unregister all succeeded RAM blocks
1645 */
82ea3e3b
AG
1646 uffd_change_protection(rs->uffdio_fd, block->host, block->max_length,
1647 false, false);
1648 uffd_unregister_memory(rs->uffdio_fd, block->host, block->max_length);
278e2f55 1649 /* Cleanup flags and remove reference */
82ea3e3b
AG
1650 block->flags &= ~RAM_UF_WRITEPROTECT;
1651 memory_region_unref(block->mr);
278e2f55
AG
1652 }
1653
1654 uffd_close_fd(uffd_fd);
1655 rs->uffdio_fd = -1;
1656 return -1;
1657}
1658
1659/**
1660 * ram_write_tracking_stop: stop UFFD-WP memory tracking and remove protection
1661 */
1662void ram_write_tracking_stop(void)
1663{
1664 RAMState *rs = ram_state;
82ea3e3b 1665 RAMBlock *block;
278e2f55
AG
1666
1667 RCU_READ_LOCK_GUARD();
1668
82ea3e3b
AG
1669 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
1670 if ((block->flags & RAM_UF_WRITEPROTECT) == 0) {
278e2f55
AG
1671 continue;
1672 }
1673 /* Remove protection and unregister all affected RAM blocks */
82ea3e3b
AG
1674 uffd_change_protection(rs->uffdio_fd, block->host, block->max_length,
1675 false, false);
1676 uffd_unregister_memory(rs->uffdio_fd, block->host, block->max_length);
278e2f55 1677
82ea3e3b
AG
1678 trace_ram_write_tracking_ramblock_stop(block->idstr, block->page_size,
1679 block->host, block->max_length);
278e2f55
AG
1680
1681 /* Cleanup flags and remove reference */
82ea3e3b
AG
1682 block->flags &= ~RAM_UF_WRITEPROTECT;
1683 memory_region_unref(block->mr);
278e2f55
AG
1684 }
1685
1686 /* Finally close UFFD file descriptor */
1687 uffd_close_fd(rs->uffdio_fd);
1688 rs->uffdio_fd = -1;
1689}
1690
1691#else
1692/* No target OS support, stubs just fail or ignore */
1693
1694static RAMBlock *poll_fault_page(RAMState *rs, ram_addr_t *offset)
1695{
1696 (void) rs;
1697 (void) offset;
1698
1699 return NULL;
1700}
1701
1702static int ram_save_release_protection(RAMState *rs, PageSearchStatus *pss,
1703 unsigned long start_page)
1704{
1705 (void) rs;
1706 (void) pss;
1707 (void) start_page;
1708
1709 return 0;
1710}
1711
1712bool ram_write_tracking_available(void)
1713{
1714 return false;
1715}
1716
1717bool ram_write_tracking_compatible(void)
1718{
1719 assert(0);
1720 return false;
1721}
1722
1723int ram_write_tracking_start(void)
1724{
1725 assert(0);
1726 return -1;
1727}
1728
1729void ram_write_tracking_stop(void)
1730{
1731 assert(0);
1732}
1733#endif /* defined(__linux__) */
1734
3d0684b2 1735/**
ff1543af 1736 * get_queued_page: unqueue a page from the postcopy requests
3d0684b2
JQ
1737 *
1738 * Skips pages that are already sent (!dirty)
a82d593b 1739 *
a5f7b1a6 1740 * Returns true if a queued page is found
a82d593b 1741 *
6f37bb8b 1742 * @rs: current RAM state
3d0684b2 1743 * @pss: data about the state of the current dirty page scan
a82d593b 1744 */
f20e2865 1745static bool get_queued_page(RAMState *rs, PageSearchStatus *pss)
a82d593b
DDAG
1746{
1747 RAMBlock *block;
1748 ram_addr_t offset;
1749 bool dirty;
1750
1751 do {
f20e2865 1752 block = unqueue_page(rs, &offset);
a82d593b
DDAG
1753 /*
1754 * We're sending this page, and since it's postcopy nothing else
1755 * will dirty it, and we must make sure it doesn't get sent again
1756 * even if this queue request was received after the background
1757 * search already sent it.
1758 */
1759 if (block) {
f20e2865
JQ
1760 unsigned long page;
1761
6b6712ef
JQ
1762 page = offset >> TARGET_PAGE_BITS;
1763 dirty = test_bit(page, block->bmap);
a82d593b 1764 if (!dirty) {
06b10688 1765 trace_get_queued_page_not_dirty(block->idstr, (uint64_t)offset,
64737606 1766 page);
a82d593b 1767 } else {
f20e2865 1768 trace_get_queued_page(block->idstr, (uint64_t)offset, page);
a82d593b
DDAG
1769 }
1770 }
1771
1772 } while (block && !dirty);
1773
278e2f55
AG
1774 if (!block) {
1775 /*
1776 * Poll write faults too if background snapshot is enabled; that's
1777 * when we have vcpus got blocked by the write protected pages.
1778 */
1779 block = poll_fault_page(rs, &offset);
1780 }
1781
a82d593b 1782 if (block) {
a82d593b
DDAG
1783 /*
1784 * We want the background search to continue from the queued page
1785 * since the guest is likely to want other pages near to the page
1786 * it just requested.
1787 */
1788 pss->block = block;
a935e30f 1789 pss->page = offset >> TARGET_PAGE_BITS;
422314e7
WY
1790
1791 /*
1792 * This unqueued page would break the "one round" check, even is
1793 * really rare.
1794 */
1795 pss->complete_round = false;
a82d593b
DDAG
1796 }
1797
1798 return !!block;
1799}
1800
6c595cde 1801/**
5e58f968
JQ
1802 * migration_page_queue_free: drop any remaining pages in the ram
1803 * request queue
6c595cde 1804 *
3d0684b2
JQ
1805 * It should be empty at the end anyway, but in error cases there may
1806 * be some left. in case that there is any page left, we drop it.
1807 *
6c595cde 1808 */
83c13382 1809static void migration_page_queue_free(RAMState *rs)
6c595cde 1810{
ec481c6c 1811 struct RAMSrcPageRequest *mspr, *next_mspr;
6c595cde
DDAG
1812 /* This queue generally should be empty - but in the case of a failed
1813 * migration might have some droppings in.
1814 */
89ac5a1d 1815 RCU_READ_LOCK_GUARD();
ec481c6c 1816 QSIMPLEQ_FOREACH_SAFE(mspr, &rs->src_page_requests, next_req, next_mspr) {
6c595cde 1817 memory_region_unref(mspr->rb->mr);
ec481c6c 1818 QSIMPLEQ_REMOVE_HEAD(&rs->src_page_requests, next_req);
6c595cde
DDAG
1819 g_free(mspr);
1820 }
6c595cde
DDAG
1821}
1822
1823/**
3d0684b2
JQ
1824 * ram_save_queue_pages: queue the page for transmission
1825 *
1826 * A request from postcopy destination for example.
1827 *
1828 * Returns zero on success or negative on error
1829 *
3d0684b2
JQ
1830 * @rbname: Name of the RAMBLock of the request. NULL means the
1831 * same that last one.
1832 * @start: starting address from the start of the RAMBlock
1833 * @len: length (in bytes) to send
6c595cde 1834 */
96506894 1835int ram_save_queue_pages(const char *rbname, ram_addr_t start, ram_addr_t len)
6c595cde
DDAG
1836{
1837 RAMBlock *ramblock;
53518d94 1838 RAMState *rs = ram_state;
6c595cde 1839
9360447d 1840 ram_counters.postcopy_requests++;
89ac5a1d
DDAG
1841 RCU_READ_LOCK_GUARD();
1842
6c595cde
DDAG
1843 if (!rbname) {
1844 /* Reuse last RAMBlock */
68a098f3 1845 ramblock = rs->last_req_rb;
6c595cde
DDAG
1846
1847 if (!ramblock) {
1848 /*
1849 * Shouldn't happen, we can't reuse the last RAMBlock if
1850 * it's the 1st request.
1851 */
1852 error_report("ram_save_queue_pages no previous block");
03acb4e9 1853 return -1;
6c595cde
DDAG
1854 }
1855 } else {
1856 ramblock = qemu_ram_block_by_name(rbname);
1857
1858 if (!ramblock) {
1859 /* We shouldn't be asked for a non-existent RAMBlock */
1860 error_report("ram_save_queue_pages no block '%s'", rbname);
03acb4e9 1861 return -1;
6c595cde 1862 }
68a098f3 1863 rs->last_req_rb = ramblock;
6c595cde
DDAG
1864 }
1865 trace_ram_save_queue_pages(ramblock->idstr, start, len);
395cb450 1866 if (start + len > ramblock->used_length) {
9458ad6b
JQ
1867 error_report("%s request overrun start=" RAM_ADDR_FMT " len="
1868 RAM_ADDR_FMT " blocklen=" RAM_ADDR_FMT,
6c595cde 1869 __func__, start, len, ramblock->used_length);
03acb4e9 1870 return -1;
6c595cde
DDAG
1871 }
1872
ec481c6c
JQ
1873 struct RAMSrcPageRequest *new_entry =
1874 g_malloc0(sizeof(struct RAMSrcPageRequest));
6c595cde
DDAG
1875 new_entry->rb = ramblock;
1876 new_entry->offset = start;
1877 new_entry->len = len;
1878
1879 memory_region_ref(ramblock->mr);
ec481c6c
JQ
1880 qemu_mutex_lock(&rs->src_page_req_mutex);
1881 QSIMPLEQ_INSERT_TAIL(&rs->src_page_requests, new_entry, next_req);
e03a34f8 1882 migration_make_urgent_request();
ec481c6c 1883 qemu_mutex_unlock(&rs->src_page_req_mutex);
6c595cde
DDAG
1884
1885 return 0;
6c595cde
DDAG
1886}
1887
d7400a34
XG
1888static bool save_page_use_compression(RAMState *rs)
1889{
1890 if (!migrate_use_compression()) {
1891 return false;
1892 }
1893
1894 /*
1a373522
DH
1895 * If xbzrle is enabled (e.g., after first round of migration), stop
1896 * using the data compression. In theory, xbzrle can do better than
1897 * compression.
d7400a34 1898 */
1a373522
DH
1899 if (rs->xbzrle_enabled) {
1900 return false;
d7400a34
XG
1901 }
1902
1a373522 1903 return true;
d7400a34
XG
1904}
1905
5e5fdcff
XG
1906/*
1907 * try to compress the page before posting it out, return true if the page
1908 * has been properly handled by compression, otherwise needs other
1909 * paths to handle it
1910 */
1911static bool save_compress_page(RAMState *rs, RAMBlock *block, ram_addr_t offset)
1912{
1913 if (!save_page_use_compression(rs)) {
1914 return false;
1915 }
1916
1917 /*
1918 * When starting the process of a new block, the first page of
1919 * the block should be sent out before other pages in the same
1920 * block, and all the pages in last block should have been sent
1921 * out, keeping this order is important, because the 'cont' flag
1922 * is used to avoid resending the block name.
1923 *
1924 * We post the fist page as normal page as compression will take
1925 * much CPU resource.
1926 */
1927 if (block != rs->last_sent_block) {
1928 flush_compressed_data(rs);
1929 return false;
1930 }
1931
1932 if (compress_page_with_multi_thread(rs, block, offset) > 0) {
1933 return true;
1934 }
1935
76e03000 1936 compression_counters.busy++;
5e5fdcff
XG
1937 return false;
1938}
1939
a82d593b 1940/**
3d0684b2 1941 * ram_save_target_page: save one target page
a82d593b 1942 *
3d0684b2 1943 * Returns the number of pages written
a82d593b 1944 *
6f37bb8b 1945 * @rs: current RAM state
3d0684b2 1946 * @pss: data about the page we want to send
a82d593b 1947 * @last_stage: if we are at the completion stage
a82d593b 1948 */
a0a8aa14 1949static int ram_save_target_page(RAMState *rs, PageSearchStatus *pss,
f20e2865 1950 bool last_stage)
a82d593b 1951{
a8ec91f9 1952 RAMBlock *block = pss->block;
8bba004c 1953 ram_addr_t offset = ((ram_addr_t)pss->page) << TARGET_PAGE_BITS;
a8ec91f9
XG
1954 int res;
1955
1956 if (control_save_page(rs, block, offset, &res)) {
1957 return res;
1958 }
1959
5e5fdcff
XG
1960 if (save_compress_page(rs, block, offset)) {
1961 return 1;
d7400a34
XG
1962 }
1963
1964 res = save_zero_page(rs, block, offset);
1965 if (res > 0) {
1966 /* Must let xbzrle know, otherwise a previous (now 0'd) cached
1967 * page would be stale
1968 */
1969 if (!save_page_use_compression(rs)) {
1970 XBZRLE_cache_lock();
1971 xbzrle_cache_zero_page(rs, block->offset + offset);
1972 XBZRLE_cache_unlock();
1973 }
1974 ram_release_pages(block->idstr, offset, res);
1975 return res;
1976 }
1977
da3f56cb 1978 /*
c6b3a2e0
WY
1979 * Do not use multifd for:
1980 * 1. Compression as the first page in the new block should be posted out
1981 * before sending the compressed page
1982 * 2. In postcopy as one whole host page should be placed
da3f56cb 1983 */
c6b3a2e0
WY
1984 if (!save_page_use_compression(rs) && migrate_use_multifd()
1985 && !migration_in_postcopy()) {
b9ee2f7d 1986 return ram_save_multifd_page(rs, block, offset);
a82d593b
DDAG
1987 }
1988
1faa5665 1989 return ram_save_page(rs, pss, last_stage);
a82d593b
DDAG
1990}
1991
1992/**
3d0684b2 1993 * ram_save_host_page: save a whole host page
a82d593b 1994 *
3d0684b2
JQ
1995 * Starting at *offset send pages up to the end of the current host
1996 * page. It's valid for the initial offset to point into the middle of
1997 * a host page in which case the remainder of the hostpage is sent.
1998 * Only dirty target pages are sent. Note that the host page size may
1999 * be a huge page for this block.
1eb3fc0a
DDAG
2000 * The saving stops at the boundary of the used_length of the block
2001 * if the RAMBlock isn't a multiple of the host page size.
a82d593b 2002 *
3d0684b2
JQ
2003 * Returns the number of pages written or negative on error
2004 *
6f37bb8b 2005 * @rs: current RAM state
3d0684b2 2006 * @ms: current migration state
3d0684b2 2007 * @pss: data about the page we want to send
a82d593b 2008 * @last_stage: if we are at the completion stage
a82d593b 2009 */
a0a8aa14 2010static int ram_save_host_page(RAMState *rs, PageSearchStatus *pss,
f20e2865 2011 bool last_stage)
a82d593b
DDAG
2012{
2013 int tmppages, pages = 0;
a935e30f
JQ
2014 size_t pagesize_bits =
2015 qemu_ram_pagesize(pss->block) >> TARGET_PAGE_BITS;
278e2f55
AG
2016 unsigned long start_page = pss->page;
2017 int res;
4c011c37 2018
fbd162e6 2019 if (ramblock_is_ignored(pss->block)) {
b895de50
CLG
2020 error_report("block %s should not be migrated !", pss->block->idstr);
2021 return 0;
2022 }
2023
a82d593b 2024 do {
1faa5665
XG
2025 /* Check the pages is dirty and if it is send it */
2026 if (!migration_bitmap_clear_dirty(rs, pss->block, pss->page)) {
2027 pss->page++;
2028 continue;
2029 }
2030
f20e2865 2031 tmppages = ram_save_target_page(rs, pss, last_stage);
a82d593b
DDAG
2032 if (tmppages < 0) {
2033 return tmppages;
2034 }
2035
2036 pages += tmppages;
a935e30f 2037 pss->page++;
23feba90
KJ
2038 /*
2039 * Allow rate limiting to happen in the middle of huge pages if
2040 * something is sent in the current iteration.
2041 */
2042 if (pagesize_bits > 1 && tmppages > 0) {
2043 migration_rate_limit();
2044 }
1eb3fc0a 2045 } while ((pss->page & (pagesize_bits - 1)) &&
8bba004c
AR
2046 offset_in_ramblock(pss->block,
2047 ((ram_addr_t)pss->page) << TARGET_PAGE_BITS));
a82d593b 2048 /* The offset we leave with is the last one we looked at */
a935e30f 2049 pss->page--;
278e2f55
AG
2050
2051 res = ram_save_release_protection(rs, pss, start_page);
2052 return (res < 0 ? res : pages);
a82d593b 2053}
6c595cde 2054
56e93d26 2055/**
3d0684b2 2056 * ram_find_and_save_block: finds a dirty page and sends it to f
56e93d26
JQ
2057 *
2058 * Called within an RCU critical section.
2059 *
e8f3735f
XG
2060 * Returns the number of pages written where zero means no dirty pages,
2061 * or negative on error
56e93d26 2062 *
6f37bb8b 2063 * @rs: current RAM state
56e93d26 2064 * @last_stage: if we are at the completion stage
a82d593b
DDAG
2065 *
2066 * On systems where host-page-size > target-page-size it will send all the
2067 * pages in a host page that are dirty.
56e93d26
JQ
2068 */
2069
ce25d337 2070static int ram_find_and_save_block(RAMState *rs, bool last_stage)
56e93d26 2071{
b8fb8cb7 2072 PageSearchStatus pss;
56e93d26 2073 int pages = 0;
b9e60928 2074 bool again, found;
56e93d26 2075
0827b9e9
AA
2076 /* No dirty page as there is zero RAM */
2077 if (!ram_bytes_total()) {
2078 return pages;
2079 }
2080
6f37bb8b 2081 pss.block = rs->last_seen_block;
a935e30f 2082 pss.page = rs->last_page;
b8fb8cb7
DDAG
2083 pss.complete_round = false;
2084
2085 if (!pss.block) {
2086 pss.block = QLIST_FIRST_RCU(&ram_list.blocks);
2087 }
56e93d26 2088
b9e60928 2089 do {
a82d593b 2090 again = true;
f20e2865 2091 found = get_queued_page(rs, &pss);
b9e60928 2092
a82d593b
DDAG
2093 if (!found) {
2094 /* priority queue empty, so just search for something dirty */
f20e2865 2095 found = find_dirty_block(rs, &pss, &again);
a82d593b 2096 }
f3f491fc 2097
a82d593b 2098 if (found) {
f20e2865 2099 pages = ram_save_host_page(rs, &pss, last_stage);
56e93d26 2100 }
b9e60928 2101 } while (!pages && again);
56e93d26 2102
6f37bb8b 2103 rs->last_seen_block = pss.block;
a935e30f 2104 rs->last_page = pss.page;
56e93d26
JQ
2105
2106 return pages;
2107}
2108
2109void acct_update_position(QEMUFile *f, size_t size, bool zero)
2110{
2111 uint64_t pages = size / TARGET_PAGE_SIZE;
f7ccd61b 2112
56e93d26 2113 if (zero) {
9360447d 2114 ram_counters.duplicate += pages;
56e93d26 2115 } else {
9360447d
JQ
2116 ram_counters.normal += pages;
2117 ram_counters.transferred += size;
56e93d26
JQ
2118 qemu_update_position(f, size);
2119 }
2120}
2121
fbd162e6 2122static uint64_t ram_bytes_total_common(bool count_ignored)
56e93d26
JQ
2123{
2124 RAMBlock *block;
2125 uint64_t total = 0;
2126
89ac5a1d
DDAG
2127 RCU_READ_LOCK_GUARD();
2128
fbd162e6
YK
2129 if (count_ignored) {
2130 RAMBLOCK_FOREACH_MIGRATABLE(block) {
2131 total += block->used_length;
2132 }
2133 } else {
2134 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
2135 total += block->used_length;
2136 }
99e15582 2137 }
56e93d26
JQ
2138 return total;
2139}
2140
fbd162e6
YK
2141uint64_t ram_bytes_total(void)
2142{
2143 return ram_bytes_total_common(false);
2144}
2145
f265e0e4 2146static void xbzrle_load_setup(void)
56e93d26 2147{
f265e0e4 2148 XBZRLE.decoded_buf = g_malloc(TARGET_PAGE_SIZE);
56e93d26
JQ
2149}
2150
f265e0e4
JQ
2151static void xbzrle_load_cleanup(void)
2152{
2153 g_free(XBZRLE.decoded_buf);
2154 XBZRLE.decoded_buf = NULL;
2155}
2156
7d7c96be
PX
2157static void ram_state_cleanup(RAMState **rsp)
2158{
b9ccaf6d
DDAG
2159 if (*rsp) {
2160 migration_page_queue_free(*rsp);
2161 qemu_mutex_destroy(&(*rsp)->bitmap_mutex);
2162 qemu_mutex_destroy(&(*rsp)->src_page_req_mutex);
2163 g_free(*rsp);
2164 *rsp = NULL;
2165 }
7d7c96be
PX
2166}
2167
84593a08
PX
2168static void xbzrle_cleanup(void)
2169{
2170 XBZRLE_cache_lock();
2171 if (XBZRLE.cache) {
2172 cache_fini(XBZRLE.cache);
2173 g_free(XBZRLE.encoded_buf);
2174 g_free(XBZRLE.current_buf);
2175 g_free(XBZRLE.zero_target_page);
2176 XBZRLE.cache = NULL;
2177 XBZRLE.encoded_buf = NULL;
2178 XBZRLE.current_buf = NULL;
2179 XBZRLE.zero_target_page = NULL;
2180 }
2181 XBZRLE_cache_unlock();
2182}
2183
f265e0e4 2184static void ram_save_cleanup(void *opaque)
56e93d26 2185{
53518d94 2186 RAMState **rsp = opaque;
6b6712ef 2187 RAMBlock *block;
eb859c53 2188
278e2f55
AG
2189 /* We don't use dirty log with background snapshots */
2190 if (!migrate_background_snapshot()) {
2191 /* caller have hold iothread lock or is in a bh, so there is
2192 * no writing race against the migration bitmap
2193 */
2194 memory_global_dirty_log_stop();
2195 }
6b6712ef 2196
fbd162e6 2197 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
002cad6b
PX
2198 g_free(block->clear_bmap);
2199 block->clear_bmap = NULL;
6b6712ef
JQ
2200 g_free(block->bmap);
2201 block->bmap = NULL;
56e93d26
JQ
2202 }
2203
84593a08 2204 xbzrle_cleanup();
f0afa331 2205 compress_threads_save_cleanup();
7d7c96be 2206 ram_state_cleanup(rsp);
56e93d26
JQ
2207}
2208
6f37bb8b 2209static void ram_state_reset(RAMState *rs)
56e93d26 2210{
6f37bb8b
JQ
2211 rs->last_seen_block = NULL;
2212 rs->last_sent_block = NULL;
269ace29 2213 rs->last_page = 0;
6f37bb8b 2214 rs->last_version = ram_list.version;
1a373522 2215 rs->xbzrle_enabled = false;
56e93d26
JQ
2216}
2217
2218#define MAX_WAIT 50 /* ms, half buffered_file limit */
2219
4f2e4252
DDAG
2220/*
2221 * 'expected' is the value you expect the bitmap mostly to be full
2222 * of; it won't bother printing lines that are all this value.
2223 * If 'todump' is null the migration bitmap is dumped.
2224 */
6b6712ef
JQ
2225void ram_debug_dump_bitmap(unsigned long *todump, bool expected,
2226 unsigned long pages)
4f2e4252 2227{
4f2e4252
DDAG
2228 int64_t cur;
2229 int64_t linelen = 128;
2230 char linebuf[129];
2231
6b6712ef 2232 for (cur = 0; cur < pages; cur += linelen) {
4f2e4252
DDAG
2233 int64_t curb;
2234 bool found = false;
2235 /*
2236 * Last line; catch the case where the line length
2237 * is longer than remaining ram
2238 */
6b6712ef
JQ
2239 if (cur + linelen > pages) {
2240 linelen = pages - cur;
4f2e4252
DDAG
2241 }
2242 for (curb = 0; curb < linelen; curb++) {
2243 bool thisbit = test_bit(cur + curb, todump);
2244 linebuf[curb] = thisbit ? '1' : '.';
2245 found = found || (thisbit != expected);
2246 }
2247 if (found) {
2248 linebuf[curb] = '\0';
2249 fprintf(stderr, "0x%08" PRIx64 " : %s\n", cur, linebuf);
2250 }
2251 }
2252}
2253
e0b266f0
DDAG
2254/* **** functions for postcopy ***** */
2255
ced1c616
PB
2256void ram_postcopy_migrated_memory_release(MigrationState *ms)
2257{
2258 struct RAMBlock *block;
ced1c616 2259
fbd162e6 2260 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
6b6712ef
JQ
2261 unsigned long *bitmap = block->bmap;
2262 unsigned long range = block->used_length >> TARGET_PAGE_BITS;
2263 unsigned long run_start = find_next_zero_bit(bitmap, range, 0);
ced1c616
PB
2264
2265 while (run_start < range) {
2266 unsigned long run_end = find_next_bit(bitmap, range, run_start + 1);
8bba004c
AR
2267 ram_discard_range(block->idstr,
2268 ((ram_addr_t)run_start) << TARGET_PAGE_BITS,
2269 ((ram_addr_t)(run_end - run_start))
2270 << TARGET_PAGE_BITS);
ced1c616
PB
2271 run_start = find_next_zero_bit(bitmap, range, run_end + 1);
2272 }
2273 }
2274}
2275
3d0684b2
JQ
2276/**
2277 * postcopy_send_discard_bm_ram: discard a RAMBlock
2278 *
2279 * Returns zero on success
2280 *
e0b266f0 2281 * Callback from postcopy_each_ram_send_discard for each RAMBlock
3d0684b2
JQ
2282 *
2283 * @ms: current migration state
89dab31b 2284 * @block: RAMBlock to discard
e0b266f0 2285 */
810cf2bb 2286static int postcopy_send_discard_bm_ram(MigrationState *ms, RAMBlock *block)
e0b266f0 2287{
6b6712ef 2288 unsigned long end = block->used_length >> TARGET_PAGE_BITS;
e0b266f0 2289 unsigned long current;
1e7cf8c3 2290 unsigned long *bitmap = block->bmap;
e0b266f0 2291
6b6712ef 2292 for (current = 0; current < end; ) {
1e7cf8c3 2293 unsigned long one = find_next_bit(bitmap, end, current);
33a5cb62 2294 unsigned long zero, discard_length;
e0b266f0 2295
33a5cb62
WY
2296 if (one >= end) {
2297 break;
2298 }
e0b266f0 2299
1e7cf8c3 2300 zero = find_next_zero_bit(bitmap, end, one + 1);
33a5cb62
WY
2301
2302 if (zero >= end) {
2303 discard_length = end - one;
e0b266f0 2304 } else {
33a5cb62
WY
2305 discard_length = zero - one;
2306 }
810cf2bb 2307 postcopy_discard_send_range(ms, one, discard_length);
33a5cb62 2308 current = one + discard_length;
e0b266f0
DDAG
2309 }
2310
2311 return 0;
2312}
2313
3d0684b2
JQ
2314/**
2315 * postcopy_each_ram_send_discard: discard all RAMBlocks
2316 *
2317 * Returns 0 for success or negative for error
2318 *
e0b266f0
DDAG
2319 * Utility for the outgoing postcopy code.
2320 * Calls postcopy_send_discard_bm_ram for each RAMBlock
2321 * passing it bitmap indexes and name.
e0b266f0
DDAG
2322 * (qemu_ram_foreach_block ends up passing unscaled lengths
2323 * which would mean postcopy code would have to deal with target page)
3d0684b2
JQ
2324 *
2325 * @ms: current migration state
e0b266f0
DDAG
2326 */
2327static int postcopy_each_ram_send_discard(MigrationState *ms)
2328{
2329 struct RAMBlock *block;
2330 int ret;
2331
fbd162e6 2332 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
810cf2bb 2333 postcopy_discard_send_init(ms, block->idstr);
e0b266f0
DDAG
2334
2335 /*
2336 * Postcopy sends chunks of bitmap over the wire, but it
2337 * just needs indexes at this point, avoids it having
2338 * target page specific code.
2339 */
810cf2bb
WY
2340 ret = postcopy_send_discard_bm_ram(ms, block);
2341 postcopy_discard_send_finish(ms);
e0b266f0
DDAG
2342 if (ret) {
2343 return ret;
2344 }
2345 }
2346
2347 return 0;
2348}
2349
3d0684b2 2350/**
8324ef86 2351 * postcopy_chunk_hostpages_pass: canonicalize bitmap in hostpages
3d0684b2
JQ
2352 *
2353 * Helper for postcopy_chunk_hostpages; it's called twice to
2354 * canonicalize the two bitmaps, that are similar, but one is
2355 * inverted.
99e314eb 2356 *
3d0684b2
JQ
2357 * Postcopy requires that all target pages in a hostpage are dirty or
2358 * clean, not a mix. This function canonicalizes the bitmaps.
99e314eb 2359 *
3d0684b2 2360 * @ms: current migration state
3d0684b2 2361 * @block: block that contains the page we want to canonicalize
99e314eb 2362 */
1e7cf8c3 2363static void postcopy_chunk_hostpages_pass(MigrationState *ms, RAMBlock *block)
99e314eb 2364{
53518d94 2365 RAMState *rs = ram_state;
6b6712ef 2366 unsigned long *bitmap = block->bmap;
29c59172 2367 unsigned int host_ratio = block->page_size / TARGET_PAGE_SIZE;
6b6712ef 2368 unsigned long pages = block->used_length >> TARGET_PAGE_BITS;
99e314eb
DDAG
2369 unsigned long run_start;
2370
29c59172
DDAG
2371 if (block->page_size == TARGET_PAGE_SIZE) {
2372 /* Easy case - TPS==HPS for a non-huge page RAMBlock */
2373 return;
2374 }
2375
1e7cf8c3
WY
2376 /* Find a dirty page */
2377 run_start = find_next_bit(bitmap, pages, 0);
99e314eb 2378
6b6712ef 2379 while (run_start < pages) {
99e314eb
DDAG
2380
2381 /*
2382 * If the start of this run of pages is in the middle of a host
2383 * page, then we need to fixup this host page.
2384 */
9dec3cc3 2385 if (QEMU_IS_ALIGNED(run_start, host_ratio)) {
99e314eb 2386 /* Find the end of this run */
1e7cf8c3 2387 run_start = find_next_zero_bit(bitmap, pages, run_start + 1);
99e314eb
DDAG
2388 /*
2389 * If the end isn't at the start of a host page, then the
2390 * run doesn't finish at the end of a host page
2391 * and we need to discard.
2392 */
99e314eb
DDAG
2393 }
2394
9dec3cc3 2395 if (!QEMU_IS_ALIGNED(run_start, host_ratio)) {
99e314eb 2396 unsigned long page;
dad45ab2
WY
2397 unsigned long fixup_start_addr = QEMU_ALIGN_DOWN(run_start,
2398 host_ratio);
2399 run_start = QEMU_ALIGN_UP(run_start, host_ratio);
99e314eb 2400
99e314eb
DDAG
2401 /* Clean up the bitmap */
2402 for (page = fixup_start_addr;
2403 page < fixup_start_addr + host_ratio; page++) {
99e314eb
DDAG
2404 /*
2405 * Remark them as dirty, updating the count for any pages
2406 * that weren't previously dirty.
2407 */
0d8ec885 2408 rs->migration_dirty_pages += !test_and_set_bit(page, bitmap);
99e314eb
DDAG
2409 }
2410 }
2411
1e7cf8c3
WY
2412 /* Find the next dirty page for the next iteration */
2413 run_start = find_next_bit(bitmap, pages, run_start);
99e314eb
DDAG
2414 }
2415}
2416
3d0684b2 2417/**
89dab31b 2418 * postcopy_chunk_hostpages: discard any partially sent host page
3d0684b2 2419 *
99e314eb
DDAG
2420 * Utility for the outgoing postcopy code.
2421 *
2422 * Discard any partially sent host-page size chunks, mark any partially
29c59172
DDAG
2423 * dirty host-page size chunks as all dirty. In this case the host-page
2424 * is the host-page for the particular RAMBlock, i.e. it might be a huge page
99e314eb 2425 *
3d0684b2
JQ
2426 * Returns zero on success
2427 *
2428 * @ms: current migration state
6b6712ef 2429 * @block: block we want to work with
99e314eb 2430 */
6b6712ef 2431static int postcopy_chunk_hostpages(MigrationState *ms, RAMBlock *block)
99e314eb 2432{
810cf2bb 2433 postcopy_discard_send_init(ms, block->idstr);
99e314eb 2434
6b6712ef 2435 /*
1e7cf8c3 2436 * Ensure that all partially dirty host pages are made fully dirty.
6b6712ef 2437 */
1e7cf8c3 2438 postcopy_chunk_hostpages_pass(ms, block);
99e314eb 2439
810cf2bb 2440 postcopy_discard_send_finish(ms);
99e314eb
DDAG
2441 return 0;
2442}
2443
3d0684b2
JQ
2444/**
2445 * ram_postcopy_send_discard_bitmap: transmit the discard bitmap
2446 *
2447 * Returns zero on success
2448 *
e0b266f0
DDAG
2449 * Transmit the set of pages to be discarded after precopy to the target
2450 * these are pages that:
2451 * a) Have been previously transmitted but are now dirty again
2452 * b) Pages that have never been transmitted, this ensures that
2453 * any pages on the destination that have been mapped by background
2454 * tasks get discarded (transparent huge pages is the specific concern)
2455 * Hopefully this is pretty sparse
3d0684b2
JQ
2456 *
2457 * @ms: current migration state
e0b266f0
DDAG
2458 */
2459int ram_postcopy_send_discard_bitmap(MigrationState *ms)
2460{
53518d94 2461 RAMState *rs = ram_state;
6b6712ef 2462 RAMBlock *block;
e0b266f0 2463 int ret;
e0b266f0 2464
89ac5a1d 2465 RCU_READ_LOCK_GUARD();
e0b266f0
DDAG
2466
2467 /* This should be our last sync, the src is now paused */
eb859c53 2468 migration_bitmap_sync(rs);
e0b266f0 2469
6b6712ef
JQ
2470 /* Easiest way to make sure we don't resume in the middle of a host-page */
2471 rs->last_seen_block = NULL;
2472 rs->last_sent_block = NULL;
2473 rs->last_page = 0;
e0b266f0 2474
fbd162e6 2475 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
6b6712ef
JQ
2476 /* Deal with TPS != HPS and huge pages */
2477 ret = postcopy_chunk_hostpages(ms, block);
2478 if (ret) {
6b6712ef
JQ
2479 return ret;
2480 }
e0b266f0 2481
e0b266f0 2482#ifdef DEBUG_POSTCOPY
1e7cf8c3
WY
2483 ram_debug_dump_bitmap(block->bmap, true,
2484 block->used_length >> TARGET_PAGE_BITS);
e0b266f0 2485#endif
6b6712ef
JQ
2486 }
2487 trace_ram_postcopy_send_discard_bitmap();
e0b266f0 2488
b3ac2b94 2489 return postcopy_each_ram_send_discard(ms);
e0b266f0
DDAG
2490}
2491
3d0684b2
JQ
2492/**
2493 * ram_discard_range: discard dirtied pages at the beginning of postcopy
e0b266f0 2494 *
3d0684b2 2495 * Returns zero on success
e0b266f0 2496 *
36449157
JQ
2497 * @rbname: name of the RAMBlock of the request. NULL means the
2498 * same that last one.
3d0684b2
JQ
2499 * @start: RAMBlock starting page
2500 * @length: RAMBlock size
e0b266f0 2501 */
aaa2064c 2502int ram_discard_range(const char *rbname, uint64_t start, size_t length)
e0b266f0 2503{
36449157 2504 trace_ram_discard_range(rbname, start, length);
d3a5038c 2505
89ac5a1d 2506 RCU_READ_LOCK_GUARD();
36449157 2507 RAMBlock *rb = qemu_ram_block_by_name(rbname);
e0b266f0
DDAG
2508
2509 if (!rb) {
36449157 2510 error_report("ram_discard_range: Failed to find block '%s'", rbname);
03acb4e9 2511 return -1;
e0b266f0
DDAG
2512 }
2513
814bb08f
PX
2514 /*
2515 * On source VM, we don't need to update the received bitmap since
2516 * we don't even have one.
2517 */
2518 if (rb->receivedmap) {
2519 bitmap_clear(rb->receivedmap, start >> qemu_target_page_bits(),
2520 length >> qemu_target_page_bits());
2521 }
2522
03acb4e9 2523 return ram_block_discard_range(rb, start, length);
e0b266f0
DDAG
2524}
2525
84593a08
PX
2526/*
2527 * For every allocation, we will try not to crash the VM if the
2528 * allocation failed.
2529 */
2530static int xbzrle_init(void)
2531{
2532 Error *local_err = NULL;
2533
2534 if (!migrate_use_xbzrle()) {
2535 return 0;
2536 }
2537
2538 XBZRLE_cache_lock();
2539
2540 XBZRLE.zero_target_page = g_try_malloc0(TARGET_PAGE_SIZE);
2541 if (!XBZRLE.zero_target_page) {
2542 error_report("%s: Error allocating zero page", __func__);
2543 goto err_out;
2544 }
2545
2546 XBZRLE.cache = cache_init(migrate_xbzrle_cache_size(),
2547 TARGET_PAGE_SIZE, &local_err);
2548 if (!XBZRLE.cache) {
2549 error_report_err(local_err);
2550 goto free_zero_page;
2551 }
2552
2553 XBZRLE.encoded_buf = g_try_malloc0(TARGET_PAGE_SIZE);
2554 if (!XBZRLE.encoded_buf) {
2555 error_report("%s: Error allocating encoded_buf", __func__);
2556 goto free_cache;
2557 }
2558
2559 XBZRLE.current_buf = g_try_malloc(TARGET_PAGE_SIZE);
2560 if (!XBZRLE.current_buf) {
2561 error_report("%s: Error allocating current_buf", __func__);
2562 goto free_encoded_buf;
2563 }
2564
2565 /* We are all good */
2566 XBZRLE_cache_unlock();
2567 return 0;
2568
2569free_encoded_buf:
2570 g_free(XBZRLE.encoded_buf);
2571 XBZRLE.encoded_buf = NULL;
2572free_cache:
2573 cache_fini(XBZRLE.cache);
2574 XBZRLE.cache = NULL;
2575free_zero_page:
2576 g_free(XBZRLE.zero_target_page);
2577 XBZRLE.zero_target_page = NULL;
2578err_out:
2579 XBZRLE_cache_unlock();
2580 return -ENOMEM;
2581}
2582
53518d94 2583static int ram_state_init(RAMState **rsp)
56e93d26 2584{
7d00ee6a
PX
2585 *rsp = g_try_new0(RAMState, 1);
2586
2587 if (!*rsp) {
2588 error_report("%s: Init ramstate fail", __func__);
2589 return -1;
2590 }
53518d94
JQ
2591
2592 qemu_mutex_init(&(*rsp)->bitmap_mutex);
2593 qemu_mutex_init(&(*rsp)->src_page_req_mutex);
2594 QSIMPLEQ_INIT(&(*rsp)->src_page_requests);
56e93d26 2595
7d00ee6a 2596 /*
40c4d4a8
IR
2597 * Count the total number of pages used by ram blocks not including any
2598 * gaps due to alignment or unplugs.
03158519 2599 * This must match with the initial values of dirty bitmap.
7d00ee6a 2600 */
40c4d4a8 2601 (*rsp)->migration_dirty_pages = ram_bytes_total() >> TARGET_PAGE_BITS;
7d00ee6a
PX
2602 ram_state_reset(*rsp);
2603
2604 return 0;
2605}
2606
d6eff5d7 2607static void ram_list_init_bitmaps(void)
7d00ee6a 2608{
002cad6b 2609 MigrationState *ms = migrate_get_current();
d6eff5d7
PX
2610 RAMBlock *block;
2611 unsigned long pages;
002cad6b 2612 uint8_t shift;
56e93d26 2613
0827b9e9
AA
2614 /* Skip setting bitmap if there is no RAM */
2615 if (ram_bytes_total()) {
002cad6b
PX
2616 shift = ms->clear_bitmap_shift;
2617 if (shift > CLEAR_BITMAP_SHIFT_MAX) {
2618 error_report("clear_bitmap_shift (%u) too big, using "
2619 "max value (%u)", shift, CLEAR_BITMAP_SHIFT_MAX);
2620 shift = CLEAR_BITMAP_SHIFT_MAX;
2621 } else if (shift < CLEAR_BITMAP_SHIFT_MIN) {
2622 error_report("clear_bitmap_shift (%u) too small, using "
2623 "min value (%u)", shift, CLEAR_BITMAP_SHIFT_MIN);
2624 shift = CLEAR_BITMAP_SHIFT_MIN;
2625 }
2626
fbd162e6 2627 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
d6eff5d7 2628 pages = block->max_length >> TARGET_PAGE_BITS;
03158519
WY
2629 /*
2630 * The initial dirty bitmap for migration must be set with all
2631 * ones to make sure we'll migrate every guest RAM page to
2632 * destination.
40c4d4a8
IR
2633 * Here we set RAMBlock.bmap all to 1 because when rebegin a
2634 * new migration after a failed migration, ram_list.
2635 * dirty_memory[DIRTY_MEMORY_MIGRATION] don't include the whole
2636 * guest memory.
03158519 2637 */
6b6712ef 2638 block->bmap = bitmap_new(pages);
40c4d4a8 2639 bitmap_set(block->bmap, 0, pages);
002cad6b
PX
2640 block->clear_bmap_shift = shift;
2641 block->clear_bmap = bitmap_new(clear_bmap_size(pages, shift));
0827b9e9 2642 }
f3f491fc 2643 }
d6eff5d7
PX
2644}
2645
2646static void ram_init_bitmaps(RAMState *rs)
2647{
2648 /* For memory_global_dirty_log_start below. */
2649 qemu_mutex_lock_iothread();
2650 qemu_mutex_lock_ramlist();
f3f491fc 2651
89ac5a1d
DDAG
2652 WITH_RCU_READ_LOCK_GUARD() {
2653 ram_list_init_bitmaps();
278e2f55
AG
2654 /* We don't use dirty log with background snapshots */
2655 if (!migrate_background_snapshot()) {
2656 memory_global_dirty_log_start();
2657 migration_bitmap_sync_precopy(rs);
2658 }
89ac5a1d 2659 }
56e93d26 2660 qemu_mutex_unlock_ramlist();
49877834 2661 qemu_mutex_unlock_iothread();
d6eff5d7
PX
2662}
2663
2664static int ram_init_all(RAMState **rsp)
2665{
2666 if (ram_state_init(rsp)) {
2667 return -1;
2668 }
2669
2670 if (xbzrle_init()) {
2671 ram_state_cleanup(rsp);
2672 return -1;
2673 }
2674
2675 ram_init_bitmaps(*rsp);
a91246c9
HZ
2676
2677 return 0;
2678}
2679
08614f34
PX
2680static void ram_state_resume_prepare(RAMState *rs, QEMUFile *out)
2681{
2682 RAMBlock *block;
2683 uint64_t pages = 0;
2684
2685 /*
2686 * Postcopy is not using xbzrle/compression, so no need for that.
2687 * Also, since source are already halted, we don't need to care
2688 * about dirty page logging as well.
2689 */
2690
fbd162e6 2691 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
08614f34
PX
2692 pages += bitmap_count_one(block->bmap,
2693 block->used_length >> TARGET_PAGE_BITS);
2694 }
2695
2696 /* This may not be aligned with current bitmaps. Recalculate. */
2697 rs->migration_dirty_pages = pages;
2698
1a373522 2699 ram_state_reset(rs);
08614f34
PX
2700
2701 /* Update RAMState cache of output QEMUFile */
2702 rs->f = out;
2703
2704 trace_ram_state_resume_prepare(pages);
2705}
2706
6bcb05fc
WW
2707/*
2708 * This function clears bits of the free pages reported by the caller from the
2709 * migration dirty bitmap. @addr is the host address corresponding to the
2710 * start of the continuous guest free pages, and @len is the total bytes of
2711 * those pages.
2712 */
2713void qemu_guest_free_page_hint(void *addr, size_t len)
2714{
2715 RAMBlock *block;
2716 ram_addr_t offset;
2717 size_t used_len, start, npages;
2718 MigrationState *s = migrate_get_current();
2719
2720 /* This function is currently expected to be used during live migration */
2721 if (!migration_is_setup_or_active(s->state)) {
2722 return;
2723 }
2724
2725 for (; len > 0; len -= used_len, addr += used_len) {
2726 block = qemu_ram_block_from_host(addr, false, &offset);
2727 if (unlikely(!block || offset >= block->used_length)) {
2728 /*
2729 * The implementation might not support RAMBlock resize during
2730 * live migration, but it could happen in theory with future
2731 * updates. So we add a check here to capture that case.
2732 */
2733 error_report_once("%s unexpected error", __func__);
2734 return;
2735 }
2736
2737 if (len <= block->used_length - offset) {
2738 used_len = len;
2739 } else {
2740 used_len = block->used_length - offset;
2741 }
2742
2743 start = offset >> TARGET_PAGE_BITS;
2744 npages = used_len >> TARGET_PAGE_BITS;
2745
2746 qemu_mutex_lock(&ram_state->bitmap_mutex);
2747 ram_state->migration_dirty_pages -=
2748 bitmap_count_one_with_offset(block->bmap, start, npages);
2749 bitmap_clear(block->bmap, start, npages);
2750 qemu_mutex_unlock(&ram_state->bitmap_mutex);
2751 }
2752}
2753
3d0684b2
JQ
2754/*
2755 * Each of ram_save_setup, ram_save_iterate and ram_save_complete has
a91246c9
HZ
2756 * long-running RCU critical section. When rcu-reclaims in the code
2757 * start to become numerous it will be necessary to reduce the
2758 * granularity of these critical sections.
2759 */
2760
3d0684b2
JQ
2761/**
2762 * ram_save_setup: Setup RAM for migration
2763 *
2764 * Returns zero to indicate success and negative for error
2765 *
2766 * @f: QEMUFile where to send the data
2767 * @opaque: RAMState pointer
2768 */
a91246c9
HZ
2769static int ram_save_setup(QEMUFile *f, void *opaque)
2770{
53518d94 2771 RAMState **rsp = opaque;
a91246c9
HZ
2772 RAMBlock *block;
2773
dcaf446e
XG
2774 if (compress_threads_save_setup()) {
2775 return -1;
2776 }
2777
a91246c9
HZ
2778 /* migration has already setup the bitmap, reuse it. */
2779 if (!migration_in_colo_state()) {
7d00ee6a 2780 if (ram_init_all(rsp) != 0) {
dcaf446e 2781 compress_threads_save_cleanup();
a91246c9 2782 return -1;
53518d94 2783 }
a91246c9 2784 }
53518d94 2785 (*rsp)->f = f;
a91246c9 2786
0e6ebd48
DDAG
2787 WITH_RCU_READ_LOCK_GUARD() {
2788 qemu_put_be64(f, ram_bytes_total_common(true) | RAM_SAVE_FLAG_MEM_SIZE);
56e93d26 2789
0e6ebd48
DDAG
2790 RAMBLOCK_FOREACH_MIGRATABLE(block) {
2791 qemu_put_byte(f, strlen(block->idstr));
2792 qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));
2793 qemu_put_be64(f, block->used_length);
2794 if (migrate_postcopy_ram() && block->page_size !=
2795 qemu_host_page_size) {
2796 qemu_put_be64(f, block->page_size);
2797 }
2798 if (migrate_ignore_shared()) {
2799 qemu_put_be64(f, block->mr->addr);
2800 }
fbd162e6 2801 }
56e93d26
JQ
2802 }
2803
56e93d26
JQ
2804 ram_control_before_iterate(f, RAM_CONTROL_SETUP);
2805 ram_control_after_iterate(f, RAM_CONTROL_SETUP);
2806
99f2c6fb 2807 multifd_send_sync_main(f);
56e93d26 2808 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
35374cbd 2809 qemu_fflush(f);
56e93d26
JQ
2810
2811 return 0;
2812}
2813
3d0684b2
JQ
2814/**
2815 * ram_save_iterate: iterative stage for migration
2816 *
2817 * Returns zero to indicate success and negative for error
2818 *
2819 * @f: QEMUFile where to send the data
2820 * @opaque: RAMState pointer
2821 */
56e93d26
JQ
2822static int ram_save_iterate(QEMUFile *f, void *opaque)
2823{
53518d94
JQ
2824 RAMState **temp = opaque;
2825 RAMState *rs = *temp;
3d4095b2 2826 int ret = 0;
56e93d26
JQ
2827 int i;
2828 int64_t t0;
5c90308f 2829 int done = 0;
56e93d26 2830
b2557345
PL
2831 if (blk_mig_bulk_active()) {
2832 /* Avoid transferring ram during bulk phase of block migration as
2833 * the bulk phase will usually take a long time and transferring
2834 * ram updates during that time is pointless. */
2835 goto out;
2836 }
2837
89ac5a1d
DDAG
2838 WITH_RCU_READ_LOCK_GUARD() {
2839 if (ram_list.version != rs->last_version) {
2840 ram_state_reset(rs);
2841 }
56e93d26 2842
89ac5a1d
DDAG
2843 /* Read version before ram_list.blocks */
2844 smp_rmb();
56e93d26 2845
89ac5a1d 2846 ram_control_before_iterate(f, RAM_CONTROL_ROUND);
56e93d26 2847
89ac5a1d
DDAG
2848 t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
2849 i = 0;
2850 while ((ret = qemu_file_rate_limit(f)) == 0 ||
2851 !QSIMPLEQ_EMPTY(&rs->src_page_requests)) {
2852 int pages;
e03a34f8 2853
89ac5a1d
DDAG
2854 if (qemu_file_get_error(f)) {
2855 break;
2856 }
e8f3735f 2857
89ac5a1d
DDAG
2858 pages = ram_find_and_save_block(rs, false);
2859 /* no more pages to sent */
2860 if (pages == 0) {
2861 done = 1;
2862 break;
2863 }
e8f3735f 2864
89ac5a1d
DDAG
2865 if (pages < 0) {
2866 qemu_file_set_error(f, pages);
56e93d26
JQ
2867 break;
2868 }
89ac5a1d
DDAG
2869
2870 rs->target_page_count += pages;
2871
644acf99
WY
2872 /*
2873 * During postcopy, it is necessary to make sure one whole host
2874 * page is sent in one chunk.
2875 */
2876 if (migrate_postcopy_ram()) {
2877 flush_compressed_data(rs);
2878 }
2879
89ac5a1d
DDAG
2880 /*
2881 * we want to check in the 1st loop, just in case it was the 1st
2882 * time and we had to sync the dirty bitmap.
2883 * qemu_clock_get_ns() is a bit expensive, so we only check each
2884 * some iterations
2885 */
2886 if ((i & 63) == 0) {
2887 uint64_t t1 = (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - t0) /
2888 1000000;
2889 if (t1 > MAX_WAIT) {
2890 trace_ram_save_iterate_big_wait(t1, i);
2891 break;
2892 }
2893 }
2894 i++;
56e93d26 2895 }
56e93d26 2896 }
56e93d26
JQ
2897
2898 /*
2899 * Must occur before EOS (or any QEMUFile operation)
2900 * because of RDMA protocol.
2901 */
2902 ram_control_after_iterate(f, RAM_CONTROL_ROUND);
2903
b2557345 2904out:
b69a0227
JQ
2905 if (ret >= 0
2906 && migration_is_setup_or_active(migrate_get_current()->state)) {
99f2c6fb 2907 multifd_send_sync_main(rs->f);
3d4095b2
JQ
2908 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2909 qemu_fflush(f);
2910 ram_counters.transferred += 8;
56e93d26 2911
3d4095b2
JQ
2912 ret = qemu_file_get_error(f);
2913 }
56e93d26
JQ
2914 if (ret < 0) {
2915 return ret;
2916 }
2917
5c90308f 2918 return done;
56e93d26
JQ
2919}
2920
3d0684b2
JQ
2921/**
2922 * ram_save_complete: function called to send the remaining amount of ram
2923 *
e8f3735f 2924 * Returns zero to indicate success or negative on error
3d0684b2
JQ
2925 *
2926 * Called with iothread lock
2927 *
2928 * @f: QEMUFile where to send the data
2929 * @opaque: RAMState pointer
2930 */
56e93d26
JQ
2931static int ram_save_complete(QEMUFile *f, void *opaque)
2932{
53518d94
JQ
2933 RAMState **temp = opaque;
2934 RAMState *rs = *temp;
e8f3735f 2935 int ret = 0;
6f37bb8b 2936
89ac5a1d
DDAG
2937 WITH_RCU_READ_LOCK_GUARD() {
2938 if (!migration_in_postcopy()) {
2939 migration_bitmap_sync_precopy(rs);
2940 }
56e93d26 2941
89ac5a1d 2942 ram_control_before_iterate(f, RAM_CONTROL_FINISH);
56e93d26 2943
89ac5a1d 2944 /* try transferring iterative blocks of memory */
56e93d26 2945
89ac5a1d
DDAG
2946 /* flush all remaining blocks regardless of rate limiting */
2947 while (true) {
2948 int pages;
56e93d26 2949
89ac5a1d
DDAG
2950 pages = ram_find_and_save_block(rs, !migration_in_colo_state());
2951 /* no more blocks to sent */
2952 if (pages == 0) {
2953 break;
2954 }
2955 if (pages < 0) {
2956 ret = pages;
2957 break;
2958 }
e8f3735f 2959 }
56e93d26 2960
89ac5a1d
DDAG
2961 flush_compressed_data(rs);
2962 ram_control_after_iterate(f, RAM_CONTROL_FINISH);
2963 }
d09a6fde 2964
3d4095b2 2965 if (ret >= 0) {
99f2c6fb 2966 multifd_send_sync_main(rs->f);
3d4095b2
JQ
2967 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2968 qemu_fflush(f);
2969 }
56e93d26 2970
e8f3735f 2971 return ret;
56e93d26
JQ
2972}
2973
c31b098f 2974static void ram_save_pending(QEMUFile *f, void *opaque, uint64_t max_size,
47995026
VSO
2975 uint64_t *res_precopy_only,
2976 uint64_t *res_compatible,
2977 uint64_t *res_postcopy_only)
56e93d26 2978{
53518d94
JQ
2979 RAMState **temp = opaque;
2980 RAMState *rs = *temp;
56e93d26
JQ
2981 uint64_t remaining_size;
2982
9edabd4d 2983 remaining_size = rs->migration_dirty_pages * TARGET_PAGE_SIZE;
56e93d26 2984
5727309d 2985 if (!migration_in_postcopy() &&
663e6c1d 2986 remaining_size < max_size) {
56e93d26 2987 qemu_mutex_lock_iothread();
89ac5a1d
DDAG
2988 WITH_RCU_READ_LOCK_GUARD() {
2989 migration_bitmap_sync_precopy(rs);
2990 }
56e93d26 2991 qemu_mutex_unlock_iothread();
9edabd4d 2992 remaining_size = rs->migration_dirty_pages * TARGET_PAGE_SIZE;
56e93d26 2993 }
c31b098f 2994
86e1167e
VSO
2995 if (migrate_postcopy_ram()) {
2996 /* We can do postcopy, and all the data is postcopiable */
47995026 2997 *res_compatible += remaining_size;
86e1167e 2998 } else {
47995026 2999 *res_precopy_only += remaining_size;
86e1167e 3000 }
56e93d26
JQ
3001}
3002
3003static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host)
3004{
3005 unsigned int xh_len;
3006 int xh_flags;
063e760a 3007 uint8_t *loaded_data;
56e93d26 3008
56e93d26
JQ
3009 /* extract RLE header */
3010 xh_flags = qemu_get_byte(f);
3011 xh_len = qemu_get_be16(f);
3012
3013 if (xh_flags != ENCODING_FLAG_XBZRLE) {
3014 error_report("Failed to load XBZRLE page - wrong compression!");
3015 return -1;
3016 }
3017
3018 if (xh_len > TARGET_PAGE_SIZE) {
3019 error_report("Failed to load XBZRLE page - len overflow!");
3020 return -1;
3021 }
f265e0e4 3022 loaded_data = XBZRLE.decoded_buf;
56e93d26 3023 /* load data and decode */
f265e0e4 3024 /* it can change loaded_data to point to an internal buffer */
063e760a 3025 qemu_get_buffer_in_place(f, &loaded_data, xh_len);
56e93d26
JQ
3026
3027 /* decode RLE */
063e760a 3028 if (xbzrle_decode_buffer(loaded_data, xh_len, host,
56e93d26
JQ
3029 TARGET_PAGE_SIZE) == -1) {
3030 error_report("Failed to load XBZRLE page - decode error!");
3031 return -1;
3032 }
3033
3034 return 0;
3035}
3036
3d0684b2
JQ
3037/**
3038 * ram_block_from_stream: read a RAMBlock id from the migration stream
3039 *
3040 * Must be called from within a rcu critical section.
3041 *
56e93d26 3042 * Returns a pointer from within the RCU-protected ram_list.
a7180877 3043 *
3d0684b2
JQ
3044 * @f: QEMUFile where to read the data from
3045 * @flags: Page flags (mostly to see if it's a continuation of previous block)
a7180877 3046 */
3d0684b2 3047static inline RAMBlock *ram_block_from_stream(QEMUFile *f, int flags)
56e93d26 3048{
49324e93 3049 static RAMBlock *block;
56e93d26
JQ
3050 char id[256];
3051 uint8_t len;
3052
3053 if (flags & RAM_SAVE_FLAG_CONTINUE) {
4c4bad48 3054 if (!block) {
56e93d26
JQ
3055 error_report("Ack, bad migration stream!");
3056 return NULL;
3057 }
4c4bad48 3058 return block;
56e93d26
JQ
3059 }
3060
3061 len = qemu_get_byte(f);
3062 qemu_get_buffer(f, (uint8_t *)id, len);
3063 id[len] = 0;
3064
e3dd7493 3065 block = qemu_ram_block_by_name(id);
4c4bad48
HZ
3066 if (!block) {
3067 error_report("Can't find block %s", id);
3068 return NULL;
56e93d26
JQ
3069 }
3070
fbd162e6 3071 if (ramblock_is_ignored(block)) {
b895de50
CLG
3072 error_report("block %s should not be migrated !", id);
3073 return NULL;
3074 }
3075
4c4bad48
HZ
3076 return block;
3077}
3078
3079static inline void *host_from_ram_block_offset(RAMBlock *block,
3080 ram_addr_t offset)
3081{
3082 if (!offset_in_ramblock(block, offset)) {
3083 return NULL;
3084 }
3085
3086 return block->host + offset;
56e93d26
JQ
3087}
3088
13af18f2 3089static inline void *colo_cache_from_block_offset(RAMBlock *block,
8af66371 3090 ram_addr_t offset, bool record_bitmap)
13af18f2
ZC
3091{
3092 if (!offset_in_ramblock(block, offset)) {
3093 return NULL;
3094 }
3095 if (!block->colo_cache) {
3096 error_report("%s: colo_cache is NULL in block :%s",
3097 __func__, block->idstr);
3098 return NULL;
3099 }
7d9acafa
ZC
3100
3101 /*
3102 * During colo checkpoint, we need bitmap of these migrated pages.
3103 * It help us to decide which pages in ram cache should be flushed
3104 * into VM's RAM later.
3105 */
8af66371
HZ
3106 if (record_bitmap &&
3107 !test_and_set_bit(offset >> TARGET_PAGE_BITS, block->bmap)) {
7d9acafa
ZC
3108 ram_state->migration_dirty_pages++;
3109 }
13af18f2
ZC
3110 return block->colo_cache + offset;
3111}
3112
3d0684b2
JQ
3113/**
3114 * ram_handle_compressed: handle the zero page case
3115 *
56e93d26
JQ
3116 * If a page (or a whole RDMA chunk) has been
3117 * determined to be zero, then zap it.
3d0684b2
JQ
3118 *
3119 * @host: host address for the zero page
3120 * @ch: what the page is filled from. We only support zero
3121 * @size: size of the zero page
56e93d26
JQ
3122 */
3123void ram_handle_compressed(void *host, uint8_t ch, uint64_t size)
3124{
3125 if (ch != 0 || !is_zero_range(host, size)) {
3126 memset(host, ch, size);
3127 }
3128}
3129
797ca154
XG
3130/* return the size after decompression, or negative value on error */
3131static int
3132qemu_uncompress_data(z_stream *stream, uint8_t *dest, size_t dest_len,
3133 const uint8_t *source, size_t source_len)
3134{
3135 int err;
3136
3137 err = inflateReset(stream);
3138 if (err != Z_OK) {
3139 return -1;
3140 }
3141
3142 stream->avail_in = source_len;
3143 stream->next_in = (uint8_t *)source;
3144 stream->avail_out = dest_len;
3145 stream->next_out = dest;
3146
3147 err = inflate(stream, Z_NO_FLUSH);
3148 if (err != Z_STREAM_END) {
3149 return -1;
3150 }
3151
3152 return stream->total_out;
3153}
3154
56e93d26
JQ
3155static void *do_data_decompress(void *opaque)
3156{
3157 DecompressParam *param = opaque;
3158 unsigned long pagesize;
33d151f4 3159 uint8_t *des;
34ab9e97 3160 int len, ret;
56e93d26 3161
33d151f4 3162 qemu_mutex_lock(&param->mutex);
90e56fb4 3163 while (!param->quit) {
33d151f4
LL
3164 if (param->des) {
3165 des = param->des;
3166 len = param->len;
3167 param->des = 0;
3168 qemu_mutex_unlock(&param->mutex);
3169
56e93d26 3170 pagesize = TARGET_PAGE_SIZE;
34ab9e97
XG
3171
3172 ret = qemu_uncompress_data(&param->stream, des, pagesize,
3173 param->compbuf, len);
f548222c 3174 if (ret < 0 && migrate_get_current()->decompress_error_check) {
34ab9e97
XG
3175 error_report("decompress data failed");
3176 qemu_file_set_error(decomp_file, ret);
3177 }
73a8912b 3178
33d151f4
LL
3179 qemu_mutex_lock(&decomp_done_lock);
3180 param->done = true;
3181 qemu_cond_signal(&decomp_done_cond);
3182 qemu_mutex_unlock(&decomp_done_lock);
3183
3184 qemu_mutex_lock(&param->mutex);
3185 } else {
3186 qemu_cond_wait(&param->cond, &param->mutex);
3187 }
56e93d26 3188 }
33d151f4 3189 qemu_mutex_unlock(&param->mutex);
56e93d26
JQ
3190
3191 return NULL;
3192}
3193
34ab9e97 3194static int wait_for_decompress_done(void)
5533b2e9
LL
3195{
3196 int idx, thread_count;
3197
3198 if (!migrate_use_compression()) {
34ab9e97 3199 return 0;
5533b2e9
LL
3200 }
3201
3202 thread_count = migrate_decompress_threads();
3203 qemu_mutex_lock(&decomp_done_lock);
3204 for (idx = 0; idx < thread_count; idx++) {
3205 while (!decomp_param[idx].done) {
3206 qemu_cond_wait(&decomp_done_cond, &decomp_done_lock);
3207 }
3208 }
3209 qemu_mutex_unlock(&decomp_done_lock);
34ab9e97 3210 return qemu_file_get_error(decomp_file);
5533b2e9
LL
3211}
3212
f0afa331 3213static void compress_threads_load_cleanup(void)
56e93d26
JQ
3214{
3215 int i, thread_count;
3216
3416ab5b
JQ
3217 if (!migrate_use_compression()) {
3218 return;
3219 }
56e93d26
JQ
3220 thread_count = migrate_decompress_threads();
3221 for (i = 0; i < thread_count; i++) {
797ca154
XG
3222 /*
3223 * we use it as a indicator which shows if the thread is
3224 * properly init'd or not
3225 */
3226 if (!decomp_param[i].compbuf) {
3227 break;
3228 }
3229
56e93d26 3230 qemu_mutex_lock(&decomp_param[i].mutex);
90e56fb4 3231 decomp_param[i].quit = true;
56e93d26
JQ
3232 qemu_cond_signal(&decomp_param[i].cond);
3233 qemu_mutex_unlock(&decomp_param[i].mutex);
3234 }
3235 for (i = 0; i < thread_count; i++) {
797ca154
XG
3236 if (!decomp_param[i].compbuf) {
3237 break;
3238 }
3239
56e93d26
JQ
3240 qemu_thread_join(decompress_threads + i);
3241 qemu_mutex_destroy(&decomp_param[i].mutex);
3242 qemu_cond_destroy(&decomp_param[i].cond);
797ca154 3243 inflateEnd(&decomp_param[i].stream);
56e93d26 3244 g_free(decomp_param[i].compbuf);
797ca154 3245 decomp_param[i].compbuf = NULL;
56e93d26
JQ
3246 }
3247 g_free(decompress_threads);
3248 g_free(decomp_param);
56e93d26
JQ
3249 decompress_threads = NULL;
3250 decomp_param = NULL;
34ab9e97 3251 decomp_file = NULL;
56e93d26
JQ
3252}
3253
34ab9e97 3254static int compress_threads_load_setup(QEMUFile *f)
797ca154
XG
3255{
3256 int i, thread_count;
3257
3258 if (!migrate_use_compression()) {
3259 return 0;
3260 }
3261
3262 thread_count = migrate_decompress_threads();
3263 decompress_threads = g_new0(QemuThread, thread_count);
3264 decomp_param = g_new0(DecompressParam, thread_count);
3265 qemu_mutex_init(&decomp_done_lock);
3266 qemu_cond_init(&decomp_done_cond);
34ab9e97 3267 decomp_file = f;
797ca154
XG
3268 for (i = 0; i < thread_count; i++) {
3269 if (inflateInit(&decomp_param[i].stream) != Z_OK) {
3270 goto exit;
3271 }
3272
3273 decomp_param[i].compbuf = g_malloc0(compressBound(TARGET_PAGE_SIZE));
3274 qemu_mutex_init(&decomp_param[i].mutex);
3275 qemu_cond_init(&decomp_param[i].cond);
3276 decomp_param[i].done = true;
3277 decomp_param[i].quit = false;
3278 qemu_thread_create(decompress_threads + i, "decompress",
3279 do_data_decompress, decomp_param + i,
3280 QEMU_THREAD_JOINABLE);
3281 }
3282 return 0;
3283exit:
3284 compress_threads_load_cleanup();
3285 return -1;
3286}
3287
c1bc6626 3288static void decompress_data_with_multi_threads(QEMUFile *f,
56e93d26
JQ
3289 void *host, int len)
3290{
3291 int idx, thread_count;
3292
3293 thread_count = migrate_decompress_threads();
37396950 3294 QEMU_LOCK_GUARD(&decomp_done_lock);
56e93d26
JQ
3295 while (true) {
3296 for (idx = 0; idx < thread_count; idx++) {
73a8912b 3297 if (decomp_param[idx].done) {
33d151f4
LL
3298 decomp_param[idx].done = false;
3299 qemu_mutex_lock(&decomp_param[idx].mutex);
c1bc6626 3300 qemu_get_buffer(f, decomp_param[idx].compbuf, len);
56e93d26
JQ
3301 decomp_param[idx].des = host;
3302 decomp_param[idx].len = len;
33d151f4
LL
3303 qemu_cond_signal(&decomp_param[idx].cond);
3304 qemu_mutex_unlock(&decomp_param[idx].mutex);
56e93d26
JQ
3305 break;
3306 }
3307 }
3308 if (idx < thread_count) {
3309 break;
73a8912b
LL
3310 } else {
3311 qemu_cond_wait(&decomp_done_cond, &decomp_done_lock);
56e93d26
JQ
3312 }
3313 }
3314}
3315
b70cb3b4
RL
3316static void colo_init_ram_state(void)
3317{
3318 ram_state_init(&ram_state);
b70cb3b4
RL
3319}
3320
13af18f2
ZC
3321/*
3322 * colo cache: this is for secondary VM, we cache the whole
3323 * memory of the secondary VM, it is need to hold the global lock
3324 * to call this helper.
3325 */
3326int colo_init_ram_cache(void)
3327{
3328 RAMBlock *block;
3329
44901b5a
PB
3330 WITH_RCU_READ_LOCK_GUARD() {
3331 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
3332 block->colo_cache = qemu_anon_ram_alloc(block->used_length,
3333 NULL,
3334 false);
3335 if (!block->colo_cache) {
3336 error_report("%s: Can't alloc memory for COLO cache of block %s,"
3337 "size 0x" RAM_ADDR_FMT, __func__, block->idstr,
3338 block->used_length);
3339 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
3340 if (block->colo_cache) {
3341 qemu_anon_ram_free(block->colo_cache, block->used_length);
3342 block->colo_cache = NULL;
3343 }
89ac5a1d 3344 }
44901b5a 3345 return -errno;
89ac5a1d 3346 }
13af18f2 3347 }
13af18f2 3348 }
44901b5a 3349
7d9acafa
ZC
3350 /*
3351 * Record the dirty pages that sent by PVM, we use this dirty bitmap together
3352 * with to decide which page in cache should be flushed into SVM's RAM. Here
3353 * we use the same name 'ram_bitmap' as for migration.
3354 */
3355 if (ram_bytes_total()) {
3356 RAMBlock *block;
3357
fbd162e6 3358 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
7d9acafa 3359 unsigned long pages = block->max_length >> TARGET_PAGE_BITS;
7d9acafa 3360 block->bmap = bitmap_new(pages);
7d9acafa
ZC
3361 }
3362 }
7d9acafa 3363
b70cb3b4 3364 colo_init_ram_state();
13af18f2 3365 return 0;
13af18f2
ZC
3366}
3367
0393031a
HZ
3368/* TODO: duplicated with ram_init_bitmaps */
3369void colo_incoming_start_dirty_log(void)
3370{
3371 RAMBlock *block = NULL;
3372 /* For memory_global_dirty_log_start below. */
3373 qemu_mutex_lock_iothread();
3374 qemu_mutex_lock_ramlist();
3375
3376 memory_global_dirty_log_sync();
3377 WITH_RCU_READ_LOCK_GUARD() {
3378 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
3379 ramblock_sync_dirty_bitmap(ram_state, block);
3380 /* Discard this dirty bitmap record */
3381 bitmap_zero(block->bmap, block->max_length >> TARGET_PAGE_BITS);
3382 }
3383 memory_global_dirty_log_start();
3384 }
3385 ram_state->migration_dirty_pages = 0;
3386 qemu_mutex_unlock_ramlist();
3387 qemu_mutex_unlock_iothread();
3388}
3389
13af18f2
ZC
3390/* It is need to hold the global lock to call this helper */
3391void colo_release_ram_cache(void)
3392{
3393 RAMBlock *block;
3394
d1955d22 3395 memory_global_dirty_log_stop();
fbd162e6 3396 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
7d9acafa
ZC
3397 g_free(block->bmap);
3398 block->bmap = NULL;
3399 }
3400
89ac5a1d
DDAG
3401 WITH_RCU_READ_LOCK_GUARD() {
3402 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
3403 if (block->colo_cache) {
3404 qemu_anon_ram_free(block->colo_cache, block->used_length);
3405 block->colo_cache = NULL;
3406 }
13af18f2
ZC
3407 }
3408 }
0393031a 3409 ram_state_cleanup(&ram_state);
13af18f2
ZC
3410}
3411
f265e0e4
JQ
3412/**
3413 * ram_load_setup: Setup RAM for migration incoming side
3414 *
3415 * Returns zero to indicate success and negative for error
3416 *
3417 * @f: QEMUFile where to receive the data
3418 * @opaque: RAMState pointer
3419 */
3420static int ram_load_setup(QEMUFile *f, void *opaque)
3421{
34ab9e97 3422 if (compress_threads_load_setup(f)) {
797ca154
XG
3423 return -1;
3424 }
3425
f265e0e4 3426 xbzrle_load_setup();
f9494614 3427 ramblock_recv_map_init();
13af18f2 3428
f265e0e4
JQ
3429 return 0;
3430}
3431
3432static int ram_load_cleanup(void *opaque)
3433{
f9494614 3434 RAMBlock *rb;
56eb90af 3435
fbd162e6 3436 RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
bd108a44 3437 qemu_ram_block_writeback(rb);
56eb90af
JH
3438 }
3439
f265e0e4 3440 xbzrle_load_cleanup();
f0afa331 3441 compress_threads_load_cleanup();
f9494614 3442
fbd162e6 3443 RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
f9494614
AP
3444 g_free(rb->receivedmap);
3445 rb->receivedmap = NULL;
3446 }
13af18f2 3447
f265e0e4
JQ
3448 return 0;
3449}
3450
3d0684b2
JQ
3451/**
3452 * ram_postcopy_incoming_init: allocate postcopy data structures
3453 *
3454 * Returns 0 for success and negative if there was one error
3455 *
3456 * @mis: current migration incoming state
3457 *
3458 * Allocate data structures etc needed by incoming migration with
3459 * postcopy-ram. postcopy-ram's similarly names
3460 * postcopy_ram_incoming_init does the work.
1caddf8a
DDAG
3461 */
3462int ram_postcopy_incoming_init(MigrationIncomingState *mis)
3463{
c136180c 3464 return postcopy_ram_incoming_init(mis);
1caddf8a
DDAG
3465}
3466
3d0684b2
JQ
3467/**
3468 * ram_load_postcopy: load a page in postcopy case
3469 *
3470 * Returns 0 for success or -errno in case of error
3471 *
a7180877
DDAG
3472 * Called in postcopy mode by ram_load().
3473 * rcu_read_lock is taken prior to this being called.
3d0684b2
JQ
3474 *
3475 * @f: QEMUFile where to send the data
a7180877
DDAG
3476 */
3477static int ram_load_postcopy(QEMUFile *f)
3478{
3479 int flags = 0, ret = 0;
3480 bool place_needed = false;
1aa83678 3481 bool matches_target_page_size = false;
a7180877
DDAG
3482 MigrationIncomingState *mis = migration_incoming_get_current();
3483 /* Temporary page that is later 'placed' */
3414322a 3484 void *postcopy_host_page = mis->postcopy_tmp_page;
91ba442f 3485 void *this_host = NULL;
ddf35bdf 3486 bool all_zero = true;
4cbb3c63 3487 int target_pages = 0;
a7180877
DDAG
3488
3489 while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
3490 ram_addr_t addr;
3491 void *host = NULL;
3492 void *page_buffer = NULL;
3493 void *place_source = NULL;
df9ff5e1 3494 RAMBlock *block = NULL;
a7180877 3495 uint8_t ch;
644acf99 3496 int len;
a7180877
DDAG
3497
3498 addr = qemu_get_be64(f);
7a9ddfbf
PX
3499
3500 /*
3501 * If qemu file error, we should stop here, and then "addr"
3502 * may be invalid
3503 */
3504 ret = qemu_file_get_error(f);
3505 if (ret) {
3506 break;
3507 }
3508
a7180877
DDAG
3509 flags = addr & ~TARGET_PAGE_MASK;
3510 addr &= TARGET_PAGE_MASK;
3511
3512 trace_ram_load_postcopy_loop((uint64_t)addr, flags);
644acf99
WY
3513 if (flags & (RAM_SAVE_FLAG_ZERO | RAM_SAVE_FLAG_PAGE |
3514 RAM_SAVE_FLAG_COMPRESS_PAGE)) {
df9ff5e1 3515 block = ram_block_from_stream(f, flags);
4c4bad48
HZ
3516
3517 host = host_from_ram_block_offset(block, addr);
a7180877
DDAG
3518 if (!host) {
3519 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
3520 ret = -EINVAL;
3521 break;
3522 }
4cbb3c63 3523 target_pages++;
1aa83678 3524 matches_target_page_size = block->page_size == TARGET_PAGE_SIZE;
a7180877 3525 /*
28abd200
DDAG
3526 * Postcopy requires that we place whole host pages atomically;
3527 * these may be huge pages for RAMBlocks that are backed by
3528 * hugetlbfs.
a7180877
DDAG
3529 * To make it atomic, the data is read into a temporary page
3530 * that's moved into place later.
3531 * The migration protocol uses, possibly smaller, target-pages
3532 * however the source ensures it always sends all the components
91ba442f 3533 * of a host page in one chunk.
a7180877
DDAG
3534 */
3535 page_buffer = postcopy_host_page +
28abd200 3536 ((uintptr_t)host & (block->page_size - 1));
e5e73b0f 3537 if (target_pages == 1) {
91ba442f
WY
3538 this_host = (void *)QEMU_ALIGN_DOWN((uintptr_t)host,
3539 block->page_size);
c53b7ddc
DDAG
3540 } else {
3541 /* not the 1st TP within the HP */
91ba442f
WY
3542 if (QEMU_ALIGN_DOWN((uintptr_t)host, block->page_size) !=
3543 (uintptr_t)this_host) {
3544 error_report("Non-same host page %p/%p",
3545 host, this_host);
c53b7ddc
DDAG
3546 ret = -EINVAL;
3547 break;
3548 }
a7180877
DDAG
3549 }
3550
3551 /*
3552 * If it's the last part of a host page then we place the host
3553 * page
3554 */
4cbb3c63
WY
3555 if (target_pages == (block->page_size / TARGET_PAGE_SIZE)) {
3556 place_needed = true;
4cbb3c63 3557 }
a7180877
DDAG
3558 place_source = postcopy_host_page;
3559 }
3560
3561 switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
bb890ed5 3562 case RAM_SAVE_FLAG_ZERO:
a7180877 3563 ch = qemu_get_byte(f);
2e36bc1b
WY
3564 /*
3565 * Can skip to set page_buffer when
3566 * this is a zero page and (block->page_size == TARGET_PAGE_SIZE).
3567 */
3568 if (ch || !matches_target_page_size) {
3569 memset(page_buffer, ch, TARGET_PAGE_SIZE);
3570 }
a7180877
DDAG
3571 if (ch) {
3572 all_zero = false;
3573 }
3574 break;
3575
3576 case RAM_SAVE_FLAG_PAGE:
3577 all_zero = false;
1aa83678
PX
3578 if (!matches_target_page_size) {
3579 /* For huge pages, we always use temporary buffer */
a7180877
DDAG
3580 qemu_get_buffer(f, page_buffer, TARGET_PAGE_SIZE);
3581 } else {
1aa83678
PX
3582 /*
3583 * For small pages that matches target page size, we
3584 * avoid the qemu_file copy. Instead we directly use
3585 * the buffer of QEMUFile to place the page. Note: we
3586 * cannot do any QEMUFile operation before using that
3587 * buffer to make sure the buffer is valid when
3588 * placing the page.
a7180877
DDAG
3589 */
3590 qemu_get_buffer_in_place(f, (uint8_t **)&place_source,
3591 TARGET_PAGE_SIZE);
3592 }
3593 break;
644acf99
WY
3594 case RAM_SAVE_FLAG_COMPRESS_PAGE:
3595 all_zero = false;
3596 len = qemu_get_be32(f);
3597 if (len < 0 || len > compressBound(TARGET_PAGE_SIZE)) {
3598 error_report("Invalid compressed data length: %d", len);
3599 ret = -EINVAL;
3600 break;
3601 }
3602 decompress_data_with_multi_threads(f, page_buffer, len);
3603 break;
3604
a7180877
DDAG
3605 case RAM_SAVE_FLAG_EOS:
3606 /* normal exit */
6df264ac 3607 multifd_recv_sync_main();
a7180877
DDAG
3608 break;
3609 default:
29fccade 3610 error_report("Unknown combination of migration flags: 0x%x"
a7180877
DDAG
3611 " (postcopy mode)", flags);
3612 ret = -EINVAL;
7a9ddfbf
PX
3613 break;
3614 }
3615
644acf99
WY
3616 /* Got the whole host page, wait for decompress before placing. */
3617 if (place_needed) {
3618 ret |= wait_for_decompress_done();
3619 }
3620
7a9ddfbf
PX
3621 /* Detect for any possible file errors */
3622 if (!ret && qemu_file_get_error(f)) {
3623 ret = qemu_file_get_error(f);
a7180877
DDAG
3624 }
3625
7a9ddfbf 3626 if (!ret && place_needed) {
a7180877 3627 /* This gets called at the last target page in the host page */
91ba442f
WY
3628 void *place_dest = (void *)QEMU_ALIGN_DOWN((uintptr_t)host,
3629 block->page_size);
df9ff5e1 3630
a7180877 3631 if (all_zero) {
df9ff5e1 3632 ret = postcopy_place_page_zero(mis, place_dest,
8be4620b 3633 block);
a7180877 3634 } else {
df9ff5e1 3635 ret = postcopy_place_page(mis, place_dest,
8be4620b 3636 place_source, block);
a7180877 3637 }
ddf35bdf
DH
3638 place_needed = false;
3639 target_pages = 0;
3640 /* Assume we have a zero page until we detect something different */
3641 all_zero = true;
a7180877 3642 }
a7180877
DDAG
3643 }
3644
3645 return ret;
3646}
3647
acab30b8
DHB
3648static bool postcopy_is_advised(void)
3649{
3650 PostcopyState ps = postcopy_state_get();
3651 return ps >= POSTCOPY_INCOMING_ADVISE && ps < POSTCOPY_INCOMING_END;
3652}
3653
3654static bool postcopy_is_running(void)
3655{
3656 PostcopyState ps = postcopy_state_get();
3657 return ps >= POSTCOPY_INCOMING_LISTENING && ps < POSTCOPY_INCOMING_END;
3658}
3659
e6f4aa18
ZC
3660/*
3661 * Flush content of RAM cache into SVM's memory.
3662 * Only flush the pages that be dirtied by PVM or SVM or both.
3663 */
24fa16f8 3664void colo_flush_ram_cache(void)
e6f4aa18
ZC
3665{
3666 RAMBlock *block = NULL;
3667 void *dst_host;
3668 void *src_host;
3669 unsigned long offset = 0;
3670
d1955d22 3671 memory_global_dirty_log_sync();
89ac5a1d
DDAG
3672 WITH_RCU_READ_LOCK_GUARD() {
3673 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
3674 ramblock_sync_dirty_bitmap(ram_state, block);
3675 }
d1955d22 3676 }
d1955d22 3677
e6f4aa18 3678 trace_colo_flush_ram_cache_begin(ram_state->migration_dirty_pages);
89ac5a1d
DDAG
3679 WITH_RCU_READ_LOCK_GUARD() {
3680 block = QLIST_FIRST_RCU(&ram_list.blocks);
e6f4aa18 3681
89ac5a1d
DDAG
3682 while (block) {
3683 offset = migration_bitmap_find_dirty(ram_state, block, offset);
e6f4aa18 3684
8bba004c
AR
3685 if (((ram_addr_t)offset) << TARGET_PAGE_BITS
3686 >= block->used_length) {
89ac5a1d
DDAG
3687 offset = 0;
3688 block = QLIST_NEXT_RCU(block, next);
3689 } else {
3690 migration_bitmap_clear_dirty(ram_state, block, offset);
8bba004c
AR
3691 dst_host = block->host
3692 + (((ram_addr_t)offset) << TARGET_PAGE_BITS);
3693 src_host = block->colo_cache
3694 + (((ram_addr_t)offset) << TARGET_PAGE_BITS);
89ac5a1d
DDAG
3695 memcpy(dst_host, src_host, TARGET_PAGE_SIZE);
3696 }
e6f4aa18
ZC
3697 }
3698 }
e6f4aa18
ZC
3699 trace_colo_flush_ram_cache_end();
3700}
3701
10da4a36
WY
3702/**
3703 * ram_load_precopy: load pages in precopy case
3704 *
3705 * Returns 0 for success or -errno in case of error
3706 *
3707 * Called in precopy mode by ram_load().
3708 * rcu_read_lock is taken prior to this being called.
3709 *
3710 * @f: QEMUFile where to send the data
3711 */
3712static int ram_load_precopy(QEMUFile *f)
56e93d26 3713{
e65cec5e 3714 int flags = 0, ret = 0, invalid_flags = 0, len = 0, i = 0;
ef08fb38 3715 /* ADVISE is earlier, it shows the source has the postcopy capability on */
acab30b8 3716 bool postcopy_advised = postcopy_is_advised();
edc60127
JQ
3717 if (!migrate_use_compression()) {
3718 invalid_flags |= RAM_SAVE_FLAG_COMPRESS_PAGE;
3719 }
a7180877 3720
10da4a36 3721 while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
56e93d26 3722 ram_addr_t addr, total_ram_bytes;
0393031a 3723 void *host = NULL, *host_bak = NULL;
56e93d26
JQ
3724 uint8_t ch;
3725
e65cec5e
YK
3726 /*
3727 * Yield periodically to let main loop run, but an iteration of
3728 * the main loop is expensive, so do it each some iterations
3729 */
3730 if ((i & 32767) == 0 && qemu_in_coroutine()) {
3731 aio_co_schedule(qemu_get_current_aio_context(),
3732 qemu_coroutine_self());
3733 qemu_coroutine_yield();
3734 }
3735 i++;
3736
56e93d26
JQ
3737 addr = qemu_get_be64(f);
3738 flags = addr & ~TARGET_PAGE_MASK;
3739 addr &= TARGET_PAGE_MASK;
3740
edc60127
JQ
3741 if (flags & invalid_flags) {
3742 if (flags & invalid_flags & RAM_SAVE_FLAG_COMPRESS_PAGE) {
3743 error_report("Received an unexpected compressed page");
3744 }
3745
3746 ret = -EINVAL;
3747 break;
3748 }
3749
bb890ed5 3750 if (flags & (RAM_SAVE_FLAG_ZERO | RAM_SAVE_FLAG_PAGE |
a776aa15 3751 RAM_SAVE_FLAG_COMPRESS_PAGE | RAM_SAVE_FLAG_XBZRLE)) {
4c4bad48
HZ
3752 RAMBlock *block = ram_block_from_stream(f, flags);
3753
0393031a 3754 host = host_from_ram_block_offset(block, addr);
13af18f2 3755 /*
0393031a
HZ
3756 * After going into COLO stage, we should not load the page
3757 * into SVM's memory directly, we put them into colo_cache firstly.
3758 * NOTE: We need to keep a copy of SVM's ram in colo_cache.
3759 * Previously, we copied all these memory in preparing stage of COLO
3760 * while we need to stop VM, which is a time-consuming process.
3761 * Here we optimize it by a trick, back-up every page while in
3762 * migration process while COLO is enabled, though it affects the
3763 * speed of the migration, but it obviously reduce the downtime of
3764 * back-up all SVM'S memory in COLO preparing stage.
13af18f2 3765 */
0393031a
HZ
3766 if (migration_incoming_colo_enabled()) {
3767 if (migration_incoming_in_colo_state()) {
3768 /* In COLO stage, put all pages into cache temporarily */
8af66371 3769 host = colo_cache_from_block_offset(block, addr, true);
0393031a
HZ
3770 } else {
3771 /*
3772 * In migration stage but before COLO stage,
3773 * Put all pages into both cache and SVM's memory.
3774 */
8af66371 3775 host_bak = colo_cache_from_block_offset(block, addr, false);
0393031a 3776 }
13af18f2 3777 }
a776aa15
DDAG
3778 if (!host) {
3779 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
3780 ret = -EINVAL;
3781 break;
3782 }
13af18f2
ZC
3783 if (!migration_incoming_in_colo_state()) {
3784 ramblock_recv_bitmap_set(block, host);
3785 }
3786
1db9d8e5 3787 trace_ram_load_loop(block->idstr, (uint64_t)addr, flags, host);
a776aa15
DDAG
3788 }
3789
56e93d26
JQ
3790 switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
3791 case RAM_SAVE_FLAG_MEM_SIZE:
3792 /* Synchronize RAM block list */
3793 total_ram_bytes = addr;
3794 while (!ret && total_ram_bytes) {
3795 RAMBlock *block;
56e93d26
JQ
3796 char id[256];
3797 ram_addr_t length;
3798
3799 len = qemu_get_byte(f);
3800 qemu_get_buffer(f, (uint8_t *)id, len);
3801 id[len] = 0;
3802 length = qemu_get_be64(f);
3803
e3dd7493 3804 block = qemu_ram_block_by_name(id);
b895de50
CLG
3805 if (block && !qemu_ram_is_migratable(block)) {
3806 error_report("block %s should not be migrated !", id);
3807 ret = -EINVAL;
3808 } else if (block) {
e3dd7493
DDAG
3809 if (length != block->used_length) {
3810 Error *local_err = NULL;
56e93d26 3811
fa53a0e5 3812 ret = qemu_ram_resize(block, length,
e3dd7493
DDAG
3813 &local_err);
3814 if (local_err) {
3815 error_report_err(local_err);
56e93d26 3816 }
56e93d26 3817 }
ef08fb38 3818 /* For postcopy we need to check hugepage sizes match */
e846b746 3819 if (postcopy_advised && migrate_postcopy_ram() &&
ef08fb38
DDAG
3820 block->page_size != qemu_host_page_size) {
3821 uint64_t remote_page_size = qemu_get_be64(f);
3822 if (remote_page_size != block->page_size) {
3823 error_report("Mismatched RAM page size %s "
3824 "(local) %zd != %" PRId64,
3825 id, block->page_size,
3826 remote_page_size);
3827 ret = -EINVAL;
3828 }
3829 }
fbd162e6
YK
3830 if (migrate_ignore_shared()) {
3831 hwaddr addr = qemu_get_be64(f);
fbd162e6
YK
3832 if (ramblock_is_ignored(block) &&
3833 block->mr->addr != addr) {
3834 error_report("Mismatched GPAs for block %s "
3835 "%" PRId64 "!= %" PRId64,
3836 id, (uint64_t)addr,
3837 (uint64_t)block->mr->addr);
3838 ret = -EINVAL;
3839 }
3840 }
e3dd7493
DDAG
3841 ram_control_load_hook(f, RAM_CONTROL_BLOCK_REG,
3842 block->idstr);
3843 } else {
56e93d26
JQ
3844 error_report("Unknown ramblock \"%s\", cannot "
3845 "accept migration", id);
3846 ret = -EINVAL;
3847 }
3848
3849 total_ram_bytes -= length;
3850 }
3851 break;
a776aa15 3852
bb890ed5 3853 case RAM_SAVE_FLAG_ZERO:
56e93d26
JQ
3854 ch = qemu_get_byte(f);
3855 ram_handle_compressed(host, ch, TARGET_PAGE_SIZE);
3856 break;
a776aa15 3857
56e93d26 3858 case RAM_SAVE_FLAG_PAGE:
56e93d26
JQ
3859 qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
3860 break;
56e93d26 3861
a776aa15 3862 case RAM_SAVE_FLAG_COMPRESS_PAGE:
56e93d26
JQ
3863 len = qemu_get_be32(f);
3864 if (len < 0 || len > compressBound(TARGET_PAGE_SIZE)) {
3865 error_report("Invalid compressed data length: %d", len);
3866 ret = -EINVAL;
3867 break;
3868 }
c1bc6626 3869 decompress_data_with_multi_threads(f, host, len);
56e93d26 3870 break;
a776aa15 3871
56e93d26 3872 case RAM_SAVE_FLAG_XBZRLE:
56e93d26
JQ
3873 if (load_xbzrle(f, addr, host) < 0) {
3874 error_report("Failed to decompress XBZRLE page at "
3875 RAM_ADDR_FMT, addr);
3876 ret = -EINVAL;
3877 break;
3878 }
3879 break;
3880 case RAM_SAVE_FLAG_EOS:
3881 /* normal exit */
6df264ac 3882 multifd_recv_sync_main();
56e93d26
JQ
3883 break;
3884 default:
3885 if (flags & RAM_SAVE_FLAG_HOOK) {
632e3a5c 3886 ram_control_load_hook(f, RAM_CONTROL_HOOK, NULL);
56e93d26 3887 } else {
29fccade 3888 error_report("Unknown combination of migration flags: 0x%x",
56e93d26
JQ
3889 flags);
3890 ret = -EINVAL;
3891 }
3892 }
3893 if (!ret) {
3894 ret = qemu_file_get_error(f);
3895 }
0393031a
HZ
3896 if (!ret && host_bak) {
3897 memcpy(host_bak, host, TARGET_PAGE_SIZE);
3898 }
56e93d26
JQ
3899 }
3900
ca1a6b70 3901 ret |= wait_for_decompress_done();
10da4a36
WY
3902 return ret;
3903}
3904
3905static int ram_load(QEMUFile *f, void *opaque, int version_id)
3906{
3907 int ret = 0;
3908 static uint64_t seq_iter;
3909 /*
3910 * If system is running in postcopy mode, page inserts to host memory must
3911 * be atomic
3912 */
3913 bool postcopy_running = postcopy_is_running();
3914
3915 seq_iter++;
3916
3917 if (version_id != 4) {
3918 return -EINVAL;
3919 }
3920
3921 /*
3922 * This RCU critical section can be very long running.
3923 * When RCU reclaims in the code start to become numerous,
3924 * it will be necessary to reduce the granularity of this
3925 * critical section.
3926 */
89ac5a1d
DDAG
3927 WITH_RCU_READ_LOCK_GUARD() {
3928 if (postcopy_running) {
3929 ret = ram_load_postcopy(f);
3930 } else {
3931 ret = ram_load_precopy(f);
3932 }
10da4a36 3933 }
55c4446b 3934 trace_ram_load_complete(ret, seq_iter);
e6f4aa18 3935
56e93d26
JQ
3936 return ret;
3937}
3938
c6467627
VSO
3939static bool ram_has_postcopy(void *opaque)
3940{
469dd51b 3941 RAMBlock *rb;
fbd162e6 3942 RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
469dd51b
JH
3943 if (ramblock_is_pmem(rb)) {
3944 info_report("Block: %s, host: %p is a nvdimm memory, postcopy"
3945 "is not supported now!", rb->idstr, rb->host);
3946 return false;
3947 }
3948 }
3949
c6467627
VSO
3950 return migrate_postcopy_ram();
3951}
3952
edd090c7
PX
3953/* Sync all the dirty bitmap with destination VM. */
3954static int ram_dirty_bitmap_sync_all(MigrationState *s, RAMState *rs)
3955{
3956 RAMBlock *block;
3957 QEMUFile *file = s->to_dst_file;
3958 int ramblock_count = 0;
3959
3960 trace_ram_dirty_bitmap_sync_start();
3961
fbd162e6 3962 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
edd090c7
PX
3963 qemu_savevm_send_recv_bitmap(file, block->idstr);
3964 trace_ram_dirty_bitmap_request(block->idstr);
3965 ramblock_count++;
3966 }
3967
3968 trace_ram_dirty_bitmap_sync_wait();
3969
3970 /* Wait until all the ramblocks' dirty bitmap synced */
3971 while (ramblock_count--) {
3972 qemu_sem_wait(&s->rp_state.rp_sem);
3973 }
3974
3975 trace_ram_dirty_bitmap_sync_complete();
3976
3977 return 0;
3978}
3979
3980static void ram_dirty_bitmap_reload_notify(MigrationState *s)
3981{
3982 qemu_sem_post(&s->rp_state.rp_sem);
3983}
3984
a335debb
PX
3985/*
3986 * Read the received bitmap, revert it as the initial dirty bitmap.
3987 * This is only used when the postcopy migration is paused but wants
3988 * to resume from a middle point.
3989 */
3990int ram_dirty_bitmap_reload(MigrationState *s, RAMBlock *block)
3991{
3992 int ret = -EINVAL;
3993 QEMUFile *file = s->rp_state.from_dst_file;
3994 unsigned long *le_bitmap, nbits = block->used_length >> TARGET_PAGE_BITS;
a725ef9f 3995 uint64_t local_size = DIV_ROUND_UP(nbits, 8);
a335debb
PX
3996 uint64_t size, end_mark;
3997
3998 trace_ram_dirty_bitmap_reload_begin(block->idstr);
3999
4000 if (s->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
4001 error_report("%s: incorrect state %s", __func__,
4002 MigrationStatus_str(s->state));
4003 return -EINVAL;
4004 }
4005
4006 /*
4007 * Note: see comments in ramblock_recv_bitmap_send() on why we
3a4452d8 4008 * need the endianness conversion, and the paddings.
a335debb
PX
4009 */
4010 local_size = ROUND_UP(local_size, 8);
4011
4012 /* Add paddings */
4013 le_bitmap = bitmap_new(nbits + BITS_PER_LONG);
4014
4015 size = qemu_get_be64(file);
4016
4017 /* The size of the bitmap should match with our ramblock */
4018 if (size != local_size) {
4019 error_report("%s: ramblock '%s' bitmap size mismatch "
4020 "(0x%"PRIx64" != 0x%"PRIx64")", __func__,
4021 block->idstr, size, local_size);
4022 ret = -EINVAL;
4023 goto out;
4024 }
4025
4026 size = qemu_get_buffer(file, (uint8_t *)le_bitmap, local_size);
4027 end_mark = qemu_get_be64(file);
4028
4029 ret = qemu_file_get_error(file);
4030 if (ret || size != local_size) {
4031 error_report("%s: read bitmap failed for ramblock '%s': %d"
4032 " (size 0x%"PRIx64", got: 0x%"PRIx64")",
4033 __func__, block->idstr, ret, local_size, size);
4034 ret = -EIO;
4035 goto out;
4036 }
4037
4038 if (end_mark != RAMBLOCK_RECV_BITMAP_ENDING) {
af3bbbe9 4039 error_report("%s: ramblock '%s' end mark incorrect: 0x%"PRIx64,
a335debb
PX
4040 __func__, block->idstr, end_mark);
4041 ret = -EINVAL;
4042 goto out;
4043 }
4044
4045 /*
3a4452d8 4046 * Endianness conversion. We are during postcopy (though paused).
a335debb
PX
4047 * The dirty bitmap won't change. We can directly modify it.
4048 */
4049 bitmap_from_le(block->bmap, le_bitmap, nbits);
4050
4051 /*
4052 * What we received is "received bitmap". Revert it as the initial
4053 * dirty bitmap for this ramblock.
4054 */
4055 bitmap_complement(block->bmap, block->bmap, nbits);
4056
4057 trace_ram_dirty_bitmap_reload_complete(block->idstr);
4058
edd090c7
PX
4059 /*
4060 * We succeeded to sync bitmap for current ramblock. If this is
4061 * the last one to sync, we need to notify the main send thread.
4062 */
4063 ram_dirty_bitmap_reload_notify(s);
4064
a335debb
PX
4065 ret = 0;
4066out:
bf269906 4067 g_free(le_bitmap);
a335debb
PX
4068 return ret;
4069}
4070
edd090c7
PX
4071static int ram_resume_prepare(MigrationState *s, void *opaque)
4072{
4073 RAMState *rs = *(RAMState **)opaque;
08614f34 4074 int ret;
edd090c7 4075
08614f34
PX
4076 ret = ram_dirty_bitmap_sync_all(s, rs);
4077 if (ret) {
4078 return ret;
4079 }
4080
4081 ram_state_resume_prepare(rs, s->to_dst_file);
4082
4083 return 0;
edd090c7
PX
4084}
4085
56e93d26 4086static SaveVMHandlers savevm_ram_handlers = {
9907e842 4087 .save_setup = ram_save_setup,
56e93d26 4088 .save_live_iterate = ram_save_iterate,
763c906b 4089 .save_live_complete_postcopy = ram_save_complete,
a3e06c3d 4090 .save_live_complete_precopy = ram_save_complete,
c6467627 4091 .has_postcopy = ram_has_postcopy,
56e93d26
JQ
4092 .save_live_pending = ram_save_pending,
4093 .load_state = ram_load,
f265e0e4
JQ
4094 .save_cleanup = ram_save_cleanup,
4095 .load_setup = ram_load_setup,
4096 .load_cleanup = ram_load_cleanup,
edd090c7 4097 .resume_prepare = ram_resume_prepare,
56e93d26
JQ
4098};
4099
4100void ram_mig_init(void)
4101{
4102 qemu_mutex_init(&XBZRLE.lock);
ce62df53 4103 register_savevm_live("ram", 0, 4, &savevm_ram_handlers, &ram_state);
56e93d26 4104}