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