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