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