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