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