]> git.proxmox.com Git - mirror_qemu.git/blame - migration/ram.c
ram: Use MigrationStats for statistics
[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
207static RAMState ram_state;
208
9edabd4d 209uint64_t ram_bytes_remaining(void)
2f4fde93 210{
9edabd4d 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{
24795694 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;
68a098f3 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{
83c13382 1364 RAMState *rs = 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();
83c13382 1391 migration_page_queue_free(rs);
56e93d26
JQ
1392}
1393
6f37bb8b 1394static void ram_state_reset(RAMState *rs)
56e93d26 1395{
6f37bb8b
JQ
1396 rs->last_seen_block = NULL;
1397 rs->last_sent_block = NULL;
269ace29 1398 rs->last_page = 0;
6f37bb8b
JQ
1399 rs->last_version = ram_list.version;
1400 rs->ram_bulk_stage = true;
56e93d26
JQ
1401}
1402
1403#define MAX_WAIT 50 /* ms, half buffered_file limit */
1404
4f2e4252
DDAG
1405/*
1406 * 'expected' is the value you expect the bitmap mostly to be full
1407 * of; it won't bother printing lines that are all this value.
1408 * If 'todump' is null the migration bitmap is dumped.
1409 */
6b6712ef
JQ
1410void ram_debug_dump_bitmap(unsigned long *todump, bool expected,
1411 unsigned long pages)
4f2e4252 1412{
4f2e4252
DDAG
1413 int64_t cur;
1414 int64_t linelen = 128;
1415 char linebuf[129];
1416
6b6712ef 1417 for (cur = 0; cur < pages; cur += linelen) {
4f2e4252
DDAG
1418 int64_t curb;
1419 bool found = false;
1420 /*
1421 * Last line; catch the case where the line length
1422 * is longer than remaining ram
1423 */
6b6712ef
JQ
1424 if (cur + linelen > pages) {
1425 linelen = pages - cur;
4f2e4252
DDAG
1426 }
1427 for (curb = 0; curb < linelen; curb++) {
1428 bool thisbit = test_bit(cur + curb, todump);
1429 linebuf[curb] = thisbit ? '1' : '.';
1430 found = found || (thisbit != expected);
1431 }
1432 if (found) {
1433 linebuf[curb] = '\0';
1434 fprintf(stderr, "0x%08" PRIx64 " : %s\n", cur, linebuf);
1435 }
1436 }
1437}
1438
e0b266f0
DDAG
1439/* **** functions for postcopy ***** */
1440
ced1c616
PB
1441void ram_postcopy_migrated_memory_release(MigrationState *ms)
1442{
1443 struct RAMBlock *block;
ced1c616 1444
99e15582 1445 RAMBLOCK_FOREACH(block) {
6b6712ef
JQ
1446 unsigned long *bitmap = block->bmap;
1447 unsigned long range = block->used_length >> TARGET_PAGE_BITS;
1448 unsigned long run_start = find_next_zero_bit(bitmap, range, 0);
ced1c616
PB
1449
1450 while (run_start < range) {
1451 unsigned long run_end = find_next_bit(bitmap, range, run_start + 1);
aaa2064c 1452 ram_discard_range(block->idstr, run_start << TARGET_PAGE_BITS,
ced1c616
PB
1453 (run_end - run_start) << TARGET_PAGE_BITS);
1454 run_start = find_next_zero_bit(bitmap, range, run_end + 1);
1455 }
1456 }
1457}
1458
3d0684b2
JQ
1459/**
1460 * postcopy_send_discard_bm_ram: discard a RAMBlock
1461 *
1462 * Returns zero on success
1463 *
e0b266f0
DDAG
1464 * Callback from postcopy_each_ram_send_discard for each RAMBlock
1465 * Note: At this point the 'unsentmap' is the processed bitmap combined
1466 * with the dirtymap; so a '1' means it's either dirty or unsent.
3d0684b2
JQ
1467 *
1468 * @ms: current migration state
1469 * @pds: state for postcopy
1470 * @start: RAMBlock starting page
1471 * @length: RAMBlock size
e0b266f0
DDAG
1472 */
1473static int postcopy_send_discard_bm_ram(MigrationState *ms,
1474 PostcopyDiscardState *pds,
6b6712ef 1475 RAMBlock *block)
e0b266f0 1476{
6b6712ef 1477 unsigned long end = block->used_length >> TARGET_PAGE_BITS;
e0b266f0 1478 unsigned long current;
6b6712ef 1479 unsigned long *unsentmap = block->unsentmap;
e0b266f0 1480
6b6712ef 1481 for (current = 0; current < end; ) {
e0b266f0
DDAG
1482 unsigned long one = find_next_bit(unsentmap, end, current);
1483
1484 if (one <= end) {
1485 unsigned long zero = find_next_zero_bit(unsentmap, end, one + 1);
1486 unsigned long discard_length;
1487
1488 if (zero >= end) {
1489 discard_length = end - one;
1490 } else {
1491 discard_length = zero - one;
1492 }
d688c62d
DDAG
1493 if (discard_length) {
1494 postcopy_discard_send_range(ms, pds, one, discard_length);
1495 }
e0b266f0
DDAG
1496 current = one + discard_length;
1497 } else {
1498 current = one;
1499 }
1500 }
1501
1502 return 0;
1503}
1504
3d0684b2
JQ
1505/**
1506 * postcopy_each_ram_send_discard: discard all RAMBlocks
1507 *
1508 * Returns 0 for success or negative for error
1509 *
e0b266f0
DDAG
1510 * Utility for the outgoing postcopy code.
1511 * Calls postcopy_send_discard_bm_ram for each RAMBlock
1512 * passing it bitmap indexes and name.
e0b266f0
DDAG
1513 * (qemu_ram_foreach_block ends up passing unscaled lengths
1514 * which would mean postcopy code would have to deal with target page)
3d0684b2
JQ
1515 *
1516 * @ms: current migration state
e0b266f0
DDAG
1517 */
1518static int postcopy_each_ram_send_discard(MigrationState *ms)
1519{
1520 struct RAMBlock *block;
1521 int ret;
1522
99e15582 1523 RAMBLOCK_FOREACH(block) {
6b6712ef
JQ
1524 PostcopyDiscardState *pds =
1525 postcopy_discard_send_init(ms, block->idstr);
e0b266f0
DDAG
1526
1527 /*
1528 * Postcopy sends chunks of bitmap over the wire, but it
1529 * just needs indexes at this point, avoids it having
1530 * target page specific code.
1531 */
6b6712ef 1532 ret = postcopy_send_discard_bm_ram(ms, pds, block);
e0b266f0
DDAG
1533 postcopy_discard_send_finish(ms, pds);
1534 if (ret) {
1535 return ret;
1536 }
1537 }
1538
1539 return 0;
1540}
1541
3d0684b2
JQ
1542/**
1543 * postcopy_chunk_hostpages_pass: canocalize bitmap in hostpages
1544 *
1545 * Helper for postcopy_chunk_hostpages; it's called twice to
1546 * canonicalize the two bitmaps, that are similar, but one is
1547 * inverted.
99e314eb 1548 *
3d0684b2
JQ
1549 * Postcopy requires that all target pages in a hostpage are dirty or
1550 * clean, not a mix. This function canonicalizes the bitmaps.
99e314eb 1551 *
3d0684b2
JQ
1552 * @ms: current migration state
1553 * @unsent_pass: if true we need to canonicalize partially unsent host pages
1554 * otherwise we need to canonicalize partially dirty host pages
1555 * @block: block that contains the page we want to canonicalize
1556 * @pds: state for postcopy
99e314eb
DDAG
1557 */
1558static void postcopy_chunk_hostpages_pass(MigrationState *ms, bool unsent_pass,
1559 RAMBlock *block,
1560 PostcopyDiscardState *pds)
1561{
0d8ec885 1562 RAMState *rs = &ram_state;
6b6712ef
JQ
1563 unsigned long *bitmap = block->bmap;
1564 unsigned long *unsentmap = block->unsentmap;
29c59172 1565 unsigned int host_ratio = block->page_size / TARGET_PAGE_SIZE;
6b6712ef 1566 unsigned long pages = block->used_length >> TARGET_PAGE_BITS;
99e314eb
DDAG
1567 unsigned long run_start;
1568
29c59172
DDAG
1569 if (block->page_size == TARGET_PAGE_SIZE) {
1570 /* Easy case - TPS==HPS for a non-huge page RAMBlock */
1571 return;
1572 }
1573
99e314eb
DDAG
1574 if (unsent_pass) {
1575 /* Find a sent page */
6b6712ef 1576 run_start = find_next_zero_bit(unsentmap, pages, 0);
99e314eb
DDAG
1577 } else {
1578 /* Find a dirty page */
6b6712ef 1579 run_start = find_next_bit(bitmap, pages, 0);
99e314eb
DDAG
1580 }
1581
6b6712ef 1582 while (run_start < pages) {
99e314eb
DDAG
1583 bool do_fixup = false;
1584 unsigned long fixup_start_addr;
1585 unsigned long host_offset;
1586
1587 /*
1588 * If the start of this run of pages is in the middle of a host
1589 * page, then we need to fixup this host page.
1590 */
1591 host_offset = run_start % host_ratio;
1592 if (host_offset) {
1593 do_fixup = true;
1594 run_start -= host_offset;
1595 fixup_start_addr = run_start;
1596 /* For the next pass */
1597 run_start = run_start + host_ratio;
1598 } else {
1599 /* Find the end of this run */
1600 unsigned long run_end;
1601 if (unsent_pass) {
6b6712ef 1602 run_end = find_next_bit(unsentmap, pages, run_start + 1);
99e314eb 1603 } else {
6b6712ef 1604 run_end = find_next_zero_bit(bitmap, pages, run_start + 1);
99e314eb
DDAG
1605 }
1606 /*
1607 * If the end isn't at the start of a host page, then the
1608 * run doesn't finish at the end of a host page
1609 * and we need to discard.
1610 */
1611 host_offset = run_end % host_ratio;
1612 if (host_offset) {
1613 do_fixup = true;
1614 fixup_start_addr = run_end - host_offset;
1615 /*
1616 * This host page has gone, the next loop iteration starts
1617 * from after the fixup
1618 */
1619 run_start = fixup_start_addr + host_ratio;
1620 } else {
1621 /*
1622 * No discards on this iteration, next loop starts from
1623 * next sent/dirty page
1624 */
1625 run_start = run_end + 1;
1626 }
1627 }
1628
1629 if (do_fixup) {
1630 unsigned long page;
1631
1632 /* Tell the destination to discard this page */
1633 if (unsent_pass || !test_bit(fixup_start_addr, unsentmap)) {
1634 /* For the unsent_pass we:
1635 * discard partially sent pages
1636 * For the !unsent_pass (dirty) we:
1637 * discard partially dirty pages that were sent
1638 * (any partially sent pages were already discarded
1639 * by the previous unsent_pass)
1640 */
1641 postcopy_discard_send_range(ms, pds, fixup_start_addr,
1642 host_ratio);
1643 }
1644
1645 /* Clean up the bitmap */
1646 for (page = fixup_start_addr;
1647 page < fixup_start_addr + host_ratio; page++) {
1648 /* All pages in this host page are now not sent */
1649 set_bit(page, unsentmap);
1650
1651 /*
1652 * Remark them as dirty, updating the count for any pages
1653 * that weren't previously dirty.
1654 */
0d8ec885 1655 rs->migration_dirty_pages += !test_and_set_bit(page, bitmap);
99e314eb
DDAG
1656 }
1657 }
1658
1659 if (unsent_pass) {
1660 /* Find the next sent page for the next iteration */
6b6712ef 1661 run_start = find_next_zero_bit(unsentmap, pages, run_start);
99e314eb
DDAG
1662 } else {
1663 /* Find the next dirty page for the next iteration */
6b6712ef 1664 run_start = find_next_bit(bitmap, pages, run_start);
99e314eb
DDAG
1665 }
1666 }
1667}
1668
3d0684b2
JQ
1669/**
1670 * postcopy_chuck_hostpages: discrad any partially sent host page
1671 *
99e314eb
DDAG
1672 * Utility for the outgoing postcopy code.
1673 *
1674 * Discard any partially sent host-page size chunks, mark any partially
29c59172
DDAG
1675 * dirty host-page size chunks as all dirty. In this case the host-page
1676 * is the host-page for the particular RAMBlock, i.e. it might be a huge page
99e314eb 1677 *
3d0684b2
JQ
1678 * Returns zero on success
1679 *
1680 * @ms: current migration state
6b6712ef 1681 * @block: block we want to work with
99e314eb 1682 */
6b6712ef 1683static int postcopy_chunk_hostpages(MigrationState *ms, RAMBlock *block)
99e314eb 1684{
6b6712ef
JQ
1685 PostcopyDiscardState *pds =
1686 postcopy_discard_send_init(ms, block->idstr);
99e314eb 1687
6b6712ef
JQ
1688 /* First pass: Discard all partially sent host pages */
1689 postcopy_chunk_hostpages_pass(ms, true, block, pds);
1690 /*
1691 * Second pass: Ensure that all partially dirty host pages are made
1692 * fully dirty.
1693 */
1694 postcopy_chunk_hostpages_pass(ms, false, block, pds);
99e314eb 1695
6b6712ef 1696 postcopy_discard_send_finish(ms, pds);
99e314eb
DDAG
1697 return 0;
1698}
1699
3d0684b2
JQ
1700/**
1701 * ram_postcopy_send_discard_bitmap: transmit the discard bitmap
1702 *
1703 * Returns zero on success
1704 *
e0b266f0
DDAG
1705 * Transmit the set of pages to be discarded after precopy to the target
1706 * these are pages that:
1707 * a) Have been previously transmitted but are now dirty again
1708 * b) Pages that have never been transmitted, this ensures that
1709 * any pages on the destination that have been mapped by background
1710 * tasks get discarded (transparent huge pages is the specific concern)
1711 * Hopefully this is pretty sparse
3d0684b2
JQ
1712 *
1713 * @ms: current migration state
e0b266f0
DDAG
1714 */
1715int ram_postcopy_send_discard_bitmap(MigrationState *ms)
1716{
eb859c53 1717 RAMState *rs = &ram_state;
6b6712ef 1718 RAMBlock *block;
e0b266f0 1719 int ret;
e0b266f0
DDAG
1720
1721 rcu_read_lock();
1722
1723 /* This should be our last sync, the src is now paused */
eb859c53 1724 migration_bitmap_sync(rs);
e0b266f0 1725
6b6712ef
JQ
1726 /* Easiest way to make sure we don't resume in the middle of a host-page */
1727 rs->last_seen_block = NULL;
1728 rs->last_sent_block = NULL;
1729 rs->last_page = 0;
e0b266f0 1730
6b6712ef
JQ
1731 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1732 unsigned long pages = block->used_length >> TARGET_PAGE_BITS;
1733 unsigned long *bitmap = block->bmap;
1734 unsigned long *unsentmap = block->unsentmap;
1735
1736 if (!unsentmap) {
1737 /* We don't have a safe way to resize the sentmap, so
1738 * if the bitmap was resized it will be NULL at this
1739 * point.
1740 */
1741 error_report("migration ram resized during precopy phase");
1742 rcu_read_unlock();
1743 return -EINVAL;
1744 }
1745 /* Deal with TPS != HPS and huge pages */
1746 ret = postcopy_chunk_hostpages(ms, block);
1747 if (ret) {
1748 rcu_read_unlock();
1749 return ret;
1750 }
e0b266f0 1751
6b6712ef
JQ
1752 /*
1753 * Update the unsentmap to be unsentmap = unsentmap | dirty
1754 */
1755 bitmap_or(unsentmap, unsentmap, bitmap, pages);
e0b266f0 1756#ifdef DEBUG_POSTCOPY
6b6712ef 1757 ram_debug_dump_bitmap(unsentmap, true, pages);
e0b266f0 1758#endif
6b6712ef
JQ
1759 }
1760 trace_ram_postcopy_send_discard_bitmap();
e0b266f0
DDAG
1761
1762 ret = postcopy_each_ram_send_discard(ms);
1763 rcu_read_unlock();
1764
1765 return ret;
1766}
1767
3d0684b2
JQ
1768/**
1769 * ram_discard_range: discard dirtied pages at the beginning of postcopy
e0b266f0 1770 *
3d0684b2 1771 * Returns zero on success
e0b266f0 1772 *
36449157
JQ
1773 * @rbname: name of the RAMBlock of the request. NULL means the
1774 * same that last one.
3d0684b2
JQ
1775 * @start: RAMBlock starting page
1776 * @length: RAMBlock size
e0b266f0 1777 */
aaa2064c 1778int ram_discard_range(const char *rbname, uint64_t start, size_t length)
e0b266f0
DDAG
1779{
1780 int ret = -1;
1781
36449157 1782 trace_ram_discard_range(rbname, start, length);
d3a5038c 1783
e0b266f0 1784 rcu_read_lock();
36449157 1785 RAMBlock *rb = qemu_ram_block_by_name(rbname);
e0b266f0
DDAG
1786
1787 if (!rb) {
36449157 1788 error_report("ram_discard_range: Failed to find block '%s'", rbname);
e0b266f0
DDAG
1789 goto err;
1790 }
1791
d3a5038c 1792 ret = ram_block_discard_range(rb, start, length);
e0b266f0
DDAG
1793
1794err:
1795 rcu_read_unlock();
1796
1797 return ret;
1798}
1799
ceb4d168 1800static int ram_state_init(RAMState *rs)
56e93d26 1801{
ceb4d168 1802 memset(rs, 0, sizeof(*rs));
108cfae0 1803 qemu_mutex_init(&rs->bitmap_mutex);
ec481c6c
JQ
1804 qemu_mutex_init(&rs->src_page_req_mutex);
1805 QSIMPLEQ_INIT(&rs->src_page_requests);
56e93d26
JQ
1806
1807 if (migrate_use_xbzrle()) {
1808 XBZRLE_cache_lock();
c00e0928 1809 XBZRLE.zero_target_page = g_malloc0(TARGET_PAGE_SIZE);
56e93d26
JQ
1810 XBZRLE.cache = cache_init(migrate_xbzrle_cache_size() /
1811 TARGET_PAGE_SIZE,
1812 TARGET_PAGE_SIZE);
1813 if (!XBZRLE.cache) {
1814 XBZRLE_cache_unlock();
1815 error_report("Error creating cache");
1816 return -1;
1817 }
1818 XBZRLE_cache_unlock();
1819
1820 /* We prefer not to abort if there is no memory */
1821 XBZRLE.encoded_buf = g_try_malloc0(TARGET_PAGE_SIZE);
1822 if (!XBZRLE.encoded_buf) {
1823 error_report("Error allocating encoded_buf");
1824 return -1;
1825 }
1826
1827 XBZRLE.current_buf = g_try_malloc(TARGET_PAGE_SIZE);
1828 if (!XBZRLE.current_buf) {
1829 error_report("Error allocating current_buf");
1830 g_free(XBZRLE.encoded_buf);
1831 XBZRLE.encoded_buf = NULL;
1832 return -1;
1833 }
56e93d26
JQ
1834 }
1835
49877834
PB
1836 /* For memory_global_dirty_log_start below. */
1837 qemu_mutex_lock_iothread();
1838
56e93d26
JQ
1839 qemu_mutex_lock_ramlist();
1840 rcu_read_lock();
6f37bb8b 1841 ram_state_reset(rs);
56e93d26 1842
0827b9e9
AA
1843 /* Skip setting bitmap if there is no RAM */
1844 if (ram_bytes_total()) {
6b6712ef
JQ
1845 RAMBlock *block;
1846
1847 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1848 unsigned long pages = block->max_length >> TARGET_PAGE_BITS;
0827b9e9 1849
6b6712ef
JQ
1850 block->bmap = bitmap_new(pages);
1851 bitmap_set(block->bmap, 0, pages);
1852 if (migrate_postcopy_ram()) {
1853 block->unsentmap = bitmap_new(pages);
1854 bitmap_set(block->unsentmap, 0, pages);
1855 }
0827b9e9 1856 }
f3f491fc
DDAG
1857 }
1858
56e93d26
JQ
1859 /*
1860 * Count the total number of pages used by ram blocks not including any
1861 * gaps due to alignment or unplugs.
1862 */
0d8ec885 1863 rs->migration_dirty_pages = ram_bytes_total() >> TARGET_PAGE_BITS;
56e93d26
JQ
1864
1865 memory_global_dirty_log_start();
8d820d6f 1866 migration_bitmap_sync(rs);
56e93d26 1867 qemu_mutex_unlock_ramlist();
49877834 1868 qemu_mutex_unlock_iothread();
a91246c9
HZ
1869 rcu_read_unlock();
1870
1871 return 0;
1872}
1873
3d0684b2
JQ
1874/*
1875 * Each of ram_save_setup, ram_save_iterate and ram_save_complete has
a91246c9
HZ
1876 * long-running RCU critical section. When rcu-reclaims in the code
1877 * start to become numerous it will be necessary to reduce the
1878 * granularity of these critical sections.
1879 */
1880
3d0684b2
JQ
1881/**
1882 * ram_save_setup: Setup RAM for migration
1883 *
1884 * Returns zero to indicate success and negative for error
1885 *
1886 * @f: QEMUFile where to send the data
1887 * @opaque: RAMState pointer
1888 */
a91246c9
HZ
1889static int ram_save_setup(QEMUFile *f, void *opaque)
1890{
6f37bb8b 1891 RAMState *rs = opaque;
a91246c9
HZ
1892 RAMBlock *block;
1893
1894 /* migration has already setup the bitmap, reuse it. */
1895 if (!migration_in_colo_state()) {
ceb4d168 1896 if (ram_state_init(rs) < 0) {
a91246c9
HZ
1897 return -1;
1898 }
1899 }
204b88b8 1900 rs->f = f;
a91246c9
HZ
1901
1902 rcu_read_lock();
56e93d26
JQ
1903
1904 qemu_put_be64(f, ram_bytes_total() | RAM_SAVE_FLAG_MEM_SIZE);
1905
99e15582 1906 RAMBLOCK_FOREACH(block) {
56e93d26
JQ
1907 qemu_put_byte(f, strlen(block->idstr));
1908 qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));
1909 qemu_put_be64(f, block->used_length);
ef08fb38
DDAG
1910 if (migrate_postcopy_ram() && block->page_size != qemu_host_page_size) {
1911 qemu_put_be64(f, block->page_size);
1912 }
56e93d26
JQ
1913 }
1914
1915 rcu_read_unlock();
1916
1917 ram_control_before_iterate(f, RAM_CONTROL_SETUP);
1918 ram_control_after_iterate(f, RAM_CONTROL_SETUP);
1919
1920 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1921
1922 return 0;
1923}
1924
3d0684b2
JQ
1925/**
1926 * ram_save_iterate: iterative stage for migration
1927 *
1928 * Returns zero to indicate success and negative for error
1929 *
1930 * @f: QEMUFile where to send the data
1931 * @opaque: RAMState pointer
1932 */
56e93d26
JQ
1933static int ram_save_iterate(QEMUFile *f, void *opaque)
1934{
6f37bb8b 1935 RAMState *rs = opaque;
56e93d26
JQ
1936 int ret;
1937 int i;
1938 int64_t t0;
5c90308f 1939 int done = 0;
56e93d26
JQ
1940
1941 rcu_read_lock();
6f37bb8b
JQ
1942 if (ram_list.version != rs->last_version) {
1943 ram_state_reset(rs);
56e93d26
JQ
1944 }
1945
1946 /* Read version before ram_list.blocks */
1947 smp_rmb();
1948
1949 ram_control_before_iterate(f, RAM_CONTROL_ROUND);
1950
1951 t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1952 i = 0;
1953 while ((ret = qemu_file_rate_limit(f)) == 0) {
1954 int pages;
1955
ce25d337 1956 pages = ram_find_and_save_block(rs, false);
56e93d26
JQ
1957 /* no more pages to sent */
1958 if (pages == 0) {
5c90308f 1959 done = 1;
56e93d26
JQ
1960 break;
1961 }
23b28c3c 1962 rs->iterations++;
070afca2 1963
56e93d26
JQ
1964 /* we want to check in the 1st loop, just in case it was the 1st time
1965 and we had to sync the dirty bitmap.
1966 qemu_get_clock_ns() is a bit expensive, so we only check each some
1967 iterations
1968 */
1969 if ((i & 63) == 0) {
1970 uint64_t t1 = (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - t0) / 1000000;
1971 if (t1 > MAX_WAIT) {
55c4446b 1972 trace_ram_save_iterate_big_wait(t1, i);
56e93d26
JQ
1973 break;
1974 }
1975 }
1976 i++;
1977 }
ce25d337 1978 flush_compressed_data(rs);
56e93d26
JQ
1979 rcu_read_unlock();
1980
1981 /*
1982 * Must occur before EOS (or any QEMUFile operation)
1983 * because of RDMA protocol.
1984 */
1985 ram_control_after_iterate(f, RAM_CONTROL_ROUND);
1986
1987 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
9360447d 1988 ram_counters.transferred += 8;
56e93d26
JQ
1989
1990 ret = qemu_file_get_error(f);
1991 if (ret < 0) {
1992 return ret;
1993 }
1994
5c90308f 1995 return done;
56e93d26
JQ
1996}
1997
3d0684b2
JQ
1998/**
1999 * ram_save_complete: function called to send the remaining amount of ram
2000 *
2001 * Returns zero to indicate success
2002 *
2003 * Called with iothread lock
2004 *
2005 * @f: QEMUFile where to send the data
2006 * @opaque: RAMState pointer
2007 */
56e93d26
JQ
2008static int ram_save_complete(QEMUFile *f, void *opaque)
2009{
6f37bb8b
JQ
2010 RAMState *rs = opaque;
2011
56e93d26
JQ
2012 rcu_read_lock();
2013
5727309d 2014 if (!migration_in_postcopy()) {
8d820d6f 2015 migration_bitmap_sync(rs);
663e6c1d 2016 }
56e93d26
JQ
2017
2018 ram_control_before_iterate(f, RAM_CONTROL_FINISH);
2019
2020 /* try transferring iterative blocks of memory */
2021
2022 /* flush all remaining blocks regardless of rate limiting */
2023 while (true) {
2024 int pages;
2025
ce25d337 2026 pages = ram_find_and_save_block(rs, !migration_in_colo_state());
56e93d26
JQ
2027 /* no more blocks to sent */
2028 if (pages == 0) {
2029 break;
2030 }
2031 }
2032
ce25d337 2033 flush_compressed_data(rs);
56e93d26 2034 ram_control_after_iterate(f, RAM_CONTROL_FINISH);
56e93d26
JQ
2035
2036 rcu_read_unlock();
d09a6fde 2037
56e93d26
JQ
2038 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2039
2040 return 0;
2041}
2042
c31b098f
DDAG
2043static void ram_save_pending(QEMUFile *f, void *opaque, uint64_t max_size,
2044 uint64_t *non_postcopiable_pending,
2045 uint64_t *postcopiable_pending)
56e93d26 2046{
8d820d6f 2047 RAMState *rs = opaque;
56e93d26
JQ
2048 uint64_t remaining_size;
2049
9edabd4d 2050 remaining_size = rs->migration_dirty_pages * TARGET_PAGE_SIZE;
56e93d26 2051
5727309d 2052 if (!migration_in_postcopy() &&
663e6c1d 2053 remaining_size < max_size) {
56e93d26
JQ
2054 qemu_mutex_lock_iothread();
2055 rcu_read_lock();
8d820d6f 2056 migration_bitmap_sync(rs);
56e93d26
JQ
2057 rcu_read_unlock();
2058 qemu_mutex_unlock_iothread();
9edabd4d 2059 remaining_size = rs->migration_dirty_pages * TARGET_PAGE_SIZE;
56e93d26 2060 }
c31b098f
DDAG
2061
2062 /* We can do postcopy, and all the data is postcopiable */
2063 *postcopiable_pending += remaining_size;
56e93d26
JQ
2064}
2065
2066static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host)
2067{
2068 unsigned int xh_len;
2069 int xh_flags;
063e760a 2070 uint8_t *loaded_data;
56e93d26
JQ
2071
2072 if (!xbzrle_decoded_buf) {
2073 xbzrle_decoded_buf = g_malloc(TARGET_PAGE_SIZE);
2074 }
063e760a 2075 loaded_data = xbzrle_decoded_buf;
56e93d26
JQ
2076
2077 /* extract RLE header */
2078 xh_flags = qemu_get_byte(f);
2079 xh_len = qemu_get_be16(f);
2080
2081 if (xh_flags != ENCODING_FLAG_XBZRLE) {
2082 error_report("Failed to load XBZRLE page - wrong compression!");
2083 return -1;
2084 }
2085
2086 if (xh_len > TARGET_PAGE_SIZE) {
2087 error_report("Failed to load XBZRLE page - len overflow!");
2088 return -1;
2089 }
2090 /* load data and decode */
063e760a 2091 qemu_get_buffer_in_place(f, &loaded_data, xh_len);
56e93d26
JQ
2092
2093 /* decode RLE */
063e760a 2094 if (xbzrle_decode_buffer(loaded_data, xh_len, host,
56e93d26
JQ
2095 TARGET_PAGE_SIZE) == -1) {
2096 error_report("Failed to load XBZRLE page - decode error!");
2097 return -1;
2098 }
2099
2100 return 0;
2101}
2102
3d0684b2
JQ
2103/**
2104 * ram_block_from_stream: read a RAMBlock id from the migration stream
2105 *
2106 * Must be called from within a rcu critical section.
2107 *
56e93d26 2108 * Returns a pointer from within the RCU-protected ram_list.
a7180877 2109 *
3d0684b2
JQ
2110 * @f: QEMUFile where to read the data from
2111 * @flags: Page flags (mostly to see if it's a continuation of previous block)
a7180877 2112 */
3d0684b2 2113static inline RAMBlock *ram_block_from_stream(QEMUFile *f, int flags)
56e93d26
JQ
2114{
2115 static RAMBlock *block = NULL;
2116 char id[256];
2117 uint8_t len;
2118
2119 if (flags & RAM_SAVE_FLAG_CONTINUE) {
4c4bad48 2120 if (!block) {
56e93d26
JQ
2121 error_report("Ack, bad migration stream!");
2122 return NULL;
2123 }
4c4bad48 2124 return block;
56e93d26
JQ
2125 }
2126
2127 len = qemu_get_byte(f);
2128 qemu_get_buffer(f, (uint8_t *)id, len);
2129 id[len] = 0;
2130
e3dd7493 2131 block = qemu_ram_block_by_name(id);
4c4bad48
HZ
2132 if (!block) {
2133 error_report("Can't find block %s", id);
2134 return NULL;
56e93d26
JQ
2135 }
2136
4c4bad48
HZ
2137 return block;
2138}
2139
2140static inline void *host_from_ram_block_offset(RAMBlock *block,
2141 ram_addr_t offset)
2142{
2143 if (!offset_in_ramblock(block, offset)) {
2144 return NULL;
2145 }
2146
2147 return block->host + offset;
56e93d26
JQ
2148}
2149
3d0684b2
JQ
2150/**
2151 * ram_handle_compressed: handle the zero page case
2152 *
56e93d26
JQ
2153 * If a page (or a whole RDMA chunk) has been
2154 * determined to be zero, then zap it.
3d0684b2
JQ
2155 *
2156 * @host: host address for the zero page
2157 * @ch: what the page is filled from. We only support zero
2158 * @size: size of the zero page
56e93d26
JQ
2159 */
2160void ram_handle_compressed(void *host, uint8_t ch, uint64_t size)
2161{
2162 if (ch != 0 || !is_zero_range(host, size)) {
2163 memset(host, ch, size);
2164 }
2165}
2166
2167static void *do_data_decompress(void *opaque)
2168{
2169 DecompressParam *param = opaque;
2170 unsigned long pagesize;
33d151f4
LL
2171 uint8_t *des;
2172 int len;
56e93d26 2173
33d151f4 2174 qemu_mutex_lock(&param->mutex);
90e56fb4 2175 while (!param->quit) {
33d151f4
LL
2176 if (param->des) {
2177 des = param->des;
2178 len = param->len;
2179 param->des = 0;
2180 qemu_mutex_unlock(&param->mutex);
2181
56e93d26 2182 pagesize = TARGET_PAGE_SIZE;
73a8912b
LL
2183 /* uncompress() will return failed in some case, especially
2184 * when the page is dirted when doing the compression, it's
2185 * not a problem because the dirty page will be retransferred
2186 * and uncompress() won't break the data in other pages.
2187 */
33d151f4
LL
2188 uncompress((Bytef *)des, &pagesize,
2189 (const Bytef *)param->compbuf, len);
73a8912b 2190
33d151f4
LL
2191 qemu_mutex_lock(&decomp_done_lock);
2192 param->done = true;
2193 qemu_cond_signal(&decomp_done_cond);
2194 qemu_mutex_unlock(&decomp_done_lock);
2195
2196 qemu_mutex_lock(&param->mutex);
2197 } else {
2198 qemu_cond_wait(&param->cond, &param->mutex);
2199 }
56e93d26 2200 }
33d151f4 2201 qemu_mutex_unlock(&param->mutex);
56e93d26
JQ
2202
2203 return NULL;
2204}
2205
5533b2e9
LL
2206static void wait_for_decompress_done(void)
2207{
2208 int idx, thread_count;
2209
2210 if (!migrate_use_compression()) {
2211 return;
2212 }
2213
2214 thread_count = migrate_decompress_threads();
2215 qemu_mutex_lock(&decomp_done_lock);
2216 for (idx = 0; idx < thread_count; idx++) {
2217 while (!decomp_param[idx].done) {
2218 qemu_cond_wait(&decomp_done_cond, &decomp_done_lock);
2219 }
2220 }
2221 qemu_mutex_unlock(&decomp_done_lock);
2222}
2223
56e93d26
JQ
2224void migrate_decompress_threads_create(void)
2225{
2226 int i, thread_count;
2227
2228 thread_count = migrate_decompress_threads();
2229 decompress_threads = g_new0(QemuThread, thread_count);
2230 decomp_param = g_new0(DecompressParam, thread_count);
73a8912b
LL
2231 qemu_mutex_init(&decomp_done_lock);
2232 qemu_cond_init(&decomp_done_cond);
56e93d26
JQ
2233 for (i = 0; i < thread_count; i++) {
2234 qemu_mutex_init(&decomp_param[i].mutex);
2235 qemu_cond_init(&decomp_param[i].cond);
2236 decomp_param[i].compbuf = g_malloc0(compressBound(TARGET_PAGE_SIZE));
73a8912b 2237 decomp_param[i].done = true;
90e56fb4 2238 decomp_param[i].quit = false;
56e93d26
JQ
2239 qemu_thread_create(decompress_threads + i, "decompress",
2240 do_data_decompress, decomp_param + i,
2241 QEMU_THREAD_JOINABLE);
2242 }
2243}
2244
2245void migrate_decompress_threads_join(void)
2246{
2247 int i, thread_count;
2248
56e93d26
JQ
2249 thread_count = migrate_decompress_threads();
2250 for (i = 0; i < thread_count; i++) {
2251 qemu_mutex_lock(&decomp_param[i].mutex);
90e56fb4 2252 decomp_param[i].quit = true;
56e93d26
JQ
2253 qemu_cond_signal(&decomp_param[i].cond);
2254 qemu_mutex_unlock(&decomp_param[i].mutex);
2255 }
2256 for (i = 0; i < thread_count; i++) {
2257 qemu_thread_join(decompress_threads + i);
2258 qemu_mutex_destroy(&decomp_param[i].mutex);
2259 qemu_cond_destroy(&decomp_param[i].cond);
2260 g_free(decomp_param[i].compbuf);
2261 }
2262 g_free(decompress_threads);
2263 g_free(decomp_param);
56e93d26
JQ
2264 decompress_threads = NULL;
2265 decomp_param = NULL;
56e93d26
JQ
2266}
2267
c1bc6626 2268static void decompress_data_with_multi_threads(QEMUFile *f,
56e93d26
JQ
2269 void *host, int len)
2270{
2271 int idx, thread_count;
2272
2273 thread_count = migrate_decompress_threads();
73a8912b 2274 qemu_mutex_lock(&decomp_done_lock);
56e93d26
JQ
2275 while (true) {
2276 for (idx = 0; idx < thread_count; idx++) {
73a8912b 2277 if (decomp_param[idx].done) {
33d151f4
LL
2278 decomp_param[idx].done = false;
2279 qemu_mutex_lock(&decomp_param[idx].mutex);
c1bc6626 2280 qemu_get_buffer(f, decomp_param[idx].compbuf, len);
56e93d26
JQ
2281 decomp_param[idx].des = host;
2282 decomp_param[idx].len = len;
33d151f4
LL
2283 qemu_cond_signal(&decomp_param[idx].cond);
2284 qemu_mutex_unlock(&decomp_param[idx].mutex);
56e93d26
JQ
2285 break;
2286 }
2287 }
2288 if (idx < thread_count) {
2289 break;
73a8912b
LL
2290 } else {
2291 qemu_cond_wait(&decomp_done_cond, &decomp_done_lock);
56e93d26
JQ
2292 }
2293 }
73a8912b 2294 qemu_mutex_unlock(&decomp_done_lock);
56e93d26
JQ
2295}
2296
3d0684b2
JQ
2297/**
2298 * ram_postcopy_incoming_init: allocate postcopy data structures
2299 *
2300 * Returns 0 for success and negative if there was one error
2301 *
2302 * @mis: current migration incoming state
2303 *
2304 * Allocate data structures etc needed by incoming migration with
2305 * postcopy-ram. postcopy-ram's similarly names
2306 * postcopy_ram_incoming_init does the work.
1caddf8a
DDAG
2307 */
2308int ram_postcopy_incoming_init(MigrationIncomingState *mis)
2309{
b8c48993 2310 unsigned long ram_pages = last_ram_page();
1caddf8a
DDAG
2311
2312 return postcopy_ram_incoming_init(mis, ram_pages);
2313}
2314
3d0684b2
JQ
2315/**
2316 * ram_load_postcopy: load a page in postcopy case
2317 *
2318 * Returns 0 for success or -errno in case of error
2319 *
a7180877
DDAG
2320 * Called in postcopy mode by ram_load().
2321 * rcu_read_lock is taken prior to this being called.
3d0684b2
JQ
2322 *
2323 * @f: QEMUFile where to send the data
a7180877
DDAG
2324 */
2325static int ram_load_postcopy(QEMUFile *f)
2326{
2327 int flags = 0, ret = 0;
2328 bool place_needed = false;
28abd200 2329 bool matching_page_sizes = false;
a7180877
DDAG
2330 MigrationIncomingState *mis = migration_incoming_get_current();
2331 /* Temporary page that is later 'placed' */
2332 void *postcopy_host_page = postcopy_get_tmp_page(mis);
c53b7ddc 2333 void *last_host = NULL;
a3b6ff6d 2334 bool all_zero = false;
a7180877
DDAG
2335
2336 while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
2337 ram_addr_t addr;
2338 void *host = NULL;
2339 void *page_buffer = NULL;
2340 void *place_source = NULL;
df9ff5e1 2341 RAMBlock *block = NULL;
a7180877 2342 uint8_t ch;
a7180877
DDAG
2343
2344 addr = qemu_get_be64(f);
2345 flags = addr & ~TARGET_PAGE_MASK;
2346 addr &= TARGET_PAGE_MASK;
2347
2348 trace_ram_load_postcopy_loop((uint64_t)addr, flags);
2349 place_needed = false;
bb890ed5 2350 if (flags & (RAM_SAVE_FLAG_ZERO | RAM_SAVE_FLAG_PAGE)) {
df9ff5e1 2351 block = ram_block_from_stream(f, flags);
4c4bad48
HZ
2352
2353 host = host_from_ram_block_offset(block, addr);
a7180877
DDAG
2354 if (!host) {
2355 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
2356 ret = -EINVAL;
2357 break;
2358 }
28abd200 2359 matching_page_sizes = block->page_size == TARGET_PAGE_SIZE;
a7180877 2360 /*
28abd200
DDAG
2361 * Postcopy requires that we place whole host pages atomically;
2362 * these may be huge pages for RAMBlocks that are backed by
2363 * hugetlbfs.
a7180877
DDAG
2364 * To make it atomic, the data is read into a temporary page
2365 * that's moved into place later.
2366 * The migration protocol uses, possibly smaller, target-pages
2367 * however the source ensures it always sends all the components
2368 * of a host page in order.
2369 */
2370 page_buffer = postcopy_host_page +
28abd200 2371 ((uintptr_t)host & (block->page_size - 1));
a7180877 2372 /* If all TP are zero then we can optimise the place */
28abd200 2373 if (!((uintptr_t)host & (block->page_size - 1))) {
a7180877 2374 all_zero = true;
c53b7ddc
DDAG
2375 } else {
2376 /* not the 1st TP within the HP */
2377 if (host != (last_host + TARGET_PAGE_SIZE)) {
9af9e0fe 2378 error_report("Non-sequential target page %p/%p",
c53b7ddc
DDAG
2379 host, last_host);
2380 ret = -EINVAL;
2381 break;
2382 }
a7180877
DDAG
2383 }
2384
c53b7ddc 2385
a7180877
DDAG
2386 /*
2387 * If it's the last part of a host page then we place the host
2388 * page
2389 */
2390 place_needed = (((uintptr_t)host + TARGET_PAGE_SIZE) &
28abd200 2391 (block->page_size - 1)) == 0;
a7180877
DDAG
2392 place_source = postcopy_host_page;
2393 }
c53b7ddc 2394 last_host = host;
a7180877
DDAG
2395
2396 switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
bb890ed5 2397 case RAM_SAVE_FLAG_ZERO:
a7180877
DDAG
2398 ch = qemu_get_byte(f);
2399 memset(page_buffer, ch, TARGET_PAGE_SIZE);
2400 if (ch) {
2401 all_zero = false;
2402 }
2403 break;
2404
2405 case RAM_SAVE_FLAG_PAGE:
2406 all_zero = false;
2407 if (!place_needed || !matching_page_sizes) {
2408 qemu_get_buffer(f, page_buffer, TARGET_PAGE_SIZE);
2409 } else {
2410 /* Avoids the qemu_file copy during postcopy, which is
2411 * going to do a copy later; can only do it when we
2412 * do this read in one go (matching page sizes)
2413 */
2414 qemu_get_buffer_in_place(f, (uint8_t **)&place_source,
2415 TARGET_PAGE_SIZE);
2416 }
2417 break;
2418 case RAM_SAVE_FLAG_EOS:
2419 /* normal exit */
2420 break;
2421 default:
2422 error_report("Unknown combination of migration flags: %#x"
2423 " (postcopy mode)", flags);
2424 ret = -EINVAL;
2425 }
2426
2427 if (place_needed) {
2428 /* This gets called at the last target page in the host page */
df9ff5e1
DDAG
2429 void *place_dest = host + TARGET_PAGE_SIZE - block->page_size;
2430
a7180877 2431 if (all_zero) {
df9ff5e1
DDAG
2432 ret = postcopy_place_page_zero(mis, place_dest,
2433 block->page_size);
a7180877 2434 } else {
df9ff5e1
DDAG
2435 ret = postcopy_place_page(mis, place_dest,
2436 place_source, block->page_size);
a7180877
DDAG
2437 }
2438 }
2439 if (!ret) {
2440 ret = qemu_file_get_error(f);
2441 }
2442 }
2443
2444 return ret;
2445}
2446
56e93d26
JQ
2447static int ram_load(QEMUFile *f, void *opaque, int version_id)
2448{
2449 int flags = 0, ret = 0;
2450 static uint64_t seq_iter;
2451 int len = 0;
a7180877
DDAG
2452 /*
2453 * If system is running in postcopy mode, page inserts to host memory must
2454 * be atomic
2455 */
2456 bool postcopy_running = postcopy_state_get() >= POSTCOPY_INCOMING_LISTENING;
ef08fb38
DDAG
2457 /* ADVISE is earlier, it shows the source has the postcopy capability on */
2458 bool postcopy_advised = postcopy_state_get() >= POSTCOPY_INCOMING_ADVISE;
56e93d26
JQ
2459
2460 seq_iter++;
2461
2462 if (version_id != 4) {
2463 ret = -EINVAL;
2464 }
2465
2466 /* This RCU critical section can be very long running.
2467 * When RCU reclaims in the code start to become numerous,
2468 * it will be necessary to reduce the granularity of this
2469 * critical section.
2470 */
2471 rcu_read_lock();
a7180877
DDAG
2472
2473 if (postcopy_running) {
2474 ret = ram_load_postcopy(f);
2475 }
2476
2477 while (!postcopy_running && !ret && !(flags & RAM_SAVE_FLAG_EOS)) {
56e93d26 2478 ram_addr_t addr, total_ram_bytes;
a776aa15 2479 void *host = NULL;
56e93d26
JQ
2480 uint8_t ch;
2481
2482 addr = qemu_get_be64(f);
2483 flags = addr & ~TARGET_PAGE_MASK;
2484 addr &= TARGET_PAGE_MASK;
2485
bb890ed5 2486 if (flags & (RAM_SAVE_FLAG_ZERO | RAM_SAVE_FLAG_PAGE |
a776aa15 2487 RAM_SAVE_FLAG_COMPRESS_PAGE | RAM_SAVE_FLAG_XBZRLE)) {
4c4bad48
HZ
2488 RAMBlock *block = ram_block_from_stream(f, flags);
2489
2490 host = host_from_ram_block_offset(block, addr);
a776aa15
DDAG
2491 if (!host) {
2492 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
2493 ret = -EINVAL;
2494 break;
2495 }
1db9d8e5 2496 trace_ram_load_loop(block->idstr, (uint64_t)addr, flags, host);
a776aa15
DDAG
2497 }
2498
56e93d26
JQ
2499 switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
2500 case RAM_SAVE_FLAG_MEM_SIZE:
2501 /* Synchronize RAM block list */
2502 total_ram_bytes = addr;
2503 while (!ret && total_ram_bytes) {
2504 RAMBlock *block;
56e93d26
JQ
2505 char id[256];
2506 ram_addr_t length;
2507
2508 len = qemu_get_byte(f);
2509 qemu_get_buffer(f, (uint8_t *)id, len);
2510 id[len] = 0;
2511 length = qemu_get_be64(f);
2512
e3dd7493
DDAG
2513 block = qemu_ram_block_by_name(id);
2514 if (block) {
2515 if (length != block->used_length) {
2516 Error *local_err = NULL;
56e93d26 2517
fa53a0e5 2518 ret = qemu_ram_resize(block, length,
e3dd7493
DDAG
2519 &local_err);
2520 if (local_err) {
2521 error_report_err(local_err);
56e93d26 2522 }
56e93d26 2523 }
ef08fb38
DDAG
2524 /* For postcopy we need to check hugepage sizes match */
2525 if (postcopy_advised &&
2526 block->page_size != qemu_host_page_size) {
2527 uint64_t remote_page_size = qemu_get_be64(f);
2528 if (remote_page_size != block->page_size) {
2529 error_report("Mismatched RAM page size %s "
2530 "(local) %zd != %" PRId64,
2531 id, block->page_size,
2532 remote_page_size);
2533 ret = -EINVAL;
2534 }
2535 }
e3dd7493
DDAG
2536 ram_control_load_hook(f, RAM_CONTROL_BLOCK_REG,
2537 block->idstr);
2538 } else {
56e93d26
JQ
2539 error_report("Unknown ramblock \"%s\", cannot "
2540 "accept migration", id);
2541 ret = -EINVAL;
2542 }
2543
2544 total_ram_bytes -= length;
2545 }
2546 break;
a776aa15 2547
bb890ed5 2548 case RAM_SAVE_FLAG_ZERO:
56e93d26
JQ
2549 ch = qemu_get_byte(f);
2550 ram_handle_compressed(host, ch, TARGET_PAGE_SIZE);
2551 break;
a776aa15 2552
56e93d26 2553 case RAM_SAVE_FLAG_PAGE:
56e93d26
JQ
2554 qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
2555 break;
56e93d26 2556
a776aa15 2557 case RAM_SAVE_FLAG_COMPRESS_PAGE:
56e93d26
JQ
2558 len = qemu_get_be32(f);
2559 if (len < 0 || len > compressBound(TARGET_PAGE_SIZE)) {
2560 error_report("Invalid compressed data length: %d", len);
2561 ret = -EINVAL;
2562 break;
2563 }
c1bc6626 2564 decompress_data_with_multi_threads(f, host, len);
56e93d26 2565 break;
a776aa15 2566
56e93d26 2567 case RAM_SAVE_FLAG_XBZRLE:
56e93d26
JQ
2568 if (load_xbzrle(f, addr, host) < 0) {
2569 error_report("Failed to decompress XBZRLE page at "
2570 RAM_ADDR_FMT, addr);
2571 ret = -EINVAL;
2572 break;
2573 }
2574 break;
2575 case RAM_SAVE_FLAG_EOS:
2576 /* normal exit */
2577 break;
2578 default:
2579 if (flags & RAM_SAVE_FLAG_HOOK) {
632e3a5c 2580 ram_control_load_hook(f, RAM_CONTROL_HOOK, NULL);
56e93d26
JQ
2581 } else {
2582 error_report("Unknown combination of migration flags: %#x",
2583 flags);
2584 ret = -EINVAL;
2585 }
2586 }
2587 if (!ret) {
2588 ret = qemu_file_get_error(f);
2589 }
2590 }
2591
5533b2e9 2592 wait_for_decompress_done();
56e93d26 2593 rcu_read_unlock();
55c4446b 2594 trace_ram_load_complete(ret, seq_iter);
56e93d26
JQ
2595 return ret;
2596}
2597
2598static SaveVMHandlers savevm_ram_handlers = {
2599 .save_live_setup = ram_save_setup,
2600 .save_live_iterate = ram_save_iterate,
763c906b 2601 .save_live_complete_postcopy = ram_save_complete,
a3e06c3d 2602 .save_live_complete_precopy = ram_save_complete,
56e93d26
JQ
2603 .save_live_pending = ram_save_pending,
2604 .load_state = ram_load,
6ad2a215 2605 .cleanup = ram_migration_cleanup,
56e93d26
JQ
2606};
2607
2608void ram_mig_init(void)
2609{
2610 qemu_mutex_init(&XBZRLE.lock);
6f37bb8b 2611 register_savevm_live(NULL, "ram", 0, 4, &savevm_ram_handlers, &ram_state);
56e93d26 2612}