]> git.proxmox.com Git - mirror_qemu.git/blame - migration/ram.c
migration: Convert ram to use new load_setup()/load_cleanup()
[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 */
1393a485 28#include "qemu/osdep.h"
33c11879 29#include "cpu.h"
56e93d26 30#include <zlib.h>
4addcd4f 31#include "qapi-event.h"
f348b6d1 32#include "qemu/cutils.h"
56e93d26
JQ
33#include "qemu/bitops.h"
34#include "qemu/bitmap.h"
7205c9ec 35#include "qemu/main-loop.h"
709e3fe8 36#include "xbzrle.h"
7b1e1a22 37#include "ram.h"
6666c96a 38#include "migration.h"
f2a8f0a6 39#include "migration/register.h"
7b1e1a22 40#include "migration/misc.h"
08a0aee1 41#include "qemu-file.h"
be07b0ac 42#include "postcopy-ram.h"
56e93d26 43#include "migration/page_cache.h"
56e93d26 44#include "qemu/error-report.h"
56e93d26 45#include "trace.h"
56e93d26 46#include "exec/ram_addr.h"
56e93d26 47#include "qemu/rcu_queue.h"
a91246c9 48#include "migration/colo.h"
56e93d26 49
56e93d26
JQ
50/***********************************************************/
51/* ram save/restore */
52
bb890ed5
JQ
53/* RAM_SAVE_FLAG_ZERO used to be named RAM_SAVE_FLAG_COMPRESS, it
54 * worked for pages that where filled with the same char. We switched
55 * it to only search for the zero value. And to avoid confusion with
56 * RAM_SSAVE_FLAG_COMPRESS_PAGE just rename it.
57 */
58
56e93d26 59#define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
bb890ed5 60#define RAM_SAVE_FLAG_ZERO 0x02
56e93d26
JQ
61#define RAM_SAVE_FLAG_MEM_SIZE 0x04
62#define RAM_SAVE_FLAG_PAGE 0x08
63#define RAM_SAVE_FLAG_EOS 0x10
64#define RAM_SAVE_FLAG_CONTINUE 0x20
65#define RAM_SAVE_FLAG_XBZRLE 0x40
66/* 0x80 is reserved in migration.h start with 0x100 next */
67#define RAM_SAVE_FLAG_COMPRESS_PAGE 0x100
68
56e93d26
JQ
69static inline bool is_zero_range(uint8_t *p, uint64_t size)
70{
a1febc49 71 return buffer_is_zero(p, size);
56e93d26
JQ
72}
73
9360447d
JQ
74XBZRLECacheStats xbzrle_counters;
75
56e93d26
JQ
76/* struct contains XBZRLE cache and a static page
77 used by the compression */
78static struct {
79 /* buffer used for XBZRLE encoding */
80 uint8_t *encoded_buf;
81 /* buffer for storing page content */
82 uint8_t *current_buf;
83 /* Cache for XBZRLE, Protected by lock. */
84 PageCache *cache;
85 QemuMutex lock;
c00e0928
JQ
86 /* it will store a page full of zeros */
87 uint8_t *zero_target_page;
f265e0e4
JQ
88 /* buffer used for XBZRLE decoding */
89 uint8_t *decoded_buf;
56e93d26
JQ
90} XBZRLE;
91
56e93d26
JQ
92static void XBZRLE_cache_lock(void)
93{
94 if (migrate_use_xbzrle())
95 qemu_mutex_lock(&XBZRLE.lock);
96}
97
98static void XBZRLE_cache_unlock(void)
99{
100 if (migrate_use_xbzrle())
101 qemu_mutex_unlock(&XBZRLE.lock);
102}
103
3d0684b2
JQ
104/**
105 * xbzrle_cache_resize: resize the xbzrle cache
106 *
107 * This function is called from qmp_migrate_set_cache_size in main
108 * thread, possibly while a migration is in progress. A running
109 * migration may be using the cache and might finish during this call,
110 * hence changes to the cache are protected by XBZRLE.lock().
111 *
112 * Returns the new_size or negative in case of error.
113 *
114 * @new_size: new cache size
56e93d26
JQ
115 */
116int64_t xbzrle_cache_resize(int64_t new_size)
117{
118 PageCache *new_cache;
119 int64_t ret;
120
121 if (new_size < TARGET_PAGE_SIZE) {
122 return -1;
123 }
124
125 XBZRLE_cache_lock();
126
127 if (XBZRLE.cache != NULL) {
128 if (pow2floor(new_size) == migrate_xbzrle_cache_size()) {
129 goto out_new_size;
130 }
131 new_cache = cache_init(new_size / TARGET_PAGE_SIZE,
132 TARGET_PAGE_SIZE);
133 if (!new_cache) {
134 error_report("Error creating cache");
135 ret = -1;
136 goto out;
137 }
138
139 cache_fini(XBZRLE.cache);
140 XBZRLE.cache = new_cache;
141 }
142
143out_new_size:
144 ret = pow2floor(new_size);
145out:
146 XBZRLE_cache_unlock();
147 return ret;
148}
149
ec481c6c
JQ
150/*
151 * An outstanding page request, on the source, having been received
152 * and queued
153 */
154struct RAMSrcPageRequest {
155 RAMBlock *rb;
156 hwaddr offset;
157 hwaddr len;
158
159 QSIMPLEQ_ENTRY(RAMSrcPageRequest) next_req;
160};
161
6f37bb8b
JQ
162/* State of RAM for migration */
163struct RAMState {
204b88b8
JQ
164 /* QEMUFile used for this migration */
165 QEMUFile *f;
6f37bb8b
JQ
166 /* Last block that we have visited searching for dirty pages */
167 RAMBlock *last_seen_block;
168 /* Last block from where we have sent data */
169 RAMBlock *last_sent_block;
269ace29
JQ
170 /* Last dirty target page we have sent */
171 ram_addr_t last_page;
6f37bb8b
JQ
172 /* last ram version we have seen */
173 uint32_t last_version;
174 /* We are in the first round */
175 bool ram_bulk_stage;
8d820d6f
JQ
176 /* How many times we have dirty too many pages */
177 int dirty_rate_high_cnt;
f664da80
JQ
178 /* these variables are used for bitmap sync */
179 /* last time we did a full bitmap_sync */
180 int64_t time_last_bitmap_sync;
eac74159 181 /* bytes transferred at start_time */
c4bdf0cf 182 uint64_t bytes_xfer_prev;
a66cd90c 183 /* number of dirty pages since start_time */
68908ed6 184 uint64_t num_dirty_pages_period;
b5833fde
JQ
185 /* xbzrle misses since the beginning of the period */
186 uint64_t xbzrle_cache_miss_prev;
36040d9c
JQ
187 /* number of iterations at the beginning of period */
188 uint64_t iterations_prev;
23b28c3c
JQ
189 /* Iterations since start */
190 uint64_t iterations;
108cfae0 191 /* protects modification of the bitmap */
9360447d
JQ
192 uint64_t migration_dirty_pages;
193 /* number of dirty bits in the bitmap */
108cfae0 194 QemuMutex bitmap_mutex;
68a098f3
JQ
195 /* The RAMBlock used in the last src_page_requests */
196 RAMBlock *last_req_rb;
ec481c6c
JQ
197 /* Queue of outstanding page requests from the destination */
198 QemuMutex src_page_req_mutex;
199 QSIMPLEQ_HEAD(src_page_requests, RAMSrcPageRequest) src_page_requests;
6f37bb8b
JQ
200};
201typedef struct RAMState RAMState;
202
53518d94 203static RAMState *ram_state;
6f37bb8b 204
9edabd4d 205uint64_t ram_bytes_remaining(void)
2f4fde93 206{
53518d94 207 return ram_state->migration_dirty_pages * TARGET_PAGE_SIZE;
2f4fde93
JQ
208}
209
9360447d 210MigrationStats ram_counters;
96506894 211
b8fb8cb7
DDAG
212/* used by the search for pages to send */
213struct PageSearchStatus {
214 /* Current block being searched */
215 RAMBlock *block;
a935e30f
JQ
216 /* Current page to search from */
217 unsigned long page;
b8fb8cb7
DDAG
218 /* Set once we wrap around */
219 bool complete_round;
220};
221typedef struct PageSearchStatus PageSearchStatus;
222
56e93d26 223struct CompressParam {
56e93d26 224 bool done;
90e56fb4 225 bool quit;
56e93d26
JQ
226 QEMUFile *file;
227 QemuMutex mutex;
228 QemuCond cond;
229 RAMBlock *block;
230 ram_addr_t offset;
231};
232typedef struct CompressParam CompressParam;
233
234struct DecompressParam {
73a8912b 235 bool done;
90e56fb4 236 bool quit;
56e93d26
JQ
237 QemuMutex mutex;
238 QemuCond cond;
239 void *des;
d341d9f3 240 uint8_t *compbuf;
56e93d26
JQ
241 int len;
242};
243typedef struct DecompressParam DecompressParam;
244
245static CompressParam *comp_param;
246static QemuThread *compress_threads;
247/* comp_done_cond is used to wake up the migration thread when
248 * one of the compression threads has finished the compression.
249 * comp_done_lock is used to co-work with comp_done_cond.
250 */
0d9f9a5c
LL
251static QemuMutex comp_done_lock;
252static QemuCond comp_done_cond;
56e93d26
JQ
253/* The empty QEMUFileOps will be used by file in CompressParam */
254static const QEMUFileOps empty_ops = { };
255
56e93d26
JQ
256static DecompressParam *decomp_param;
257static QemuThread *decompress_threads;
73a8912b
LL
258static QemuMutex decomp_done_lock;
259static QemuCond decomp_done_cond;
56e93d26 260
a7a9a88f
LL
261static int do_compress_ram_page(QEMUFile *f, RAMBlock *block,
262 ram_addr_t offset);
56e93d26
JQ
263
264static void *do_data_compress(void *opaque)
265{
266 CompressParam *param = opaque;
a7a9a88f
LL
267 RAMBlock *block;
268 ram_addr_t offset;
56e93d26 269
a7a9a88f 270 qemu_mutex_lock(&param->mutex);
90e56fb4 271 while (!param->quit) {
a7a9a88f
LL
272 if (param->block) {
273 block = param->block;
274 offset = param->offset;
275 param->block = NULL;
276 qemu_mutex_unlock(&param->mutex);
277
278 do_compress_ram_page(param->file, block, offset);
279
0d9f9a5c 280 qemu_mutex_lock(&comp_done_lock);
a7a9a88f 281 param->done = true;
0d9f9a5c
LL
282 qemu_cond_signal(&comp_done_cond);
283 qemu_mutex_unlock(&comp_done_lock);
a7a9a88f
LL
284
285 qemu_mutex_lock(&param->mutex);
286 } else {
56e93d26
JQ
287 qemu_cond_wait(&param->cond, &param->mutex);
288 }
56e93d26 289 }
a7a9a88f 290 qemu_mutex_unlock(&param->mutex);
56e93d26
JQ
291
292 return NULL;
293}
294
295static inline void terminate_compression_threads(void)
296{
297 int idx, thread_count;
298
299 thread_count = migrate_compress_threads();
3d0684b2 300
56e93d26
JQ
301 for (idx = 0; idx < thread_count; idx++) {
302 qemu_mutex_lock(&comp_param[idx].mutex);
90e56fb4 303 comp_param[idx].quit = true;
56e93d26
JQ
304 qemu_cond_signal(&comp_param[idx].cond);
305 qemu_mutex_unlock(&comp_param[idx].mutex);
306 }
307}
308
309void migrate_compress_threads_join(void)
310{
311 int i, thread_count;
312
313 if (!migrate_use_compression()) {
314 return;
315 }
316 terminate_compression_threads();
317 thread_count = migrate_compress_threads();
318 for (i = 0; i < thread_count; i++) {
319 qemu_thread_join(compress_threads + i);
320 qemu_fclose(comp_param[i].file);
321 qemu_mutex_destroy(&comp_param[i].mutex);
322 qemu_cond_destroy(&comp_param[i].cond);
323 }
0d9f9a5c
LL
324 qemu_mutex_destroy(&comp_done_lock);
325 qemu_cond_destroy(&comp_done_cond);
56e93d26
JQ
326 g_free(compress_threads);
327 g_free(comp_param);
56e93d26
JQ
328 compress_threads = NULL;
329 comp_param = NULL;
56e93d26
JQ
330}
331
332void migrate_compress_threads_create(void)
333{
334 int i, thread_count;
335
336 if (!migrate_use_compression()) {
337 return;
338 }
56e93d26
JQ
339 thread_count = migrate_compress_threads();
340 compress_threads = g_new0(QemuThread, thread_count);
341 comp_param = g_new0(CompressParam, thread_count);
0d9f9a5c
LL
342 qemu_cond_init(&comp_done_cond);
343 qemu_mutex_init(&comp_done_lock);
56e93d26 344 for (i = 0; i < thread_count; i++) {
e110aa91
C
345 /* comp_param[i].file is just used as a dummy buffer to save data,
346 * set its ops to empty.
56e93d26
JQ
347 */
348 comp_param[i].file = qemu_fopen_ops(NULL, &empty_ops);
349 comp_param[i].done = true;
90e56fb4 350 comp_param[i].quit = false;
56e93d26
JQ
351 qemu_mutex_init(&comp_param[i].mutex);
352 qemu_cond_init(&comp_param[i].cond);
353 qemu_thread_create(compress_threads + i, "compress",
354 do_data_compress, comp_param + i,
355 QEMU_THREAD_JOINABLE);
356 }
357}
358
359/**
3d0684b2 360 * save_page_header: write page header to wire
56e93d26
JQ
361 *
362 * If this is the 1st block, it also writes the block identification
363 *
3d0684b2 364 * Returns the number of bytes written
56e93d26
JQ
365 *
366 * @f: QEMUFile where to send the data
367 * @block: block that contains the page we want to send
368 * @offset: offset inside the block for the page
369 * in the lower bits, it contains flags
370 */
2bf3aa85
JQ
371static size_t save_page_header(RAMState *rs, QEMUFile *f, RAMBlock *block,
372 ram_addr_t offset)
56e93d26 373{
9f5f380b 374 size_t size, len;
56e93d26 375
24795694
JQ
376 if (block == rs->last_sent_block) {
377 offset |= RAM_SAVE_FLAG_CONTINUE;
378 }
2bf3aa85 379 qemu_put_be64(f, offset);
56e93d26
JQ
380 size = 8;
381
382 if (!(offset & RAM_SAVE_FLAG_CONTINUE)) {
9f5f380b 383 len = strlen(block->idstr);
2bf3aa85
JQ
384 qemu_put_byte(f, len);
385 qemu_put_buffer(f, (uint8_t *)block->idstr, len);
9f5f380b 386 size += 1 + len;
24795694 387 rs->last_sent_block = block;
56e93d26
JQ
388 }
389 return size;
390}
391
3d0684b2
JQ
392/**
393 * mig_throttle_guest_down: throotle down the guest
394 *
395 * Reduce amount of guest cpu execution to hopefully slow down memory
396 * writes. If guest dirty memory rate is reduced below the rate at
397 * which we can transfer pages to the destination then we should be
398 * able to complete migration. Some workloads dirty memory way too
399 * fast and will not effectively converge, even with auto-converge.
070afca2
JH
400 */
401static void mig_throttle_guest_down(void)
402{
403 MigrationState *s = migrate_get_current();
2594f56d
DB
404 uint64_t pct_initial = s->parameters.cpu_throttle_initial;
405 uint64_t pct_icrement = s->parameters.cpu_throttle_increment;
070afca2
JH
406
407 /* We have not started throttling yet. Let's start it. */
408 if (!cpu_throttle_active()) {
409 cpu_throttle_set(pct_initial);
410 } else {
411 /* Throttling already on, just increase the rate */
412 cpu_throttle_set(cpu_throttle_get_percentage() + pct_icrement);
413 }
414}
415
3d0684b2
JQ
416/**
417 * xbzrle_cache_zero_page: insert a zero page in the XBZRLE cache
418 *
6f37bb8b 419 * @rs: current RAM state
3d0684b2
JQ
420 * @current_addr: address for the zero page
421 *
422 * Update the xbzrle cache to reflect a page that's been sent as all 0.
56e93d26
JQ
423 * The important thing is that a stale (not-yet-0'd) page be replaced
424 * by the new data.
425 * As a bonus, if the page wasn't in the cache it gets added so that
3d0684b2 426 * when a small write is made into the 0'd page it gets XBZRLE sent.
56e93d26 427 */
6f37bb8b 428static void xbzrle_cache_zero_page(RAMState *rs, ram_addr_t current_addr)
56e93d26 429{
6f37bb8b 430 if (rs->ram_bulk_stage || !migrate_use_xbzrle()) {
56e93d26
JQ
431 return;
432 }
433
434 /* We don't care if this fails to allocate a new cache page
435 * as long as it updated an old one */
c00e0928 436 cache_insert(XBZRLE.cache, current_addr, XBZRLE.zero_target_page,
9360447d 437 ram_counters.dirty_sync_count);
56e93d26
JQ
438}
439
440#define ENCODING_FLAG_XBZRLE 0x1
441
442/**
443 * save_xbzrle_page: compress and send current page
444 *
445 * Returns: 1 means that we wrote the page
446 * 0 means that page is identical to the one already sent
447 * -1 means that xbzrle would be longer than normal
448 *
5a987738 449 * @rs: current RAM state
3d0684b2
JQ
450 * @current_data: pointer to the address of the page contents
451 * @current_addr: addr of the page
56e93d26
JQ
452 * @block: block that contains the page we want to send
453 * @offset: offset inside the block for the page
454 * @last_stage: if we are at the completion stage
56e93d26 455 */
204b88b8 456static int save_xbzrle_page(RAMState *rs, uint8_t **current_data,
56e93d26 457 ram_addr_t current_addr, RAMBlock *block,
072c2511 458 ram_addr_t offset, bool last_stage)
56e93d26
JQ
459{
460 int encoded_len = 0, bytes_xbzrle;
461 uint8_t *prev_cached_page;
462
9360447d
JQ
463 if (!cache_is_cached(XBZRLE.cache, current_addr,
464 ram_counters.dirty_sync_count)) {
465 xbzrle_counters.cache_miss++;
56e93d26
JQ
466 if (!last_stage) {
467 if (cache_insert(XBZRLE.cache, current_addr, *current_data,
9360447d 468 ram_counters.dirty_sync_count) == -1) {
56e93d26
JQ
469 return -1;
470 } else {
471 /* update *current_data when the page has been
472 inserted into cache */
473 *current_data = get_cached_data(XBZRLE.cache, current_addr);
474 }
475 }
476 return -1;
477 }
478
479 prev_cached_page = get_cached_data(XBZRLE.cache, current_addr);
480
481 /* save current buffer into memory */
482 memcpy(XBZRLE.current_buf, *current_data, TARGET_PAGE_SIZE);
483
484 /* XBZRLE encoding (if there is no overflow) */
485 encoded_len = xbzrle_encode_buffer(prev_cached_page, XBZRLE.current_buf,
486 TARGET_PAGE_SIZE, XBZRLE.encoded_buf,
487 TARGET_PAGE_SIZE);
488 if (encoded_len == 0) {
55c4446b 489 trace_save_xbzrle_page_skipping();
56e93d26
JQ
490 return 0;
491 } else if (encoded_len == -1) {
55c4446b 492 trace_save_xbzrle_page_overflow();
9360447d 493 xbzrle_counters.overflow++;
56e93d26
JQ
494 /* update data in the cache */
495 if (!last_stage) {
496 memcpy(prev_cached_page, *current_data, TARGET_PAGE_SIZE);
497 *current_data = prev_cached_page;
498 }
499 return -1;
500 }
501
502 /* we need to update the data in the cache, in order to get the same data */
503 if (!last_stage) {
504 memcpy(prev_cached_page, XBZRLE.current_buf, TARGET_PAGE_SIZE);
505 }
506
507 /* Send XBZRLE based compressed page */
2bf3aa85 508 bytes_xbzrle = save_page_header(rs, rs->f, block,
204b88b8
JQ
509 offset | RAM_SAVE_FLAG_XBZRLE);
510 qemu_put_byte(rs->f, ENCODING_FLAG_XBZRLE);
511 qemu_put_be16(rs->f, encoded_len);
512 qemu_put_buffer(rs->f, XBZRLE.encoded_buf, encoded_len);
56e93d26 513 bytes_xbzrle += encoded_len + 1 + 2;
9360447d
JQ
514 xbzrle_counters.pages++;
515 xbzrle_counters.bytes += bytes_xbzrle;
516 ram_counters.transferred += bytes_xbzrle;
56e93d26
JQ
517
518 return 1;
519}
520
3d0684b2
JQ
521/**
522 * migration_bitmap_find_dirty: find the next dirty page from start
f3f491fc 523 *
3d0684b2
JQ
524 * Called with rcu_read_lock() to protect migration_bitmap
525 *
526 * Returns the byte offset within memory region of the start of a dirty page
527 *
6f37bb8b 528 * @rs: current RAM state
3d0684b2 529 * @rb: RAMBlock where to search for dirty pages
a935e30f 530 * @start: page where we start the search
f3f491fc 531 */
56e93d26 532static inline
a935e30f 533unsigned long migration_bitmap_find_dirty(RAMState *rs, RAMBlock *rb,
f20e2865 534 unsigned long start)
56e93d26 535{
6b6712ef
JQ
536 unsigned long size = rb->used_length >> TARGET_PAGE_BITS;
537 unsigned long *bitmap = rb->bmap;
56e93d26
JQ
538 unsigned long next;
539
6b6712ef
JQ
540 if (rs->ram_bulk_stage && start > 0) {
541 next = start + 1;
56e93d26 542 } else {
6b6712ef 543 next = find_next_bit(bitmap, size, start);
56e93d26
JQ
544 }
545
6b6712ef 546 return next;
56e93d26
JQ
547}
548
06b10688 549static inline bool migration_bitmap_clear_dirty(RAMState *rs,
f20e2865
JQ
550 RAMBlock *rb,
551 unsigned long page)
a82d593b
DDAG
552{
553 bool ret;
a82d593b 554
6b6712ef 555 ret = test_and_clear_bit(page, rb->bmap);
a82d593b
DDAG
556
557 if (ret) {
0d8ec885 558 rs->migration_dirty_pages--;
a82d593b
DDAG
559 }
560 return ret;
561}
562
15440dd5
JQ
563static void migration_bitmap_sync_range(RAMState *rs, RAMBlock *rb,
564 ram_addr_t start, ram_addr_t length)
56e93d26 565{
0d8ec885 566 rs->migration_dirty_pages +=
6b6712ef 567 cpu_physical_memory_sync_dirty_bitmap(rb, start, length,
0d8ec885 568 &rs->num_dirty_pages_period);
56e93d26
JQ
569}
570
3d0684b2
JQ
571/**
572 * ram_pagesize_summary: calculate all the pagesizes of a VM
573 *
574 * Returns a summary bitmap of the page sizes of all RAMBlocks
575 *
576 * For VMs with just normal pages this is equivalent to the host page
577 * size. If it's got some huge pages then it's the OR of all the
578 * different page sizes.
e8ca1db2
DDAG
579 */
580uint64_t ram_pagesize_summary(void)
581{
582 RAMBlock *block;
583 uint64_t summary = 0;
584
99e15582 585 RAMBLOCK_FOREACH(block) {
e8ca1db2
DDAG
586 summary |= block->page_size;
587 }
588
589 return summary;
590}
591
8d820d6f 592static void migration_bitmap_sync(RAMState *rs)
56e93d26
JQ
593{
594 RAMBlock *block;
56e93d26 595 int64_t end_time;
c4bdf0cf 596 uint64_t bytes_xfer_now;
56e93d26 597
9360447d 598 ram_counters.dirty_sync_count++;
56e93d26 599
f664da80
JQ
600 if (!rs->time_last_bitmap_sync) {
601 rs->time_last_bitmap_sync = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
56e93d26
JQ
602 }
603
604 trace_migration_bitmap_sync_start();
9c1f8f44 605 memory_global_dirty_log_sync();
56e93d26 606
108cfae0 607 qemu_mutex_lock(&rs->bitmap_mutex);
56e93d26 608 rcu_read_lock();
99e15582 609 RAMBLOCK_FOREACH(block) {
15440dd5 610 migration_bitmap_sync_range(rs, block, 0, block->used_length);
56e93d26
JQ
611 }
612 rcu_read_unlock();
108cfae0 613 qemu_mutex_unlock(&rs->bitmap_mutex);
56e93d26 614
a66cd90c 615 trace_migration_bitmap_sync_end(rs->num_dirty_pages_period);
1ffb5dfd 616
56e93d26
JQ
617 end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
618
619 /* more than 1 second = 1000 millisecons */
f664da80 620 if (end_time > rs->time_last_bitmap_sync + 1000) {
d693c6f1 621 /* calculate period counters */
9360447d 622 ram_counters.dirty_pages_rate = rs->num_dirty_pages_period * 1000
d693c6f1 623 / (end_time - rs->time_last_bitmap_sync);
9360447d 624 bytes_xfer_now = ram_counters.transferred;
d693c6f1 625
56e93d26
JQ
626 if (migrate_auto_converge()) {
627 /* The following detection logic can be refined later. For now:
628 Check to see if the dirtied bytes is 50% more than the approx.
629 amount of bytes that just got transferred since the last time we
070afca2
JH
630 were in this routine. If that happens twice, start or increase
631 throttling */
070afca2 632
d693c6f1 633 if ((rs->num_dirty_pages_period * TARGET_PAGE_SIZE >
eac74159 634 (bytes_xfer_now - rs->bytes_xfer_prev) / 2) &&
b4a3c64b 635 (++rs->dirty_rate_high_cnt >= 2)) {
56e93d26 636 trace_migration_throttle();
8d820d6f 637 rs->dirty_rate_high_cnt = 0;
070afca2 638 mig_throttle_guest_down();
d693c6f1 639 }
56e93d26 640 }
070afca2 641
56e93d26 642 if (migrate_use_xbzrle()) {
23b28c3c 643 if (rs->iterations_prev != rs->iterations) {
9360447d
JQ
644 xbzrle_counters.cache_miss_rate =
645 (double)(xbzrle_counters.cache_miss -
b5833fde 646 rs->xbzrle_cache_miss_prev) /
23b28c3c 647 (rs->iterations - rs->iterations_prev);
56e93d26 648 }
23b28c3c 649 rs->iterations_prev = rs->iterations;
9360447d 650 rs->xbzrle_cache_miss_prev = xbzrle_counters.cache_miss;
56e93d26 651 }
d693c6f1
FF
652
653 /* reset period counters */
f664da80 654 rs->time_last_bitmap_sync = end_time;
a66cd90c 655 rs->num_dirty_pages_period = 0;
d2a4d85a 656 rs->bytes_xfer_prev = bytes_xfer_now;
56e93d26 657 }
4addcd4f 658 if (migrate_use_events()) {
9360447d 659 qapi_event_send_migration_pass(ram_counters.dirty_sync_count, NULL);
4addcd4f 660 }
56e93d26
JQ
661}
662
663/**
3d0684b2 664 * save_zero_page: send the zero page to the stream
56e93d26 665 *
3d0684b2 666 * Returns the number of pages written.
56e93d26 667 *
f7ccd61b 668 * @rs: current RAM state
56e93d26
JQ
669 * @block: block that contains the page we want to send
670 * @offset: offset inside the block for the page
671 * @p: pointer to the page
56e93d26 672 */
ce25d337
JQ
673static int save_zero_page(RAMState *rs, RAMBlock *block, ram_addr_t offset,
674 uint8_t *p)
56e93d26
JQ
675{
676 int pages = -1;
677
678 if (is_zero_range(p, TARGET_PAGE_SIZE)) {
9360447d
JQ
679 ram_counters.duplicate++;
680 ram_counters.transferred +=
bb890ed5 681 save_page_header(rs, rs->f, block, offset | RAM_SAVE_FLAG_ZERO);
ce25d337 682 qemu_put_byte(rs->f, 0);
9360447d 683 ram_counters.transferred += 1;
56e93d26
JQ
684 pages = 1;
685 }
686
687 return pages;
688}
689
5727309d 690static void ram_release_pages(const char *rbname, uint64_t offset, int pages)
53f09a10 691{
5727309d 692 if (!migrate_release_ram() || !migration_in_postcopy()) {
53f09a10
PB
693 return;
694 }
695
aaa2064c 696 ram_discard_range(rbname, offset, pages << TARGET_PAGE_BITS);
53f09a10
PB
697}
698
56e93d26 699/**
3d0684b2 700 * ram_save_page: send the given page to the stream
56e93d26 701 *
3d0684b2 702 * Returns the number of pages written.
3fd3c4b3
DDAG
703 * < 0 - error
704 * >=0 - Number of pages written - this might legally be 0
705 * if xbzrle noticed the page was the same.
56e93d26 706 *
6f37bb8b 707 * @rs: current RAM state
56e93d26
JQ
708 * @block: block that contains the page we want to send
709 * @offset: offset inside the block for the page
710 * @last_stage: if we are at the completion stage
56e93d26 711 */
a0a8aa14 712static int ram_save_page(RAMState *rs, PageSearchStatus *pss, bool last_stage)
56e93d26
JQ
713{
714 int pages = -1;
715 uint64_t bytes_xmit;
716 ram_addr_t current_addr;
56e93d26
JQ
717 uint8_t *p;
718 int ret;
719 bool send_async = true;
a08f6890 720 RAMBlock *block = pss->block;
a935e30f 721 ram_addr_t offset = pss->page << TARGET_PAGE_BITS;
56e93d26 722
2f68e399 723 p = block->host + offset;
1db9d8e5 724 trace_ram_save_page(block->idstr, (uint64_t)offset, p);
56e93d26
JQ
725
726 /* In doubt sent page as normal */
727 bytes_xmit = 0;
ce25d337 728 ret = ram_control_save_page(rs->f, block->offset,
56e93d26
JQ
729 offset, TARGET_PAGE_SIZE, &bytes_xmit);
730 if (bytes_xmit) {
9360447d 731 ram_counters.transferred += bytes_xmit;
56e93d26
JQ
732 pages = 1;
733 }
734
735 XBZRLE_cache_lock();
736
737 current_addr = block->offset + offset;
738
56e93d26
JQ
739 if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {
740 if (ret != RAM_SAVE_CONTROL_DELAYED) {
741 if (bytes_xmit > 0) {
9360447d 742 ram_counters.normal++;
56e93d26 743 } else if (bytes_xmit == 0) {
9360447d 744 ram_counters.duplicate++;
56e93d26
JQ
745 }
746 }
747 } else {
ce25d337 748 pages = save_zero_page(rs, block, offset, p);
56e93d26
JQ
749 if (pages > 0) {
750 /* Must let xbzrle know, otherwise a previous (now 0'd) cached
751 * page would be stale
752 */
6f37bb8b 753 xbzrle_cache_zero_page(rs, current_addr);
a935e30f 754 ram_release_pages(block->idstr, offset, pages);
6f37bb8b 755 } else if (!rs->ram_bulk_stage &&
5727309d 756 !migration_in_postcopy() && migrate_use_xbzrle()) {
204b88b8 757 pages = save_xbzrle_page(rs, &p, current_addr, block,
072c2511 758 offset, last_stage);
56e93d26
JQ
759 if (!last_stage) {
760 /* Can't send this cached data async, since the cache page
761 * might get updated before it gets to the wire
762 */
763 send_async = false;
764 }
765 }
766 }
767
768 /* XBZRLE overflow or normal page */
769 if (pages == -1) {
9360447d
JQ
770 ram_counters.transferred +=
771 save_page_header(rs, rs->f, block, offset | RAM_SAVE_FLAG_PAGE);
56e93d26 772 if (send_async) {
ce25d337 773 qemu_put_buffer_async(rs->f, p, TARGET_PAGE_SIZE,
53f09a10 774 migrate_release_ram() &
5727309d 775 migration_in_postcopy());
56e93d26 776 } else {
ce25d337 777 qemu_put_buffer(rs->f, p, TARGET_PAGE_SIZE);
56e93d26 778 }
9360447d 779 ram_counters.transferred += TARGET_PAGE_SIZE;
56e93d26 780 pages = 1;
9360447d 781 ram_counters.normal++;
56e93d26
JQ
782 }
783
784 XBZRLE_cache_unlock();
785
786 return pages;
787}
788
a7a9a88f
LL
789static int do_compress_ram_page(QEMUFile *f, RAMBlock *block,
790 ram_addr_t offset)
56e93d26 791{
53518d94 792 RAMState *rs = ram_state;
56e93d26 793 int bytes_sent, blen;
a7a9a88f 794 uint8_t *p = block->host + (offset & TARGET_PAGE_MASK);
56e93d26 795
2bf3aa85 796 bytes_sent = save_page_header(rs, f, block, offset |
56e93d26 797 RAM_SAVE_FLAG_COMPRESS_PAGE);
a7a9a88f 798 blen = qemu_put_compression_data(f, p, TARGET_PAGE_SIZE,
56e93d26 799 migrate_compress_level());
b3be2896
LL
800 if (blen < 0) {
801 bytes_sent = 0;
802 qemu_file_set_error(migrate_get_current()->to_dst_file, blen);
803 error_report("compressed data failed!");
804 } else {
805 bytes_sent += blen;
5727309d 806 ram_release_pages(block->idstr, offset & TARGET_PAGE_MASK, 1);
b3be2896 807 }
56e93d26
JQ
808
809 return bytes_sent;
810}
811
ce25d337 812static void flush_compressed_data(RAMState *rs)
56e93d26
JQ
813{
814 int idx, len, thread_count;
815
816 if (!migrate_use_compression()) {
817 return;
818 }
819 thread_count = migrate_compress_threads();
a7a9a88f 820
0d9f9a5c 821 qemu_mutex_lock(&comp_done_lock);
56e93d26 822 for (idx = 0; idx < thread_count; idx++) {
a7a9a88f 823 while (!comp_param[idx].done) {
0d9f9a5c 824 qemu_cond_wait(&comp_done_cond, &comp_done_lock);
56e93d26 825 }
a7a9a88f 826 }
0d9f9a5c 827 qemu_mutex_unlock(&comp_done_lock);
a7a9a88f
LL
828
829 for (idx = 0; idx < thread_count; idx++) {
830 qemu_mutex_lock(&comp_param[idx].mutex);
90e56fb4 831 if (!comp_param[idx].quit) {
ce25d337 832 len = qemu_put_qemu_file(rs->f, comp_param[idx].file);
9360447d 833 ram_counters.transferred += len;
56e93d26 834 }
a7a9a88f 835 qemu_mutex_unlock(&comp_param[idx].mutex);
56e93d26
JQ
836 }
837}
838
839static inline void set_compress_params(CompressParam *param, RAMBlock *block,
840 ram_addr_t offset)
841{
842 param->block = block;
843 param->offset = offset;
844}
845
ce25d337
JQ
846static int compress_page_with_multi_thread(RAMState *rs, RAMBlock *block,
847 ram_addr_t offset)
56e93d26
JQ
848{
849 int idx, thread_count, bytes_xmit = -1, pages = -1;
850
851 thread_count = migrate_compress_threads();
0d9f9a5c 852 qemu_mutex_lock(&comp_done_lock);
56e93d26
JQ
853 while (true) {
854 for (idx = 0; idx < thread_count; idx++) {
855 if (comp_param[idx].done) {
a7a9a88f 856 comp_param[idx].done = false;
ce25d337 857 bytes_xmit = qemu_put_qemu_file(rs->f, comp_param[idx].file);
a7a9a88f 858 qemu_mutex_lock(&comp_param[idx].mutex);
56e93d26 859 set_compress_params(&comp_param[idx], block, offset);
a7a9a88f
LL
860 qemu_cond_signal(&comp_param[idx].cond);
861 qemu_mutex_unlock(&comp_param[idx].mutex);
56e93d26 862 pages = 1;
9360447d
JQ
863 ram_counters.normal++;
864 ram_counters.transferred += bytes_xmit;
56e93d26
JQ
865 break;
866 }
867 }
868 if (pages > 0) {
869 break;
870 } else {
0d9f9a5c 871 qemu_cond_wait(&comp_done_cond, &comp_done_lock);
56e93d26
JQ
872 }
873 }
0d9f9a5c 874 qemu_mutex_unlock(&comp_done_lock);
56e93d26
JQ
875
876 return pages;
877}
878
879/**
880 * ram_save_compressed_page: compress the given page and send it to the stream
881 *
3d0684b2 882 * Returns the number of pages written.
56e93d26 883 *
6f37bb8b 884 * @rs: current RAM state
56e93d26
JQ
885 * @block: block that contains the page we want to send
886 * @offset: offset inside the block for the page
887 * @last_stage: if we are at the completion stage
56e93d26 888 */
a0a8aa14
JQ
889static int ram_save_compressed_page(RAMState *rs, PageSearchStatus *pss,
890 bool last_stage)
56e93d26
JQ
891{
892 int pages = -1;
fc50438e 893 uint64_t bytes_xmit = 0;
56e93d26 894 uint8_t *p;
fc50438e 895 int ret, blen;
a08f6890 896 RAMBlock *block = pss->block;
a935e30f 897 ram_addr_t offset = pss->page << TARGET_PAGE_BITS;
56e93d26 898
2f68e399 899 p = block->host + offset;
56e93d26 900
ce25d337 901 ret = ram_control_save_page(rs->f, block->offset,
56e93d26
JQ
902 offset, TARGET_PAGE_SIZE, &bytes_xmit);
903 if (bytes_xmit) {
9360447d 904 ram_counters.transferred += bytes_xmit;
56e93d26
JQ
905 pages = 1;
906 }
56e93d26
JQ
907 if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {
908 if (ret != RAM_SAVE_CONTROL_DELAYED) {
909 if (bytes_xmit > 0) {
9360447d 910 ram_counters.normal++;
56e93d26 911 } else if (bytes_xmit == 0) {
9360447d 912 ram_counters.duplicate++;
56e93d26
JQ
913 }
914 }
915 } else {
916 /* When starting the process of a new block, the first page of
917 * the block should be sent out before other pages in the same
918 * block, and all the pages in last block should have been sent
919 * out, keeping this order is important, because the 'cont' flag
920 * is used to avoid resending the block name.
921 */
6f37bb8b 922 if (block != rs->last_sent_block) {
ce25d337
JQ
923 flush_compressed_data(rs);
924 pages = save_zero_page(rs, block, offset, p);
56e93d26 925 if (pages == -1) {
fc50438e 926 /* Make sure the first page is sent out before other pages */
2bf3aa85 927 bytes_xmit = save_page_header(rs, rs->f, block, offset |
fc50438e 928 RAM_SAVE_FLAG_COMPRESS_PAGE);
ce25d337 929 blen = qemu_put_compression_data(rs->f, p, TARGET_PAGE_SIZE,
fc50438e
LL
930 migrate_compress_level());
931 if (blen > 0) {
9360447d
JQ
932 ram_counters.transferred += bytes_xmit + blen;
933 ram_counters.normal++;
b3be2896 934 pages = 1;
fc50438e 935 } else {
ce25d337 936 qemu_file_set_error(rs->f, blen);
fc50438e 937 error_report("compressed data failed!");
b3be2896 938 }
56e93d26 939 }
53f09a10 940 if (pages > 0) {
a935e30f 941 ram_release_pages(block->idstr, offset, pages);
53f09a10 942 }
56e93d26 943 } else {
ce25d337 944 pages = save_zero_page(rs, block, offset, p);
56e93d26 945 if (pages == -1) {
ce25d337 946 pages = compress_page_with_multi_thread(rs, block, offset);
53f09a10 947 } else {
a935e30f 948 ram_release_pages(block->idstr, offset, pages);
56e93d26
JQ
949 }
950 }
951 }
952
953 return pages;
954}
955
3d0684b2
JQ
956/**
957 * find_dirty_block: find the next dirty page and update any state
958 * associated with the search process.
b9e60928 959 *
3d0684b2 960 * Returns if a page is found
b9e60928 961 *
6f37bb8b 962 * @rs: current RAM state
3d0684b2
JQ
963 * @pss: data about the state of the current dirty page scan
964 * @again: set to false if the search has scanned the whole of RAM
b9e60928 965 */
f20e2865 966static bool find_dirty_block(RAMState *rs, PageSearchStatus *pss, bool *again)
b9e60928 967{
f20e2865 968 pss->page = migration_bitmap_find_dirty(rs, pss->block, pss->page);
6f37bb8b 969 if (pss->complete_round && pss->block == rs->last_seen_block &&
a935e30f 970 pss->page >= rs->last_page) {
b9e60928
DDAG
971 /*
972 * We've been once around the RAM and haven't found anything.
973 * Give up.
974 */
975 *again = false;
976 return false;
977 }
a935e30f 978 if ((pss->page << TARGET_PAGE_BITS) >= pss->block->used_length) {
b9e60928 979 /* Didn't find anything in this RAM Block */
a935e30f 980 pss->page = 0;
b9e60928
DDAG
981 pss->block = QLIST_NEXT_RCU(pss->block, next);
982 if (!pss->block) {
983 /* Hit the end of the list */
984 pss->block = QLIST_FIRST_RCU(&ram_list.blocks);
985 /* Flag that we've looped */
986 pss->complete_round = true;
6f37bb8b 987 rs->ram_bulk_stage = false;
b9e60928
DDAG
988 if (migrate_use_xbzrle()) {
989 /* If xbzrle is on, stop using the data compression at this
990 * point. In theory, xbzrle can do better than compression.
991 */
ce25d337 992 flush_compressed_data(rs);
b9e60928
DDAG
993 }
994 }
995 /* Didn't find anything this time, but try again on the new block */
996 *again = true;
997 return false;
998 } else {
999 /* Can go around again, but... */
1000 *again = true;
1001 /* We've found something so probably don't need to */
1002 return true;
1003 }
1004}
1005
3d0684b2
JQ
1006/**
1007 * unqueue_page: gets a page of the queue
1008 *
a82d593b 1009 * Helper for 'get_queued_page' - gets a page off the queue
a82d593b 1010 *
3d0684b2
JQ
1011 * Returns the block of the page (or NULL if none available)
1012 *
ec481c6c 1013 * @rs: current RAM state
3d0684b2 1014 * @offset: used to return the offset within the RAMBlock
a82d593b 1015 */
f20e2865 1016static RAMBlock *unqueue_page(RAMState *rs, ram_addr_t *offset)
a82d593b
DDAG
1017{
1018 RAMBlock *block = NULL;
1019
ec481c6c
JQ
1020 qemu_mutex_lock(&rs->src_page_req_mutex);
1021 if (!QSIMPLEQ_EMPTY(&rs->src_page_requests)) {
1022 struct RAMSrcPageRequest *entry =
1023 QSIMPLEQ_FIRST(&rs->src_page_requests);
a82d593b
DDAG
1024 block = entry->rb;
1025 *offset = entry->offset;
a82d593b
DDAG
1026
1027 if (entry->len > TARGET_PAGE_SIZE) {
1028 entry->len -= TARGET_PAGE_SIZE;
1029 entry->offset += TARGET_PAGE_SIZE;
1030 } else {
1031 memory_region_unref(block->mr);
ec481c6c 1032 QSIMPLEQ_REMOVE_HEAD(&rs->src_page_requests, next_req);
a82d593b
DDAG
1033 g_free(entry);
1034 }
1035 }
ec481c6c 1036 qemu_mutex_unlock(&rs->src_page_req_mutex);
a82d593b
DDAG
1037
1038 return block;
1039}
1040
3d0684b2
JQ
1041/**
1042 * get_queued_page: unqueue a page from the postocpy requests
1043 *
1044 * Skips pages that are already sent (!dirty)
a82d593b 1045 *
3d0684b2 1046 * Returns if a queued page is found
a82d593b 1047 *
6f37bb8b 1048 * @rs: current RAM state
3d0684b2 1049 * @pss: data about the state of the current dirty page scan
a82d593b 1050 */
f20e2865 1051static bool get_queued_page(RAMState *rs, PageSearchStatus *pss)
a82d593b
DDAG
1052{
1053 RAMBlock *block;
1054 ram_addr_t offset;
1055 bool dirty;
1056
1057 do {
f20e2865 1058 block = unqueue_page(rs, &offset);
a82d593b
DDAG
1059 /*
1060 * We're sending this page, and since it's postcopy nothing else
1061 * will dirty it, and we must make sure it doesn't get sent again
1062 * even if this queue request was received after the background
1063 * search already sent it.
1064 */
1065 if (block) {
f20e2865
JQ
1066 unsigned long page;
1067
6b6712ef
JQ
1068 page = offset >> TARGET_PAGE_BITS;
1069 dirty = test_bit(page, block->bmap);
a82d593b 1070 if (!dirty) {
06b10688 1071 trace_get_queued_page_not_dirty(block->idstr, (uint64_t)offset,
6b6712ef 1072 page, test_bit(page, block->unsentmap));
a82d593b 1073 } else {
f20e2865 1074 trace_get_queued_page(block->idstr, (uint64_t)offset, page);
a82d593b
DDAG
1075 }
1076 }
1077
1078 } while (block && !dirty);
1079
1080 if (block) {
1081 /*
1082 * As soon as we start servicing pages out of order, then we have
1083 * to kill the bulk stage, since the bulk stage assumes
1084 * in (migration_bitmap_find_and_reset_dirty) that every page is
1085 * dirty, that's no longer true.
1086 */
6f37bb8b 1087 rs->ram_bulk_stage = false;
a82d593b
DDAG
1088
1089 /*
1090 * We want the background search to continue from the queued page
1091 * since the guest is likely to want other pages near to the page
1092 * it just requested.
1093 */
1094 pss->block = block;
a935e30f 1095 pss->page = offset >> TARGET_PAGE_BITS;
a82d593b
DDAG
1096 }
1097
1098 return !!block;
1099}
1100
6c595cde 1101/**
5e58f968
JQ
1102 * migration_page_queue_free: drop any remaining pages in the ram
1103 * request queue
6c595cde 1104 *
3d0684b2
JQ
1105 * It should be empty at the end anyway, but in error cases there may
1106 * be some left. in case that there is any page left, we drop it.
1107 *
6c595cde 1108 */
83c13382 1109static void migration_page_queue_free(RAMState *rs)
6c595cde 1110{
ec481c6c 1111 struct RAMSrcPageRequest *mspr, *next_mspr;
6c595cde
DDAG
1112 /* This queue generally should be empty - but in the case of a failed
1113 * migration might have some droppings in.
1114 */
1115 rcu_read_lock();
ec481c6c 1116 QSIMPLEQ_FOREACH_SAFE(mspr, &rs->src_page_requests, next_req, next_mspr) {
6c595cde 1117 memory_region_unref(mspr->rb->mr);
ec481c6c 1118 QSIMPLEQ_REMOVE_HEAD(&rs->src_page_requests, next_req);
6c595cde
DDAG
1119 g_free(mspr);
1120 }
1121 rcu_read_unlock();
1122}
1123
1124/**
3d0684b2
JQ
1125 * ram_save_queue_pages: queue the page for transmission
1126 *
1127 * A request from postcopy destination for example.
1128 *
1129 * Returns zero on success or negative on error
1130 *
3d0684b2
JQ
1131 * @rbname: Name of the RAMBLock of the request. NULL means the
1132 * same that last one.
1133 * @start: starting address from the start of the RAMBlock
1134 * @len: length (in bytes) to send
6c595cde 1135 */
96506894 1136int ram_save_queue_pages(const char *rbname, ram_addr_t start, ram_addr_t len)
6c595cde
DDAG
1137{
1138 RAMBlock *ramblock;
53518d94 1139 RAMState *rs = ram_state;
6c595cde 1140
9360447d 1141 ram_counters.postcopy_requests++;
6c595cde
DDAG
1142 rcu_read_lock();
1143 if (!rbname) {
1144 /* Reuse last RAMBlock */
68a098f3 1145 ramblock = rs->last_req_rb;
6c595cde
DDAG
1146
1147 if (!ramblock) {
1148 /*
1149 * Shouldn't happen, we can't reuse the last RAMBlock if
1150 * it's the 1st request.
1151 */
1152 error_report("ram_save_queue_pages no previous block");
1153 goto err;
1154 }
1155 } else {
1156 ramblock = qemu_ram_block_by_name(rbname);
1157
1158 if (!ramblock) {
1159 /* We shouldn't be asked for a non-existent RAMBlock */
1160 error_report("ram_save_queue_pages no block '%s'", rbname);
1161 goto err;
1162 }
68a098f3 1163 rs->last_req_rb = ramblock;
6c595cde
DDAG
1164 }
1165 trace_ram_save_queue_pages(ramblock->idstr, start, len);
1166 if (start+len > ramblock->used_length) {
9458ad6b
JQ
1167 error_report("%s request overrun start=" RAM_ADDR_FMT " len="
1168 RAM_ADDR_FMT " blocklen=" RAM_ADDR_FMT,
6c595cde
DDAG
1169 __func__, start, len, ramblock->used_length);
1170 goto err;
1171 }
1172
ec481c6c
JQ
1173 struct RAMSrcPageRequest *new_entry =
1174 g_malloc0(sizeof(struct RAMSrcPageRequest));
6c595cde
DDAG
1175 new_entry->rb = ramblock;
1176 new_entry->offset = start;
1177 new_entry->len = len;
1178
1179 memory_region_ref(ramblock->mr);
ec481c6c
JQ
1180 qemu_mutex_lock(&rs->src_page_req_mutex);
1181 QSIMPLEQ_INSERT_TAIL(&rs->src_page_requests, new_entry, next_req);
1182 qemu_mutex_unlock(&rs->src_page_req_mutex);
6c595cde
DDAG
1183 rcu_read_unlock();
1184
1185 return 0;
1186
1187err:
1188 rcu_read_unlock();
1189 return -1;
1190}
1191
a82d593b 1192/**
3d0684b2 1193 * ram_save_target_page: save one target page
a82d593b 1194 *
3d0684b2 1195 * Returns the number of pages written
a82d593b 1196 *
6f37bb8b 1197 * @rs: current RAM state
3d0684b2 1198 * @ms: current migration state
3d0684b2 1199 * @pss: data about the page we want to send
a82d593b 1200 * @last_stage: if we are at the completion stage
a82d593b 1201 */
a0a8aa14 1202static int ram_save_target_page(RAMState *rs, PageSearchStatus *pss,
f20e2865 1203 bool last_stage)
a82d593b
DDAG
1204{
1205 int res = 0;
1206
1207 /* Check the pages is dirty and if it is send it */
f20e2865 1208 if (migration_bitmap_clear_dirty(rs, pss->block, pss->page)) {
6d358d94
JQ
1209 /*
1210 * If xbzrle is on, stop using the data compression after first
1211 * round of migration even if compression is enabled. In theory,
1212 * xbzrle can do better than compression.
1213 */
6b6712ef
JQ
1214 if (migrate_use_compression() &&
1215 (rs->ram_bulk_stage || !migrate_use_xbzrle())) {
a0a8aa14 1216 res = ram_save_compressed_page(rs, pss, last_stage);
a82d593b 1217 } else {
a0a8aa14 1218 res = ram_save_page(rs, pss, last_stage);
a82d593b
DDAG
1219 }
1220
1221 if (res < 0) {
1222 return res;
1223 }
6b6712ef
JQ
1224 if (pss->block->unsentmap) {
1225 clear_bit(pss->page, pss->block->unsentmap);
a82d593b
DDAG
1226 }
1227 }
1228
1229 return res;
1230}
1231
1232/**
3d0684b2 1233 * ram_save_host_page: save a whole host page
a82d593b 1234 *
3d0684b2
JQ
1235 * Starting at *offset send pages up to the end of the current host
1236 * page. It's valid for the initial offset to point into the middle of
1237 * a host page in which case the remainder of the hostpage is sent.
1238 * Only dirty target pages are sent. Note that the host page size may
1239 * be a huge page for this block.
1eb3fc0a
DDAG
1240 * The saving stops at the boundary of the used_length of the block
1241 * if the RAMBlock isn't a multiple of the host page size.
a82d593b 1242 *
3d0684b2
JQ
1243 * Returns the number of pages written or negative on error
1244 *
6f37bb8b 1245 * @rs: current RAM state
3d0684b2 1246 * @ms: current migration state
3d0684b2 1247 * @pss: data about the page we want to send
a82d593b 1248 * @last_stage: if we are at the completion stage
a82d593b 1249 */
a0a8aa14 1250static int ram_save_host_page(RAMState *rs, PageSearchStatus *pss,
f20e2865 1251 bool last_stage)
a82d593b
DDAG
1252{
1253 int tmppages, pages = 0;
a935e30f
JQ
1254 size_t pagesize_bits =
1255 qemu_ram_pagesize(pss->block) >> TARGET_PAGE_BITS;
4c011c37 1256
a82d593b 1257 do {
f20e2865 1258 tmppages = ram_save_target_page(rs, pss, last_stage);
a82d593b
DDAG
1259 if (tmppages < 0) {
1260 return tmppages;
1261 }
1262
1263 pages += tmppages;
a935e30f 1264 pss->page++;
1eb3fc0a
DDAG
1265 } while ((pss->page & (pagesize_bits - 1)) &&
1266 offset_in_ramblock(pss->block, pss->page << TARGET_PAGE_BITS));
a82d593b
DDAG
1267
1268 /* The offset we leave with is the last one we looked at */
a935e30f 1269 pss->page--;
a82d593b
DDAG
1270 return pages;
1271}
6c595cde 1272
56e93d26 1273/**
3d0684b2 1274 * ram_find_and_save_block: finds a dirty page and sends it to f
56e93d26
JQ
1275 *
1276 * Called within an RCU critical section.
1277 *
3d0684b2 1278 * Returns the number of pages written where zero means no dirty pages
56e93d26 1279 *
6f37bb8b 1280 * @rs: current RAM state
56e93d26 1281 * @last_stage: if we are at the completion stage
a82d593b
DDAG
1282 *
1283 * On systems where host-page-size > target-page-size it will send all the
1284 * pages in a host page that are dirty.
56e93d26
JQ
1285 */
1286
ce25d337 1287static int ram_find_and_save_block(RAMState *rs, bool last_stage)
56e93d26 1288{
b8fb8cb7 1289 PageSearchStatus pss;
56e93d26 1290 int pages = 0;
b9e60928 1291 bool again, found;
56e93d26 1292
0827b9e9
AA
1293 /* No dirty page as there is zero RAM */
1294 if (!ram_bytes_total()) {
1295 return pages;
1296 }
1297
6f37bb8b 1298 pss.block = rs->last_seen_block;
a935e30f 1299 pss.page = rs->last_page;
b8fb8cb7
DDAG
1300 pss.complete_round = false;
1301
1302 if (!pss.block) {
1303 pss.block = QLIST_FIRST_RCU(&ram_list.blocks);
1304 }
56e93d26 1305
b9e60928 1306 do {
a82d593b 1307 again = true;
f20e2865 1308 found = get_queued_page(rs, &pss);
b9e60928 1309
a82d593b
DDAG
1310 if (!found) {
1311 /* priority queue empty, so just search for something dirty */
f20e2865 1312 found = find_dirty_block(rs, &pss, &again);
a82d593b 1313 }
f3f491fc 1314
a82d593b 1315 if (found) {
f20e2865 1316 pages = ram_save_host_page(rs, &pss, last_stage);
56e93d26 1317 }
b9e60928 1318 } while (!pages && again);
56e93d26 1319
6f37bb8b 1320 rs->last_seen_block = pss.block;
a935e30f 1321 rs->last_page = pss.page;
56e93d26
JQ
1322
1323 return pages;
1324}
1325
1326void acct_update_position(QEMUFile *f, size_t size, bool zero)
1327{
1328 uint64_t pages = size / TARGET_PAGE_SIZE;
f7ccd61b 1329
56e93d26 1330 if (zero) {
9360447d 1331 ram_counters.duplicate += pages;
56e93d26 1332 } else {
9360447d
JQ
1333 ram_counters.normal += pages;
1334 ram_counters.transferred += size;
56e93d26
JQ
1335 qemu_update_position(f, size);
1336 }
1337}
1338
56e93d26
JQ
1339uint64_t ram_bytes_total(void)
1340{
1341 RAMBlock *block;
1342 uint64_t total = 0;
1343
1344 rcu_read_lock();
99e15582 1345 RAMBLOCK_FOREACH(block) {
56e93d26 1346 total += block->used_length;
99e15582 1347 }
56e93d26
JQ
1348 rcu_read_unlock();
1349 return total;
1350}
1351
f265e0e4 1352static void xbzrle_load_setup(void)
56e93d26 1353{
f265e0e4 1354 XBZRLE.decoded_buf = g_malloc(TARGET_PAGE_SIZE);
56e93d26
JQ
1355}
1356
f265e0e4
JQ
1357static void xbzrle_load_cleanup(void)
1358{
1359 g_free(XBZRLE.decoded_buf);
1360 XBZRLE.decoded_buf = NULL;
1361}
1362
1363static void ram_save_cleanup(void *opaque)
56e93d26 1364{
53518d94 1365 RAMState **rsp = opaque;
6b6712ef 1366 RAMBlock *block;
eb859c53 1367
2ff64038
LZ
1368 /* caller have hold iothread lock or is in a bh, so there is
1369 * no writing race against this migration_bitmap
1370 */
6b6712ef
JQ
1371 memory_global_dirty_log_stop();
1372
1373 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1374 g_free(block->bmap);
1375 block->bmap = NULL;
1376 g_free(block->unsentmap);
1377 block->unsentmap = NULL;
56e93d26
JQ
1378 }
1379
1380 XBZRLE_cache_lock();
1381 if (XBZRLE.cache) {
1382 cache_fini(XBZRLE.cache);
1383 g_free(XBZRLE.encoded_buf);
1384 g_free(XBZRLE.current_buf);
c00e0928 1385 g_free(XBZRLE.zero_target_page);
56e93d26
JQ
1386 XBZRLE.cache = NULL;
1387 XBZRLE.encoded_buf = NULL;
1388 XBZRLE.current_buf = NULL;
c00e0928 1389 XBZRLE.zero_target_page = NULL;
56e93d26
JQ
1390 }
1391 XBZRLE_cache_unlock();
53518d94
JQ
1392 migration_page_queue_free(*rsp);
1393 g_free(*rsp);
1394 *rsp = NULL;
56e93d26
JQ
1395}
1396
6f37bb8b 1397static void ram_state_reset(RAMState *rs)
56e93d26 1398{
6f37bb8b
JQ
1399 rs->last_seen_block = NULL;
1400 rs->last_sent_block = NULL;
269ace29 1401 rs->last_page = 0;
6f37bb8b
JQ
1402 rs->last_version = ram_list.version;
1403 rs->ram_bulk_stage = true;
56e93d26
JQ
1404}
1405
1406#define MAX_WAIT 50 /* ms, half buffered_file limit */
1407
4f2e4252
DDAG
1408/*
1409 * 'expected' is the value you expect the bitmap mostly to be full
1410 * of; it won't bother printing lines that are all this value.
1411 * If 'todump' is null the migration bitmap is dumped.
1412 */
6b6712ef
JQ
1413void ram_debug_dump_bitmap(unsigned long *todump, bool expected,
1414 unsigned long pages)
4f2e4252 1415{
4f2e4252
DDAG
1416 int64_t cur;
1417 int64_t linelen = 128;
1418 char linebuf[129];
1419
6b6712ef 1420 for (cur = 0; cur < pages; cur += linelen) {
4f2e4252
DDAG
1421 int64_t curb;
1422 bool found = false;
1423 /*
1424 * Last line; catch the case where the line length
1425 * is longer than remaining ram
1426 */
6b6712ef
JQ
1427 if (cur + linelen > pages) {
1428 linelen = pages - cur;
4f2e4252
DDAG
1429 }
1430 for (curb = 0; curb < linelen; curb++) {
1431 bool thisbit = test_bit(cur + curb, todump);
1432 linebuf[curb] = thisbit ? '1' : '.';
1433 found = found || (thisbit != expected);
1434 }
1435 if (found) {
1436 linebuf[curb] = '\0';
1437 fprintf(stderr, "0x%08" PRIx64 " : %s\n", cur, linebuf);
1438 }
1439 }
1440}
1441
e0b266f0
DDAG
1442/* **** functions for postcopy ***** */
1443
ced1c616
PB
1444void ram_postcopy_migrated_memory_release(MigrationState *ms)
1445{
1446 struct RAMBlock *block;
ced1c616 1447
99e15582 1448 RAMBLOCK_FOREACH(block) {
6b6712ef
JQ
1449 unsigned long *bitmap = block->bmap;
1450 unsigned long range = block->used_length >> TARGET_PAGE_BITS;
1451 unsigned long run_start = find_next_zero_bit(bitmap, range, 0);
ced1c616
PB
1452
1453 while (run_start < range) {
1454 unsigned long run_end = find_next_bit(bitmap, range, run_start + 1);
aaa2064c 1455 ram_discard_range(block->idstr, run_start << TARGET_PAGE_BITS,
ced1c616
PB
1456 (run_end - run_start) << TARGET_PAGE_BITS);
1457 run_start = find_next_zero_bit(bitmap, range, run_end + 1);
1458 }
1459 }
1460}
1461
3d0684b2
JQ
1462/**
1463 * postcopy_send_discard_bm_ram: discard a RAMBlock
1464 *
1465 * Returns zero on success
1466 *
e0b266f0
DDAG
1467 * Callback from postcopy_each_ram_send_discard for each RAMBlock
1468 * Note: At this point the 'unsentmap' is the processed bitmap combined
1469 * with the dirtymap; so a '1' means it's either dirty or unsent.
3d0684b2
JQ
1470 *
1471 * @ms: current migration state
1472 * @pds: state for postcopy
1473 * @start: RAMBlock starting page
1474 * @length: RAMBlock size
e0b266f0
DDAG
1475 */
1476static int postcopy_send_discard_bm_ram(MigrationState *ms,
1477 PostcopyDiscardState *pds,
6b6712ef 1478 RAMBlock *block)
e0b266f0 1479{
6b6712ef 1480 unsigned long end = block->used_length >> TARGET_PAGE_BITS;
e0b266f0 1481 unsigned long current;
6b6712ef 1482 unsigned long *unsentmap = block->unsentmap;
e0b266f0 1483
6b6712ef 1484 for (current = 0; current < end; ) {
e0b266f0
DDAG
1485 unsigned long one = find_next_bit(unsentmap, end, current);
1486
1487 if (one <= end) {
1488 unsigned long zero = find_next_zero_bit(unsentmap, end, one + 1);
1489 unsigned long discard_length;
1490
1491 if (zero >= end) {
1492 discard_length = end - one;
1493 } else {
1494 discard_length = zero - one;
1495 }
d688c62d
DDAG
1496 if (discard_length) {
1497 postcopy_discard_send_range(ms, pds, one, discard_length);
1498 }
e0b266f0
DDAG
1499 current = one + discard_length;
1500 } else {
1501 current = one;
1502 }
1503 }
1504
1505 return 0;
1506}
1507
3d0684b2
JQ
1508/**
1509 * postcopy_each_ram_send_discard: discard all RAMBlocks
1510 *
1511 * Returns 0 for success or negative for error
1512 *
e0b266f0
DDAG
1513 * Utility for the outgoing postcopy code.
1514 * Calls postcopy_send_discard_bm_ram for each RAMBlock
1515 * passing it bitmap indexes and name.
e0b266f0
DDAG
1516 * (qemu_ram_foreach_block ends up passing unscaled lengths
1517 * which would mean postcopy code would have to deal with target page)
3d0684b2
JQ
1518 *
1519 * @ms: current migration state
e0b266f0
DDAG
1520 */
1521static int postcopy_each_ram_send_discard(MigrationState *ms)
1522{
1523 struct RAMBlock *block;
1524 int ret;
1525
99e15582 1526 RAMBLOCK_FOREACH(block) {
6b6712ef
JQ
1527 PostcopyDiscardState *pds =
1528 postcopy_discard_send_init(ms, block->idstr);
e0b266f0
DDAG
1529
1530 /*
1531 * Postcopy sends chunks of bitmap over the wire, but it
1532 * just needs indexes at this point, avoids it having
1533 * target page specific code.
1534 */
6b6712ef 1535 ret = postcopy_send_discard_bm_ram(ms, pds, block);
e0b266f0
DDAG
1536 postcopy_discard_send_finish(ms, pds);
1537 if (ret) {
1538 return ret;
1539 }
1540 }
1541
1542 return 0;
1543}
1544
3d0684b2
JQ
1545/**
1546 * postcopy_chunk_hostpages_pass: canocalize bitmap in hostpages
1547 *
1548 * Helper for postcopy_chunk_hostpages; it's called twice to
1549 * canonicalize the two bitmaps, that are similar, but one is
1550 * inverted.
99e314eb 1551 *
3d0684b2
JQ
1552 * Postcopy requires that all target pages in a hostpage are dirty or
1553 * clean, not a mix. This function canonicalizes the bitmaps.
99e314eb 1554 *
3d0684b2
JQ
1555 * @ms: current migration state
1556 * @unsent_pass: if true we need to canonicalize partially unsent host pages
1557 * otherwise we need to canonicalize partially dirty host pages
1558 * @block: block that contains the page we want to canonicalize
1559 * @pds: state for postcopy
99e314eb
DDAG
1560 */
1561static void postcopy_chunk_hostpages_pass(MigrationState *ms, bool unsent_pass,
1562 RAMBlock *block,
1563 PostcopyDiscardState *pds)
1564{
53518d94 1565 RAMState *rs = ram_state;
6b6712ef
JQ
1566 unsigned long *bitmap = block->bmap;
1567 unsigned long *unsentmap = block->unsentmap;
29c59172 1568 unsigned int host_ratio = block->page_size / TARGET_PAGE_SIZE;
6b6712ef 1569 unsigned long pages = block->used_length >> TARGET_PAGE_BITS;
99e314eb
DDAG
1570 unsigned long run_start;
1571
29c59172
DDAG
1572 if (block->page_size == TARGET_PAGE_SIZE) {
1573 /* Easy case - TPS==HPS for a non-huge page RAMBlock */
1574 return;
1575 }
1576
99e314eb
DDAG
1577 if (unsent_pass) {
1578 /* Find a sent page */
6b6712ef 1579 run_start = find_next_zero_bit(unsentmap, pages, 0);
99e314eb
DDAG
1580 } else {
1581 /* Find a dirty page */
6b6712ef 1582 run_start = find_next_bit(bitmap, pages, 0);
99e314eb
DDAG
1583 }
1584
6b6712ef 1585 while (run_start < pages) {
99e314eb
DDAG
1586 bool do_fixup = false;
1587 unsigned long fixup_start_addr;
1588 unsigned long host_offset;
1589
1590 /*
1591 * If the start of this run of pages is in the middle of a host
1592 * page, then we need to fixup this host page.
1593 */
1594 host_offset = run_start % host_ratio;
1595 if (host_offset) {
1596 do_fixup = true;
1597 run_start -= host_offset;
1598 fixup_start_addr = run_start;
1599 /* For the next pass */
1600 run_start = run_start + host_ratio;
1601 } else {
1602 /* Find the end of this run */
1603 unsigned long run_end;
1604 if (unsent_pass) {
6b6712ef 1605 run_end = find_next_bit(unsentmap, pages, run_start + 1);
99e314eb 1606 } else {
6b6712ef 1607 run_end = find_next_zero_bit(bitmap, pages, run_start + 1);
99e314eb
DDAG
1608 }
1609 /*
1610 * If the end isn't at the start of a host page, then the
1611 * run doesn't finish at the end of a host page
1612 * and we need to discard.
1613 */
1614 host_offset = run_end % host_ratio;
1615 if (host_offset) {
1616 do_fixup = true;
1617 fixup_start_addr = run_end - host_offset;
1618 /*
1619 * This host page has gone, the next loop iteration starts
1620 * from after the fixup
1621 */
1622 run_start = fixup_start_addr + host_ratio;
1623 } else {
1624 /*
1625 * No discards on this iteration, next loop starts from
1626 * next sent/dirty page
1627 */
1628 run_start = run_end + 1;
1629 }
1630 }
1631
1632 if (do_fixup) {
1633 unsigned long page;
1634
1635 /* Tell the destination to discard this page */
1636 if (unsent_pass || !test_bit(fixup_start_addr, unsentmap)) {
1637 /* For the unsent_pass we:
1638 * discard partially sent pages
1639 * For the !unsent_pass (dirty) we:
1640 * discard partially dirty pages that were sent
1641 * (any partially sent pages were already discarded
1642 * by the previous unsent_pass)
1643 */
1644 postcopy_discard_send_range(ms, pds, fixup_start_addr,
1645 host_ratio);
1646 }
1647
1648 /* Clean up the bitmap */
1649 for (page = fixup_start_addr;
1650 page < fixup_start_addr + host_ratio; page++) {
1651 /* All pages in this host page are now not sent */
1652 set_bit(page, unsentmap);
1653
1654 /*
1655 * Remark them as dirty, updating the count for any pages
1656 * that weren't previously dirty.
1657 */
0d8ec885 1658 rs->migration_dirty_pages += !test_and_set_bit(page, bitmap);
99e314eb
DDAG
1659 }
1660 }
1661
1662 if (unsent_pass) {
1663 /* Find the next sent page for the next iteration */
6b6712ef 1664 run_start = find_next_zero_bit(unsentmap, pages, run_start);
99e314eb
DDAG
1665 } else {
1666 /* Find the next dirty page for the next iteration */
6b6712ef 1667 run_start = find_next_bit(bitmap, pages, run_start);
99e314eb
DDAG
1668 }
1669 }
1670}
1671
3d0684b2
JQ
1672/**
1673 * postcopy_chuck_hostpages: discrad any partially sent host page
1674 *
99e314eb
DDAG
1675 * Utility for the outgoing postcopy code.
1676 *
1677 * Discard any partially sent host-page size chunks, mark any partially
29c59172
DDAG
1678 * dirty host-page size chunks as all dirty. In this case the host-page
1679 * is the host-page for the particular RAMBlock, i.e. it might be a huge page
99e314eb 1680 *
3d0684b2
JQ
1681 * Returns zero on success
1682 *
1683 * @ms: current migration state
6b6712ef 1684 * @block: block we want to work with
99e314eb 1685 */
6b6712ef 1686static int postcopy_chunk_hostpages(MigrationState *ms, RAMBlock *block)
99e314eb 1687{
6b6712ef
JQ
1688 PostcopyDiscardState *pds =
1689 postcopy_discard_send_init(ms, block->idstr);
99e314eb 1690
6b6712ef
JQ
1691 /* First pass: Discard all partially sent host pages */
1692 postcopy_chunk_hostpages_pass(ms, true, block, pds);
1693 /*
1694 * Second pass: Ensure that all partially dirty host pages are made
1695 * fully dirty.
1696 */
1697 postcopy_chunk_hostpages_pass(ms, false, block, pds);
99e314eb 1698
6b6712ef 1699 postcopy_discard_send_finish(ms, pds);
99e314eb
DDAG
1700 return 0;
1701}
1702
3d0684b2
JQ
1703/**
1704 * ram_postcopy_send_discard_bitmap: transmit the discard bitmap
1705 *
1706 * Returns zero on success
1707 *
e0b266f0
DDAG
1708 * Transmit the set of pages to be discarded after precopy to the target
1709 * these are pages that:
1710 * a) Have been previously transmitted but are now dirty again
1711 * b) Pages that have never been transmitted, this ensures that
1712 * any pages on the destination that have been mapped by background
1713 * tasks get discarded (transparent huge pages is the specific concern)
1714 * Hopefully this is pretty sparse
3d0684b2
JQ
1715 *
1716 * @ms: current migration state
e0b266f0
DDAG
1717 */
1718int ram_postcopy_send_discard_bitmap(MigrationState *ms)
1719{
53518d94 1720 RAMState *rs = ram_state;
6b6712ef 1721 RAMBlock *block;
e0b266f0 1722 int ret;
e0b266f0
DDAG
1723
1724 rcu_read_lock();
1725
1726 /* This should be our last sync, the src is now paused */
eb859c53 1727 migration_bitmap_sync(rs);
e0b266f0 1728
6b6712ef
JQ
1729 /* Easiest way to make sure we don't resume in the middle of a host-page */
1730 rs->last_seen_block = NULL;
1731 rs->last_sent_block = NULL;
1732 rs->last_page = 0;
e0b266f0 1733
6b6712ef
JQ
1734 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1735 unsigned long pages = block->used_length >> TARGET_PAGE_BITS;
1736 unsigned long *bitmap = block->bmap;
1737 unsigned long *unsentmap = block->unsentmap;
1738
1739 if (!unsentmap) {
1740 /* We don't have a safe way to resize the sentmap, so
1741 * if the bitmap was resized it will be NULL at this
1742 * point.
1743 */
1744 error_report("migration ram resized during precopy phase");
1745 rcu_read_unlock();
1746 return -EINVAL;
1747 }
1748 /* Deal with TPS != HPS and huge pages */
1749 ret = postcopy_chunk_hostpages(ms, block);
1750 if (ret) {
1751 rcu_read_unlock();
1752 return ret;
1753 }
e0b266f0 1754
6b6712ef
JQ
1755 /*
1756 * Update the unsentmap to be unsentmap = unsentmap | dirty
1757 */
1758 bitmap_or(unsentmap, unsentmap, bitmap, pages);
e0b266f0 1759#ifdef DEBUG_POSTCOPY
6b6712ef 1760 ram_debug_dump_bitmap(unsentmap, true, pages);
e0b266f0 1761#endif
6b6712ef
JQ
1762 }
1763 trace_ram_postcopy_send_discard_bitmap();
e0b266f0
DDAG
1764
1765 ret = postcopy_each_ram_send_discard(ms);
1766 rcu_read_unlock();
1767
1768 return ret;
1769}
1770
3d0684b2
JQ
1771/**
1772 * ram_discard_range: discard dirtied pages at the beginning of postcopy
e0b266f0 1773 *
3d0684b2 1774 * Returns zero on success
e0b266f0 1775 *
36449157
JQ
1776 * @rbname: name of the RAMBlock of the request. NULL means the
1777 * same that last one.
3d0684b2
JQ
1778 * @start: RAMBlock starting page
1779 * @length: RAMBlock size
e0b266f0 1780 */
aaa2064c 1781int ram_discard_range(const char *rbname, uint64_t start, size_t length)
e0b266f0
DDAG
1782{
1783 int ret = -1;
1784
36449157 1785 trace_ram_discard_range(rbname, start, length);
d3a5038c 1786
e0b266f0 1787 rcu_read_lock();
36449157 1788 RAMBlock *rb = qemu_ram_block_by_name(rbname);
e0b266f0
DDAG
1789
1790 if (!rb) {
36449157 1791 error_report("ram_discard_range: Failed to find block '%s'", rbname);
e0b266f0
DDAG
1792 goto err;
1793 }
1794
d3a5038c 1795 ret = ram_block_discard_range(rb, start, length);
e0b266f0
DDAG
1796
1797err:
1798 rcu_read_unlock();
1799
1800 return ret;
1801}
1802
53518d94 1803static int ram_state_init(RAMState **rsp)
56e93d26 1804{
53518d94
JQ
1805 *rsp = g_new0(RAMState, 1);
1806
1807 qemu_mutex_init(&(*rsp)->bitmap_mutex);
1808 qemu_mutex_init(&(*rsp)->src_page_req_mutex);
1809 QSIMPLEQ_INIT(&(*rsp)->src_page_requests);
56e93d26
JQ
1810
1811 if (migrate_use_xbzrle()) {
1812 XBZRLE_cache_lock();
c00e0928 1813 XBZRLE.zero_target_page = g_malloc0(TARGET_PAGE_SIZE);
56e93d26
JQ
1814 XBZRLE.cache = cache_init(migrate_xbzrle_cache_size() /
1815 TARGET_PAGE_SIZE,
1816 TARGET_PAGE_SIZE);
1817 if (!XBZRLE.cache) {
1818 XBZRLE_cache_unlock();
1819 error_report("Error creating cache");
53518d94
JQ
1820 g_free(*rsp);
1821 *rsp = NULL;
56e93d26
JQ
1822 return -1;
1823 }
1824 XBZRLE_cache_unlock();
1825
1826 /* We prefer not to abort if there is no memory */
1827 XBZRLE.encoded_buf = g_try_malloc0(TARGET_PAGE_SIZE);
1828 if (!XBZRLE.encoded_buf) {
1829 error_report("Error allocating encoded_buf");
53518d94
JQ
1830 g_free(*rsp);
1831 *rsp = NULL;
56e93d26
JQ
1832 return -1;
1833 }
1834
1835 XBZRLE.current_buf = g_try_malloc(TARGET_PAGE_SIZE);
1836 if (!XBZRLE.current_buf) {
1837 error_report("Error allocating current_buf");
1838 g_free(XBZRLE.encoded_buf);
1839 XBZRLE.encoded_buf = NULL;
53518d94
JQ
1840 g_free(*rsp);
1841 *rsp = NULL;
56e93d26
JQ
1842 return -1;
1843 }
56e93d26
JQ
1844 }
1845
49877834
PB
1846 /* For memory_global_dirty_log_start below. */
1847 qemu_mutex_lock_iothread();
1848
56e93d26
JQ
1849 qemu_mutex_lock_ramlist();
1850 rcu_read_lock();
53518d94 1851 ram_state_reset(*rsp);
56e93d26 1852
0827b9e9
AA
1853 /* Skip setting bitmap if there is no RAM */
1854 if (ram_bytes_total()) {
6b6712ef
JQ
1855 RAMBlock *block;
1856
1857 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1858 unsigned long pages = block->max_length >> TARGET_PAGE_BITS;
0827b9e9 1859
6b6712ef
JQ
1860 block->bmap = bitmap_new(pages);
1861 bitmap_set(block->bmap, 0, pages);
1862 if (migrate_postcopy_ram()) {
1863 block->unsentmap = bitmap_new(pages);
1864 bitmap_set(block->unsentmap, 0, pages);
1865 }
0827b9e9 1866 }
f3f491fc
DDAG
1867 }
1868
56e93d26
JQ
1869 /*
1870 * Count the total number of pages used by ram blocks not including any
1871 * gaps due to alignment or unplugs.
1872 */
53518d94 1873 (*rsp)->migration_dirty_pages = ram_bytes_total() >> TARGET_PAGE_BITS;
56e93d26
JQ
1874
1875 memory_global_dirty_log_start();
53518d94 1876 migration_bitmap_sync(*rsp);
56e93d26 1877 qemu_mutex_unlock_ramlist();
49877834 1878 qemu_mutex_unlock_iothread();
a91246c9
HZ
1879 rcu_read_unlock();
1880
1881 return 0;
1882}
1883
3d0684b2
JQ
1884/*
1885 * Each of ram_save_setup, ram_save_iterate and ram_save_complete has
a91246c9
HZ
1886 * long-running RCU critical section. When rcu-reclaims in the code
1887 * start to become numerous it will be necessary to reduce the
1888 * granularity of these critical sections.
1889 */
1890
3d0684b2
JQ
1891/**
1892 * ram_save_setup: Setup RAM for migration
1893 *
1894 * Returns zero to indicate success and negative for error
1895 *
1896 * @f: QEMUFile where to send the data
1897 * @opaque: RAMState pointer
1898 */
a91246c9
HZ
1899static int ram_save_setup(QEMUFile *f, void *opaque)
1900{
53518d94 1901 RAMState **rsp = opaque;
a91246c9
HZ
1902 RAMBlock *block;
1903
1904 /* migration has already setup the bitmap, reuse it. */
1905 if (!migration_in_colo_state()) {
53518d94 1906 if (ram_state_init(rsp) != 0) {
a91246c9 1907 return -1;
53518d94 1908 }
a91246c9 1909 }
53518d94 1910 (*rsp)->f = f;
a91246c9
HZ
1911
1912 rcu_read_lock();
56e93d26
JQ
1913
1914 qemu_put_be64(f, ram_bytes_total() | RAM_SAVE_FLAG_MEM_SIZE);
1915
99e15582 1916 RAMBLOCK_FOREACH(block) {
56e93d26
JQ
1917 qemu_put_byte(f, strlen(block->idstr));
1918 qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));
1919 qemu_put_be64(f, block->used_length);
ef08fb38
DDAG
1920 if (migrate_postcopy_ram() && block->page_size != qemu_host_page_size) {
1921 qemu_put_be64(f, block->page_size);
1922 }
56e93d26
JQ
1923 }
1924
1925 rcu_read_unlock();
1926
1927 ram_control_before_iterate(f, RAM_CONTROL_SETUP);
1928 ram_control_after_iterate(f, RAM_CONTROL_SETUP);
1929
1930 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1931
1932 return 0;
1933}
1934
3d0684b2
JQ
1935/**
1936 * ram_save_iterate: iterative stage for migration
1937 *
1938 * Returns zero to indicate success and negative for error
1939 *
1940 * @f: QEMUFile where to send the data
1941 * @opaque: RAMState pointer
1942 */
56e93d26
JQ
1943static int ram_save_iterate(QEMUFile *f, void *opaque)
1944{
53518d94
JQ
1945 RAMState **temp = opaque;
1946 RAMState *rs = *temp;
56e93d26
JQ
1947 int ret;
1948 int i;
1949 int64_t t0;
5c90308f 1950 int done = 0;
56e93d26
JQ
1951
1952 rcu_read_lock();
6f37bb8b
JQ
1953 if (ram_list.version != rs->last_version) {
1954 ram_state_reset(rs);
56e93d26
JQ
1955 }
1956
1957 /* Read version before ram_list.blocks */
1958 smp_rmb();
1959
1960 ram_control_before_iterate(f, RAM_CONTROL_ROUND);
1961
1962 t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1963 i = 0;
1964 while ((ret = qemu_file_rate_limit(f)) == 0) {
1965 int pages;
1966
ce25d337 1967 pages = ram_find_and_save_block(rs, false);
56e93d26
JQ
1968 /* no more pages to sent */
1969 if (pages == 0) {
5c90308f 1970 done = 1;
56e93d26
JQ
1971 break;
1972 }
23b28c3c 1973 rs->iterations++;
070afca2 1974
56e93d26
JQ
1975 /* we want to check in the 1st loop, just in case it was the 1st time
1976 and we had to sync the dirty bitmap.
1977 qemu_get_clock_ns() is a bit expensive, so we only check each some
1978 iterations
1979 */
1980 if ((i & 63) == 0) {
1981 uint64_t t1 = (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - t0) / 1000000;
1982 if (t1 > MAX_WAIT) {
55c4446b 1983 trace_ram_save_iterate_big_wait(t1, i);
56e93d26
JQ
1984 break;
1985 }
1986 }
1987 i++;
1988 }
ce25d337 1989 flush_compressed_data(rs);
56e93d26
JQ
1990 rcu_read_unlock();
1991
1992 /*
1993 * Must occur before EOS (or any QEMUFile operation)
1994 * because of RDMA protocol.
1995 */
1996 ram_control_after_iterate(f, RAM_CONTROL_ROUND);
1997
1998 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
9360447d 1999 ram_counters.transferred += 8;
56e93d26
JQ
2000
2001 ret = qemu_file_get_error(f);
2002 if (ret < 0) {
2003 return ret;
2004 }
2005
5c90308f 2006 return done;
56e93d26
JQ
2007}
2008
3d0684b2
JQ
2009/**
2010 * ram_save_complete: function called to send the remaining amount of ram
2011 *
2012 * Returns zero to indicate success
2013 *
2014 * Called with iothread lock
2015 *
2016 * @f: QEMUFile where to send the data
2017 * @opaque: RAMState pointer
2018 */
56e93d26
JQ
2019static int ram_save_complete(QEMUFile *f, void *opaque)
2020{
53518d94
JQ
2021 RAMState **temp = opaque;
2022 RAMState *rs = *temp;
6f37bb8b 2023
56e93d26
JQ
2024 rcu_read_lock();
2025
5727309d 2026 if (!migration_in_postcopy()) {
8d820d6f 2027 migration_bitmap_sync(rs);
663e6c1d 2028 }
56e93d26
JQ
2029
2030 ram_control_before_iterate(f, RAM_CONTROL_FINISH);
2031
2032 /* try transferring iterative blocks of memory */
2033
2034 /* flush all remaining blocks regardless of rate limiting */
2035 while (true) {
2036 int pages;
2037
ce25d337 2038 pages = ram_find_and_save_block(rs, !migration_in_colo_state());
56e93d26
JQ
2039 /* no more blocks to sent */
2040 if (pages == 0) {
2041 break;
2042 }
2043 }
2044
ce25d337 2045 flush_compressed_data(rs);
56e93d26 2046 ram_control_after_iterate(f, RAM_CONTROL_FINISH);
56e93d26
JQ
2047
2048 rcu_read_unlock();
d09a6fde 2049
56e93d26
JQ
2050 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2051
2052 return 0;
2053}
2054
c31b098f
DDAG
2055static void ram_save_pending(QEMUFile *f, void *opaque, uint64_t max_size,
2056 uint64_t *non_postcopiable_pending,
2057 uint64_t *postcopiable_pending)
56e93d26 2058{
53518d94
JQ
2059 RAMState **temp = opaque;
2060 RAMState *rs = *temp;
56e93d26
JQ
2061 uint64_t remaining_size;
2062
9edabd4d 2063 remaining_size = rs->migration_dirty_pages * TARGET_PAGE_SIZE;
56e93d26 2064
5727309d 2065 if (!migration_in_postcopy() &&
663e6c1d 2066 remaining_size < max_size) {
56e93d26
JQ
2067 qemu_mutex_lock_iothread();
2068 rcu_read_lock();
8d820d6f 2069 migration_bitmap_sync(rs);
56e93d26
JQ
2070 rcu_read_unlock();
2071 qemu_mutex_unlock_iothread();
9edabd4d 2072 remaining_size = rs->migration_dirty_pages * TARGET_PAGE_SIZE;
56e93d26 2073 }
c31b098f
DDAG
2074
2075 /* We can do postcopy, and all the data is postcopiable */
2076 *postcopiable_pending += remaining_size;
56e93d26
JQ
2077}
2078
2079static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host)
2080{
2081 unsigned int xh_len;
2082 int xh_flags;
063e760a 2083 uint8_t *loaded_data;
56e93d26 2084
56e93d26
JQ
2085 /* extract RLE header */
2086 xh_flags = qemu_get_byte(f);
2087 xh_len = qemu_get_be16(f);
2088
2089 if (xh_flags != ENCODING_FLAG_XBZRLE) {
2090 error_report("Failed to load XBZRLE page - wrong compression!");
2091 return -1;
2092 }
2093
2094 if (xh_len > TARGET_PAGE_SIZE) {
2095 error_report("Failed to load XBZRLE page - len overflow!");
2096 return -1;
2097 }
f265e0e4 2098 loaded_data = XBZRLE.decoded_buf;
56e93d26 2099 /* load data and decode */
f265e0e4 2100 /* it can change loaded_data to point to an internal buffer */
063e760a 2101 qemu_get_buffer_in_place(f, &loaded_data, xh_len);
56e93d26
JQ
2102
2103 /* decode RLE */
063e760a 2104 if (xbzrle_decode_buffer(loaded_data, xh_len, host,
56e93d26
JQ
2105 TARGET_PAGE_SIZE) == -1) {
2106 error_report("Failed to load XBZRLE page - decode error!");
2107 return -1;
2108 }
2109
2110 return 0;
2111}
2112
3d0684b2
JQ
2113/**
2114 * ram_block_from_stream: read a RAMBlock id from the migration stream
2115 *
2116 * Must be called from within a rcu critical section.
2117 *
56e93d26 2118 * Returns a pointer from within the RCU-protected ram_list.
a7180877 2119 *
3d0684b2
JQ
2120 * @f: QEMUFile where to read the data from
2121 * @flags: Page flags (mostly to see if it's a continuation of previous block)
a7180877 2122 */
3d0684b2 2123static inline RAMBlock *ram_block_from_stream(QEMUFile *f, int flags)
56e93d26
JQ
2124{
2125 static RAMBlock *block = NULL;
2126 char id[256];
2127 uint8_t len;
2128
2129 if (flags & RAM_SAVE_FLAG_CONTINUE) {
4c4bad48 2130 if (!block) {
56e93d26
JQ
2131 error_report("Ack, bad migration stream!");
2132 return NULL;
2133 }
4c4bad48 2134 return block;
56e93d26
JQ
2135 }
2136
2137 len = qemu_get_byte(f);
2138 qemu_get_buffer(f, (uint8_t *)id, len);
2139 id[len] = 0;
2140
e3dd7493 2141 block = qemu_ram_block_by_name(id);
4c4bad48
HZ
2142 if (!block) {
2143 error_report("Can't find block %s", id);
2144 return NULL;
56e93d26
JQ
2145 }
2146
4c4bad48
HZ
2147 return block;
2148}
2149
2150static inline void *host_from_ram_block_offset(RAMBlock *block,
2151 ram_addr_t offset)
2152{
2153 if (!offset_in_ramblock(block, offset)) {
2154 return NULL;
2155 }
2156
2157 return block->host + offset;
56e93d26
JQ
2158}
2159
3d0684b2
JQ
2160/**
2161 * ram_handle_compressed: handle the zero page case
2162 *
56e93d26
JQ
2163 * If a page (or a whole RDMA chunk) has been
2164 * determined to be zero, then zap it.
3d0684b2
JQ
2165 *
2166 * @host: host address for the zero page
2167 * @ch: what the page is filled from. We only support zero
2168 * @size: size of the zero page
56e93d26
JQ
2169 */
2170void ram_handle_compressed(void *host, uint8_t ch, uint64_t size)
2171{
2172 if (ch != 0 || !is_zero_range(host, size)) {
2173 memset(host, ch, size);
2174 }
2175}
2176
2177static void *do_data_decompress(void *opaque)
2178{
2179 DecompressParam *param = opaque;
2180 unsigned long pagesize;
33d151f4
LL
2181 uint8_t *des;
2182 int len;
56e93d26 2183
33d151f4 2184 qemu_mutex_lock(&param->mutex);
90e56fb4 2185 while (!param->quit) {
33d151f4
LL
2186 if (param->des) {
2187 des = param->des;
2188 len = param->len;
2189 param->des = 0;
2190 qemu_mutex_unlock(&param->mutex);
2191
56e93d26 2192 pagesize = TARGET_PAGE_SIZE;
73a8912b
LL
2193 /* uncompress() will return failed in some case, especially
2194 * when the page is dirted when doing the compression, it's
2195 * not a problem because the dirty page will be retransferred
2196 * and uncompress() won't break the data in other pages.
2197 */
33d151f4
LL
2198 uncompress((Bytef *)des, &pagesize,
2199 (const Bytef *)param->compbuf, len);
73a8912b 2200
33d151f4
LL
2201 qemu_mutex_lock(&decomp_done_lock);
2202 param->done = true;
2203 qemu_cond_signal(&decomp_done_cond);
2204 qemu_mutex_unlock(&decomp_done_lock);
2205
2206 qemu_mutex_lock(&param->mutex);
2207 } else {
2208 qemu_cond_wait(&param->cond, &param->mutex);
2209 }
56e93d26 2210 }
33d151f4 2211 qemu_mutex_unlock(&param->mutex);
56e93d26
JQ
2212
2213 return NULL;
2214}
2215
5533b2e9
LL
2216static void wait_for_decompress_done(void)
2217{
2218 int idx, thread_count;
2219
2220 if (!migrate_use_compression()) {
2221 return;
2222 }
2223
2224 thread_count = migrate_decompress_threads();
2225 qemu_mutex_lock(&decomp_done_lock);
2226 for (idx = 0; idx < thread_count; idx++) {
2227 while (!decomp_param[idx].done) {
2228 qemu_cond_wait(&decomp_done_cond, &decomp_done_lock);
2229 }
2230 }
2231 qemu_mutex_unlock(&decomp_done_lock);
2232}
2233
56e93d26
JQ
2234void migrate_decompress_threads_create(void)
2235{
2236 int i, thread_count;
2237
3416ab5b
JQ
2238 if (!migrate_use_compression()) {
2239 return;
2240 }
56e93d26
JQ
2241 thread_count = migrate_decompress_threads();
2242 decompress_threads = g_new0(QemuThread, thread_count);
2243 decomp_param = g_new0(DecompressParam, thread_count);
73a8912b
LL
2244 qemu_mutex_init(&decomp_done_lock);
2245 qemu_cond_init(&decomp_done_cond);
56e93d26
JQ
2246 for (i = 0; i < thread_count; i++) {
2247 qemu_mutex_init(&decomp_param[i].mutex);
2248 qemu_cond_init(&decomp_param[i].cond);
2249 decomp_param[i].compbuf = g_malloc0(compressBound(TARGET_PAGE_SIZE));
73a8912b 2250 decomp_param[i].done = true;
90e56fb4 2251 decomp_param[i].quit = false;
56e93d26
JQ
2252 qemu_thread_create(decompress_threads + i, "decompress",
2253 do_data_decompress, decomp_param + i,
2254 QEMU_THREAD_JOINABLE);
2255 }
2256}
2257
2258void migrate_decompress_threads_join(void)
2259{
2260 int i, thread_count;
2261
3416ab5b
JQ
2262 if (!migrate_use_compression()) {
2263 return;
2264 }
56e93d26
JQ
2265 thread_count = migrate_decompress_threads();
2266 for (i = 0; i < thread_count; i++) {
2267 qemu_mutex_lock(&decomp_param[i].mutex);
90e56fb4 2268 decomp_param[i].quit = true;
56e93d26
JQ
2269 qemu_cond_signal(&decomp_param[i].cond);
2270 qemu_mutex_unlock(&decomp_param[i].mutex);
2271 }
2272 for (i = 0; i < thread_count; i++) {
2273 qemu_thread_join(decompress_threads + i);
2274 qemu_mutex_destroy(&decomp_param[i].mutex);
2275 qemu_cond_destroy(&decomp_param[i].cond);
2276 g_free(decomp_param[i].compbuf);
2277 }
2278 g_free(decompress_threads);
2279 g_free(decomp_param);
56e93d26
JQ
2280 decompress_threads = NULL;
2281 decomp_param = NULL;
56e93d26
JQ
2282}
2283
c1bc6626 2284static void decompress_data_with_multi_threads(QEMUFile *f,
56e93d26
JQ
2285 void *host, int len)
2286{
2287 int idx, thread_count;
2288
2289 thread_count = migrate_decompress_threads();
73a8912b 2290 qemu_mutex_lock(&decomp_done_lock);
56e93d26
JQ
2291 while (true) {
2292 for (idx = 0; idx < thread_count; idx++) {
73a8912b 2293 if (decomp_param[idx].done) {
33d151f4
LL
2294 decomp_param[idx].done = false;
2295 qemu_mutex_lock(&decomp_param[idx].mutex);
c1bc6626 2296 qemu_get_buffer(f, decomp_param[idx].compbuf, len);
56e93d26
JQ
2297 decomp_param[idx].des = host;
2298 decomp_param[idx].len = len;
33d151f4
LL
2299 qemu_cond_signal(&decomp_param[idx].cond);
2300 qemu_mutex_unlock(&decomp_param[idx].mutex);
56e93d26
JQ
2301 break;
2302 }
2303 }
2304 if (idx < thread_count) {
2305 break;
73a8912b
LL
2306 } else {
2307 qemu_cond_wait(&decomp_done_cond, &decomp_done_lock);
56e93d26
JQ
2308 }
2309 }
73a8912b 2310 qemu_mutex_unlock(&decomp_done_lock);
56e93d26
JQ
2311}
2312
f265e0e4
JQ
2313/**
2314 * ram_load_setup: Setup RAM for migration incoming side
2315 *
2316 * Returns zero to indicate success and negative for error
2317 *
2318 * @f: QEMUFile where to receive the data
2319 * @opaque: RAMState pointer
2320 */
2321static int ram_load_setup(QEMUFile *f, void *opaque)
2322{
2323 xbzrle_load_setup();
2324 return 0;
2325}
2326
2327static int ram_load_cleanup(void *opaque)
2328{
2329 xbzrle_load_cleanup();
2330 return 0;
2331}
2332
3d0684b2
JQ
2333/**
2334 * ram_postcopy_incoming_init: allocate postcopy data structures
2335 *
2336 * Returns 0 for success and negative if there was one error
2337 *
2338 * @mis: current migration incoming state
2339 *
2340 * Allocate data structures etc needed by incoming migration with
2341 * postcopy-ram. postcopy-ram's similarly names
2342 * postcopy_ram_incoming_init does the work.
1caddf8a
DDAG
2343 */
2344int ram_postcopy_incoming_init(MigrationIncomingState *mis)
2345{
b8c48993 2346 unsigned long ram_pages = last_ram_page();
1caddf8a
DDAG
2347
2348 return postcopy_ram_incoming_init(mis, ram_pages);
2349}
2350
3d0684b2
JQ
2351/**
2352 * ram_load_postcopy: load a page in postcopy case
2353 *
2354 * Returns 0 for success or -errno in case of error
2355 *
a7180877
DDAG
2356 * Called in postcopy mode by ram_load().
2357 * rcu_read_lock is taken prior to this being called.
3d0684b2
JQ
2358 *
2359 * @f: QEMUFile where to send the data
a7180877
DDAG
2360 */
2361static int ram_load_postcopy(QEMUFile *f)
2362{
2363 int flags = 0, ret = 0;
2364 bool place_needed = false;
28abd200 2365 bool matching_page_sizes = false;
a7180877
DDAG
2366 MigrationIncomingState *mis = migration_incoming_get_current();
2367 /* Temporary page that is later 'placed' */
2368 void *postcopy_host_page = postcopy_get_tmp_page(mis);
c53b7ddc 2369 void *last_host = NULL;
a3b6ff6d 2370 bool all_zero = false;
a7180877
DDAG
2371
2372 while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
2373 ram_addr_t addr;
2374 void *host = NULL;
2375 void *page_buffer = NULL;
2376 void *place_source = NULL;
df9ff5e1 2377 RAMBlock *block = NULL;
a7180877 2378 uint8_t ch;
a7180877
DDAG
2379
2380 addr = qemu_get_be64(f);
2381 flags = addr & ~TARGET_PAGE_MASK;
2382 addr &= TARGET_PAGE_MASK;
2383
2384 trace_ram_load_postcopy_loop((uint64_t)addr, flags);
2385 place_needed = false;
bb890ed5 2386 if (flags & (RAM_SAVE_FLAG_ZERO | RAM_SAVE_FLAG_PAGE)) {
df9ff5e1 2387 block = ram_block_from_stream(f, flags);
4c4bad48
HZ
2388
2389 host = host_from_ram_block_offset(block, addr);
a7180877
DDAG
2390 if (!host) {
2391 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
2392 ret = -EINVAL;
2393 break;
2394 }
28abd200 2395 matching_page_sizes = block->page_size == TARGET_PAGE_SIZE;
a7180877 2396 /*
28abd200
DDAG
2397 * Postcopy requires that we place whole host pages atomically;
2398 * these may be huge pages for RAMBlocks that are backed by
2399 * hugetlbfs.
a7180877
DDAG
2400 * To make it atomic, the data is read into a temporary page
2401 * that's moved into place later.
2402 * The migration protocol uses, possibly smaller, target-pages
2403 * however the source ensures it always sends all the components
2404 * of a host page in order.
2405 */
2406 page_buffer = postcopy_host_page +
28abd200 2407 ((uintptr_t)host & (block->page_size - 1));
a7180877 2408 /* If all TP are zero then we can optimise the place */
28abd200 2409 if (!((uintptr_t)host & (block->page_size - 1))) {
a7180877 2410 all_zero = true;
c53b7ddc
DDAG
2411 } else {
2412 /* not the 1st TP within the HP */
2413 if (host != (last_host + TARGET_PAGE_SIZE)) {
9af9e0fe 2414 error_report("Non-sequential target page %p/%p",
c53b7ddc
DDAG
2415 host, last_host);
2416 ret = -EINVAL;
2417 break;
2418 }
a7180877
DDAG
2419 }
2420
c53b7ddc 2421
a7180877
DDAG
2422 /*
2423 * If it's the last part of a host page then we place the host
2424 * page
2425 */
2426 place_needed = (((uintptr_t)host + TARGET_PAGE_SIZE) &
28abd200 2427 (block->page_size - 1)) == 0;
a7180877
DDAG
2428 place_source = postcopy_host_page;
2429 }
c53b7ddc 2430 last_host = host;
a7180877
DDAG
2431
2432 switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
bb890ed5 2433 case RAM_SAVE_FLAG_ZERO:
a7180877
DDAG
2434 ch = qemu_get_byte(f);
2435 memset(page_buffer, ch, TARGET_PAGE_SIZE);
2436 if (ch) {
2437 all_zero = false;
2438 }
2439 break;
2440
2441 case RAM_SAVE_FLAG_PAGE:
2442 all_zero = false;
2443 if (!place_needed || !matching_page_sizes) {
2444 qemu_get_buffer(f, page_buffer, TARGET_PAGE_SIZE);
2445 } else {
2446 /* Avoids the qemu_file copy during postcopy, which is
2447 * going to do a copy later; can only do it when we
2448 * do this read in one go (matching page sizes)
2449 */
2450 qemu_get_buffer_in_place(f, (uint8_t **)&place_source,
2451 TARGET_PAGE_SIZE);
2452 }
2453 break;
2454 case RAM_SAVE_FLAG_EOS:
2455 /* normal exit */
2456 break;
2457 default:
2458 error_report("Unknown combination of migration flags: %#x"
2459 " (postcopy mode)", flags);
2460 ret = -EINVAL;
2461 }
2462
2463 if (place_needed) {
2464 /* This gets called at the last target page in the host page */
df9ff5e1
DDAG
2465 void *place_dest = host + TARGET_PAGE_SIZE - block->page_size;
2466
a7180877 2467 if (all_zero) {
df9ff5e1
DDAG
2468 ret = postcopy_place_page_zero(mis, place_dest,
2469 block->page_size);
a7180877 2470 } else {
df9ff5e1
DDAG
2471 ret = postcopy_place_page(mis, place_dest,
2472 place_source, block->page_size);
a7180877
DDAG
2473 }
2474 }
2475 if (!ret) {
2476 ret = qemu_file_get_error(f);
2477 }
2478 }
2479
2480 return ret;
2481}
2482
56e93d26
JQ
2483static int ram_load(QEMUFile *f, void *opaque, int version_id)
2484{
edc60127 2485 int flags = 0, ret = 0, invalid_flags = 0;
56e93d26
JQ
2486 static uint64_t seq_iter;
2487 int len = 0;
a7180877
DDAG
2488 /*
2489 * If system is running in postcopy mode, page inserts to host memory must
2490 * be atomic
2491 */
2492 bool postcopy_running = postcopy_state_get() >= POSTCOPY_INCOMING_LISTENING;
ef08fb38
DDAG
2493 /* ADVISE is earlier, it shows the source has the postcopy capability on */
2494 bool postcopy_advised = postcopy_state_get() >= POSTCOPY_INCOMING_ADVISE;
56e93d26
JQ
2495
2496 seq_iter++;
2497
2498 if (version_id != 4) {
2499 ret = -EINVAL;
2500 }
2501
edc60127
JQ
2502 if (!migrate_use_compression()) {
2503 invalid_flags |= RAM_SAVE_FLAG_COMPRESS_PAGE;
2504 }
56e93d26
JQ
2505 /* This RCU critical section can be very long running.
2506 * When RCU reclaims in the code start to become numerous,
2507 * it will be necessary to reduce the granularity of this
2508 * critical section.
2509 */
2510 rcu_read_lock();
a7180877
DDAG
2511
2512 if (postcopy_running) {
2513 ret = ram_load_postcopy(f);
2514 }
2515
2516 while (!postcopy_running && !ret && !(flags & RAM_SAVE_FLAG_EOS)) {
56e93d26 2517 ram_addr_t addr, total_ram_bytes;
a776aa15 2518 void *host = NULL;
56e93d26
JQ
2519 uint8_t ch;
2520
2521 addr = qemu_get_be64(f);
2522 flags = addr & ~TARGET_PAGE_MASK;
2523 addr &= TARGET_PAGE_MASK;
2524
edc60127
JQ
2525 if (flags & invalid_flags) {
2526 if (flags & invalid_flags & RAM_SAVE_FLAG_COMPRESS_PAGE) {
2527 error_report("Received an unexpected compressed page");
2528 }
2529
2530 ret = -EINVAL;
2531 break;
2532 }
2533
bb890ed5 2534 if (flags & (RAM_SAVE_FLAG_ZERO | RAM_SAVE_FLAG_PAGE |
a776aa15 2535 RAM_SAVE_FLAG_COMPRESS_PAGE | RAM_SAVE_FLAG_XBZRLE)) {
4c4bad48
HZ
2536 RAMBlock *block = ram_block_from_stream(f, flags);
2537
2538 host = host_from_ram_block_offset(block, addr);
a776aa15
DDAG
2539 if (!host) {
2540 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
2541 ret = -EINVAL;
2542 break;
2543 }
1db9d8e5 2544 trace_ram_load_loop(block->idstr, (uint64_t)addr, flags, host);
a776aa15
DDAG
2545 }
2546
56e93d26
JQ
2547 switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
2548 case RAM_SAVE_FLAG_MEM_SIZE:
2549 /* Synchronize RAM block list */
2550 total_ram_bytes = addr;
2551 while (!ret && total_ram_bytes) {
2552 RAMBlock *block;
56e93d26
JQ
2553 char id[256];
2554 ram_addr_t length;
2555
2556 len = qemu_get_byte(f);
2557 qemu_get_buffer(f, (uint8_t *)id, len);
2558 id[len] = 0;
2559 length = qemu_get_be64(f);
2560
e3dd7493
DDAG
2561 block = qemu_ram_block_by_name(id);
2562 if (block) {
2563 if (length != block->used_length) {
2564 Error *local_err = NULL;
56e93d26 2565
fa53a0e5 2566 ret = qemu_ram_resize(block, length,
e3dd7493
DDAG
2567 &local_err);
2568 if (local_err) {
2569 error_report_err(local_err);
56e93d26 2570 }
56e93d26 2571 }
ef08fb38
DDAG
2572 /* For postcopy we need to check hugepage sizes match */
2573 if (postcopy_advised &&
2574 block->page_size != qemu_host_page_size) {
2575 uint64_t remote_page_size = qemu_get_be64(f);
2576 if (remote_page_size != block->page_size) {
2577 error_report("Mismatched RAM page size %s "
2578 "(local) %zd != %" PRId64,
2579 id, block->page_size,
2580 remote_page_size);
2581 ret = -EINVAL;
2582 }
2583 }
e3dd7493
DDAG
2584 ram_control_load_hook(f, RAM_CONTROL_BLOCK_REG,
2585 block->idstr);
2586 } else {
56e93d26
JQ
2587 error_report("Unknown ramblock \"%s\", cannot "
2588 "accept migration", id);
2589 ret = -EINVAL;
2590 }
2591
2592 total_ram_bytes -= length;
2593 }
2594 break;
a776aa15 2595
bb890ed5 2596 case RAM_SAVE_FLAG_ZERO:
56e93d26
JQ
2597 ch = qemu_get_byte(f);
2598 ram_handle_compressed(host, ch, TARGET_PAGE_SIZE);
2599 break;
a776aa15 2600
56e93d26 2601 case RAM_SAVE_FLAG_PAGE:
56e93d26
JQ
2602 qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
2603 break;
56e93d26 2604
a776aa15 2605 case RAM_SAVE_FLAG_COMPRESS_PAGE:
56e93d26
JQ
2606 len = qemu_get_be32(f);
2607 if (len < 0 || len > compressBound(TARGET_PAGE_SIZE)) {
2608 error_report("Invalid compressed data length: %d", len);
2609 ret = -EINVAL;
2610 break;
2611 }
c1bc6626 2612 decompress_data_with_multi_threads(f, host, len);
56e93d26 2613 break;
a776aa15 2614
56e93d26 2615 case RAM_SAVE_FLAG_XBZRLE:
56e93d26
JQ
2616 if (load_xbzrle(f, addr, host) < 0) {
2617 error_report("Failed to decompress XBZRLE page at "
2618 RAM_ADDR_FMT, addr);
2619 ret = -EINVAL;
2620 break;
2621 }
2622 break;
2623 case RAM_SAVE_FLAG_EOS:
2624 /* normal exit */
2625 break;
2626 default:
2627 if (flags & RAM_SAVE_FLAG_HOOK) {
632e3a5c 2628 ram_control_load_hook(f, RAM_CONTROL_HOOK, NULL);
56e93d26
JQ
2629 } else {
2630 error_report("Unknown combination of migration flags: %#x",
2631 flags);
2632 ret = -EINVAL;
2633 }
2634 }
2635 if (!ret) {
2636 ret = qemu_file_get_error(f);
2637 }
2638 }
2639
5533b2e9 2640 wait_for_decompress_done();
56e93d26 2641 rcu_read_unlock();
55c4446b 2642 trace_ram_load_complete(ret, seq_iter);
56e93d26
JQ
2643 return ret;
2644}
2645
2646static SaveVMHandlers savevm_ram_handlers = {
9907e842 2647 .save_setup = ram_save_setup,
56e93d26 2648 .save_live_iterate = ram_save_iterate,
763c906b 2649 .save_live_complete_postcopy = ram_save_complete,
a3e06c3d 2650 .save_live_complete_precopy = ram_save_complete,
56e93d26
JQ
2651 .save_live_pending = ram_save_pending,
2652 .load_state = ram_load,
f265e0e4
JQ
2653 .save_cleanup = ram_save_cleanup,
2654 .load_setup = ram_load_setup,
2655 .load_cleanup = ram_load_cleanup,
56e93d26
JQ
2656};
2657
2658void ram_mig_init(void)
2659{
2660 qemu_mutex_init(&XBZRLE.lock);
6f37bb8b 2661 register_savevm_live(NULL, "ram", 0, 4, &savevm_ram_handlers, &ram_state);
56e93d26 2662}