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