]> git.proxmox.com Git - mirror_qemu.git/blame - migration/ram.c
bitmap: bitmap_count_one_with_offset
[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"
56eb90af 36#include "qemu/pmem.h"
709e3fe8 37#include "xbzrle.h"
7b1e1a22 38#include "ram.h"
6666c96a 39#include "migration.h"
71bb07db 40#include "socket.h"
f2a8f0a6 41#include "migration/register.h"
7b1e1a22 42#include "migration/misc.h"
08a0aee1 43#include "qemu-file.h"
be07b0ac 44#include "postcopy-ram.h"
53d37d36 45#include "page_cache.h"
56e93d26 46#include "qemu/error-report.h"
e688df6b 47#include "qapi/error.h"
9af23989 48#include "qapi/qapi-events-migration.h"
8acabf69 49#include "qapi/qmp/qerror.h"
56e93d26 50#include "trace.h"
56e93d26 51#include "exec/ram_addr.h"
f9494614 52#include "exec/target_page.h"
56e93d26 53#include "qemu/rcu_queue.h"
a91246c9 54#include "migration/colo.h"
53d37d36 55#include "block.h"
af8b7d2b
JQ
56#include "sysemu/sysemu.h"
57#include "qemu/uuid.h"
edd090c7 58#include "savevm.h"
b9ee2f7d 59#include "qemu/iov.h"
56e93d26 60
56e93d26
JQ
61/***********************************************************/
62/* ram save/restore */
63
bb890ed5
JQ
64/* RAM_SAVE_FLAG_ZERO used to be named RAM_SAVE_FLAG_COMPRESS, it
65 * worked for pages that where filled with the same char. We switched
66 * it to only search for the zero value. And to avoid confusion with
67 * RAM_SSAVE_FLAG_COMPRESS_PAGE just rename it.
68 */
69
56e93d26 70#define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
bb890ed5 71#define RAM_SAVE_FLAG_ZERO 0x02
56e93d26
JQ
72#define RAM_SAVE_FLAG_MEM_SIZE 0x04
73#define RAM_SAVE_FLAG_PAGE 0x08
74#define RAM_SAVE_FLAG_EOS 0x10
75#define RAM_SAVE_FLAG_CONTINUE 0x20
76#define RAM_SAVE_FLAG_XBZRLE 0x40
77/* 0x80 is reserved in migration.h start with 0x100 next */
78#define RAM_SAVE_FLAG_COMPRESS_PAGE 0x100
79
56e93d26
JQ
80static inline bool is_zero_range(uint8_t *p, uint64_t size)
81{
a1febc49 82 return buffer_is_zero(p, size);
56e93d26
JQ
83}
84
9360447d
JQ
85XBZRLECacheStats xbzrle_counters;
86
56e93d26
JQ
87/* struct contains XBZRLE cache and a static page
88 used by the compression */
89static struct {
90 /* buffer used for XBZRLE encoding */
91 uint8_t *encoded_buf;
92 /* buffer for storing page content */
93 uint8_t *current_buf;
94 /* Cache for XBZRLE, Protected by lock. */
95 PageCache *cache;
96 QemuMutex lock;
c00e0928
JQ
97 /* it will store a page full of zeros */
98 uint8_t *zero_target_page;
f265e0e4
JQ
99 /* buffer used for XBZRLE decoding */
100 uint8_t *decoded_buf;
56e93d26
JQ
101} XBZRLE;
102
56e93d26
JQ
103static void XBZRLE_cache_lock(void)
104{
105 if (migrate_use_xbzrle())
106 qemu_mutex_lock(&XBZRLE.lock);
107}
108
109static void XBZRLE_cache_unlock(void)
110{
111 if (migrate_use_xbzrle())
112 qemu_mutex_unlock(&XBZRLE.lock);
113}
114
3d0684b2
JQ
115/**
116 * xbzrle_cache_resize: resize the xbzrle cache
117 *
118 * This function is called from qmp_migrate_set_cache_size in main
119 * thread, possibly while a migration is in progress. A running
120 * migration may be using the cache and might finish during this call,
121 * hence changes to the cache are protected by XBZRLE.lock().
122 *
c9dede2d 123 * Returns 0 for success or -1 for error
3d0684b2
JQ
124 *
125 * @new_size: new cache size
8acabf69 126 * @errp: set *errp if the check failed, with reason
56e93d26 127 */
c9dede2d 128int xbzrle_cache_resize(int64_t new_size, Error **errp)
56e93d26
JQ
129{
130 PageCache *new_cache;
c9dede2d 131 int64_t ret = 0;
56e93d26 132
8acabf69
JQ
133 /* Check for truncation */
134 if (new_size != (size_t)new_size) {
135 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
136 "exceeding address space");
137 return -1;
138 }
139
2a313e5c
JQ
140 if (new_size == migrate_xbzrle_cache_size()) {
141 /* nothing to do */
c9dede2d 142 return 0;
2a313e5c
JQ
143 }
144
56e93d26
JQ
145 XBZRLE_cache_lock();
146
147 if (XBZRLE.cache != NULL) {
80f8dfde 148 new_cache = cache_init(new_size, TARGET_PAGE_SIZE, errp);
56e93d26 149 if (!new_cache) {
56e93d26
JQ
150 ret = -1;
151 goto out;
152 }
153
154 cache_fini(XBZRLE.cache);
155 XBZRLE.cache = new_cache;
156 }
56e93d26
JQ
157out:
158 XBZRLE_cache_unlock();
159 return ret;
160}
161
fbd162e6
YK
162static bool ramblock_is_ignored(RAMBlock *block)
163{
164 return !qemu_ram_is_migratable(block) ||
165 (migrate_ignore_shared() && qemu_ram_is_shared(block));
166}
167
b895de50 168/* Should be holding either ram_list.mutex, or the RCU lock. */
fbd162e6
YK
169#define RAMBLOCK_FOREACH_NOT_IGNORED(block) \
170 INTERNAL_RAMBLOCK_FOREACH(block) \
171 if (ramblock_is_ignored(block)) {} else
172
b895de50 173#define RAMBLOCK_FOREACH_MIGRATABLE(block) \
343f632c 174 INTERNAL_RAMBLOCK_FOREACH(block) \
b895de50
CLG
175 if (!qemu_ram_is_migratable(block)) {} else
176
343f632c
DDAG
177#undef RAMBLOCK_FOREACH
178
fbd162e6
YK
179int foreach_not_ignored_block(RAMBlockIterFunc func, void *opaque)
180{
181 RAMBlock *block;
182 int ret = 0;
183
184 rcu_read_lock();
185 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
186 ret = func(block, opaque);
187 if (ret) {
188 break;
189 }
190 }
191 rcu_read_unlock();
192 return ret;
193}
194
f9494614
AP
195static void ramblock_recv_map_init(void)
196{
197 RAMBlock *rb;
198
fbd162e6 199 RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
f9494614
AP
200 assert(!rb->receivedmap);
201 rb->receivedmap = bitmap_new(rb->max_length >> qemu_target_page_bits());
202 }
203}
204
205int ramblock_recv_bitmap_test(RAMBlock *rb, void *host_addr)
206{
207 return test_bit(ramblock_recv_bitmap_offset(host_addr, rb),
208 rb->receivedmap);
209}
210
1cba9f6e
DDAG
211bool ramblock_recv_bitmap_test_byte_offset(RAMBlock *rb, uint64_t byte_offset)
212{
213 return test_bit(byte_offset >> TARGET_PAGE_BITS, rb->receivedmap);
214}
215
f9494614
AP
216void ramblock_recv_bitmap_set(RAMBlock *rb, void *host_addr)
217{
218 set_bit_atomic(ramblock_recv_bitmap_offset(host_addr, rb), rb->receivedmap);
219}
220
221void ramblock_recv_bitmap_set_range(RAMBlock *rb, void *host_addr,
222 size_t nr)
223{
224 bitmap_set_atomic(rb->receivedmap,
225 ramblock_recv_bitmap_offset(host_addr, rb),
226 nr);
227}
228
a335debb
PX
229#define RAMBLOCK_RECV_BITMAP_ENDING (0x0123456789abcdefULL)
230
231/*
232 * Format: bitmap_size (8 bytes) + whole_bitmap (N bytes).
233 *
234 * Returns >0 if success with sent bytes, or <0 if error.
235 */
236int64_t ramblock_recv_bitmap_send(QEMUFile *file,
237 const char *block_name)
238{
239 RAMBlock *block = qemu_ram_block_by_name(block_name);
240 unsigned long *le_bitmap, nbits;
241 uint64_t size;
242
243 if (!block) {
244 error_report("%s: invalid block name: %s", __func__, block_name);
245 return -1;
246 }
247
248 nbits = block->used_length >> TARGET_PAGE_BITS;
249
250 /*
251 * Make sure the tmp bitmap buffer is big enough, e.g., on 32bit
252 * machines we may need 4 more bytes for padding (see below
253 * comment). So extend it a bit before hand.
254 */
255 le_bitmap = bitmap_new(nbits + BITS_PER_LONG);
256
257 /*
258 * Always use little endian when sending the bitmap. This is
259 * required that when source and destination VMs are not using the
260 * same endianess. (Note: big endian won't work.)
261 */
262 bitmap_to_le(le_bitmap, block->receivedmap, nbits);
263
264 /* Size of the bitmap, in bytes */
a725ef9f 265 size = DIV_ROUND_UP(nbits, 8);
a335debb
PX
266
267 /*
268 * size is always aligned to 8 bytes for 64bit machines, but it
269 * may not be true for 32bit machines. We need this padding to
270 * make sure the migration can survive even between 32bit and
271 * 64bit machines.
272 */
273 size = ROUND_UP(size, 8);
274
275 qemu_put_be64(file, size);
276 qemu_put_buffer(file, (const uint8_t *)le_bitmap, size);
277 /*
278 * Mark as an end, in case the middle part is screwed up due to
279 * some "misterious" reason.
280 */
281 qemu_put_be64(file, RAMBLOCK_RECV_BITMAP_ENDING);
282 qemu_fflush(file);
283
bf269906 284 g_free(le_bitmap);
a335debb
PX
285
286 if (qemu_file_get_error(file)) {
287 return qemu_file_get_error(file);
288 }
289
290 return size + sizeof(size);
291}
292
ec481c6c
JQ
293/*
294 * An outstanding page request, on the source, having been received
295 * and queued
296 */
297struct RAMSrcPageRequest {
298 RAMBlock *rb;
299 hwaddr offset;
300 hwaddr len;
301
302 QSIMPLEQ_ENTRY(RAMSrcPageRequest) next_req;
303};
304
6f37bb8b
JQ
305/* State of RAM for migration */
306struct RAMState {
204b88b8
JQ
307 /* QEMUFile used for this migration */
308 QEMUFile *f;
6f37bb8b
JQ
309 /* Last block that we have visited searching for dirty pages */
310 RAMBlock *last_seen_block;
311 /* Last block from where we have sent data */
312 RAMBlock *last_sent_block;
269ace29
JQ
313 /* Last dirty target page we have sent */
314 ram_addr_t last_page;
6f37bb8b
JQ
315 /* last ram version we have seen */
316 uint32_t last_version;
317 /* We are in the first round */
318 bool ram_bulk_stage;
8d820d6f
JQ
319 /* How many times we have dirty too many pages */
320 int dirty_rate_high_cnt;
f664da80
JQ
321 /* these variables are used for bitmap sync */
322 /* last time we did a full bitmap_sync */
323 int64_t time_last_bitmap_sync;
eac74159 324 /* bytes transferred at start_time */
c4bdf0cf 325 uint64_t bytes_xfer_prev;
a66cd90c 326 /* number of dirty pages since start_time */
68908ed6 327 uint64_t num_dirty_pages_period;
b5833fde
JQ
328 /* xbzrle misses since the beginning of the period */
329 uint64_t xbzrle_cache_miss_prev;
76e03000
XG
330
331 /* compression statistics since the beginning of the period */
332 /* amount of count that no free thread to compress data */
333 uint64_t compress_thread_busy_prev;
334 /* amount bytes after compression */
335 uint64_t compressed_size_prev;
336 /* amount of compressed pages */
337 uint64_t compress_pages_prev;
338
be8b02ed
XG
339 /* total handled target pages at the beginning of period */
340 uint64_t target_page_count_prev;
341 /* total handled target pages since start */
342 uint64_t target_page_count;
9360447d 343 /* number of dirty bits in the bitmap */
2dfaf12e
PX
344 uint64_t migration_dirty_pages;
345 /* protects modification of the bitmap */
108cfae0 346 QemuMutex bitmap_mutex;
68a098f3
JQ
347 /* The RAMBlock used in the last src_page_requests */
348 RAMBlock *last_req_rb;
ec481c6c
JQ
349 /* Queue of outstanding page requests from the destination */
350 QemuMutex src_page_req_mutex;
b58deb34 351 QSIMPLEQ_HEAD(, RAMSrcPageRequest) src_page_requests;
6f37bb8b
JQ
352};
353typedef struct RAMState RAMState;
354
53518d94 355static RAMState *ram_state;
6f37bb8b 356
9edabd4d 357uint64_t ram_bytes_remaining(void)
2f4fde93 358{
bae416e5
DDAG
359 return ram_state ? (ram_state->migration_dirty_pages * TARGET_PAGE_SIZE) :
360 0;
2f4fde93
JQ
361}
362
9360447d 363MigrationStats ram_counters;
96506894 364
b8fb8cb7
DDAG
365/* used by the search for pages to send */
366struct PageSearchStatus {
367 /* Current block being searched */
368 RAMBlock *block;
a935e30f
JQ
369 /* Current page to search from */
370 unsigned long page;
b8fb8cb7
DDAG
371 /* Set once we wrap around */
372 bool complete_round;
373};
374typedef struct PageSearchStatus PageSearchStatus;
375
76e03000
XG
376CompressionStats compression_counters;
377
56e93d26 378struct CompressParam {
56e93d26 379 bool done;
90e56fb4 380 bool quit;
5e5fdcff 381 bool zero_page;
56e93d26
JQ
382 QEMUFile *file;
383 QemuMutex mutex;
384 QemuCond cond;
385 RAMBlock *block;
386 ram_addr_t offset;
34ab9e97
XG
387
388 /* internally used fields */
dcaf446e 389 z_stream stream;
34ab9e97 390 uint8_t *originbuf;
56e93d26
JQ
391};
392typedef struct CompressParam CompressParam;
393
394struct DecompressParam {
73a8912b 395 bool done;
90e56fb4 396 bool quit;
56e93d26
JQ
397 QemuMutex mutex;
398 QemuCond cond;
399 void *des;
d341d9f3 400 uint8_t *compbuf;
56e93d26 401 int len;
797ca154 402 z_stream stream;
56e93d26
JQ
403};
404typedef struct DecompressParam DecompressParam;
405
406static CompressParam *comp_param;
407static QemuThread *compress_threads;
408/* comp_done_cond is used to wake up the migration thread when
409 * one of the compression threads has finished the compression.
410 * comp_done_lock is used to co-work with comp_done_cond.
411 */
0d9f9a5c
LL
412static QemuMutex comp_done_lock;
413static QemuCond comp_done_cond;
56e93d26
JQ
414/* The empty QEMUFileOps will be used by file in CompressParam */
415static const QEMUFileOps empty_ops = { };
416
34ab9e97 417static QEMUFile *decomp_file;
56e93d26
JQ
418static DecompressParam *decomp_param;
419static QemuThread *decompress_threads;
73a8912b
LL
420static QemuMutex decomp_done_lock;
421static QemuCond decomp_done_cond;
56e93d26 422
5e5fdcff 423static bool do_compress_ram_page(QEMUFile *f, z_stream *stream, RAMBlock *block,
6ef3771c 424 ram_addr_t offset, uint8_t *source_buf);
56e93d26
JQ
425
426static void *do_data_compress(void *opaque)
427{
428 CompressParam *param = opaque;
a7a9a88f
LL
429 RAMBlock *block;
430 ram_addr_t offset;
5e5fdcff 431 bool zero_page;
56e93d26 432
a7a9a88f 433 qemu_mutex_lock(&param->mutex);
90e56fb4 434 while (!param->quit) {
a7a9a88f
LL
435 if (param->block) {
436 block = param->block;
437 offset = param->offset;
438 param->block = NULL;
439 qemu_mutex_unlock(&param->mutex);
440
5e5fdcff
XG
441 zero_page = do_compress_ram_page(param->file, &param->stream,
442 block, offset, param->originbuf);
a7a9a88f 443
0d9f9a5c 444 qemu_mutex_lock(&comp_done_lock);
a7a9a88f 445 param->done = true;
5e5fdcff 446 param->zero_page = zero_page;
0d9f9a5c
LL
447 qemu_cond_signal(&comp_done_cond);
448 qemu_mutex_unlock(&comp_done_lock);
a7a9a88f
LL
449
450 qemu_mutex_lock(&param->mutex);
451 } else {
56e93d26
JQ
452 qemu_cond_wait(&param->cond, &param->mutex);
453 }
56e93d26 454 }
a7a9a88f 455 qemu_mutex_unlock(&param->mutex);
56e93d26
JQ
456
457 return NULL;
458}
459
f0afa331 460static void compress_threads_save_cleanup(void)
56e93d26
JQ
461{
462 int i, thread_count;
463
05306935 464 if (!migrate_use_compression() || !comp_param) {
56e93d26
JQ
465 return;
466 }
05306935 467
56e93d26
JQ
468 thread_count = migrate_compress_threads();
469 for (i = 0; i < thread_count; i++) {
dcaf446e
XG
470 /*
471 * we use it as a indicator which shows if the thread is
472 * properly init'd or not
473 */
474 if (!comp_param[i].file) {
475 break;
476 }
05306935
FL
477
478 qemu_mutex_lock(&comp_param[i].mutex);
479 comp_param[i].quit = true;
480 qemu_cond_signal(&comp_param[i].cond);
481 qemu_mutex_unlock(&comp_param[i].mutex);
482
56e93d26 483 qemu_thread_join(compress_threads + i);
56e93d26
JQ
484 qemu_mutex_destroy(&comp_param[i].mutex);
485 qemu_cond_destroy(&comp_param[i].cond);
dcaf446e 486 deflateEnd(&comp_param[i].stream);
34ab9e97 487 g_free(comp_param[i].originbuf);
dcaf446e
XG
488 qemu_fclose(comp_param[i].file);
489 comp_param[i].file = NULL;
56e93d26 490 }
0d9f9a5c
LL
491 qemu_mutex_destroy(&comp_done_lock);
492 qemu_cond_destroy(&comp_done_cond);
56e93d26
JQ
493 g_free(compress_threads);
494 g_free(comp_param);
56e93d26
JQ
495 compress_threads = NULL;
496 comp_param = NULL;
56e93d26
JQ
497}
498
dcaf446e 499static int compress_threads_save_setup(void)
56e93d26
JQ
500{
501 int i, thread_count;
502
503 if (!migrate_use_compression()) {
dcaf446e 504 return 0;
56e93d26 505 }
56e93d26
JQ
506 thread_count = migrate_compress_threads();
507 compress_threads = g_new0(QemuThread, thread_count);
508 comp_param = g_new0(CompressParam, thread_count);
0d9f9a5c
LL
509 qemu_cond_init(&comp_done_cond);
510 qemu_mutex_init(&comp_done_lock);
56e93d26 511 for (i = 0; i < thread_count; i++) {
34ab9e97
XG
512 comp_param[i].originbuf = g_try_malloc(TARGET_PAGE_SIZE);
513 if (!comp_param[i].originbuf) {
514 goto exit;
515 }
516
dcaf446e
XG
517 if (deflateInit(&comp_param[i].stream,
518 migrate_compress_level()) != Z_OK) {
34ab9e97 519 g_free(comp_param[i].originbuf);
dcaf446e
XG
520 goto exit;
521 }
522
e110aa91
C
523 /* comp_param[i].file is just used as a dummy buffer to save data,
524 * set its ops to empty.
56e93d26
JQ
525 */
526 comp_param[i].file = qemu_fopen_ops(NULL, &empty_ops);
527 comp_param[i].done = true;
90e56fb4 528 comp_param[i].quit = false;
56e93d26
JQ
529 qemu_mutex_init(&comp_param[i].mutex);
530 qemu_cond_init(&comp_param[i].cond);
531 qemu_thread_create(compress_threads + i, "compress",
532 do_data_compress, comp_param + i,
533 QEMU_THREAD_JOINABLE);
534 }
dcaf446e
XG
535 return 0;
536
537exit:
538 compress_threads_save_cleanup();
539 return -1;
56e93d26
JQ
540}
541
f986c3d2
JQ
542/* Multiple fd's */
543
af8b7d2b
JQ
544#define MULTIFD_MAGIC 0x11223344U
545#define MULTIFD_VERSION 1
546
6df264ac
JQ
547#define MULTIFD_FLAG_SYNC (1 << 0)
548
af8b7d2b
JQ
549typedef struct {
550 uint32_t magic;
551 uint32_t version;
552 unsigned char uuid[16]; /* QemuUUID */
553 uint8_t id;
554} __attribute__((packed)) MultiFDInit_t;
555
2a26c979
JQ
556typedef struct {
557 uint32_t magic;
558 uint32_t version;
559 uint32_t flags;
560 uint32_t size;
561 uint32_t used;
562 uint64_t packet_num;
563 char ramblock[256];
564 uint64_t offset[];
565} __attribute__((packed)) MultiFDPacket_t;
566
34c55a94
JQ
567typedef struct {
568 /* number of used pages */
569 uint32_t used;
570 /* number of allocated pages */
571 uint32_t allocated;
572 /* global number of generated multifd packets */
573 uint64_t packet_num;
574 /* offset of each page */
575 ram_addr_t *offset;
576 /* pointer to each page */
577 struct iovec *iov;
578 RAMBlock *block;
579} MultiFDPages_t;
580
8c4598f2
JQ
581typedef struct {
582 /* this fields are not changed once the thread is created */
583 /* channel number */
f986c3d2 584 uint8_t id;
8c4598f2 585 /* channel thread name */
f986c3d2 586 char *name;
8c4598f2 587 /* channel thread id */
f986c3d2 588 QemuThread thread;
8c4598f2 589 /* communication channel */
60df2d4a 590 QIOChannel *c;
8c4598f2 591 /* sem where to wait for more work */
f986c3d2 592 QemuSemaphore sem;
8c4598f2 593 /* this mutex protects the following parameters */
f986c3d2 594 QemuMutex mutex;
8c4598f2 595 /* is this channel thread running */
66770707 596 bool running;
8c4598f2 597 /* should this thread finish */
f986c3d2 598 bool quit;
0beb5ed3
JQ
599 /* thread has work to do */
600 int pending_job;
34c55a94
JQ
601 /* array of pages to sent */
602 MultiFDPages_t *pages;
2a26c979
JQ
603 /* packet allocated len */
604 uint32_t packet_len;
605 /* pointer to the packet */
606 MultiFDPacket_t *packet;
607 /* multifd flags for each packet */
608 uint32_t flags;
609 /* global number of generated multifd packets */
610 uint64_t packet_num;
408ea6ae
JQ
611 /* thread local variables */
612 /* packets sent through this channel */
613 uint64_t num_packets;
614 /* pages sent through this channel */
615 uint64_t num_pages;
6df264ac
JQ
616 /* syncs main thread and channels */
617 QemuSemaphore sem_sync;
8c4598f2
JQ
618} MultiFDSendParams;
619
620typedef struct {
621 /* this fields are not changed once the thread is created */
622 /* channel number */
623 uint8_t id;
624 /* channel thread name */
625 char *name;
626 /* channel thread id */
627 QemuThread thread;
628 /* communication channel */
629 QIOChannel *c;
8c4598f2
JQ
630 /* this mutex protects the following parameters */
631 QemuMutex mutex;
632 /* is this channel thread running */
633 bool running;
34c55a94
JQ
634 /* array of pages to receive */
635 MultiFDPages_t *pages;
2a26c979
JQ
636 /* packet allocated len */
637 uint32_t packet_len;
638 /* pointer to the packet */
639 MultiFDPacket_t *packet;
640 /* multifd flags for each packet */
641 uint32_t flags;
642 /* global number of generated multifd packets */
643 uint64_t packet_num;
408ea6ae
JQ
644 /* thread local variables */
645 /* packets sent through this channel */
646 uint64_t num_packets;
647 /* pages sent through this channel */
648 uint64_t num_pages;
6df264ac
JQ
649 /* syncs main thread and channels */
650 QemuSemaphore sem_sync;
8c4598f2 651} MultiFDRecvParams;
f986c3d2 652
af8b7d2b
JQ
653static int multifd_send_initial_packet(MultiFDSendParams *p, Error **errp)
654{
655 MultiFDInit_t msg;
656 int ret;
657
658 msg.magic = cpu_to_be32(MULTIFD_MAGIC);
659 msg.version = cpu_to_be32(MULTIFD_VERSION);
660 msg.id = p->id;
661 memcpy(msg.uuid, &qemu_uuid.data, sizeof(msg.uuid));
662
663 ret = qio_channel_write_all(p->c, (char *)&msg, sizeof(msg), errp);
664 if (ret != 0) {
665 return -1;
666 }
667 return 0;
668}
669
670static int multifd_recv_initial_packet(QIOChannel *c, Error **errp)
671{
672 MultiFDInit_t msg;
673 int ret;
674
675 ret = qio_channel_read_all(c, (char *)&msg, sizeof(msg), errp);
676 if (ret != 0) {
677 return -1;
678 }
679
341ba0df
PM
680 msg.magic = be32_to_cpu(msg.magic);
681 msg.version = be32_to_cpu(msg.version);
af8b7d2b
JQ
682
683 if (msg.magic != MULTIFD_MAGIC) {
684 error_setg(errp, "multifd: received packet magic %x "
685 "expected %x", msg.magic, MULTIFD_MAGIC);
686 return -1;
687 }
688
689 if (msg.version != MULTIFD_VERSION) {
690 error_setg(errp, "multifd: received packet version %d "
691 "expected %d", msg.version, MULTIFD_VERSION);
692 return -1;
693 }
694
695 if (memcmp(msg.uuid, &qemu_uuid, sizeof(qemu_uuid))) {
696 char *uuid = qemu_uuid_unparse_strdup(&qemu_uuid);
697 char *msg_uuid = qemu_uuid_unparse_strdup((const QemuUUID *)msg.uuid);
698
699 error_setg(errp, "multifd: received uuid '%s' and expected "
700 "uuid '%s' for channel %hhd", msg_uuid, uuid, msg.id);
701 g_free(uuid);
702 g_free(msg_uuid);
703 return -1;
704 }
705
706 if (msg.id > migrate_multifd_channels()) {
707 error_setg(errp, "multifd: received channel version %d "
708 "expected %d", msg.version, MULTIFD_VERSION);
709 return -1;
710 }
711
712 return msg.id;
713}
714
34c55a94
JQ
715static MultiFDPages_t *multifd_pages_init(size_t size)
716{
717 MultiFDPages_t *pages = g_new0(MultiFDPages_t, 1);
718
719 pages->allocated = size;
720 pages->iov = g_new0(struct iovec, size);
721 pages->offset = g_new0(ram_addr_t, size);
722
723 return pages;
724}
725
726static void multifd_pages_clear(MultiFDPages_t *pages)
727{
728 pages->used = 0;
729 pages->allocated = 0;
730 pages->packet_num = 0;
731 pages->block = NULL;
732 g_free(pages->iov);
733 pages->iov = NULL;
734 g_free(pages->offset);
735 pages->offset = NULL;
736 g_free(pages);
737}
738
2a26c979
JQ
739static void multifd_send_fill_packet(MultiFDSendParams *p)
740{
741 MultiFDPacket_t *packet = p->packet;
742 int i;
743
744 packet->magic = cpu_to_be32(MULTIFD_MAGIC);
745 packet->version = cpu_to_be32(MULTIFD_VERSION);
746 packet->flags = cpu_to_be32(p->flags);
747 packet->size = cpu_to_be32(migrate_multifd_page_count());
748 packet->used = cpu_to_be32(p->pages->used);
749 packet->packet_num = cpu_to_be64(p->packet_num);
750
751 if (p->pages->block) {
752 strncpy(packet->ramblock, p->pages->block->idstr, 256);
753 }
754
755 for (i = 0; i < p->pages->used; i++) {
756 packet->offset[i] = cpu_to_be64(p->pages->offset[i]);
757 }
758}
759
760static int multifd_recv_unfill_packet(MultiFDRecvParams *p, Error **errp)
761{
762 MultiFDPacket_t *packet = p->packet;
763 RAMBlock *block;
764 int i;
765
341ba0df 766 packet->magic = be32_to_cpu(packet->magic);
2a26c979
JQ
767 if (packet->magic != MULTIFD_MAGIC) {
768 error_setg(errp, "multifd: received packet "
769 "magic %x and expected magic %x",
770 packet->magic, MULTIFD_MAGIC);
771 return -1;
772 }
773
341ba0df 774 packet->version = be32_to_cpu(packet->version);
2a26c979
JQ
775 if (packet->version != MULTIFD_VERSION) {
776 error_setg(errp, "multifd: received packet "
777 "version %d and expected version %d",
778 packet->version, MULTIFD_VERSION);
779 return -1;
780 }
781
782 p->flags = be32_to_cpu(packet->flags);
783
341ba0df 784 packet->size = be32_to_cpu(packet->size);
2a26c979
JQ
785 if (packet->size > migrate_multifd_page_count()) {
786 error_setg(errp, "multifd: received packet "
787 "with size %d and expected maximum size %d",
788 packet->size, migrate_multifd_page_count()) ;
789 return -1;
790 }
791
792 p->pages->used = be32_to_cpu(packet->used);
793 if (p->pages->used > packet->size) {
794 error_setg(errp, "multifd: received packet "
795 "with size %d and expected maximum size %d",
796 p->pages->used, packet->size) ;
797 return -1;
798 }
799
800 p->packet_num = be64_to_cpu(packet->packet_num);
801
802 if (p->pages->used) {
803 /* make sure that ramblock is 0 terminated */
804 packet->ramblock[255] = 0;
805 block = qemu_ram_block_by_name(packet->ramblock);
806 if (!block) {
807 error_setg(errp, "multifd: unknown ram block %s",
808 packet->ramblock);
809 return -1;
810 }
811 }
812
813 for (i = 0; i < p->pages->used; i++) {
814 ram_addr_t offset = be64_to_cpu(packet->offset[i]);
815
816 if (offset > (block->used_length - TARGET_PAGE_SIZE)) {
817 error_setg(errp, "multifd: offset too long " RAM_ADDR_FMT
818 " (max " RAM_ADDR_FMT ")",
819 offset, block->max_length);
820 return -1;
821 }
822 p->pages->iov[i].iov_base = block->host + offset;
823 p->pages->iov[i].iov_len = TARGET_PAGE_SIZE;
824 }
825
826 return 0;
827}
828
f986c3d2
JQ
829struct {
830 MultiFDSendParams *params;
831 /* number of created threads */
832 int count;
34c55a94
JQ
833 /* array of pages to sent */
834 MultiFDPages_t *pages;
6df264ac
JQ
835 /* syncs main thread and channels */
836 QemuSemaphore sem_sync;
837 /* global number of generated multifd packets */
838 uint64_t packet_num;
b9ee2f7d
JQ
839 /* send channels ready */
840 QemuSemaphore channels_ready;
f986c3d2
JQ
841} *multifd_send_state;
842
b9ee2f7d
JQ
843/*
844 * How we use multifd_send_state->pages and channel->pages?
845 *
846 * We create a pages for each channel, and a main one. Each time that
847 * we need to send a batch of pages we interchange the ones between
848 * multifd_send_state and the channel that is sending it. There are
849 * two reasons for that:
850 * - to not have to do so many mallocs during migration
851 * - to make easier to know what to free at the end of migration
852 *
853 * This way we always know who is the owner of each "pages" struct,
854 * and we don't need any loocking. It belongs to the migration thread
855 * or to the channel thread. Switching is safe because the migration
856 * thread is using the channel mutex when changing it, and the channel
857 * have to had finish with its own, otherwise pending_job can't be
858 * false.
859 */
860
861static void multifd_send_pages(void)
862{
863 int i;
864 static int next_channel;
865 MultiFDSendParams *p = NULL; /* make happy gcc */
866 MultiFDPages_t *pages = multifd_send_state->pages;
867 uint64_t transferred;
868
869 qemu_sem_wait(&multifd_send_state->channels_ready);
870 for (i = next_channel;; i = (i + 1) % migrate_multifd_channels()) {
871 p = &multifd_send_state->params[i];
872
873 qemu_mutex_lock(&p->mutex);
874 if (!p->pending_job) {
875 p->pending_job++;
876 next_channel = (i + 1) % migrate_multifd_channels();
877 break;
878 }
879 qemu_mutex_unlock(&p->mutex);
880 }
881 p->pages->used = 0;
882
883 p->packet_num = multifd_send_state->packet_num++;
884 p->pages->block = NULL;
885 multifd_send_state->pages = p->pages;
886 p->pages = pages;
4fcefd44 887 transferred = ((uint64_t) pages->used) * TARGET_PAGE_SIZE + p->packet_len;
b9ee2f7d
JQ
888 ram_counters.multifd_bytes += transferred;
889 ram_counters.transferred += transferred;;
890 qemu_mutex_unlock(&p->mutex);
891 qemu_sem_post(&p->sem);
892}
893
894static void multifd_queue_page(RAMBlock *block, ram_addr_t offset)
895{
896 MultiFDPages_t *pages = multifd_send_state->pages;
897
898 if (!pages->block) {
899 pages->block = block;
900 }
901
902 if (pages->block == block) {
903 pages->offset[pages->used] = offset;
904 pages->iov[pages->used].iov_base = block->host + offset;
905 pages->iov[pages->used].iov_len = TARGET_PAGE_SIZE;
906 pages->used++;
907
908 if (pages->used < pages->allocated) {
909 return;
910 }
911 }
912
913 multifd_send_pages();
914
915 if (pages->block != block) {
916 multifd_queue_page(block, offset);
917 }
918}
919
66770707 920static void multifd_send_terminate_threads(Error *err)
f986c3d2
JQ
921{
922 int i;
923
7a169d74
JQ
924 if (err) {
925 MigrationState *s = migrate_get_current();
926 migrate_set_error(s, err);
927 if (s->state == MIGRATION_STATUS_SETUP ||
928 s->state == MIGRATION_STATUS_PRE_SWITCHOVER ||
929 s->state == MIGRATION_STATUS_DEVICE ||
930 s->state == MIGRATION_STATUS_ACTIVE) {
931 migrate_set_state(&s->state, s->state,
932 MIGRATION_STATUS_FAILED);
933 }
934 }
935
66770707 936 for (i = 0; i < migrate_multifd_channels(); i++) {
f986c3d2
JQ
937 MultiFDSendParams *p = &multifd_send_state->params[i];
938
939 qemu_mutex_lock(&p->mutex);
940 p->quit = true;
941 qemu_sem_post(&p->sem);
942 qemu_mutex_unlock(&p->mutex);
943 }
944}
945
1398b2e3 946void multifd_save_cleanup(void)
f986c3d2
JQ
947{
948 int i;
f986c3d2
JQ
949
950 if (!migrate_use_multifd()) {
1398b2e3 951 return;
f986c3d2 952 }
66770707
JQ
953 multifd_send_terminate_threads(NULL);
954 for (i = 0; i < migrate_multifd_channels(); i++) {
f986c3d2
JQ
955 MultiFDSendParams *p = &multifd_send_state->params[i];
956
66770707
JQ
957 if (p->running) {
958 qemu_thread_join(&p->thread);
959 }
60df2d4a
JQ
960 socket_send_channel_destroy(p->c);
961 p->c = NULL;
f986c3d2
JQ
962 qemu_mutex_destroy(&p->mutex);
963 qemu_sem_destroy(&p->sem);
6df264ac 964 qemu_sem_destroy(&p->sem_sync);
f986c3d2
JQ
965 g_free(p->name);
966 p->name = NULL;
34c55a94
JQ
967 multifd_pages_clear(p->pages);
968 p->pages = NULL;
2a26c979
JQ
969 p->packet_len = 0;
970 g_free(p->packet);
971 p->packet = NULL;
f986c3d2 972 }
b9ee2f7d 973 qemu_sem_destroy(&multifd_send_state->channels_ready);
6df264ac 974 qemu_sem_destroy(&multifd_send_state->sem_sync);
f986c3d2
JQ
975 g_free(multifd_send_state->params);
976 multifd_send_state->params = NULL;
34c55a94
JQ
977 multifd_pages_clear(multifd_send_state->pages);
978 multifd_send_state->pages = NULL;
f986c3d2
JQ
979 g_free(multifd_send_state);
980 multifd_send_state = NULL;
f986c3d2
JQ
981}
982
6df264ac
JQ
983static void multifd_send_sync_main(void)
984{
985 int i;
986
987 if (!migrate_use_multifd()) {
988 return;
989 }
b9ee2f7d
JQ
990 if (multifd_send_state->pages->used) {
991 multifd_send_pages();
992 }
6df264ac
JQ
993 for (i = 0; i < migrate_multifd_channels(); i++) {
994 MultiFDSendParams *p = &multifd_send_state->params[i];
995
996 trace_multifd_send_sync_main_signal(p->id);
997
998 qemu_mutex_lock(&p->mutex);
b9ee2f7d
JQ
999
1000 p->packet_num = multifd_send_state->packet_num++;
6df264ac
JQ
1001 p->flags |= MULTIFD_FLAG_SYNC;
1002 p->pending_job++;
1003 qemu_mutex_unlock(&p->mutex);
1004 qemu_sem_post(&p->sem);
1005 }
1006 for (i = 0; i < migrate_multifd_channels(); i++) {
1007 MultiFDSendParams *p = &multifd_send_state->params[i];
1008
1009 trace_multifd_send_sync_main_wait(p->id);
1010 qemu_sem_wait(&multifd_send_state->sem_sync);
1011 }
1012 trace_multifd_send_sync_main(multifd_send_state->packet_num);
1013}
1014
f986c3d2
JQ
1015static void *multifd_send_thread(void *opaque)
1016{
1017 MultiFDSendParams *p = opaque;
af8b7d2b 1018 Error *local_err = NULL;
8b2db7f5 1019 int ret;
af8b7d2b 1020
408ea6ae 1021 trace_multifd_send_thread_start(p->id);
74637e6f 1022 rcu_register_thread();
408ea6ae 1023
af8b7d2b
JQ
1024 if (multifd_send_initial_packet(p, &local_err) < 0) {
1025 goto out;
1026 }
408ea6ae
JQ
1027 /* initial packet */
1028 p->num_packets = 1;
f986c3d2
JQ
1029
1030 while (true) {
d82628e4 1031 qemu_sem_wait(&p->sem);
f986c3d2 1032 qemu_mutex_lock(&p->mutex);
0beb5ed3
JQ
1033
1034 if (p->pending_job) {
1035 uint32_t used = p->pages->used;
1036 uint64_t packet_num = p->packet_num;
1037 uint32_t flags = p->flags;
1038
1039 multifd_send_fill_packet(p);
1040 p->flags = 0;
1041 p->num_packets++;
1042 p->num_pages += used;
1043 p->pages->used = 0;
1044 qemu_mutex_unlock(&p->mutex);
1045
1046 trace_multifd_send(p->id, packet_num, used, flags);
1047
8b2db7f5
JQ
1048 ret = qio_channel_write_all(p->c, (void *)p->packet,
1049 p->packet_len, &local_err);
1050 if (ret != 0) {
1051 break;
1052 }
1053
1054 ret = qio_channel_writev_all(p->c, p->pages->iov, used, &local_err);
1055 if (ret != 0) {
1056 break;
1057 }
0beb5ed3
JQ
1058
1059 qemu_mutex_lock(&p->mutex);
1060 p->pending_job--;
1061 qemu_mutex_unlock(&p->mutex);
6df264ac
JQ
1062
1063 if (flags & MULTIFD_FLAG_SYNC) {
1064 qemu_sem_post(&multifd_send_state->sem_sync);
1065 }
b9ee2f7d 1066 qemu_sem_post(&multifd_send_state->channels_ready);
0beb5ed3 1067 } else if (p->quit) {
f986c3d2
JQ
1068 qemu_mutex_unlock(&p->mutex);
1069 break;
6df264ac
JQ
1070 } else {
1071 qemu_mutex_unlock(&p->mutex);
1072 /* sometimes there are spurious wakeups */
f986c3d2 1073 }
f986c3d2
JQ
1074 }
1075
af8b7d2b
JQ
1076out:
1077 if (local_err) {
1078 multifd_send_terminate_threads(local_err);
1079 }
1080
66770707
JQ
1081 qemu_mutex_lock(&p->mutex);
1082 p->running = false;
1083 qemu_mutex_unlock(&p->mutex);
1084
74637e6f 1085 rcu_unregister_thread();
408ea6ae
JQ
1086 trace_multifd_send_thread_end(p->id, p->num_packets, p->num_pages);
1087
f986c3d2
JQ
1088 return NULL;
1089}
1090
60df2d4a
JQ
1091static void multifd_new_send_channel_async(QIOTask *task, gpointer opaque)
1092{
1093 MultiFDSendParams *p = opaque;
1094 QIOChannel *sioc = QIO_CHANNEL(qio_task_get_source(task));
1095 Error *local_err = NULL;
1096
1097 if (qio_task_propagate_error(task, &local_err)) {
1398b2e3
FL
1098 migrate_set_error(migrate_get_current(), local_err);
1099 multifd_save_cleanup();
60df2d4a
JQ
1100 } else {
1101 p->c = QIO_CHANNEL(sioc);
1102 qio_channel_set_delay(p->c, false);
1103 p->running = true;
1104 qemu_thread_create(&p->thread, p->name, multifd_send_thread, p,
1105 QEMU_THREAD_JOINABLE);
1106
1107 atomic_inc(&multifd_send_state->count);
1108 }
1109}
1110
f986c3d2
JQ
1111int multifd_save_setup(void)
1112{
1113 int thread_count;
34c55a94 1114 uint32_t page_count = migrate_multifd_page_count();
f986c3d2
JQ
1115 uint8_t i;
1116
1117 if (!migrate_use_multifd()) {
1118 return 0;
1119 }
1120 thread_count = migrate_multifd_channels();
1121 multifd_send_state = g_malloc0(sizeof(*multifd_send_state));
1122 multifd_send_state->params = g_new0(MultiFDSendParams, thread_count);
66770707 1123 atomic_set(&multifd_send_state->count, 0);
34c55a94 1124 multifd_send_state->pages = multifd_pages_init(page_count);
6df264ac 1125 qemu_sem_init(&multifd_send_state->sem_sync, 0);
b9ee2f7d 1126 qemu_sem_init(&multifd_send_state->channels_ready, 0);
34c55a94 1127
f986c3d2
JQ
1128 for (i = 0; i < thread_count; i++) {
1129 MultiFDSendParams *p = &multifd_send_state->params[i];
1130
1131 qemu_mutex_init(&p->mutex);
1132 qemu_sem_init(&p->sem, 0);
6df264ac 1133 qemu_sem_init(&p->sem_sync, 0);
f986c3d2 1134 p->quit = false;
0beb5ed3 1135 p->pending_job = 0;
f986c3d2 1136 p->id = i;
34c55a94 1137 p->pages = multifd_pages_init(page_count);
2a26c979
JQ
1138 p->packet_len = sizeof(MultiFDPacket_t)
1139 + sizeof(ram_addr_t) * page_count;
1140 p->packet = g_malloc0(p->packet_len);
f986c3d2 1141 p->name = g_strdup_printf("multifdsend_%d", i);
60df2d4a 1142 socket_send_channel_create(multifd_new_send_channel_async, p);
f986c3d2
JQ
1143 }
1144 return 0;
1145}
1146
f986c3d2
JQ
1147struct {
1148 MultiFDRecvParams *params;
1149 /* number of created threads */
1150 int count;
6df264ac
JQ
1151 /* syncs main thread and channels */
1152 QemuSemaphore sem_sync;
1153 /* global number of generated multifd packets */
1154 uint64_t packet_num;
f986c3d2
JQ
1155} *multifd_recv_state;
1156
66770707 1157static void multifd_recv_terminate_threads(Error *err)
f986c3d2
JQ
1158{
1159 int i;
1160
7a169d74
JQ
1161 if (err) {
1162 MigrationState *s = migrate_get_current();
1163 migrate_set_error(s, err);
1164 if (s->state == MIGRATION_STATUS_SETUP ||
1165 s->state == MIGRATION_STATUS_ACTIVE) {
1166 migrate_set_state(&s->state, s->state,
1167 MIGRATION_STATUS_FAILED);
1168 }
1169 }
1170
66770707 1171 for (i = 0; i < migrate_multifd_channels(); i++) {
f986c3d2
JQ
1172 MultiFDRecvParams *p = &multifd_recv_state->params[i];
1173
1174 qemu_mutex_lock(&p->mutex);
7a5cc33c
JQ
1175 /* We could arrive here for two reasons:
1176 - normal quit, i.e. everything went fine, just finished
1177 - error quit: We close the channels so the channel threads
1178 finish the qio_channel_read_all_eof() */
1179 qio_channel_shutdown(p->c, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
f986c3d2
JQ
1180 qemu_mutex_unlock(&p->mutex);
1181 }
1182}
1183
1184int multifd_load_cleanup(Error **errp)
1185{
1186 int i;
1187 int ret = 0;
1188
1189 if (!migrate_use_multifd()) {
1190 return 0;
1191 }
66770707
JQ
1192 multifd_recv_terminate_threads(NULL);
1193 for (i = 0; i < migrate_multifd_channels(); i++) {
f986c3d2
JQ
1194 MultiFDRecvParams *p = &multifd_recv_state->params[i];
1195
66770707
JQ
1196 if (p->running) {
1197 qemu_thread_join(&p->thread);
1198 }
60df2d4a
JQ
1199 object_unref(OBJECT(p->c));
1200 p->c = NULL;
f986c3d2 1201 qemu_mutex_destroy(&p->mutex);
6df264ac 1202 qemu_sem_destroy(&p->sem_sync);
f986c3d2
JQ
1203 g_free(p->name);
1204 p->name = NULL;
34c55a94
JQ
1205 multifd_pages_clear(p->pages);
1206 p->pages = NULL;
2a26c979
JQ
1207 p->packet_len = 0;
1208 g_free(p->packet);
1209 p->packet = NULL;
f986c3d2 1210 }
6df264ac 1211 qemu_sem_destroy(&multifd_recv_state->sem_sync);
f986c3d2
JQ
1212 g_free(multifd_recv_state->params);
1213 multifd_recv_state->params = NULL;
1214 g_free(multifd_recv_state);
1215 multifd_recv_state = NULL;
1216
1217 return ret;
1218}
1219
6df264ac
JQ
1220static void multifd_recv_sync_main(void)
1221{
1222 int i;
1223
1224 if (!migrate_use_multifd()) {
1225 return;
1226 }
1227 for (i = 0; i < migrate_multifd_channels(); i++) {
1228 MultiFDRecvParams *p = &multifd_recv_state->params[i];
1229
6df264ac
JQ
1230 trace_multifd_recv_sync_main_wait(p->id);
1231 qemu_sem_wait(&multifd_recv_state->sem_sync);
1232 qemu_mutex_lock(&p->mutex);
1233 if (multifd_recv_state->packet_num < p->packet_num) {
1234 multifd_recv_state->packet_num = p->packet_num;
1235 }
1236 qemu_mutex_unlock(&p->mutex);
1237 }
1238 for (i = 0; i < migrate_multifd_channels(); i++) {
1239 MultiFDRecvParams *p = &multifd_recv_state->params[i];
1240
1241 trace_multifd_recv_sync_main_signal(p->id);
6df264ac
JQ
1242 qemu_sem_post(&p->sem_sync);
1243 }
1244 trace_multifd_recv_sync_main(multifd_recv_state->packet_num);
1245}
1246
f986c3d2
JQ
1247static void *multifd_recv_thread(void *opaque)
1248{
1249 MultiFDRecvParams *p = opaque;
2a26c979
JQ
1250 Error *local_err = NULL;
1251 int ret;
f986c3d2 1252
408ea6ae 1253 trace_multifd_recv_thread_start(p->id);
74637e6f 1254 rcu_register_thread();
408ea6ae 1255
f986c3d2 1256 while (true) {
6df264ac
JQ
1257 uint32_t used;
1258 uint32_t flags;
0beb5ed3 1259
8b2db7f5
JQ
1260 ret = qio_channel_read_all_eof(p->c, (void *)p->packet,
1261 p->packet_len, &local_err);
1262 if (ret == 0) { /* EOF */
1263 break;
1264 }
1265 if (ret == -1) { /* Error */
1266 break;
1267 }
2a26c979 1268
6df264ac
JQ
1269 qemu_mutex_lock(&p->mutex);
1270 ret = multifd_recv_unfill_packet(p, &local_err);
1271 if (ret) {
f986c3d2
JQ
1272 qemu_mutex_unlock(&p->mutex);
1273 break;
1274 }
6df264ac
JQ
1275
1276 used = p->pages->used;
1277 flags = p->flags;
1278 trace_multifd_recv(p->id, p->packet_num, used, flags);
6df264ac
JQ
1279 p->num_packets++;
1280 p->num_pages += used;
f986c3d2 1281 qemu_mutex_unlock(&p->mutex);
6df264ac 1282
8b2db7f5
JQ
1283 ret = qio_channel_readv_all(p->c, p->pages->iov, used, &local_err);
1284 if (ret != 0) {
1285 break;
1286 }
1287
6df264ac
JQ
1288 if (flags & MULTIFD_FLAG_SYNC) {
1289 qemu_sem_post(&multifd_recv_state->sem_sync);
1290 qemu_sem_wait(&p->sem_sync);
1291 }
f986c3d2
JQ
1292 }
1293
d82628e4
JQ
1294 if (local_err) {
1295 multifd_recv_terminate_threads(local_err);
1296 }
66770707
JQ
1297 qemu_mutex_lock(&p->mutex);
1298 p->running = false;
1299 qemu_mutex_unlock(&p->mutex);
1300
74637e6f 1301 rcu_unregister_thread();
408ea6ae
JQ
1302 trace_multifd_recv_thread_end(p->id, p->num_packets, p->num_pages);
1303
f986c3d2
JQ
1304 return NULL;
1305}
1306
1307int multifd_load_setup(void)
1308{
1309 int thread_count;
34c55a94 1310 uint32_t page_count = migrate_multifd_page_count();
f986c3d2
JQ
1311 uint8_t i;
1312
1313 if (!migrate_use_multifd()) {
1314 return 0;
1315 }
1316 thread_count = migrate_multifd_channels();
1317 multifd_recv_state = g_malloc0(sizeof(*multifd_recv_state));
1318 multifd_recv_state->params = g_new0(MultiFDRecvParams, thread_count);
66770707 1319 atomic_set(&multifd_recv_state->count, 0);
6df264ac 1320 qemu_sem_init(&multifd_recv_state->sem_sync, 0);
34c55a94 1321
f986c3d2
JQ
1322 for (i = 0; i < thread_count; i++) {
1323 MultiFDRecvParams *p = &multifd_recv_state->params[i];
1324
1325 qemu_mutex_init(&p->mutex);
6df264ac 1326 qemu_sem_init(&p->sem_sync, 0);
f986c3d2 1327 p->id = i;
34c55a94 1328 p->pages = multifd_pages_init(page_count);
2a26c979
JQ
1329 p->packet_len = sizeof(MultiFDPacket_t)
1330 + sizeof(ram_addr_t) * page_count;
1331 p->packet = g_malloc0(p->packet_len);
f986c3d2 1332 p->name = g_strdup_printf("multifdrecv_%d", i);
f986c3d2
JQ
1333 }
1334 return 0;
1335}
1336
62c1e0ca
JQ
1337bool multifd_recv_all_channels_created(void)
1338{
1339 int thread_count = migrate_multifd_channels();
1340
1341 if (!migrate_use_multifd()) {
1342 return true;
1343 }
1344
1345 return thread_count == atomic_read(&multifd_recv_state->count);
1346}
1347
49ed0d24
FL
1348/*
1349 * Try to receive all multifd channels to get ready for the migration.
1350 * - Return true and do not set @errp when correctly receving all channels;
1351 * - Return false and do not set @errp when correctly receiving the current one;
1352 * - Return false and set @errp when failing to receive the current channel.
1353 */
1354bool multifd_recv_new_channel(QIOChannel *ioc, Error **errp)
71bb07db 1355{
60df2d4a 1356 MultiFDRecvParams *p;
af8b7d2b
JQ
1357 Error *local_err = NULL;
1358 int id;
60df2d4a 1359
af8b7d2b
JQ
1360 id = multifd_recv_initial_packet(ioc, &local_err);
1361 if (id < 0) {
1362 multifd_recv_terminate_threads(local_err);
49ed0d24
FL
1363 error_propagate_prepend(errp, local_err,
1364 "failed to receive packet"
1365 " via multifd channel %d: ",
1366 atomic_read(&multifd_recv_state->count));
81e62053 1367 return false;
af8b7d2b
JQ
1368 }
1369
1370 p = &multifd_recv_state->params[id];
1371 if (p->c != NULL) {
1372 error_setg(&local_err, "multifd: received id '%d' already setup'",
1373 id);
1374 multifd_recv_terminate_threads(local_err);
49ed0d24 1375 error_propagate(errp, local_err);
81e62053 1376 return false;
af8b7d2b 1377 }
60df2d4a
JQ
1378 p->c = ioc;
1379 object_ref(OBJECT(ioc));
408ea6ae
JQ
1380 /* initial packet */
1381 p->num_packets = 1;
60df2d4a
JQ
1382
1383 p->running = true;
1384 qemu_thread_create(&p->thread, p->name, multifd_recv_thread, p,
1385 QEMU_THREAD_JOINABLE);
1386 atomic_inc(&multifd_recv_state->count);
49ed0d24
FL
1387 return atomic_read(&multifd_recv_state->count) ==
1388 migrate_multifd_channels();
71bb07db
JQ
1389}
1390
56e93d26 1391/**
3d0684b2 1392 * save_page_header: write page header to wire
56e93d26
JQ
1393 *
1394 * If this is the 1st block, it also writes the block identification
1395 *
3d0684b2 1396 * Returns the number of bytes written
56e93d26
JQ
1397 *
1398 * @f: QEMUFile where to send the data
1399 * @block: block that contains the page we want to send
1400 * @offset: offset inside the block for the page
1401 * in the lower bits, it contains flags
1402 */
2bf3aa85
JQ
1403static size_t save_page_header(RAMState *rs, QEMUFile *f, RAMBlock *block,
1404 ram_addr_t offset)
56e93d26 1405{
9f5f380b 1406 size_t size, len;
56e93d26 1407
24795694
JQ
1408 if (block == rs->last_sent_block) {
1409 offset |= RAM_SAVE_FLAG_CONTINUE;
1410 }
2bf3aa85 1411 qemu_put_be64(f, offset);
56e93d26
JQ
1412 size = 8;
1413
1414 if (!(offset & RAM_SAVE_FLAG_CONTINUE)) {
9f5f380b 1415 len = strlen(block->idstr);
2bf3aa85
JQ
1416 qemu_put_byte(f, len);
1417 qemu_put_buffer(f, (uint8_t *)block->idstr, len);
9f5f380b 1418 size += 1 + len;
24795694 1419 rs->last_sent_block = block;
56e93d26
JQ
1420 }
1421 return size;
1422}
1423
3d0684b2
JQ
1424/**
1425 * mig_throttle_guest_down: throotle down the guest
1426 *
1427 * Reduce amount of guest cpu execution to hopefully slow down memory
1428 * writes. If guest dirty memory rate is reduced below the rate at
1429 * which we can transfer pages to the destination then we should be
1430 * able to complete migration. Some workloads dirty memory way too
1431 * fast and will not effectively converge, even with auto-converge.
070afca2
JH
1432 */
1433static void mig_throttle_guest_down(void)
1434{
1435 MigrationState *s = migrate_get_current();
2594f56d
DB
1436 uint64_t pct_initial = s->parameters.cpu_throttle_initial;
1437 uint64_t pct_icrement = s->parameters.cpu_throttle_increment;
4cbc9c7f 1438 int pct_max = s->parameters.max_cpu_throttle;
070afca2
JH
1439
1440 /* We have not started throttling yet. Let's start it. */
1441 if (!cpu_throttle_active()) {
1442 cpu_throttle_set(pct_initial);
1443 } else {
1444 /* Throttling already on, just increase the rate */
4cbc9c7f
LQ
1445 cpu_throttle_set(MIN(cpu_throttle_get_percentage() + pct_icrement,
1446 pct_max));
070afca2
JH
1447 }
1448}
1449
3d0684b2
JQ
1450/**
1451 * xbzrle_cache_zero_page: insert a zero page in the XBZRLE cache
1452 *
6f37bb8b 1453 * @rs: current RAM state
3d0684b2
JQ
1454 * @current_addr: address for the zero page
1455 *
1456 * Update the xbzrle cache to reflect a page that's been sent as all 0.
56e93d26
JQ
1457 * The important thing is that a stale (not-yet-0'd) page be replaced
1458 * by the new data.
1459 * As a bonus, if the page wasn't in the cache it gets added so that
3d0684b2 1460 * when a small write is made into the 0'd page it gets XBZRLE sent.
56e93d26 1461 */
6f37bb8b 1462static void xbzrle_cache_zero_page(RAMState *rs, ram_addr_t current_addr)
56e93d26 1463{
6f37bb8b 1464 if (rs->ram_bulk_stage || !migrate_use_xbzrle()) {
56e93d26
JQ
1465 return;
1466 }
1467
1468 /* We don't care if this fails to allocate a new cache page
1469 * as long as it updated an old one */
c00e0928 1470 cache_insert(XBZRLE.cache, current_addr, XBZRLE.zero_target_page,
9360447d 1471 ram_counters.dirty_sync_count);
56e93d26
JQ
1472}
1473
1474#define ENCODING_FLAG_XBZRLE 0x1
1475
1476/**
1477 * save_xbzrle_page: compress and send current page
1478 *
1479 * Returns: 1 means that we wrote the page
1480 * 0 means that page is identical to the one already sent
1481 * -1 means that xbzrle would be longer than normal
1482 *
5a987738 1483 * @rs: current RAM state
3d0684b2
JQ
1484 * @current_data: pointer to the address of the page contents
1485 * @current_addr: addr of the page
56e93d26
JQ
1486 * @block: block that contains the page we want to send
1487 * @offset: offset inside the block for the page
1488 * @last_stage: if we are at the completion stage
56e93d26 1489 */
204b88b8 1490static int save_xbzrle_page(RAMState *rs, uint8_t **current_data,
56e93d26 1491 ram_addr_t current_addr, RAMBlock *block,
072c2511 1492 ram_addr_t offset, bool last_stage)
56e93d26
JQ
1493{
1494 int encoded_len = 0, bytes_xbzrle;
1495 uint8_t *prev_cached_page;
1496
9360447d
JQ
1497 if (!cache_is_cached(XBZRLE.cache, current_addr,
1498 ram_counters.dirty_sync_count)) {
1499 xbzrle_counters.cache_miss++;
56e93d26
JQ
1500 if (!last_stage) {
1501 if (cache_insert(XBZRLE.cache, current_addr, *current_data,
9360447d 1502 ram_counters.dirty_sync_count) == -1) {
56e93d26
JQ
1503 return -1;
1504 } else {
1505 /* update *current_data when the page has been
1506 inserted into cache */
1507 *current_data = get_cached_data(XBZRLE.cache, current_addr);
1508 }
1509 }
1510 return -1;
1511 }
1512
1513 prev_cached_page = get_cached_data(XBZRLE.cache, current_addr);
1514
1515 /* save current buffer into memory */
1516 memcpy(XBZRLE.current_buf, *current_data, TARGET_PAGE_SIZE);
1517
1518 /* XBZRLE encoding (if there is no overflow) */
1519 encoded_len = xbzrle_encode_buffer(prev_cached_page, XBZRLE.current_buf,
1520 TARGET_PAGE_SIZE, XBZRLE.encoded_buf,
1521 TARGET_PAGE_SIZE);
1522 if (encoded_len == 0) {
55c4446b 1523 trace_save_xbzrle_page_skipping();
56e93d26
JQ
1524 return 0;
1525 } else if (encoded_len == -1) {
55c4446b 1526 trace_save_xbzrle_page_overflow();
9360447d 1527 xbzrle_counters.overflow++;
56e93d26
JQ
1528 /* update data in the cache */
1529 if (!last_stage) {
1530 memcpy(prev_cached_page, *current_data, TARGET_PAGE_SIZE);
1531 *current_data = prev_cached_page;
1532 }
1533 return -1;
1534 }
1535
1536 /* we need to update the data in the cache, in order to get the same data */
1537 if (!last_stage) {
1538 memcpy(prev_cached_page, XBZRLE.current_buf, TARGET_PAGE_SIZE);
1539 }
1540
1541 /* Send XBZRLE based compressed page */
2bf3aa85 1542 bytes_xbzrle = save_page_header(rs, rs->f, block,
204b88b8
JQ
1543 offset | RAM_SAVE_FLAG_XBZRLE);
1544 qemu_put_byte(rs->f, ENCODING_FLAG_XBZRLE);
1545 qemu_put_be16(rs->f, encoded_len);
1546 qemu_put_buffer(rs->f, XBZRLE.encoded_buf, encoded_len);
56e93d26 1547 bytes_xbzrle += encoded_len + 1 + 2;
9360447d
JQ
1548 xbzrle_counters.pages++;
1549 xbzrle_counters.bytes += bytes_xbzrle;
1550 ram_counters.transferred += bytes_xbzrle;
56e93d26
JQ
1551
1552 return 1;
1553}
1554
3d0684b2
JQ
1555/**
1556 * migration_bitmap_find_dirty: find the next dirty page from start
f3f491fc 1557 *
3d0684b2
JQ
1558 * Called with rcu_read_lock() to protect migration_bitmap
1559 *
1560 * Returns the byte offset within memory region of the start of a dirty page
1561 *
6f37bb8b 1562 * @rs: current RAM state
3d0684b2 1563 * @rb: RAMBlock where to search for dirty pages
a935e30f 1564 * @start: page where we start the search
f3f491fc 1565 */
56e93d26 1566static inline
a935e30f 1567unsigned long migration_bitmap_find_dirty(RAMState *rs, RAMBlock *rb,
f20e2865 1568 unsigned long start)
56e93d26 1569{
6b6712ef
JQ
1570 unsigned long size = rb->used_length >> TARGET_PAGE_BITS;
1571 unsigned long *bitmap = rb->bmap;
56e93d26
JQ
1572 unsigned long next;
1573
fbd162e6 1574 if (ramblock_is_ignored(rb)) {
b895de50
CLG
1575 return size;
1576 }
1577
6b6712ef
JQ
1578 if (rs->ram_bulk_stage && start > 0) {
1579 next = start + 1;
56e93d26 1580 } else {
6b6712ef 1581 next = find_next_bit(bitmap, size, start);
56e93d26
JQ
1582 }
1583
6b6712ef 1584 return next;
56e93d26
JQ
1585}
1586
06b10688 1587static inline bool migration_bitmap_clear_dirty(RAMState *rs,
f20e2865
JQ
1588 RAMBlock *rb,
1589 unsigned long page)
a82d593b
DDAG
1590{
1591 bool ret;
a82d593b 1592
6b6712ef 1593 ret = test_and_clear_bit(page, rb->bmap);
a82d593b
DDAG
1594
1595 if (ret) {
0d8ec885 1596 rs->migration_dirty_pages--;
a82d593b
DDAG
1597 }
1598 return ret;
1599}
1600
15440dd5
JQ
1601static void migration_bitmap_sync_range(RAMState *rs, RAMBlock *rb,
1602 ram_addr_t start, ram_addr_t length)
56e93d26 1603{
0d8ec885 1604 rs->migration_dirty_pages +=
6b6712ef 1605 cpu_physical_memory_sync_dirty_bitmap(rb, start, length,
0d8ec885 1606 &rs->num_dirty_pages_period);
56e93d26
JQ
1607}
1608
3d0684b2
JQ
1609/**
1610 * ram_pagesize_summary: calculate all the pagesizes of a VM
1611 *
1612 * Returns a summary bitmap of the page sizes of all RAMBlocks
1613 *
1614 * For VMs with just normal pages this is equivalent to the host page
1615 * size. If it's got some huge pages then it's the OR of all the
1616 * different page sizes.
e8ca1db2
DDAG
1617 */
1618uint64_t ram_pagesize_summary(void)
1619{
1620 RAMBlock *block;
1621 uint64_t summary = 0;
1622
fbd162e6 1623 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
e8ca1db2
DDAG
1624 summary |= block->page_size;
1625 }
1626
1627 return summary;
1628}
1629
aecbfe9c
XG
1630uint64_t ram_get_total_transferred_pages(void)
1631{
1632 return ram_counters.normal + ram_counters.duplicate +
1633 compression_counters.pages + xbzrle_counters.pages;
1634}
1635
b734035b
XG
1636static void migration_update_rates(RAMState *rs, int64_t end_time)
1637{
be8b02ed 1638 uint64_t page_count = rs->target_page_count - rs->target_page_count_prev;
76e03000 1639 double compressed_size;
b734035b
XG
1640
1641 /* calculate period counters */
1642 ram_counters.dirty_pages_rate = rs->num_dirty_pages_period * 1000
1643 / (end_time - rs->time_last_bitmap_sync);
1644
be8b02ed 1645 if (!page_count) {
b734035b
XG
1646 return;
1647 }
1648
1649 if (migrate_use_xbzrle()) {
1650 xbzrle_counters.cache_miss_rate = (double)(xbzrle_counters.cache_miss -
be8b02ed 1651 rs->xbzrle_cache_miss_prev) / page_count;
b734035b
XG
1652 rs->xbzrle_cache_miss_prev = xbzrle_counters.cache_miss;
1653 }
76e03000
XG
1654
1655 if (migrate_use_compression()) {
1656 compression_counters.busy_rate = (double)(compression_counters.busy -
1657 rs->compress_thread_busy_prev) / page_count;
1658 rs->compress_thread_busy_prev = compression_counters.busy;
1659
1660 compressed_size = compression_counters.compressed_size -
1661 rs->compressed_size_prev;
1662 if (compressed_size) {
1663 double uncompressed_size = (compression_counters.pages -
1664 rs->compress_pages_prev) * TARGET_PAGE_SIZE;
1665
1666 /* Compression-Ratio = Uncompressed-size / Compressed-size */
1667 compression_counters.compression_rate =
1668 uncompressed_size / compressed_size;
1669
1670 rs->compress_pages_prev = compression_counters.pages;
1671 rs->compressed_size_prev = compression_counters.compressed_size;
1672 }
1673 }
b734035b
XG
1674}
1675
8d820d6f 1676static void migration_bitmap_sync(RAMState *rs)
56e93d26
JQ
1677{
1678 RAMBlock *block;
56e93d26 1679 int64_t end_time;
c4bdf0cf 1680 uint64_t bytes_xfer_now;
56e93d26 1681
9360447d 1682 ram_counters.dirty_sync_count++;
56e93d26 1683
f664da80
JQ
1684 if (!rs->time_last_bitmap_sync) {
1685 rs->time_last_bitmap_sync = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
56e93d26
JQ
1686 }
1687
1688 trace_migration_bitmap_sync_start();
9c1f8f44 1689 memory_global_dirty_log_sync();
56e93d26 1690
108cfae0 1691 qemu_mutex_lock(&rs->bitmap_mutex);
56e93d26 1692 rcu_read_lock();
fbd162e6 1693 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
15440dd5 1694 migration_bitmap_sync_range(rs, block, 0, block->used_length);
56e93d26 1695 }
650af890 1696 ram_counters.remaining = ram_bytes_remaining();
56e93d26 1697 rcu_read_unlock();
108cfae0 1698 qemu_mutex_unlock(&rs->bitmap_mutex);
56e93d26 1699
a66cd90c 1700 trace_migration_bitmap_sync_end(rs->num_dirty_pages_period);
1ffb5dfd 1701
56e93d26
JQ
1702 end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1703
1704 /* more than 1 second = 1000 millisecons */
f664da80 1705 if (end_time > rs->time_last_bitmap_sync + 1000) {
9360447d 1706 bytes_xfer_now = ram_counters.transferred;
d693c6f1 1707
9ac78b61
PL
1708 /* During block migration the auto-converge logic incorrectly detects
1709 * that ram migration makes no progress. Avoid this by disabling the
1710 * throttling logic during the bulk phase of block migration. */
1711 if (migrate_auto_converge() && !blk_mig_bulk_active()) {
56e93d26
JQ
1712 /* The following detection logic can be refined later. For now:
1713 Check to see if the dirtied bytes is 50% more than the approx.
1714 amount of bytes that just got transferred since the last time we
070afca2
JH
1715 were in this routine. If that happens twice, start or increase
1716 throttling */
070afca2 1717
d693c6f1 1718 if ((rs->num_dirty_pages_period * TARGET_PAGE_SIZE >
eac74159 1719 (bytes_xfer_now - rs->bytes_xfer_prev) / 2) &&
b4a3c64b 1720 (++rs->dirty_rate_high_cnt >= 2)) {
56e93d26 1721 trace_migration_throttle();
8d820d6f 1722 rs->dirty_rate_high_cnt = 0;
070afca2 1723 mig_throttle_guest_down();
d693c6f1 1724 }
56e93d26 1725 }
070afca2 1726
b734035b
XG
1727 migration_update_rates(rs, end_time);
1728
be8b02ed 1729 rs->target_page_count_prev = rs->target_page_count;
d693c6f1
FF
1730
1731 /* reset period counters */
f664da80 1732 rs->time_last_bitmap_sync = end_time;
a66cd90c 1733 rs->num_dirty_pages_period = 0;
d2a4d85a 1734 rs->bytes_xfer_prev = bytes_xfer_now;
56e93d26 1735 }
4addcd4f 1736 if (migrate_use_events()) {
3ab72385 1737 qapi_event_send_migration_pass(ram_counters.dirty_sync_count);
4addcd4f 1738 }
56e93d26
JQ
1739}
1740
6c97ec5f
XG
1741/**
1742 * save_zero_page_to_file: send the zero page to the file
1743 *
1744 * Returns the size of data written to the file, 0 means the page is not
1745 * a zero page
1746 *
1747 * @rs: current RAM state
1748 * @file: the file where the data is saved
1749 * @block: block that contains the page we want to send
1750 * @offset: offset inside the block for the page
1751 */
1752static int save_zero_page_to_file(RAMState *rs, QEMUFile *file,
1753 RAMBlock *block, ram_addr_t offset)
1754{
1755 uint8_t *p = block->host + offset;
1756 int len = 0;
1757
1758 if (is_zero_range(p, TARGET_PAGE_SIZE)) {
1759 len += save_page_header(rs, file, block, offset | RAM_SAVE_FLAG_ZERO);
1760 qemu_put_byte(file, 0);
1761 len += 1;
1762 }
1763 return len;
1764}
1765
56e93d26 1766/**
3d0684b2 1767 * save_zero_page: send the zero page to the stream
56e93d26 1768 *
3d0684b2 1769 * Returns the number of pages written.
56e93d26 1770 *
f7ccd61b 1771 * @rs: current RAM state
56e93d26
JQ
1772 * @block: block that contains the page we want to send
1773 * @offset: offset inside the block for the page
56e93d26 1774 */
7faccdc3 1775static int save_zero_page(RAMState *rs, RAMBlock *block, ram_addr_t offset)
56e93d26 1776{
6c97ec5f 1777 int len = save_zero_page_to_file(rs, rs->f, block, offset);
56e93d26 1778
6c97ec5f 1779 if (len) {
9360447d 1780 ram_counters.duplicate++;
6c97ec5f
XG
1781 ram_counters.transferred += len;
1782 return 1;
56e93d26 1783 }
6c97ec5f 1784 return -1;
56e93d26
JQ
1785}
1786
5727309d 1787static void ram_release_pages(const char *rbname, uint64_t offset, int pages)
53f09a10 1788{
5727309d 1789 if (!migrate_release_ram() || !migration_in_postcopy()) {
53f09a10
PB
1790 return;
1791 }
1792
aaa2064c 1793 ram_discard_range(rbname, offset, pages << TARGET_PAGE_BITS);
53f09a10
PB
1794}
1795
059ff0fb
XG
1796/*
1797 * @pages: the number of pages written by the control path,
1798 * < 0 - error
1799 * > 0 - number of pages written
1800 *
1801 * Return true if the pages has been saved, otherwise false is returned.
1802 */
1803static bool control_save_page(RAMState *rs, RAMBlock *block, ram_addr_t offset,
1804 int *pages)
1805{
1806 uint64_t bytes_xmit = 0;
1807 int ret;
1808
1809 *pages = -1;
1810 ret = ram_control_save_page(rs->f, block->offset, offset, TARGET_PAGE_SIZE,
1811 &bytes_xmit);
1812 if (ret == RAM_SAVE_CONTROL_NOT_SUPP) {
1813 return false;
1814 }
1815
1816 if (bytes_xmit) {
1817 ram_counters.transferred += bytes_xmit;
1818 *pages = 1;
1819 }
1820
1821 if (ret == RAM_SAVE_CONTROL_DELAYED) {
1822 return true;
1823 }
1824
1825 if (bytes_xmit > 0) {
1826 ram_counters.normal++;
1827 } else if (bytes_xmit == 0) {
1828 ram_counters.duplicate++;
1829 }
1830
1831 return true;
1832}
1833
65dacaa0
XG
1834/*
1835 * directly send the page to the stream
1836 *
1837 * Returns the number of pages written.
1838 *
1839 * @rs: current RAM state
1840 * @block: block that contains the page we want to send
1841 * @offset: offset inside the block for the page
1842 * @buf: the page to be sent
1843 * @async: send to page asyncly
1844 */
1845static int save_normal_page(RAMState *rs, RAMBlock *block, ram_addr_t offset,
1846 uint8_t *buf, bool async)
1847{
1848 ram_counters.transferred += save_page_header(rs, rs->f, block,
1849 offset | RAM_SAVE_FLAG_PAGE);
1850 if (async) {
1851 qemu_put_buffer_async(rs->f, buf, TARGET_PAGE_SIZE,
1852 migrate_release_ram() &
1853 migration_in_postcopy());
1854 } else {
1855 qemu_put_buffer(rs->f, buf, TARGET_PAGE_SIZE);
1856 }
1857 ram_counters.transferred += TARGET_PAGE_SIZE;
1858 ram_counters.normal++;
1859 return 1;
1860}
1861
56e93d26 1862/**
3d0684b2 1863 * ram_save_page: send the given page to the stream
56e93d26 1864 *
3d0684b2 1865 * Returns the number of pages written.
3fd3c4b3
DDAG
1866 * < 0 - error
1867 * >=0 - Number of pages written - this might legally be 0
1868 * if xbzrle noticed the page was the same.
56e93d26 1869 *
6f37bb8b 1870 * @rs: current RAM state
56e93d26
JQ
1871 * @block: block that contains the page we want to send
1872 * @offset: offset inside the block for the page
1873 * @last_stage: if we are at the completion stage
56e93d26 1874 */
a0a8aa14 1875static int ram_save_page(RAMState *rs, PageSearchStatus *pss, bool last_stage)
56e93d26
JQ
1876{
1877 int pages = -1;
56e93d26 1878 uint8_t *p;
56e93d26 1879 bool send_async = true;
a08f6890 1880 RAMBlock *block = pss->block;
a935e30f 1881 ram_addr_t offset = pss->page << TARGET_PAGE_BITS;
059ff0fb 1882 ram_addr_t current_addr = block->offset + offset;
56e93d26 1883
2f68e399 1884 p = block->host + offset;
1db9d8e5 1885 trace_ram_save_page(block->idstr, (uint64_t)offset, p);
56e93d26 1886
56e93d26 1887 XBZRLE_cache_lock();
d7400a34
XG
1888 if (!rs->ram_bulk_stage && !migration_in_postcopy() &&
1889 migrate_use_xbzrle()) {
059ff0fb
XG
1890 pages = save_xbzrle_page(rs, &p, current_addr, block,
1891 offset, last_stage);
1892 if (!last_stage) {
1893 /* Can't send this cached data async, since the cache page
1894 * might get updated before it gets to the wire
56e93d26 1895 */
059ff0fb 1896 send_async = false;
56e93d26
JQ
1897 }
1898 }
1899
1900 /* XBZRLE overflow or normal page */
1901 if (pages == -1) {
65dacaa0 1902 pages = save_normal_page(rs, block, offset, p, send_async);
56e93d26
JQ
1903 }
1904
1905 XBZRLE_cache_unlock();
1906
1907 return pages;
1908}
1909
b9ee2f7d
JQ
1910static int ram_save_multifd_page(RAMState *rs, RAMBlock *block,
1911 ram_addr_t offset)
1912{
b9ee2f7d 1913 multifd_queue_page(block, offset);
b9ee2f7d
JQ
1914 ram_counters.normal++;
1915
1916 return 1;
1917}
1918
5e5fdcff 1919static bool do_compress_ram_page(QEMUFile *f, z_stream *stream, RAMBlock *block,
6ef3771c 1920 ram_addr_t offset, uint8_t *source_buf)
56e93d26 1921{
53518d94 1922 RAMState *rs = ram_state;
a7a9a88f 1923 uint8_t *p = block->host + (offset & TARGET_PAGE_MASK);
5e5fdcff 1924 bool zero_page = false;
6ef3771c 1925 int ret;
56e93d26 1926
5e5fdcff
XG
1927 if (save_zero_page_to_file(rs, f, block, offset)) {
1928 zero_page = true;
1929 goto exit;
1930 }
1931
6ef3771c 1932 save_page_header(rs, f, block, offset | RAM_SAVE_FLAG_COMPRESS_PAGE);
34ab9e97
XG
1933
1934 /*
1935 * copy it to a internal buffer to avoid it being modified by VM
1936 * so that we can catch up the error during compression and
1937 * decompression
1938 */
1939 memcpy(source_buf, p, TARGET_PAGE_SIZE);
6ef3771c
XG
1940 ret = qemu_put_compression_data(f, stream, source_buf, TARGET_PAGE_SIZE);
1941 if (ret < 0) {
1942 qemu_file_set_error(migrate_get_current()->to_dst_file, ret);
b3be2896 1943 error_report("compressed data failed!");
5e5fdcff 1944 return false;
b3be2896 1945 }
56e93d26 1946
5e5fdcff 1947exit:
6ef3771c 1948 ram_release_pages(block->idstr, offset & TARGET_PAGE_MASK, 1);
5e5fdcff
XG
1949 return zero_page;
1950}
1951
1952static void
1953update_compress_thread_counts(const CompressParam *param, int bytes_xmit)
1954{
76e03000
XG
1955 ram_counters.transferred += bytes_xmit;
1956
5e5fdcff
XG
1957 if (param->zero_page) {
1958 ram_counters.duplicate++;
76e03000 1959 return;
5e5fdcff 1960 }
76e03000
XG
1961
1962 /* 8 means a header with RAM_SAVE_FLAG_CONTINUE. */
1963 compression_counters.compressed_size += bytes_xmit - 8;
1964 compression_counters.pages++;
56e93d26
JQ
1965}
1966
32b05495
XG
1967static bool save_page_use_compression(RAMState *rs);
1968
ce25d337 1969static void flush_compressed_data(RAMState *rs)
56e93d26
JQ
1970{
1971 int idx, len, thread_count;
1972
32b05495 1973 if (!save_page_use_compression(rs)) {
56e93d26
JQ
1974 return;
1975 }
1976 thread_count = migrate_compress_threads();
a7a9a88f 1977
0d9f9a5c 1978 qemu_mutex_lock(&comp_done_lock);
56e93d26 1979 for (idx = 0; idx < thread_count; idx++) {
a7a9a88f 1980 while (!comp_param[idx].done) {
0d9f9a5c 1981 qemu_cond_wait(&comp_done_cond, &comp_done_lock);
56e93d26 1982 }
a7a9a88f 1983 }
0d9f9a5c 1984 qemu_mutex_unlock(&comp_done_lock);
a7a9a88f
LL
1985
1986 for (idx = 0; idx < thread_count; idx++) {
1987 qemu_mutex_lock(&comp_param[idx].mutex);
90e56fb4 1988 if (!comp_param[idx].quit) {
ce25d337 1989 len = qemu_put_qemu_file(rs->f, comp_param[idx].file);
5e5fdcff
XG
1990 /*
1991 * it's safe to fetch zero_page without holding comp_done_lock
1992 * as there is no further request submitted to the thread,
1993 * i.e, the thread should be waiting for a request at this point.
1994 */
1995 update_compress_thread_counts(&comp_param[idx], len);
56e93d26 1996 }
a7a9a88f 1997 qemu_mutex_unlock(&comp_param[idx].mutex);
56e93d26
JQ
1998 }
1999}
2000
2001static inline void set_compress_params(CompressParam *param, RAMBlock *block,
2002 ram_addr_t offset)
2003{
2004 param->block = block;
2005 param->offset = offset;
2006}
2007
ce25d337
JQ
2008static int compress_page_with_multi_thread(RAMState *rs, RAMBlock *block,
2009 ram_addr_t offset)
56e93d26
JQ
2010{
2011 int idx, thread_count, bytes_xmit = -1, pages = -1;
1d58872a 2012 bool wait = migrate_compress_wait_thread();
56e93d26
JQ
2013
2014 thread_count = migrate_compress_threads();
0d9f9a5c 2015 qemu_mutex_lock(&comp_done_lock);
1d58872a
XG
2016retry:
2017 for (idx = 0; idx < thread_count; idx++) {
2018 if (comp_param[idx].done) {
2019 comp_param[idx].done = false;
2020 bytes_xmit = qemu_put_qemu_file(rs->f, comp_param[idx].file);
2021 qemu_mutex_lock(&comp_param[idx].mutex);
2022 set_compress_params(&comp_param[idx], block, offset);
2023 qemu_cond_signal(&comp_param[idx].cond);
2024 qemu_mutex_unlock(&comp_param[idx].mutex);
2025 pages = 1;
5e5fdcff 2026 update_compress_thread_counts(&comp_param[idx], bytes_xmit);
56e93d26 2027 break;
56e93d26
JQ
2028 }
2029 }
1d58872a
XG
2030
2031 /*
2032 * wait for the free thread if the user specifies 'compress-wait-thread',
2033 * otherwise we will post the page out in the main thread as normal page.
2034 */
2035 if (pages < 0 && wait) {
2036 qemu_cond_wait(&comp_done_cond, &comp_done_lock);
2037 goto retry;
2038 }
0d9f9a5c 2039 qemu_mutex_unlock(&comp_done_lock);
56e93d26
JQ
2040
2041 return pages;
2042}
2043
3d0684b2
JQ
2044/**
2045 * find_dirty_block: find the next dirty page and update any state
2046 * associated with the search process.
b9e60928 2047 *
3d0684b2 2048 * Returns if a page is found
b9e60928 2049 *
6f37bb8b 2050 * @rs: current RAM state
3d0684b2
JQ
2051 * @pss: data about the state of the current dirty page scan
2052 * @again: set to false if the search has scanned the whole of RAM
b9e60928 2053 */
f20e2865 2054static bool find_dirty_block(RAMState *rs, PageSearchStatus *pss, bool *again)
b9e60928 2055{
f20e2865 2056 pss->page = migration_bitmap_find_dirty(rs, pss->block, pss->page);
6f37bb8b 2057 if (pss->complete_round && pss->block == rs->last_seen_block &&
a935e30f 2058 pss->page >= rs->last_page) {
b9e60928
DDAG
2059 /*
2060 * We've been once around the RAM and haven't found anything.
2061 * Give up.
2062 */
2063 *again = false;
2064 return false;
2065 }
a935e30f 2066 if ((pss->page << TARGET_PAGE_BITS) >= pss->block->used_length) {
b9e60928 2067 /* Didn't find anything in this RAM Block */
a935e30f 2068 pss->page = 0;
b9e60928
DDAG
2069 pss->block = QLIST_NEXT_RCU(pss->block, next);
2070 if (!pss->block) {
48df9d80
XG
2071 /*
2072 * If memory migration starts over, we will meet a dirtied page
2073 * which may still exists in compression threads's ring, so we
2074 * should flush the compressed data to make sure the new page
2075 * is not overwritten by the old one in the destination.
2076 *
2077 * Also If xbzrle is on, stop using the data compression at this
2078 * point. In theory, xbzrle can do better than compression.
2079 */
2080 flush_compressed_data(rs);
2081
b9e60928
DDAG
2082 /* Hit the end of the list */
2083 pss->block = QLIST_FIRST_RCU(&ram_list.blocks);
2084 /* Flag that we've looped */
2085 pss->complete_round = true;
6f37bb8b 2086 rs->ram_bulk_stage = false;
b9e60928
DDAG
2087 }
2088 /* Didn't find anything this time, but try again on the new block */
2089 *again = true;
2090 return false;
2091 } else {
2092 /* Can go around again, but... */
2093 *again = true;
2094 /* We've found something so probably don't need to */
2095 return true;
2096 }
2097}
2098
3d0684b2
JQ
2099/**
2100 * unqueue_page: gets a page of the queue
2101 *
a82d593b 2102 * Helper for 'get_queued_page' - gets a page off the queue
a82d593b 2103 *
3d0684b2
JQ
2104 * Returns the block of the page (or NULL if none available)
2105 *
ec481c6c 2106 * @rs: current RAM state
3d0684b2 2107 * @offset: used to return the offset within the RAMBlock
a82d593b 2108 */
f20e2865 2109static RAMBlock *unqueue_page(RAMState *rs, ram_addr_t *offset)
a82d593b
DDAG
2110{
2111 RAMBlock *block = NULL;
2112
ae526e32
XG
2113 if (QSIMPLEQ_EMPTY_ATOMIC(&rs->src_page_requests)) {
2114 return NULL;
2115 }
2116
ec481c6c
JQ
2117 qemu_mutex_lock(&rs->src_page_req_mutex);
2118 if (!QSIMPLEQ_EMPTY(&rs->src_page_requests)) {
2119 struct RAMSrcPageRequest *entry =
2120 QSIMPLEQ_FIRST(&rs->src_page_requests);
a82d593b
DDAG
2121 block = entry->rb;
2122 *offset = entry->offset;
a82d593b
DDAG
2123
2124 if (entry->len > TARGET_PAGE_SIZE) {
2125 entry->len -= TARGET_PAGE_SIZE;
2126 entry->offset += TARGET_PAGE_SIZE;
2127 } else {
2128 memory_region_unref(block->mr);
ec481c6c 2129 QSIMPLEQ_REMOVE_HEAD(&rs->src_page_requests, next_req);
a82d593b 2130 g_free(entry);
e03a34f8 2131 migration_consume_urgent_request();
a82d593b
DDAG
2132 }
2133 }
ec481c6c 2134 qemu_mutex_unlock(&rs->src_page_req_mutex);
a82d593b
DDAG
2135
2136 return block;
2137}
2138
3d0684b2
JQ
2139/**
2140 * get_queued_page: unqueue a page from the postocpy requests
2141 *
2142 * Skips pages that are already sent (!dirty)
a82d593b 2143 *
3d0684b2 2144 * Returns if a queued page is found
a82d593b 2145 *
6f37bb8b 2146 * @rs: current RAM state
3d0684b2 2147 * @pss: data about the state of the current dirty page scan
a82d593b 2148 */
f20e2865 2149static bool get_queued_page(RAMState *rs, PageSearchStatus *pss)
a82d593b
DDAG
2150{
2151 RAMBlock *block;
2152 ram_addr_t offset;
2153 bool dirty;
2154
2155 do {
f20e2865 2156 block = unqueue_page(rs, &offset);
a82d593b
DDAG
2157 /*
2158 * We're sending this page, and since it's postcopy nothing else
2159 * will dirty it, and we must make sure it doesn't get sent again
2160 * even if this queue request was received after the background
2161 * search already sent it.
2162 */
2163 if (block) {
f20e2865
JQ
2164 unsigned long page;
2165
6b6712ef
JQ
2166 page = offset >> TARGET_PAGE_BITS;
2167 dirty = test_bit(page, block->bmap);
a82d593b 2168 if (!dirty) {
06b10688 2169 trace_get_queued_page_not_dirty(block->idstr, (uint64_t)offset,
6b6712ef 2170 page, test_bit(page, block->unsentmap));
a82d593b 2171 } else {
f20e2865 2172 trace_get_queued_page(block->idstr, (uint64_t)offset, page);
a82d593b
DDAG
2173 }
2174 }
2175
2176 } while (block && !dirty);
2177
2178 if (block) {
2179 /*
2180 * As soon as we start servicing pages out of order, then we have
2181 * to kill the bulk stage, since the bulk stage assumes
2182 * in (migration_bitmap_find_and_reset_dirty) that every page is
2183 * dirty, that's no longer true.
2184 */
6f37bb8b 2185 rs->ram_bulk_stage = false;
a82d593b
DDAG
2186
2187 /*
2188 * We want the background search to continue from the queued page
2189 * since the guest is likely to want other pages near to the page
2190 * it just requested.
2191 */
2192 pss->block = block;
a935e30f 2193 pss->page = offset >> TARGET_PAGE_BITS;
a82d593b
DDAG
2194 }
2195
2196 return !!block;
2197}
2198
6c595cde 2199/**
5e58f968
JQ
2200 * migration_page_queue_free: drop any remaining pages in the ram
2201 * request queue
6c595cde 2202 *
3d0684b2
JQ
2203 * It should be empty at the end anyway, but in error cases there may
2204 * be some left. in case that there is any page left, we drop it.
2205 *
6c595cde 2206 */
83c13382 2207static void migration_page_queue_free(RAMState *rs)
6c595cde 2208{
ec481c6c 2209 struct RAMSrcPageRequest *mspr, *next_mspr;
6c595cde
DDAG
2210 /* This queue generally should be empty - but in the case of a failed
2211 * migration might have some droppings in.
2212 */
2213 rcu_read_lock();
ec481c6c 2214 QSIMPLEQ_FOREACH_SAFE(mspr, &rs->src_page_requests, next_req, next_mspr) {
6c595cde 2215 memory_region_unref(mspr->rb->mr);
ec481c6c 2216 QSIMPLEQ_REMOVE_HEAD(&rs->src_page_requests, next_req);
6c595cde
DDAG
2217 g_free(mspr);
2218 }
2219 rcu_read_unlock();
2220}
2221
2222/**
3d0684b2
JQ
2223 * ram_save_queue_pages: queue the page for transmission
2224 *
2225 * A request from postcopy destination for example.
2226 *
2227 * Returns zero on success or negative on error
2228 *
3d0684b2
JQ
2229 * @rbname: Name of the RAMBLock of the request. NULL means the
2230 * same that last one.
2231 * @start: starting address from the start of the RAMBlock
2232 * @len: length (in bytes) to send
6c595cde 2233 */
96506894 2234int ram_save_queue_pages(const char *rbname, ram_addr_t start, ram_addr_t len)
6c595cde
DDAG
2235{
2236 RAMBlock *ramblock;
53518d94 2237 RAMState *rs = ram_state;
6c595cde 2238
9360447d 2239 ram_counters.postcopy_requests++;
6c595cde
DDAG
2240 rcu_read_lock();
2241 if (!rbname) {
2242 /* Reuse last RAMBlock */
68a098f3 2243 ramblock = rs->last_req_rb;
6c595cde
DDAG
2244
2245 if (!ramblock) {
2246 /*
2247 * Shouldn't happen, we can't reuse the last RAMBlock if
2248 * it's the 1st request.
2249 */
2250 error_report("ram_save_queue_pages no previous block");
2251 goto err;
2252 }
2253 } else {
2254 ramblock = qemu_ram_block_by_name(rbname);
2255
2256 if (!ramblock) {
2257 /* We shouldn't be asked for a non-existent RAMBlock */
2258 error_report("ram_save_queue_pages no block '%s'", rbname);
2259 goto err;
2260 }
68a098f3 2261 rs->last_req_rb = ramblock;
6c595cde
DDAG
2262 }
2263 trace_ram_save_queue_pages(ramblock->idstr, start, len);
2264 if (start+len > ramblock->used_length) {
9458ad6b
JQ
2265 error_report("%s request overrun start=" RAM_ADDR_FMT " len="
2266 RAM_ADDR_FMT " blocklen=" RAM_ADDR_FMT,
6c595cde
DDAG
2267 __func__, start, len, ramblock->used_length);
2268 goto err;
2269 }
2270
ec481c6c
JQ
2271 struct RAMSrcPageRequest *new_entry =
2272 g_malloc0(sizeof(struct RAMSrcPageRequest));
6c595cde
DDAG
2273 new_entry->rb = ramblock;
2274 new_entry->offset = start;
2275 new_entry->len = len;
2276
2277 memory_region_ref(ramblock->mr);
ec481c6c
JQ
2278 qemu_mutex_lock(&rs->src_page_req_mutex);
2279 QSIMPLEQ_INSERT_TAIL(&rs->src_page_requests, new_entry, next_req);
e03a34f8 2280 migration_make_urgent_request();
ec481c6c 2281 qemu_mutex_unlock(&rs->src_page_req_mutex);
6c595cde
DDAG
2282 rcu_read_unlock();
2283
2284 return 0;
2285
2286err:
2287 rcu_read_unlock();
2288 return -1;
2289}
2290
d7400a34
XG
2291static bool save_page_use_compression(RAMState *rs)
2292{
2293 if (!migrate_use_compression()) {
2294 return false;
2295 }
2296
2297 /*
2298 * If xbzrle is on, stop using the data compression after first
2299 * round of migration even if compression is enabled. In theory,
2300 * xbzrle can do better than compression.
2301 */
2302 if (rs->ram_bulk_stage || !migrate_use_xbzrle()) {
2303 return true;
2304 }
2305
2306 return false;
2307}
2308
5e5fdcff
XG
2309/*
2310 * try to compress the page before posting it out, return true if the page
2311 * has been properly handled by compression, otherwise needs other
2312 * paths to handle it
2313 */
2314static bool save_compress_page(RAMState *rs, RAMBlock *block, ram_addr_t offset)
2315{
2316 if (!save_page_use_compression(rs)) {
2317 return false;
2318 }
2319
2320 /*
2321 * When starting the process of a new block, the first page of
2322 * the block should be sent out before other pages in the same
2323 * block, and all the pages in last block should have been sent
2324 * out, keeping this order is important, because the 'cont' flag
2325 * is used to avoid resending the block name.
2326 *
2327 * We post the fist page as normal page as compression will take
2328 * much CPU resource.
2329 */
2330 if (block != rs->last_sent_block) {
2331 flush_compressed_data(rs);
2332 return false;
2333 }
2334
2335 if (compress_page_with_multi_thread(rs, block, offset) > 0) {
2336 return true;
2337 }
2338
76e03000 2339 compression_counters.busy++;
5e5fdcff
XG
2340 return false;
2341}
2342
a82d593b 2343/**
3d0684b2 2344 * ram_save_target_page: save one target page
a82d593b 2345 *
3d0684b2 2346 * Returns the number of pages written
a82d593b 2347 *
6f37bb8b 2348 * @rs: current RAM state
3d0684b2 2349 * @pss: data about the page we want to send
a82d593b 2350 * @last_stage: if we are at the completion stage
a82d593b 2351 */
a0a8aa14 2352static int ram_save_target_page(RAMState *rs, PageSearchStatus *pss,
f20e2865 2353 bool last_stage)
a82d593b 2354{
a8ec91f9
XG
2355 RAMBlock *block = pss->block;
2356 ram_addr_t offset = pss->page << TARGET_PAGE_BITS;
2357 int res;
2358
2359 if (control_save_page(rs, block, offset, &res)) {
2360 return res;
2361 }
2362
5e5fdcff
XG
2363 if (save_compress_page(rs, block, offset)) {
2364 return 1;
d7400a34
XG
2365 }
2366
2367 res = save_zero_page(rs, block, offset);
2368 if (res > 0) {
2369 /* Must let xbzrle know, otherwise a previous (now 0'd) cached
2370 * page would be stale
2371 */
2372 if (!save_page_use_compression(rs)) {
2373 XBZRLE_cache_lock();
2374 xbzrle_cache_zero_page(rs, block->offset + offset);
2375 XBZRLE_cache_unlock();
2376 }
2377 ram_release_pages(block->idstr, offset, res);
2378 return res;
2379 }
2380
da3f56cb 2381 /*
5e5fdcff
XG
2382 * do not use multifd for compression as the first page in the new
2383 * block should be posted out before sending the compressed page
da3f56cb 2384 */
5e5fdcff 2385 if (!save_page_use_compression(rs) && migrate_use_multifd()) {
b9ee2f7d 2386 return ram_save_multifd_page(rs, block, offset);
a82d593b
DDAG
2387 }
2388
1faa5665 2389 return ram_save_page(rs, pss, last_stage);
a82d593b
DDAG
2390}
2391
2392/**
3d0684b2 2393 * ram_save_host_page: save a whole host page
a82d593b 2394 *
3d0684b2
JQ
2395 * Starting at *offset send pages up to the end of the current host
2396 * page. It's valid for the initial offset to point into the middle of
2397 * a host page in which case the remainder of the hostpage is sent.
2398 * Only dirty target pages are sent. Note that the host page size may
2399 * be a huge page for this block.
1eb3fc0a
DDAG
2400 * The saving stops at the boundary of the used_length of the block
2401 * if the RAMBlock isn't a multiple of the host page size.
a82d593b 2402 *
3d0684b2
JQ
2403 * Returns the number of pages written or negative on error
2404 *
6f37bb8b 2405 * @rs: current RAM state
3d0684b2 2406 * @ms: current migration state
3d0684b2 2407 * @pss: data about the page we want to send
a82d593b 2408 * @last_stage: if we are at the completion stage
a82d593b 2409 */
a0a8aa14 2410static int ram_save_host_page(RAMState *rs, PageSearchStatus *pss,
f20e2865 2411 bool last_stage)
a82d593b
DDAG
2412{
2413 int tmppages, pages = 0;
a935e30f
JQ
2414 size_t pagesize_bits =
2415 qemu_ram_pagesize(pss->block) >> TARGET_PAGE_BITS;
4c011c37 2416
fbd162e6 2417 if (ramblock_is_ignored(pss->block)) {
b895de50
CLG
2418 error_report("block %s should not be migrated !", pss->block->idstr);
2419 return 0;
2420 }
2421
a82d593b 2422 do {
1faa5665
XG
2423 /* Check the pages is dirty and if it is send it */
2424 if (!migration_bitmap_clear_dirty(rs, pss->block, pss->page)) {
2425 pss->page++;
2426 continue;
2427 }
2428
f20e2865 2429 tmppages = ram_save_target_page(rs, pss, last_stage);
a82d593b
DDAG
2430 if (tmppages < 0) {
2431 return tmppages;
2432 }
2433
2434 pages += tmppages;
1faa5665
XG
2435 if (pss->block->unsentmap) {
2436 clear_bit(pss->page, pss->block->unsentmap);
2437 }
2438
a935e30f 2439 pss->page++;
1eb3fc0a
DDAG
2440 } while ((pss->page & (pagesize_bits - 1)) &&
2441 offset_in_ramblock(pss->block, pss->page << TARGET_PAGE_BITS));
a82d593b
DDAG
2442
2443 /* The offset we leave with is the last one we looked at */
a935e30f 2444 pss->page--;
a82d593b
DDAG
2445 return pages;
2446}
6c595cde 2447
56e93d26 2448/**
3d0684b2 2449 * ram_find_and_save_block: finds a dirty page and sends it to f
56e93d26
JQ
2450 *
2451 * Called within an RCU critical section.
2452 *
e8f3735f
XG
2453 * Returns the number of pages written where zero means no dirty pages,
2454 * or negative on error
56e93d26 2455 *
6f37bb8b 2456 * @rs: current RAM state
56e93d26 2457 * @last_stage: if we are at the completion stage
a82d593b
DDAG
2458 *
2459 * On systems where host-page-size > target-page-size it will send all the
2460 * pages in a host page that are dirty.
56e93d26
JQ
2461 */
2462
ce25d337 2463static int ram_find_and_save_block(RAMState *rs, bool last_stage)
56e93d26 2464{
b8fb8cb7 2465 PageSearchStatus pss;
56e93d26 2466 int pages = 0;
b9e60928 2467 bool again, found;
56e93d26 2468
0827b9e9
AA
2469 /* No dirty page as there is zero RAM */
2470 if (!ram_bytes_total()) {
2471 return pages;
2472 }
2473
6f37bb8b 2474 pss.block = rs->last_seen_block;
a935e30f 2475 pss.page = rs->last_page;
b8fb8cb7
DDAG
2476 pss.complete_round = false;
2477
2478 if (!pss.block) {
2479 pss.block = QLIST_FIRST_RCU(&ram_list.blocks);
2480 }
56e93d26 2481
b9e60928 2482 do {
a82d593b 2483 again = true;
f20e2865 2484 found = get_queued_page(rs, &pss);
b9e60928 2485
a82d593b
DDAG
2486 if (!found) {
2487 /* priority queue empty, so just search for something dirty */
f20e2865 2488 found = find_dirty_block(rs, &pss, &again);
a82d593b 2489 }
f3f491fc 2490
a82d593b 2491 if (found) {
f20e2865 2492 pages = ram_save_host_page(rs, &pss, last_stage);
56e93d26 2493 }
b9e60928 2494 } while (!pages && again);
56e93d26 2495
6f37bb8b 2496 rs->last_seen_block = pss.block;
a935e30f 2497 rs->last_page = pss.page;
56e93d26
JQ
2498
2499 return pages;
2500}
2501
2502void acct_update_position(QEMUFile *f, size_t size, bool zero)
2503{
2504 uint64_t pages = size / TARGET_PAGE_SIZE;
f7ccd61b 2505
56e93d26 2506 if (zero) {
9360447d 2507 ram_counters.duplicate += pages;
56e93d26 2508 } else {
9360447d
JQ
2509 ram_counters.normal += pages;
2510 ram_counters.transferred += size;
56e93d26
JQ
2511 qemu_update_position(f, size);
2512 }
2513}
2514
fbd162e6 2515static uint64_t ram_bytes_total_common(bool count_ignored)
56e93d26
JQ
2516{
2517 RAMBlock *block;
2518 uint64_t total = 0;
2519
2520 rcu_read_lock();
fbd162e6
YK
2521 if (count_ignored) {
2522 RAMBLOCK_FOREACH_MIGRATABLE(block) {
2523 total += block->used_length;
2524 }
2525 } else {
2526 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
2527 total += block->used_length;
2528 }
99e15582 2529 }
56e93d26
JQ
2530 rcu_read_unlock();
2531 return total;
2532}
2533
fbd162e6
YK
2534uint64_t ram_bytes_total(void)
2535{
2536 return ram_bytes_total_common(false);
2537}
2538
f265e0e4 2539static void xbzrle_load_setup(void)
56e93d26 2540{
f265e0e4 2541 XBZRLE.decoded_buf = g_malloc(TARGET_PAGE_SIZE);
56e93d26
JQ
2542}
2543
f265e0e4
JQ
2544static void xbzrle_load_cleanup(void)
2545{
2546 g_free(XBZRLE.decoded_buf);
2547 XBZRLE.decoded_buf = NULL;
2548}
2549
7d7c96be
PX
2550static void ram_state_cleanup(RAMState **rsp)
2551{
b9ccaf6d
DDAG
2552 if (*rsp) {
2553 migration_page_queue_free(*rsp);
2554 qemu_mutex_destroy(&(*rsp)->bitmap_mutex);
2555 qemu_mutex_destroy(&(*rsp)->src_page_req_mutex);
2556 g_free(*rsp);
2557 *rsp = NULL;
2558 }
7d7c96be
PX
2559}
2560
84593a08
PX
2561static void xbzrle_cleanup(void)
2562{
2563 XBZRLE_cache_lock();
2564 if (XBZRLE.cache) {
2565 cache_fini(XBZRLE.cache);
2566 g_free(XBZRLE.encoded_buf);
2567 g_free(XBZRLE.current_buf);
2568 g_free(XBZRLE.zero_target_page);
2569 XBZRLE.cache = NULL;
2570 XBZRLE.encoded_buf = NULL;
2571 XBZRLE.current_buf = NULL;
2572 XBZRLE.zero_target_page = NULL;
2573 }
2574 XBZRLE_cache_unlock();
2575}
2576
f265e0e4 2577static void ram_save_cleanup(void *opaque)
56e93d26 2578{
53518d94 2579 RAMState **rsp = opaque;
6b6712ef 2580 RAMBlock *block;
eb859c53 2581
2ff64038
LZ
2582 /* caller have hold iothread lock or is in a bh, so there is
2583 * no writing race against this migration_bitmap
2584 */
6b6712ef
JQ
2585 memory_global_dirty_log_stop();
2586
fbd162e6 2587 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
6b6712ef
JQ
2588 g_free(block->bmap);
2589 block->bmap = NULL;
2590 g_free(block->unsentmap);
2591 block->unsentmap = NULL;
56e93d26
JQ
2592 }
2593
84593a08 2594 xbzrle_cleanup();
f0afa331 2595 compress_threads_save_cleanup();
7d7c96be 2596 ram_state_cleanup(rsp);
56e93d26
JQ
2597}
2598
6f37bb8b 2599static void ram_state_reset(RAMState *rs)
56e93d26 2600{
6f37bb8b
JQ
2601 rs->last_seen_block = NULL;
2602 rs->last_sent_block = NULL;
269ace29 2603 rs->last_page = 0;
6f37bb8b
JQ
2604 rs->last_version = ram_list.version;
2605 rs->ram_bulk_stage = true;
56e93d26
JQ
2606}
2607
2608#define MAX_WAIT 50 /* ms, half buffered_file limit */
2609
4f2e4252
DDAG
2610/*
2611 * 'expected' is the value you expect the bitmap mostly to be full
2612 * of; it won't bother printing lines that are all this value.
2613 * If 'todump' is null the migration bitmap is dumped.
2614 */
6b6712ef
JQ
2615void ram_debug_dump_bitmap(unsigned long *todump, bool expected,
2616 unsigned long pages)
4f2e4252 2617{
4f2e4252
DDAG
2618 int64_t cur;
2619 int64_t linelen = 128;
2620 char linebuf[129];
2621
6b6712ef 2622 for (cur = 0; cur < pages; cur += linelen) {
4f2e4252
DDAG
2623 int64_t curb;
2624 bool found = false;
2625 /*
2626 * Last line; catch the case where the line length
2627 * is longer than remaining ram
2628 */
6b6712ef
JQ
2629 if (cur + linelen > pages) {
2630 linelen = pages - cur;
4f2e4252
DDAG
2631 }
2632 for (curb = 0; curb < linelen; curb++) {
2633 bool thisbit = test_bit(cur + curb, todump);
2634 linebuf[curb] = thisbit ? '1' : '.';
2635 found = found || (thisbit != expected);
2636 }
2637 if (found) {
2638 linebuf[curb] = '\0';
2639 fprintf(stderr, "0x%08" PRIx64 " : %s\n", cur, linebuf);
2640 }
2641 }
2642}
2643
e0b266f0
DDAG
2644/* **** functions for postcopy ***** */
2645
ced1c616
PB
2646void ram_postcopy_migrated_memory_release(MigrationState *ms)
2647{
2648 struct RAMBlock *block;
ced1c616 2649
fbd162e6 2650 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
6b6712ef
JQ
2651 unsigned long *bitmap = block->bmap;
2652 unsigned long range = block->used_length >> TARGET_PAGE_BITS;
2653 unsigned long run_start = find_next_zero_bit(bitmap, range, 0);
ced1c616
PB
2654
2655 while (run_start < range) {
2656 unsigned long run_end = find_next_bit(bitmap, range, run_start + 1);
aaa2064c 2657 ram_discard_range(block->idstr, run_start << TARGET_PAGE_BITS,
ced1c616
PB
2658 (run_end - run_start) << TARGET_PAGE_BITS);
2659 run_start = find_next_zero_bit(bitmap, range, run_end + 1);
2660 }
2661 }
2662}
2663
3d0684b2
JQ
2664/**
2665 * postcopy_send_discard_bm_ram: discard a RAMBlock
2666 *
2667 * Returns zero on success
2668 *
e0b266f0
DDAG
2669 * Callback from postcopy_each_ram_send_discard for each RAMBlock
2670 * Note: At this point the 'unsentmap' is the processed bitmap combined
2671 * with the dirtymap; so a '1' means it's either dirty or unsent.
3d0684b2
JQ
2672 *
2673 * @ms: current migration state
2674 * @pds: state for postcopy
2675 * @start: RAMBlock starting page
2676 * @length: RAMBlock size
e0b266f0
DDAG
2677 */
2678static int postcopy_send_discard_bm_ram(MigrationState *ms,
2679 PostcopyDiscardState *pds,
6b6712ef 2680 RAMBlock *block)
e0b266f0 2681{
6b6712ef 2682 unsigned long end = block->used_length >> TARGET_PAGE_BITS;
e0b266f0 2683 unsigned long current;
6b6712ef 2684 unsigned long *unsentmap = block->unsentmap;
e0b266f0 2685
6b6712ef 2686 for (current = 0; current < end; ) {
e0b266f0
DDAG
2687 unsigned long one = find_next_bit(unsentmap, end, current);
2688
2689 if (one <= end) {
2690 unsigned long zero = find_next_zero_bit(unsentmap, end, one + 1);
2691 unsigned long discard_length;
2692
2693 if (zero >= end) {
2694 discard_length = end - one;
2695 } else {
2696 discard_length = zero - one;
2697 }
d688c62d
DDAG
2698 if (discard_length) {
2699 postcopy_discard_send_range(ms, pds, one, discard_length);
2700 }
e0b266f0
DDAG
2701 current = one + discard_length;
2702 } else {
2703 current = one;
2704 }
2705 }
2706
2707 return 0;
2708}
2709
3d0684b2
JQ
2710/**
2711 * postcopy_each_ram_send_discard: discard all RAMBlocks
2712 *
2713 * Returns 0 for success or negative for error
2714 *
e0b266f0
DDAG
2715 * Utility for the outgoing postcopy code.
2716 * Calls postcopy_send_discard_bm_ram for each RAMBlock
2717 * passing it bitmap indexes and name.
e0b266f0
DDAG
2718 * (qemu_ram_foreach_block ends up passing unscaled lengths
2719 * which would mean postcopy code would have to deal with target page)
3d0684b2
JQ
2720 *
2721 * @ms: current migration state
e0b266f0
DDAG
2722 */
2723static int postcopy_each_ram_send_discard(MigrationState *ms)
2724{
2725 struct RAMBlock *block;
2726 int ret;
2727
fbd162e6 2728 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
6b6712ef
JQ
2729 PostcopyDiscardState *pds =
2730 postcopy_discard_send_init(ms, block->idstr);
e0b266f0
DDAG
2731
2732 /*
2733 * Postcopy sends chunks of bitmap over the wire, but it
2734 * just needs indexes at this point, avoids it having
2735 * target page specific code.
2736 */
6b6712ef 2737 ret = postcopy_send_discard_bm_ram(ms, pds, block);
e0b266f0
DDAG
2738 postcopy_discard_send_finish(ms, pds);
2739 if (ret) {
2740 return ret;
2741 }
2742 }
2743
2744 return 0;
2745}
2746
3d0684b2
JQ
2747/**
2748 * postcopy_chunk_hostpages_pass: canocalize bitmap in hostpages
2749 *
2750 * Helper for postcopy_chunk_hostpages; it's called twice to
2751 * canonicalize the two bitmaps, that are similar, but one is
2752 * inverted.
99e314eb 2753 *
3d0684b2
JQ
2754 * Postcopy requires that all target pages in a hostpage are dirty or
2755 * clean, not a mix. This function canonicalizes the bitmaps.
99e314eb 2756 *
3d0684b2
JQ
2757 * @ms: current migration state
2758 * @unsent_pass: if true we need to canonicalize partially unsent host pages
2759 * otherwise we need to canonicalize partially dirty host pages
2760 * @block: block that contains the page we want to canonicalize
2761 * @pds: state for postcopy
99e314eb
DDAG
2762 */
2763static void postcopy_chunk_hostpages_pass(MigrationState *ms, bool unsent_pass,
2764 RAMBlock *block,
2765 PostcopyDiscardState *pds)
2766{
53518d94 2767 RAMState *rs = ram_state;
6b6712ef
JQ
2768 unsigned long *bitmap = block->bmap;
2769 unsigned long *unsentmap = block->unsentmap;
29c59172 2770 unsigned int host_ratio = block->page_size / TARGET_PAGE_SIZE;
6b6712ef 2771 unsigned long pages = block->used_length >> TARGET_PAGE_BITS;
99e314eb
DDAG
2772 unsigned long run_start;
2773
29c59172
DDAG
2774 if (block->page_size == TARGET_PAGE_SIZE) {
2775 /* Easy case - TPS==HPS for a non-huge page RAMBlock */
2776 return;
2777 }
2778
99e314eb
DDAG
2779 if (unsent_pass) {
2780 /* Find a sent page */
6b6712ef 2781 run_start = find_next_zero_bit(unsentmap, pages, 0);
99e314eb
DDAG
2782 } else {
2783 /* Find a dirty page */
6b6712ef 2784 run_start = find_next_bit(bitmap, pages, 0);
99e314eb
DDAG
2785 }
2786
6b6712ef 2787 while (run_start < pages) {
99e314eb
DDAG
2788 bool do_fixup = false;
2789 unsigned long fixup_start_addr;
2790 unsigned long host_offset;
2791
2792 /*
2793 * If the start of this run of pages is in the middle of a host
2794 * page, then we need to fixup this host page.
2795 */
2796 host_offset = run_start % host_ratio;
2797 if (host_offset) {
2798 do_fixup = true;
2799 run_start -= host_offset;
2800 fixup_start_addr = run_start;
2801 /* For the next pass */
2802 run_start = run_start + host_ratio;
2803 } else {
2804 /* Find the end of this run */
2805 unsigned long run_end;
2806 if (unsent_pass) {
6b6712ef 2807 run_end = find_next_bit(unsentmap, pages, run_start + 1);
99e314eb 2808 } else {
6b6712ef 2809 run_end = find_next_zero_bit(bitmap, pages, run_start + 1);
99e314eb
DDAG
2810 }
2811 /*
2812 * If the end isn't at the start of a host page, then the
2813 * run doesn't finish at the end of a host page
2814 * and we need to discard.
2815 */
2816 host_offset = run_end % host_ratio;
2817 if (host_offset) {
2818 do_fixup = true;
2819 fixup_start_addr = run_end - host_offset;
2820 /*
2821 * This host page has gone, the next loop iteration starts
2822 * from after the fixup
2823 */
2824 run_start = fixup_start_addr + host_ratio;
2825 } else {
2826 /*
2827 * No discards on this iteration, next loop starts from
2828 * next sent/dirty page
2829 */
2830 run_start = run_end + 1;
2831 }
2832 }
2833
2834 if (do_fixup) {
2835 unsigned long page;
2836
2837 /* Tell the destination to discard this page */
2838 if (unsent_pass || !test_bit(fixup_start_addr, unsentmap)) {
2839 /* For the unsent_pass we:
2840 * discard partially sent pages
2841 * For the !unsent_pass (dirty) we:
2842 * discard partially dirty pages that were sent
2843 * (any partially sent pages were already discarded
2844 * by the previous unsent_pass)
2845 */
2846 postcopy_discard_send_range(ms, pds, fixup_start_addr,
2847 host_ratio);
2848 }
2849
2850 /* Clean up the bitmap */
2851 for (page = fixup_start_addr;
2852 page < fixup_start_addr + host_ratio; page++) {
2853 /* All pages in this host page are now not sent */
2854 set_bit(page, unsentmap);
2855
2856 /*
2857 * Remark them as dirty, updating the count for any pages
2858 * that weren't previously dirty.
2859 */
0d8ec885 2860 rs->migration_dirty_pages += !test_and_set_bit(page, bitmap);
99e314eb
DDAG
2861 }
2862 }
2863
2864 if (unsent_pass) {
2865 /* Find the next sent page for the next iteration */
6b6712ef 2866 run_start = find_next_zero_bit(unsentmap, pages, run_start);
99e314eb
DDAG
2867 } else {
2868 /* Find the next dirty page for the next iteration */
6b6712ef 2869 run_start = find_next_bit(bitmap, pages, run_start);
99e314eb
DDAG
2870 }
2871 }
2872}
2873
3d0684b2
JQ
2874/**
2875 * postcopy_chuck_hostpages: discrad any partially sent host page
2876 *
99e314eb
DDAG
2877 * Utility for the outgoing postcopy code.
2878 *
2879 * Discard any partially sent host-page size chunks, mark any partially
29c59172
DDAG
2880 * dirty host-page size chunks as all dirty. In this case the host-page
2881 * is the host-page for the particular RAMBlock, i.e. it might be a huge page
99e314eb 2882 *
3d0684b2
JQ
2883 * Returns zero on success
2884 *
2885 * @ms: current migration state
6b6712ef 2886 * @block: block we want to work with
99e314eb 2887 */
6b6712ef 2888static int postcopy_chunk_hostpages(MigrationState *ms, RAMBlock *block)
99e314eb 2889{
6b6712ef
JQ
2890 PostcopyDiscardState *pds =
2891 postcopy_discard_send_init(ms, block->idstr);
99e314eb 2892
6b6712ef
JQ
2893 /* First pass: Discard all partially sent host pages */
2894 postcopy_chunk_hostpages_pass(ms, true, block, pds);
2895 /*
2896 * Second pass: Ensure that all partially dirty host pages are made
2897 * fully dirty.
2898 */
2899 postcopy_chunk_hostpages_pass(ms, false, block, pds);
99e314eb 2900
6b6712ef 2901 postcopy_discard_send_finish(ms, pds);
99e314eb
DDAG
2902 return 0;
2903}
2904
3d0684b2
JQ
2905/**
2906 * ram_postcopy_send_discard_bitmap: transmit the discard bitmap
2907 *
2908 * Returns zero on success
2909 *
e0b266f0
DDAG
2910 * Transmit the set of pages to be discarded after precopy to the target
2911 * these are pages that:
2912 * a) Have been previously transmitted but are now dirty again
2913 * b) Pages that have never been transmitted, this ensures that
2914 * any pages on the destination that have been mapped by background
2915 * tasks get discarded (transparent huge pages is the specific concern)
2916 * Hopefully this is pretty sparse
3d0684b2
JQ
2917 *
2918 * @ms: current migration state
e0b266f0
DDAG
2919 */
2920int ram_postcopy_send_discard_bitmap(MigrationState *ms)
2921{
53518d94 2922 RAMState *rs = ram_state;
6b6712ef 2923 RAMBlock *block;
e0b266f0 2924 int ret;
e0b266f0
DDAG
2925
2926 rcu_read_lock();
2927
2928 /* This should be our last sync, the src is now paused */
eb859c53 2929 migration_bitmap_sync(rs);
e0b266f0 2930
6b6712ef
JQ
2931 /* Easiest way to make sure we don't resume in the middle of a host-page */
2932 rs->last_seen_block = NULL;
2933 rs->last_sent_block = NULL;
2934 rs->last_page = 0;
e0b266f0 2935
fbd162e6 2936 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
6b6712ef
JQ
2937 unsigned long pages = block->used_length >> TARGET_PAGE_BITS;
2938 unsigned long *bitmap = block->bmap;
2939 unsigned long *unsentmap = block->unsentmap;
2940
2941 if (!unsentmap) {
2942 /* We don't have a safe way to resize the sentmap, so
2943 * if the bitmap was resized it will be NULL at this
2944 * point.
2945 */
2946 error_report("migration ram resized during precopy phase");
2947 rcu_read_unlock();
2948 return -EINVAL;
2949 }
2950 /* Deal with TPS != HPS and huge pages */
2951 ret = postcopy_chunk_hostpages(ms, block);
2952 if (ret) {
2953 rcu_read_unlock();
2954 return ret;
2955 }
e0b266f0 2956
6b6712ef
JQ
2957 /*
2958 * Update the unsentmap to be unsentmap = unsentmap | dirty
2959 */
2960 bitmap_or(unsentmap, unsentmap, bitmap, pages);
e0b266f0 2961#ifdef DEBUG_POSTCOPY
6b6712ef 2962 ram_debug_dump_bitmap(unsentmap, true, pages);
e0b266f0 2963#endif
6b6712ef
JQ
2964 }
2965 trace_ram_postcopy_send_discard_bitmap();
e0b266f0
DDAG
2966
2967 ret = postcopy_each_ram_send_discard(ms);
2968 rcu_read_unlock();
2969
2970 return ret;
2971}
2972
3d0684b2
JQ
2973/**
2974 * ram_discard_range: discard dirtied pages at the beginning of postcopy
e0b266f0 2975 *
3d0684b2 2976 * Returns zero on success
e0b266f0 2977 *
36449157
JQ
2978 * @rbname: name of the RAMBlock of the request. NULL means the
2979 * same that last one.
3d0684b2
JQ
2980 * @start: RAMBlock starting page
2981 * @length: RAMBlock size
e0b266f0 2982 */
aaa2064c 2983int ram_discard_range(const char *rbname, uint64_t start, size_t length)
e0b266f0
DDAG
2984{
2985 int ret = -1;
2986
36449157 2987 trace_ram_discard_range(rbname, start, length);
d3a5038c 2988
e0b266f0 2989 rcu_read_lock();
36449157 2990 RAMBlock *rb = qemu_ram_block_by_name(rbname);
e0b266f0
DDAG
2991
2992 if (!rb) {
36449157 2993 error_report("ram_discard_range: Failed to find block '%s'", rbname);
e0b266f0
DDAG
2994 goto err;
2995 }
2996
814bb08f
PX
2997 /*
2998 * On source VM, we don't need to update the received bitmap since
2999 * we don't even have one.
3000 */
3001 if (rb->receivedmap) {
3002 bitmap_clear(rb->receivedmap, start >> qemu_target_page_bits(),
3003 length >> qemu_target_page_bits());
3004 }
3005
d3a5038c 3006 ret = ram_block_discard_range(rb, start, length);
e0b266f0
DDAG
3007
3008err:
3009 rcu_read_unlock();
3010
3011 return ret;
3012}
3013
84593a08
PX
3014/*
3015 * For every allocation, we will try not to crash the VM if the
3016 * allocation failed.
3017 */
3018static int xbzrle_init(void)
3019{
3020 Error *local_err = NULL;
3021
3022 if (!migrate_use_xbzrle()) {
3023 return 0;
3024 }
3025
3026 XBZRLE_cache_lock();
3027
3028 XBZRLE.zero_target_page = g_try_malloc0(TARGET_PAGE_SIZE);
3029 if (!XBZRLE.zero_target_page) {
3030 error_report("%s: Error allocating zero page", __func__);
3031 goto err_out;
3032 }
3033
3034 XBZRLE.cache = cache_init(migrate_xbzrle_cache_size(),
3035 TARGET_PAGE_SIZE, &local_err);
3036 if (!XBZRLE.cache) {
3037 error_report_err(local_err);
3038 goto free_zero_page;
3039 }
3040
3041 XBZRLE.encoded_buf = g_try_malloc0(TARGET_PAGE_SIZE);
3042 if (!XBZRLE.encoded_buf) {
3043 error_report("%s: Error allocating encoded_buf", __func__);
3044 goto free_cache;
3045 }
3046
3047 XBZRLE.current_buf = g_try_malloc(TARGET_PAGE_SIZE);
3048 if (!XBZRLE.current_buf) {
3049 error_report("%s: Error allocating current_buf", __func__);
3050 goto free_encoded_buf;
3051 }
3052
3053 /* We are all good */
3054 XBZRLE_cache_unlock();
3055 return 0;
3056
3057free_encoded_buf:
3058 g_free(XBZRLE.encoded_buf);
3059 XBZRLE.encoded_buf = NULL;
3060free_cache:
3061 cache_fini(XBZRLE.cache);
3062 XBZRLE.cache = NULL;
3063free_zero_page:
3064 g_free(XBZRLE.zero_target_page);
3065 XBZRLE.zero_target_page = NULL;
3066err_out:
3067 XBZRLE_cache_unlock();
3068 return -ENOMEM;
3069}
3070
53518d94 3071static int ram_state_init(RAMState **rsp)
56e93d26 3072{
7d00ee6a
PX
3073 *rsp = g_try_new0(RAMState, 1);
3074
3075 if (!*rsp) {
3076 error_report("%s: Init ramstate fail", __func__);
3077 return -1;
3078 }
53518d94
JQ
3079
3080 qemu_mutex_init(&(*rsp)->bitmap_mutex);
3081 qemu_mutex_init(&(*rsp)->src_page_req_mutex);
3082 QSIMPLEQ_INIT(&(*rsp)->src_page_requests);
56e93d26 3083
7d00ee6a
PX
3084 /*
3085 * Count the total number of pages used by ram blocks not including any
3086 * gaps due to alignment or unplugs.
3087 */
3088 (*rsp)->migration_dirty_pages = ram_bytes_total() >> TARGET_PAGE_BITS;
3089
3090 ram_state_reset(*rsp);
3091
3092 return 0;
3093}
3094
d6eff5d7 3095static void ram_list_init_bitmaps(void)
7d00ee6a 3096{
d6eff5d7
PX
3097 RAMBlock *block;
3098 unsigned long pages;
56e93d26 3099
0827b9e9
AA
3100 /* Skip setting bitmap if there is no RAM */
3101 if (ram_bytes_total()) {
fbd162e6 3102 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
d6eff5d7 3103 pages = block->max_length >> TARGET_PAGE_BITS;
6b6712ef
JQ
3104 block->bmap = bitmap_new(pages);
3105 bitmap_set(block->bmap, 0, pages);
3106 if (migrate_postcopy_ram()) {
3107 block->unsentmap = bitmap_new(pages);
3108 bitmap_set(block->unsentmap, 0, pages);
3109 }
0827b9e9 3110 }
f3f491fc 3111 }
d6eff5d7
PX
3112}
3113
3114static void ram_init_bitmaps(RAMState *rs)
3115{
3116 /* For memory_global_dirty_log_start below. */
3117 qemu_mutex_lock_iothread();
3118 qemu_mutex_lock_ramlist();
3119 rcu_read_lock();
f3f491fc 3120
d6eff5d7 3121 ram_list_init_bitmaps();
56e93d26 3122 memory_global_dirty_log_start();
d6eff5d7
PX
3123 migration_bitmap_sync(rs);
3124
3125 rcu_read_unlock();
56e93d26 3126 qemu_mutex_unlock_ramlist();
49877834 3127 qemu_mutex_unlock_iothread();
d6eff5d7
PX
3128}
3129
3130static int ram_init_all(RAMState **rsp)
3131{
3132 if (ram_state_init(rsp)) {
3133 return -1;
3134 }
3135
3136 if (xbzrle_init()) {
3137 ram_state_cleanup(rsp);
3138 return -1;
3139 }
3140
3141 ram_init_bitmaps(*rsp);
a91246c9
HZ
3142
3143 return 0;
3144}
3145
08614f34
PX
3146static void ram_state_resume_prepare(RAMState *rs, QEMUFile *out)
3147{
3148 RAMBlock *block;
3149 uint64_t pages = 0;
3150
3151 /*
3152 * Postcopy is not using xbzrle/compression, so no need for that.
3153 * Also, since source are already halted, we don't need to care
3154 * about dirty page logging as well.
3155 */
3156
fbd162e6 3157 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
08614f34
PX
3158 pages += bitmap_count_one(block->bmap,
3159 block->used_length >> TARGET_PAGE_BITS);
3160 }
3161
3162 /* This may not be aligned with current bitmaps. Recalculate. */
3163 rs->migration_dirty_pages = pages;
3164
3165 rs->last_seen_block = NULL;
3166 rs->last_sent_block = NULL;
3167 rs->last_page = 0;
3168 rs->last_version = ram_list.version;
3169 /*
3170 * Disable the bulk stage, otherwise we'll resend the whole RAM no
3171 * matter what we have sent.
3172 */
3173 rs->ram_bulk_stage = false;
3174
3175 /* Update RAMState cache of output QEMUFile */
3176 rs->f = out;
3177
3178 trace_ram_state_resume_prepare(pages);
3179}
3180
3d0684b2
JQ
3181/*
3182 * Each of ram_save_setup, ram_save_iterate and ram_save_complete has
a91246c9
HZ
3183 * long-running RCU critical section. When rcu-reclaims in the code
3184 * start to become numerous it will be necessary to reduce the
3185 * granularity of these critical sections.
3186 */
3187
3d0684b2
JQ
3188/**
3189 * ram_save_setup: Setup RAM for migration
3190 *
3191 * Returns zero to indicate success and negative for error
3192 *
3193 * @f: QEMUFile where to send the data
3194 * @opaque: RAMState pointer
3195 */
a91246c9
HZ
3196static int ram_save_setup(QEMUFile *f, void *opaque)
3197{
53518d94 3198 RAMState **rsp = opaque;
a91246c9
HZ
3199 RAMBlock *block;
3200
dcaf446e
XG
3201 if (compress_threads_save_setup()) {
3202 return -1;
3203 }
3204
a91246c9
HZ
3205 /* migration has already setup the bitmap, reuse it. */
3206 if (!migration_in_colo_state()) {
7d00ee6a 3207 if (ram_init_all(rsp) != 0) {
dcaf446e 3208 compress_threads_save_cleanup();
a91246c9 3209 return -1;
53518d94 3210 }
a91246c9 3211 }
53518d94 3212 (*rsp)->f = f;
a91246c9
HZ
3213
3214 rcu_read_lock();
56e93d26 3215
fbd162e6 3216 qemu_put_be64(f, ram_bytes_total_common(true) | RAM_SAVE_FLAG_MEM_SIZE);
56e93d26 3217
b895de50 3218 RAMBLOCK_FOREACH_MIGRATABLE(block) {
56e93d26
JQ
3219 qemu_put_byte(f, strlen(block->idstr));
3220 qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));
3221 qemu_put_be64(f, block->used_length);
ef08fb38
DDAG
3222 if (migrate_postcopy_ram() && block->page_size != qemu_host_page_size) {
3223 qemu_put_be64(f, block->page_size);
3224 }
fbd162e6
YK
3225 if (migrate_ignore_shared()) {
3226 qemu_put_be64(f, block->mr->addr);
3227 qemu_put_byte(f, ramblock_is_ignored(block) ? 1 : 0);
3228 }
56e93d26
JQ
3229 }
3230
3231 rcu_read_unlock();
3232
3233 ram_control_before_iterate(f, RAM_CONTROL_SETUP);
3234 ram_control_after_iterate(f, RAM_CONTROL_SETUP);
3235
6df264ac 3236 multifd_send_sync_main();
56e93d26 3237 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
35374cbd 3238 qemu_fflush(f);
56e93d26
JQ
3239
3240 return 0;
3241}
3242
3d0684b2
JQ
3243/**
3244 * ram_save_iterate: iterative stage for migration
3245 *
3246 * Returns zero to indicate success and negative for error
3247 *
3248 * @f: QEMUFile where to send the data
3249 * @opaque: RAMState pointer
3250 */
56e93d26
JQ
3251static int ram_save_iterate(QEMUFile *f, void *opaque)
3252{
53518d94
JQ
3253 RAMState **temp = opaque;
3254 RAMState *rs = *temp;
56e93d26
JQ
3255 int ret;
3256 int i;
3257 int64_t t0;
5c90308f 3258 int done = 0;
56e93d26 3259
b2557345
PL
3260 if (blk_mig_bulk_active()) {
3261 /* Avoid transferring ram during bulk phase of block migration as
3262 * the bulk phase will usually take a long time and transferring
3263 * ram updates during that time is pointless. */
3264 goto out;
3265 }
3266
56e93d26 3267 rcu_read_lock();
6f37bb8b
JQ
3268 if (ram_list.version != rs->last_version) {
3269 ram_state_reset(rs);
56e93d26
JQ
3270 }
3271
3272 /* Read version before ram_list.blocks */
3273 smp_rmb();
3274
3275 ram_control_before_iterate(f, RAM_CONTROL_ROUND);
3276
3277 t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
3278 i = 0;
e03a34f8
DDAG
3279 while ((ret = qemu_file_rate_limit(f)) == 0 ||
3280 !QSIMPLEQ_EMPTY(&rs->src_page_requests)) {
56e93d26
JQ
3281 int pages;
3282
e03a34f8
DDAG
3283 if (qemu_file_get_error(f)) {
3284 break;
3285 }
3286
ce25d337 3287 pages = ram_find_and_save_block(rs, false);
56e93d26
JQ
3288 /* no more pages to sent */
3289 if (pages == 0) {
5c90308f 3290 done = 1;
56e93d26
JQ
3291 break;
3292 }
e8f3735f
XG
3293
3294 if (pages < 0) {
3295 qemu_file_set_error(f, pages);
3296 break;
3297 }
3298
be8b02ed 3299 rs->target_page_count += pages;
070afca2 3300
56e93d26
JQ
3301 /* we want to check in the 1st loop, just in case it was the 1st time
3302 and we had to sync the dirty bitmap.
3303 qemu_get_clock_ns() is a bit expensive, so we only check each some
3304 iterations
3305 */
3306 if ((i & 63) == 0) {
3307 uint64_t t1 = (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - t0) / 1000000;
3308 if (t1 > MAX_WAIT) {
55c4446b 3309 trace_ram_save_iterate_big_wait(t1, i);
56e93d26
JQ
3310 break;
3311 }
3312 }
3313 i++;
3314 }
56e93d26
JQ
3315 rcu_read_unlock();
3316
3317 /*
3318 * Must occur before EOS (or any QEMUFile operation)
3319 * because of RDMA protocol.
3320 */
3321 ram_control_after_iterate(f, RAM_CONTROL_ROUND);
3322
6df264ac 3323 multifd_send_sync_main();
b2557345 3324out:
56e93d26 3325 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
35374cbd 3326 qemu_fflush(f);
9360447d 3327 ram_counters.transferred += 8;
56e93d26
JQ
3328
3329 ret = qemu_file_get_error(f);
3330 if (ret < 0) {
3331 return ret;
3332 }
3333
5c90308f 3334 return done;
56e93d26
JQ
3335}
3336
3d0684b2
JQ
3337/**
3338 * ram_save_complete: function called to send the remaining amount of ram
3339 *
e8f3735f 3340 * Returns zero to indicate success or negative on error
3d0684b2
JQ
3341 *
3342 * Called with iothread lock
3343 *
3344 * @f: QEMUFile where to send the data
3345 * @opaque: RAMState pointer
3346 */
56e93d26
JQ
3347static int ram_save_complete(QEMUFile *f, void *opaque)
3348{
53518d94
JQ
3349 RAMState **temp = opaque;
3350 RAMState *rs = *temp;
e8f3735f 3351 int ret = 0;
6f37bb8b 3352
56e93d26
JQ
3353 rcu_read_lock();
3354
5727309d 3355 if (!migration_in_postcopy()) {
8d820d6f 3356 migration_bitmap_sync(rs);
663e6c1d 3357 }
56e93d26
JQ
3358
3359 ram_control_before_iterate(f, RAM_CONTROL_FINISH);
3360
3361 /* try transferring iterative blocks of memory */
3362
3363 /* flush all remaining blocks regardless of rate limiting */
3364 while (true) {
3365 int pages;
3366
ce25d337 3367 pages = ram_find_and_save_block(rs, !migration_in_colo_state());
56e93d26
JQ
3368 /* no more blocks to sent */
3369 if (pages == 0) {
3370 break;
3371 }
e8f3735f
XG
3372 if (pages < 0) {
3373 ret = pages;
3374 break;
3375 }
56e93d26
JQ
3376 }
3377
ce25d337 3378 flush_compressed_data(rs);
56e93d26 3379 ram_control_after_iterate(f, RAM_CONTROL_FINISH);
56e93d26
JQ
3380
3381 rcu_read_unlock();
d09a6fde 3382
6df264ac 3383 multifd_send_sync_main();
56e93d26 3384 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
35374cbd 3385 qemu_fflush(f);
56e93d26 3386
e8f3735f 3387 return ret;
56e93d26
JQ
3388}
3389
c31b098f 3390static void ram_save_pending(QEMUFile *f, void *opaque, uint64_t max_size,
47995026
VSO
3391 uint64_t *res_precopy_only,
3392 uint64_t *res_compatible,
3393 uint64_t *res_postcopy_only)
56e93d26 3394{
53518d94
JQ
3395 RAMState **temp = opaque;
3396 RAMState *rs = *temp;
56e93d26
JQ
3397 uint64_t remaining_size;
3398
9edabd4d 3399 remaining_size = rs->migration_dirty_pages * TARGET_PAGE_SIZE;
56e93d26 3400
5727309d 3401 if (!migration_in_postcopy() &&
663e6c1d 3402 remaining_size < max_size) {
56e93d26
JQ
3403 qemu_mutex_lock_iothread();
3404 rcu_read_lock();
8d820d6f 3405 migration_bitmap_sync(rs);
56e93d26
JQ
3406 rcu_read_unlock();
3407 qemu_mutex_unlock_iothread();
9edabd4d 3408 remaining_size = rs->migration_dirty_pages * TARGET_PAGE_SIZE;
56e93d26 3409 }
c31b098f 3410
86e1167e
VSO
3411 if (migrate_postcopy_ram()) {
3412 /* We can do postcopy, and all the data is postcopiable */
47995026 3413 *res_compatible += remaining_size;
86e1167e 3414 } else {
47995026 3415 *res_precopy_only += remaining_size;
86e1167e 3416 }
56e93d26
JQ
3417}
3418
3419static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host)
3420{
3421 unsigned int xh_len;
3422 int xh_flags;
063e760a 3423 uint8_t *loaded_data;
56e93d26 3424
56e93d26
JQ
3425 /* extract RLE header */
3426 xh_flags = qemu_get_byte(f);
3427 xh_len = qemu_get_be16(f);
3428
3429 if (xh_flags != ENCODING_FLAG_XBZRLE) {
3430 error_report("Failed to load XBZRLE page - wrong compression!");
3431 return -1;
3432 }
3433
3434 if (xh_len > TARGET_PAGE_SIZE) {
3435 error_report("Failed to load XBZRLE page - len overflow!");
3436 return -1;
3437 }
f265e0e4 3438 loaded_data = XBZRLE.decoded_buf;
56e93d26 3439 /* load data and decode */
f265e0e4 3440 /* it can change loaded_data to point to an internal buffer */
063e760a 3441 qemu_get_buffer_in_place(f, &loaded_data, xh_len);
56e93d26
JQ
3442
3443 /* decode RLE */
063e760a 3444 if (xbzrle_decode_buffer(loaded_data, xh_len, host,
56e93d26
JQ
3445 TARGET_PAGE_SIZE) == -1) {
3446 error_report("Failed to load XBZRLE page - decode error!");
3447 return -1;
3448 }
3449
3450 return 0;
3451}
3452
3d0684b2
JQ
3453/**
3454 * ram_block_from_stream: read a RAMBlock id from the migration stream
3455 *
3456 * Must be called from within a rcu critical section.
3457 *
56e93d26 3458 * Returns a pointer from within the RCU-protected ram_list.
a7180877 3459 *
3d0684b2
JQ
3460 * @f: QEMUFile where to read the data from
3461 * @flags: Page flags (mostly to see if it's a continuation of previous block)
a7180877 3462 */
3d0684b2 3463static inline RAMBlock *ram_block_from_stream(QEMUFile *f, int flags)
56e93d26
JQ
3464{
3465 static RAMBlock *block = NULL;
3466 char id[256];
3467 uint8_t len;
3468
3469 if (flags & RAM_SAVE_FLAG_CONTINUE) {
4c4bad48 3470 if (!block) {
56e93d26
JQ
3471 error_report("Ack, bad migration stream!");
3472 return NULL;
3473 }
4c4bad48 3474 return block;
56e93d26
JQ
3475 }
3476
3477 len = qemu_get_byte(f);
3478 qemu_get_buffer(f, (uint8_t *)id, len);
3479 id[len] = 0;
3480
e3dd7493 3481 block = qemu_ram_block_by_name(id);
4c4bad48
HZ
3482 if (!block) {
3483 error_report("Can't find block %s", id);
3484 return NULL;
56e93d26
JQ
3485 }
3486
fbd162e6 3487 if (ramblock_is_ignored(block)) {
b895de50
CLG
3488 error_report("block %s should not be migrated !", id);
3489 return NULL;
3490 }
3491
4c4bad48
HZ
3492 return block;
3493}
3494
3495static inline void *host_from_ram_block_offset(RAMBlock *block,
3496 ram_addr_t offset)
3497{
3498 if (!offset_in_ramblock(block, offset)) {
3499 return NULL;
3500 }
3501
3502 return block->host + offset;
56e93d26
JQ
3503}
3504
13af18f2
ZC
3505static inline void *colo_cache_from_block_offset(RAMBlock *block,
3506 ram_addr_t offset)
3507{
3508 if (!offset_in_ramblock(block, offset)) {
3509 return NULL;
3510 }
3511 if (!block->colo_cache) {
3512 error_report("%s: colo_cache is NULL in block :%s",
3513 __func__, block->idstr);
3514 return NULL;
3515 }
7d9acafa
ZC
3516
3517 /*
3518 * During colo checkpoint, we need bitmap of these migrated pages.
3519 * It help us to decide which pages in ram cache should be flushed
3520 * into VM's RAM later.
3521 */
3522 if (!test_and_set_bit(offset >> TARGET_PAGE_BITS, block->bmap)) {
3523 ram_state->migration_dirty_pages++;
3524 }
13af18f2
ZC
3525 return block->colo_cache + offset;
3526}
3527
3d0684b2
JQ
3528/**
3529 * ram_handle_compressed: handle the zero page case
3530 *
56e93d26
JQ
3531 * If a page (or a whole RDMA chunk) has been
3532 * determined to be zero, then zap it.
3d0684b2
JQ
3533 *
3534 * @host: host address for the zero page
3535 * @ch: what the page is filled from. We only support zero
3536 * @size: size of the zero page
56e93d26
JQ
3537 */
3538void ram_handle_compressed(void *host, uint8_t ch, uint64_t size)
3539{
3540 if (ch != 0 || !is_zero_range(host, size)) {
3541 memset(host, ch, size);
3542 }
3543}
3544
797ca154
XG
3545/* return the size after decompression, or negative value on error */
3546static int
3547qemu_uncompress_data(z_stream *stream, uint8_t *dest, size_t dest_len,
3548 const uint8_t *source, size_t source_len)
3549{
3550 int err;
3551
3552 err = inflateReset(stream);
3553 if (err != Z_OK) {
3554 return -1;
3555 }
3556
3557 stream->avail_in = source_len;
3558 stream->next_in = (uint8_t *)source;
3559 stream->avail_out = dest_len;
3560 stream->next_out = dest;
3561
3562 err = inflate(stream, Z_NO_FLUSH);
3563 if (err != Z_STREAM_END) {
3564 return -1;
3565 }
3566
3567 return stream->total_out;
3568}
3569
56e93d26
JQ
3570static void *do_data_decompress(void *opaque)
3571{
3572 DecompressParam *param = opaque;
3573 unsigned long pagesize;
33d151f4 3574 uint8_t *des;
34ab9e97 3575 int len, ret;
56e93d26 3576
33d151f4 3577 qemu_mutex_lock(&param->mutex);
90e56fb4 3578 while (!param->quit) {
33d151f4
LL
3579 if (param->des) {
3580 des = param->des;
3581 len = param->len;
3582 param->des = 0;
3583 qemu_mutex_unlock(&param->mutex);
3584
56e93d26 3585 pagesize = TARGET_PAGE_SIZE;
34ab9e97
XG
3586
3587 ret = qemu_uncompress_data(&param->stream, des, pagesize,
3588 param->compbuf, len);
f548222c 3589 if (ret < 0 && migrate_get_current()->decompress_error_check) {
34ab9e97
XG
3590 error_report("decompress data failed");
3591 qemu_file_set_error(decomp_file, ret);
3592 }
73a8912b 3593
33d151f4
LL
3594 qemu_mutex_lock(&decomp_done_lock);
3595 param->done = true;
3596 qemu_cond_signal(&decomp_done_cond);
3597 qemu_mutex_unlock(&decomp_done_lock);
3598
3599 qemu_mutex_lock(&param->mutex);
3600 } else {
3601 qemu_cond_wait(&param->cond, &param->mutex);
3602 }
56e93d26 3603 }
33d151f4 3604 qemu_mutex_unlock(&param->mutex);
56e93d26
JQ
3605
3606 return NULL;
3607}
3608
34ab9e97 3609static int wait_for_decompress_done(void)
5533b2e9
LL
3610{
3611 int idx, thread_count;
3612
3613 if (!migrate_use_compression()) {
34ab9e97 3614 return 0;
5533b2e9
LL
3615 }
3616
3617 thread_count = migrate_decompress_threads();
3618 qemu_mutex_lock(&decomp_done_lock);
3619 for (idx = 0; idx < thread_count; idx++) {
3620 while (!decomp_param[idx].done) {
3621 qemu_cond_wait(&decomp_done_cond, &decomp_done_lock);
3622 }
3623 }
3624 qemu_mutex_unlock(&decomp_done_lock);
34ab9e97 3625 return qemu_file_get_error(decomp_file);
5533b2e9
LL
3626}
3627
f0afa331 3628static void compress_threads_load_cleanup(void)
56e93d26
JQ
3629{
3630 int i, thread_count;
3631
3416ab5b
JQ
3632 if (!migrate_use_compression()) {
3633 return;
3634 }
56e93d26
JQ
3635 thread_count = migrate_decompress_threads();
3636 for (i = 0; i < thread_count; i++) {
797ca154
XG
3637 /*
3638 * we use it as a indicator which shows if the thread is
3639 * properly init'd or not
3640 */
3641 if (!decomp_param[i].compbuf) {
3642 break;
3643 }
3644
56e93d26 3645 qemu_mutex_lock(&decomp_param[i].mutex);
90e56fb4 3646 decomp_param[i].quit = true;
56e93d26
JQ
3647 qemu_cond_signal(&decomp_param[i].cond);
3648 qemu_mutex_unlock(&decomp_param[i].mutex);
3649 }
3650 for (i = 0; i < thread_count; i++) {
797ca154
XG
3651 if (!decomp_param[i].compbuf) {
3652 break;
3653 }
3654
56e93d26
JQ
3655 qemu_thread_join(decompress_threads + i);
3656 qemu_mutex_destroy(&decomp_param[i].mutex);
3657 qemu_cond_destroy(&decomp_param[i].cond);
797ca154 3658 inflateEnd(&decomp_param[i].stream);
56e93d26 3659 g_free(decomp_param[i].compbuf);
797ca154 3660 decomp_param[i].compbuf = NULL;
56e93d26
JQ
3661 }
3662 g_free(decompress_threads);
3663 g_free(decomp_param);
56e93d26
JQ
3664 decompress_threads = NULL;
3665 decomp_param = NULL;
34ab9e97 3666 decomp_file = NULL;
56e93d26
JQ
3667}
3668
34ab9e97 3669static int compress_threads_load_setup(QEMUFile *f)
797ca154
XG
3670{
3671 int i, thread_count;
3672
3673 if (!migrate_use_compression()) {
3674 return 0;
3675 }
3676
3677 thread_count = migrate_decompress_threads();
3678 decompress_threads = g_new0(QemuThread, thread_count);
3679 decomp_param = g_new0(DecompressParam, thread_count);
3680 qemu_mutex_init(&decomp_done_lock);
3681 qemu_cond_init(&decomp_done_cond);
34ab9e97 3682 decomp_file = f;
797ca154
XG
3683 for (i = 0; i < thread_count; i++) {
3684 if (inflateInit(&decomp_param[i].stream) != Z_OK) {
3685 goto exit;
3686 }
3687
3688 decomp_param[i].compbuf = g_malloc0(compressBound(TARGET_PAGE_SIZE));
3689 qemu_mutex_init(&decomp_param[i].mutex);
3690 qemu_cond_init(&decomp_param[i].cond);
3691 decomp_param[i].done = true;
3692 decomp_param[i].quit = false;
3693 qemu_thread_create(decompress_threads + i, "decompress",
3694 do_data_decompress, decomp_param + i,
3695 QEMU_THREAD_JOINABLE);
3696 }
3697 return 0;
3698exit:
3699 compress_threads_load_cleanup();
3700 return -1;
3701}
3702
c1bc6626 3703static void decompress_data_with_multi_threads(QEMUFile *f,
56e93d26
JQ
3704 void *host, int len)
3705{
3706 int idx, thread_count;
3707
3708 thread_count = migrate_decompress_threads();
73a8912b 3709 qemu_mutex_lock(&decomp_done_lock);
56e93d26
JQ
3710 while (true) {
3711 for (idx = 0; idx < thread_count; idx++) {
73a8912b 3712 if (decomp_param[idx].done) {
33d151f4
LL
3713 decomp_param[idx].done = false;
3714 qemu_mutex_lock(&decomp_param[idx].mutex);
c1bc6626 3715 qemu_get_buffer(f, decomp_param[idx].compbuf, len);
56e93d26
JQ
3716 decomp_param[idx].des = host;
3717 decomp_param[idx].len = len;
33d151f4
LL
3718 qemu_cond_signal(&decomp_param[idx].cond);
3719 qemu_mutex_unlock(&decomp_param[idx].mutex);
56e93d26
JQ
3720 break;
3721 }
3722 }
3723 if (idx < thread_count) {
3724 break;
73a8912b
LL
3725 } else {
3726 qemu_cond_wait(&decomp_done_cond, &decomp_done_lock);
56e93d26
JQ
3727 }
3728 }
73a8912b 3729 qemu_mutex_unlock(&decomp_done_lock);
56e93d26
JQ
3730}
3731
13af18f2
ZC
3732/*
3733 * colo cache: this is for secondary VM, we cache the whole
3734 * memory of the secondary VM, it is need to hold the global lock
3735 * to call this helper.
3736 */
3737int colo_init_ram_cache(void)
3738{
3739 RAMBlock *block;
3740
3741 rcu_read_lock();
fbd162e6 3742 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
13af18f2
ZC
3743 block->colo_cache = qemu_anon_ram_alloc(block->used_length,
3744 NULL,
3745 false);
3746 if (!block->colo_cache) {
3747 error_report("%s: Can't alloc memory for COLO cache of block %s,"
3748 "size 0x" RAM_ADDR_FMT, __func__, block->idstr,
3749 block->used_length);
3750 goto out_locked;
3751 }
3752 memcpy(block->colo_cache, block->host, block->used_length);
3753 }
3754 rcu_read_unlock();
7d9acafa
ZC
3755 /*
3756 * Record the dirty pages that sent by PVM, we use this dirty bitmap together
3757 * with to decide which page in cache should be flushed into SVM's RAM. Here
3758 * we use the same name 'ram_bitmap' as for migration.
3759 */
3760 if (ram_bytes_total()) {
3761 RAMBlock *block;
3762
fbd162e6 3763 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
7d9acafa
ZC
3764 unsigned long pages = block->max_length >> TARGET_PAGE_BITS;
3765
3766 block->bmap = bitmap_new(pages);
3767 bitmap_set(block->bmap, 0, pages);
3768 }
3769 }
3770 ram_state = g_new0(RAMState, 1);
3771 ram_state->migration_dirty_pages = 0;
d1955d22 3772 memory_global_dirty_log_start();
7d9acafa 3773
13af18f2
ZC
3774 return 0;
3775
3776out_locked:
7d9acafa 3777
fbd162e6 3778 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
13af18f2
ZC
3779 if (block->colo_cache) {
3780 qemu_anon_ram_free(block->colo_cache, block->used_length);
3781 block->colo_cache = NULL;
3782 }
3783 }
3784
3785 rcu_read_unlock();
3786 return -errno;
3787}
3788
3789/* It is need to hold the global lock to call this helper */
3790void colo_release_ram_cache(void)
3791{
3792 RAMBlock *block;
3793
d1955d22 3794 memory_global_dirty_log_stop();
fbd162e6 3795 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
7d9acafa
ZC
3796 g_free(block->bmap);
3797 block->bmap = NULL;
3798 }
3799
13af18f2 3800 rcu_read_lock();
7d9acafa 3801
fbd162e6 3802 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
13af18f2
ZC
3803 if (block->colo_cache) {
3804 qemu_anon_ram_free(block->colo_cache, block->used_length);
3805 block->colo_cache = NULL;
3806 }
3807 }
7d9acafa 3808
13af18f2 3809 rcu_read_unlock();
7d9acafa
ZC
3810 g_free(ram_state);
3811 ram_state = NULL;
13af18f2
ZC
3812}
3813
f265e0e4
JQ
3814/**
3815 * ram_load_setup: Setup RAM for migration incoming side
3816 *
3817 * Returns zero to indicate success and negative for error
3818 *
3819 * @f: QEMUFile where to receive the data
3820 * @opaque: RAMState pointer
3821 */
3822static int ram_load_setup(QEMUFile *f, void *opaque)
3823{
34ab9e97 3824 if (compress_threads_load_setup(f)) {
797ca154
XG
3825 return -1;
3826 }
3827
f265e0e4 3828 xbzrle_load_setup();
f9494614 3829 ramblock_recv_map_init();
13af18f2 3830
f265e0e4
JQ
3831 return 0;
3832}
3833
3834static int ram_load_cleanup(void *opaque)
3835{
f9494614 3836 RAMBlock *rb;
56eb90af 3837
fbd162e6 3838 RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
56eb90af
JH
3839 if (ramblock_is_pmem(rb)) {
3840 pmem_persist(rb->host, rb->used_length);
3841 }
3842 }
3843
f265e0e4 3844 xbzrle_load_cleanup();
f0afa331 3845 compress_threads_load_cleanup();
f9494614 3846
fbd162e6 3847 RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
f9494614
AP
3848 g_free(rb->receivedmap);
3849 rb->receivedmap = NULL;
3850 }
13af18f2 3851
f265e0e4
JQ
3852 return 0;
3853}
3854
3d0684b2
JQ
3855/**
3856 * ram_postcopy_incoming_init: allocate postcopy data structures
3857 *
3858 * Returns 0 for success and negative if there was one error
3859 *
3860 * @mis: current migration incoming state
3861 *
3862 * Allocate data structures etc needed by incoming migration with
3863 * postcopy-ram. postcopy-ram's similarly names
3864 * postcopy_ram_incoming_init does the work.
1caddf8a
DDAG
3865 */
3866int ram_postcopy_incoming_init(MigrationIncomingState *mis)
3867{
c136180c 3868 return postcopy_ram_incoming_init(mis);
1caddf8a
DDAG
3869}
3870
3d0684b2
JQ
3871/**
3872 * ram_load_postcopy: load a page in postcopy case
3873 *
3874 * Returns 0 for success or -errno in case of error
3875 *
a7180877
DDAG
3876 * Called in postcopy mode by ram_load().
3877 * rcu_read_lock is taken prior to this being called.
3d0684b2
JQ
3878 *
3879 * @f: QEMUFile where to send the data
a7180877
DDAG
3880 */
3881static int ram_load_postcopy(QEMUFile *f)
3882{
3883 int flags = 0, ret = 0;
3884 bool place_needed = false;
1aa83678 3885 bool matches_target_page_size = false;
a7180877
DDAG
3886 MigrationIncomingState *mis = migration_incoming_get_current();
3887 /* Temporary page that is later 'placed' */
3888 void *postcopy_host_page = postcopy_get_tmp_page(mis);
c53b7ddc 3889 void *last_host = NULL;
a3b6ff6d 3890 bool all_zero = false;
a7180877
DDAG
3891
3892 while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
3893 ram_addr_t addr;
3894 void *host = NULL;
3895 void *page_buffer = NULL;
3896 void *place_source = NULL;
df9ff5e1 3897 RAMBlock *block = NULL;
a7180877 3898 uint8_t ch;
a7180877
DDAG
3899
3900 addr = qemu_get_be64(f);
7a9ddfbf
PX
3901
3902 /*
3903 * If qemu file error, we should stop here, and then "addr"
3904 * may be invalid
3905 */
3906 ret = qemu_file_get_error(f);
3907 if (ret) {
3908 break;
3909 }
3910
a7180877
DDAG
3911 flags = addr & ~TARGET_PAGE_MASK;
3912 addr &= TARGET_PAGE_MASK;
3913
3914 trace_ram_load_postcopy_loop((uint64_t)addr, flags);
3915 place_needed = false;
bb890ed5 3916 if (flags & (RAM_SAVE_FLAG_ZERO | RAM_SAVE_FLAG_PAGE)) {
df9ff5e1 3917 block = ram_block_from_stream(f, flags);
4c4bad48
HZ
3918
3919 host = host_from_ram_block_offset(block, addr);
a7180877
DDAG
3920 if (!host) {
3921 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
3922 ret = -EINVAL;
3923 break;
3924 }
1aa83678 3925 matches_target_page_size = block->page_size == TARGET_PAGE_SIZE;
a7180877 3926 /*
28abd200
DDAG
3927 * Postcopy requires that we place whole host pages atomically;
3928 * these may be huge pages for RAMBlocks that are backed by
3929 * hugetlbfs.
a7180877
DDAG
3930 * To make it atomic, the data is read into a temporary page
3931 * that's moved into place later.
3932 * The migration protocol uses, possibly smaller, target-pages
3933 * however the source ensures it always sends all the components
3934 * of a host page in order.
3935 */
3936 page_buffer = postcopy_host_page +
28abd200 3937 ((uintptr_t)host & (block->page_size - 1));
a7180877 3938 /* If all TP are zero then we can optimise the place */
28abd200 3939 if (!((uintptr_t)host & (block->page_size - 1))) {
a7180877 3940 all_zero = true;
c53b7ddc
DDAG
3941 } else {
3942 /* not the 1st TP within the HP */
3943 if (host != (last_host + TARGET_PAGE_SIZE)) {
9af9e0fe 3944 error_report("Non-sequential target page %p/%p",
c53b7ddc
DDAG
3945 host, last_host);
3946 ret = -EINVAL;
3947 break;
3948 }
a7180877
DDAG
3949 }
3950
c53b7ddc 3951
a7180877
DDAG
3952 /*
3953 * If it's the last part of a host page then we place the host
3954 * page
3955 */
3956 place_needed = (((uintptr_t)host + TARGET_PAGE_SIZE) &
28abd200 3957 (block->page_size - 1)) == 0;
a7180877
DDAG
3958 place_source = postcopy_host_page;
3959 }
c53b7ddc 3960 last_host = host;
a7180877
DDAG
3961
3962 switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
bb890ed5 3963 case RAM_SAVE_FLAG_ZERO:
a7180877
DDAG
3964 ch = qemu_get_byte(f);
3965 memset(page_buffer, ch, TARGET_PAGE_SIZE);
3966 if (ch) {
3967 all_zero = false;
3968 }
3969 break;
3970
3971 case RAM_SAVE_FLAG_PAGE:
3972 all_zero = false;
1aa83678
PX
3973 if (!matches_target_page_size) {
3974 /* For huge pages, we always use temporary buffer */
a7180877
DDAG
3975 qemu_get_buffer(f, page_buffer, TARGET_PAGE_SIZE);
3976 } else {
1aa83678
PX
3977 /*
3978 * For small pages that matches target page size, we
3979 * avoid the qemu_file copy. Instead we directly use
3980 * the buffer of QEMUFile to place the page. Note: we
3981 * cannot do any QEMUFile operation before using that
3982 * buffer to make sure the buffer is valid when
3983 * placing the page.
a7180877
DDAG
3984 */
3985 qemu_get_buffer_in_place(f, (uint8_t **)&place_source,
3986 TARGET_PAGE_SIZE);
3987 }
3988 break;
3989 case RAM_SAVE_FLAG_EOS:
3990 /* normal exit */
6df264ac 3991 multifd_recv_sync_main();
a7180877
DDAG
3992 break;
3993 default:
3994 error_report("Unknown combination of migration flags: %#x"
3995 " (postcopy mode)", flags);
3996 ret = -EINVAL;
7a9ddfbf
PX
3997 break;
3998 }
3999
4000 /* Detect for any possible file errors */
4001 if (!ret && qemu_file_get_error(f)) {
4002 ret = qemu_file_get_error(f);
a7180877
DDAG
4003 }
4004
7a9ddfbf 4005 if (!ret && place_needed) {
a7180877 4006 /* This gets called at the last target page in the host page */
df9ff5e1
DDAG
4007 void *place_dest = host + TARGET_PAGE_SIZE - block->page_size;
4008
a7180877 4009 if (all_zero) {
df9ff5e1 4010 ret = postcopy_place_page_zero(mis, place_dest,
8be4620b 4011 block);
a7180877 4012 } else {
df9ff5e1 4013 ret = postcopy_place_page(mis, place_dest,
8be4620b 4014 place_source, block);
a7180877
DDAG
4015 }
4016 }
a7180877
DDAG
4017 }
4018
4019 return ret;
4020}
4021
acab30b8
DHB
4022static bool postcopy_is_advised(void)
4023{
4024 PostcopyState ps = postcopy_state_get();
4025 return ps >= POSTCOPY_INCOMING_ADVISE && ps < POSTCOPY_INCOMING_END;
4026}
4027
4028static bool postcopy_is_running(void)
4029{
4030 PostcopyState ps = postcopy_state_get();
4031 return ps >= POSTCOPY_INCOMING_LISTENING && ps < POSTCOPY_INCOMING_END;
4032}
4033
e6f4aa18
ZC
4034/*
4035 * Flush content of RAM cache into SVM's memory.
4036 * Only flush the pages that be dirtied by PVM or SVM or both.
4037 */
4038static void colo_flush_ram_cache(void)
4039{
4040 RAMBlock *block = NULL;
4041 void *dst_host;
4042 void *src_host;
4043 unsigned long offset = 0;
4044
d1955d22
HZ
4045 memory_global_dirty_log_sync();
4046 rcu_read_lock();
fbd162e6 4047 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
d1955d22
HZ
4048 migration_bitmap_sync_range(ram_state, block, 0, block->used_length);
4049 }
4050 rcu_read_unlock();
4051
e6f4aa18
ZC
4052 trace_colo_flush_ram_cache_begin(ram_state->migration_dirty_pages);
4053 rcu_read_lock();
4054 block = QLIST_FIRST_RCU(&ram_list.blocks);
4055
4056 while (block) {
4057 offset = migration_bitmap_find_dirty(ram_state, block, offset);
4058
4059 if (offset << TARGET_PAGE_BITS >= block->used_length) {
4060 offset = 0;
4061 block = QLIST_NEXT_RCU(block, next);
4062 } else {
4063 migration_bitmap_clear_dirty(ram_state, block, offset);
4064 dst_host = block->host + (offset << TARGET_PAGE_BITS);
4065 src_host = block->colo_cache + (offset << TARGET_PAGE_BITS);
4066 memcpy(dst_host, src_host, TARGET_PAGE_SIZE);
4067 }
4068 }
4069
4070 rcu_read_unlock();
4071 trace_colo_flush_ram_cache_end();
4072}
4073
56e93d26
JQ
4074static int ram_load(QEMUFile *f, void *opaque, int version_id)
4075{
edc60127 4076 int flags = 0, ret = 0, invalid_flags = 0;
56e93d26
JQ
4077 static uint64_t seq_iter;
4078 int len = 0;
a7180877
DDAG
4079 /*
4080 * If system is running in postcopy mode, page inserts to host memory must
4081 * be atomic
4082 */
acab30b8 4083 bool postcopy_running = postcopy_is_running();
ef08fb38 4084 /* ADVISE is earlier, it shows the source has the postcopy capability on */
acab30b8 4085 bool postcopy_advised = postcopy_is_advised();
56e93d26
JQ
4086
4087 seq_iter++;
4088
4089 if (version_id != 4) {
4090 ret = -EINVAL;
4091 }
4092
edc60127
JQ
4093 if (!migrate_use_compression()) {
4094 invalid_flags |= RAM_SAVE_FLAG_COMPRESS_PAGE;
4095 }
56e93d26
JQ
4096 /* This RCU critical section can be very long running.
4097 * When RCU reclaims in the code start to become numerous,
4098 * it will be necessary to reduce the granularity of this
4099 * critical section.
4100 */
4101 rcu_read_lock();
a7180877
DDAG
4102
4103 if (postcopy_running) {
4104 ret = ram_load_postcopy(f);
4105 }
4106
4107 while (!postcopy_running && !ret && !(flags & RAM_SAVE_FLAG_EOS)) {
56e93d26 4108 ram_addr_t addr, total_ram_bytes;
a776aa15 4109 void *host = NULL;
56e93d26
JQ
4110 uint8_t ch;
4111
4112 addr = qemu_get_be64(f);
4113 flags = addr & ~TARGET_PAGE_MASK;
4114 addr &= TARGET_PAGE_MASK;
4115
edc60127
JQ
4116 if (flags & invalid_flags) {
4117 if (flags & invalid_flags & RAM_SAVE_FLAG_COMPRESS_PAGE) {
4118 error_report("Received an unexpected compressed page");
4119 }
4120
4121 ret = -EINVAL;
4122 break;
4123 }
4124
bb890ed5 4125 if (flags & (RAM_SAVE_FLAG_ZERO | RAM_SAVE_FLAG_PAGE |
a776aa15 4126 RAM_SAVE_FLAG_COMPRESS_PAGE | RAM_SAVE_FLAG_XBZRLE)) {
4c4bad48
HZ
4127 RAMBlock *block = ram_block_from_stream(f, flags);
4128
13af18f2
ZC
4129 /*
4130 * After going into COLO, we should load the Page into colo_cache.
4131 */
4132 if (migration_incoming_in_colo_state()) {
4133 host = colo_cache_from_block_offset(block, addr);
4134 } else {
4135 host = host_from_ram_block_offset(block, addr);
4136 }
a776aa15
DDAG
4137 if (!host) {
4138 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
4139 ret = -EINVAL;
4140 break;
4141 }
13af18f2
ZC
4142
4143 if (!migration_incoming_in_colo_state()) {
4144 ramblock_recv_bitmap_set(block, host);
4145 }
4146
1db9d8e5 4147 trace_ram_load_loop(block->idstr, (uint64_t)addr, flags, host);
a776aa15
DDAG
4148 }
4149
56e93d26
JQ
4150 switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
4151 case RAM_SAVE_FLAG_MEM_SIZE:
4152 /* Synchronize RAM block list */
4153 total_ram_bytes = addr;
4154 while (!ret && total_ram_bytes) {
4155 RAMBlock *block;
56e93d26
JQ
4156 char id[256];
4157 ram_addr_t length;
4158
4159 len = qemu_get_byte(f);
4160 qemu_get_buffer(f, (uint8_t *)id, len);
4161 id[len] = 0;
4162 length = qemu_get_be64(f);
4163
e3dd7493 4164 block = qemu_ram_block_by_name(id);
b895de50
CLG
4165 if (block && !qemu_ram_is_migratable(block)) {
4166 error_report("block %s should not be migrated !", id);
4167 ret = -EINVAL;
4168 } else if (block) {
e3dd7493
DDAG
4169 if (length != block->used_length) {
4170 Error *local_err = NULL;
56e93d26 4171
fa53a0e5 4172 ret = qemu_ram_resize(block, length,
e3dd7493
DDAG
4173 &local_err);
4174 if (local_err) {
4175 error_report_err(local_err);
56e93d26 4176 }
56e93d26 4177 }
ef08fb38
DDAG
4178 /* For postcopy we need to check hugepage sizes match */
4179 if (postcopy_advised &&
4180 block->page_size != qemu_host_page_size) {
4181 uint64_t remote_page_size = qemu_get_be64(f);
4182 if (remote_page_size != block->page_size) {
4183 error_report("Mismatched RAM page size %s "
4184 "(local) %zd != %" PRId64,
4185 id, block->page_size,
4186 remote_page_size);
4187 ret = -EINVAL;
4188 }
4189 }
fbd162e6
YK
4190 if (migrate_ignore_shared()) {
4191 hwaddr addr = qemu_get_be64(f);
4192 bool ignored = qemu_get_byte(f);
4193 if (ignored != ramblock_is_ignored(block)) {
4194 error_report("RAM block %s should %s be migrated",
4195 id, ignored ? "" : "not");
4196 ret = -EINVAL;
4197 }
4198 if (ramblock_is_ignored(block) &&
4199 block->mr->addr != addr) {
4200 error_report("Mismatched GPAs for block %s "
4201 "%" PRId64 "!= %" PRId64,
4202 id, (uint64_t)addr,
4203 (uint64_t)block->mr->addr);
4204 ret = -EINVAL;
4205 }
4206 }
e3dd7493
DDAG
4207 ram_control_load_hook(f, RAM_CONTROL_BLOCK_REG,
4208 block->idstr);
4209 } else {
56e93d26
JQ
4210 error_report("Unknown ramblock \"%s\", cannot "
4211 "accept migration", id);
4212 ret = -EINVAL;
4213 }
4214
4215 total_ram_bytes -= length;
4216 }
4217 break;
a776aa15 4218
bb890ed5 4219 case RAM_SAVE_FLAG_ZERO:
56e93d26
JQ
4220 ch = qemu_get_byte(f);
4221 ram_handle_compressed(host, ch, TARGET_PAGE_SIZE);
4222 break;
a776aa15 4223
56e93d26 4224 case RAM_SAVE_FLAG_PAGE:
56e93d26
JQ
4225 qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
4226 break;
56e93d26 4227
a776aa15 4228 case RAM_SAVE_FLAG_COMPRESS_PAGE:
56e93d26
JQ
4229 len = qemu_get_be32(f);
4230 if (len < 0 || len > compressBound(TARGET_PAGE_SIZE)) {
4231 error_report("Invalid compressed data length: %d", len);
4232 ret = -EINVAL;
4233 break;
4234 }
c1bc6626 4235 decompress_data_with_multi_threads(f, host, len);
56e93d26 4236 break;
a776aa15 4237
56e93d26 4238 case RAM_SAVE_FLAG_XBZRLE:
56e93d26
JQ
4239 if (load_xbzrle(f, addr, host) < 0) {
4240 error_report("Failed to decompress XBZRLE page at "
4241 RAM_ADDR_FMT, addr);
4242 ret = -EINVAL;
4243 break;
4244 }
4245 break;
4246 case RAM_SAVE_FLAG_EOS:
4247 /* normal exit */
6df264ac 4248 multifd_recv_sync_main();
56e93d26
JQ
4249 break;
4250 default:
4251 if (flags & RAM_SAVE_FLAG_HOOK) {
632e3a5c 4252 ram_control_load_hook(f, RAM_CONTROL_HOOK, NULL);
56e93d26
JQ
4253 } else {
4254 error_report("Unknown combination of migration flags: %#x",
4255 flags);
4256 ret = -EINVAL;
4257 }
4258 }
4259 if (!ret) {
4260 ret = qemu_file_get_error(f);
4261 }
4262 }
4263
34ab9e97 4264 ret |= wait_for_decompress_done();
56e93d26 4265 rcu_read_unlock();
55c4446b 4266 trace_ram_load_complete(ret, seq_iter);
e6f4aa18
ZC
4267
4268 if (!ret && migration_incoming_in_colo_state()) {
4269 colo_flush_ram_cache();
4270 }
56e93d26
JQ
4271 return ret;
4272}
4273
c6467627
VSO
4274static bool ram_has_postcopy(void *opaque)
4275{
469dd51b 4276 RAMBlock *rb;
fbd162e6 4277 RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
469dd51b
JH
4278 if (ramblock_is_pmem(rb)) {
4279 info_report("Block: %s, host: %p is a nvdimm memory, postcopy"
4280 "is not supported now!", rb->idstr, rb->host);
4281 return false;
4282 }
4283 }
4284
c6467627
VSO
4285 return migrate_postcopy_ram();
4286}
4287
edd090c7
PX
4288/* Sync all the dirty bitmap with destination VM. */
4289static int ram_dirty_bitmap_sync_all(MigrationState *s, RAMState *rs)
4290{
4291 RAMBlock *block;
4292 QEMUFile *file = s->to_dst_file;
4293 int ramblock_count = 0;
4294
4295 trace_ram_dirty_bitmap_sync_start();
4296
fbd162e6 4297 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
edd090c7
PX
4298 qemu_savevm_send_recv_bitmap(file, block->idstr);
4299 trace_ram_dirty_bitmap_request(block->idstr);
4300 ramblock_count++;
4301 }
4302
4303 trace_ram_dirty_bitmap_sync_wait();
4304
4305 /* Wait until all the ramblocks' dirty bitmap synced */
4306 while (ramblock_count--) {
4307 qemu_sem_wait(&s->rp_state.rp_sem);
4308 }
4309
4310 trace_ram_dirty_bitmap_sync_complete();
4311
4312 return 0;
4313}
4314
4315static void ram_dirty_bitmap_reload_notify(MigrationState *s)
4316{
4317 qemu_sem_post(&s->rp_state.rp_sem);
4318}
4319
a335debb
PX
4320/*
4321 * Read the received bitmap, revert it as the initial dirty bitmap.
4322 * This is only used when the postcopy migration is paused but wants
4323 * to resume from a middle point.
4324 */
4325int ram_dirty_bitmap_reload(MigrationState *s, RAMBlock *block)
4326{
4327 int ret = -EINVAL;
4328 QEMUFile *file = s->rp_state.from_dst_file;
4329 unsigned long *le_bitmap, nbits = block->used_length >> TARGET_PAGE_BITS;
a725ef9f 4330 uint64_t local_size = DIV_ROUND_UP(nbits, 8);
a335debb
PX
4331 uint64_t size, end_mark;
4332
4333 trace_ram_dirty_bitmap_reload_begin(block->idstr);
4334
4335 if (s->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
4336 error_report("%s: incorrect state %s", __func__,
4337 MigrationStatus_str(s->state));
4338 return -EINVAL;
4339 }
4340
4341 /*
4342 * Note: see comments in ramblock_recv_bitmap_send() on why we
4343 * need the endianess convertion, and the paddings.
4344 */
4345 local_size = ROUND_UP(local_size, 8);
4346
4347 /* Add paddings */
4348 le_bitmap = bitmap_new(nbits + BITS_PER_LONG);
4349
4350 size = qemu_get_be64(file);
4351
4352 /* The size of the bitmap should match with our ramblock */
4353 if (size != local_size) {
4354 error_report("%s: ramblock '%s' bitmap size mismatch "
4355 "(0x%"PRIx64" != 0x%"PRIx64")", __func__,
4356 block->idstr, size, local_size);
4357 ret = -EINVAL;
4358 goto out;
4359 }
4360
4361 size = qemu_get_buffer(file, (uint8_t *)le_bitmap, local_size);
4362 end_mark = qemu_get_be64(file);
4363
4364 ret = qemu_file_get_error(file);
4365 if (ret || size != local_size) {
4366 error_report("%s: read bitmap failed for ramblock '%s': %d"
4367 " (size 0x%"PRIx64", got: 0x%"PRIx64")",
4368 __func__, block->idstr, ret, local_size, size);
4369 ret = -EIO;
4370 goto out;
4371 }
4372
4373 if (end_mark != RAMBLOCK_RECV_BITMAP_ENDING) {
4374 error_report("%s: ramblock '%s' end mark incorrect: 0x%"PRIu64,
4375 __func__, block->idstr, end_mark);
4376 ret = -EINVAL;
4377 goto out;
4378 }
4379
4380 /*
4381 * Endianess convertion. We are during postcopy (though paused).
4382 * The dirty bitmap won't change. We can directly modify it.
4383 */
4384 bitmap_from_le(block->bmap, le_bitmap, nbits);
4385
4386 /*
4387 * What we received is "received bitmap". Revert it as the initial
4388 * dirty bitmap for this ramblock.
4389 */
4390 bitmap_complement(block->bmap, block->bmap, nbits);
4391
4392 trace_ram_dirty_bitmap_reload_complete(block->idstr);
4393
edd090c7
PX
4394 /*
4395 * We succeeded to sync bitmap for current ramblock. If this is
4396 * the last one to sync, we need to notify the main send thread.
4397 */
4398 ram_dirty_bitmap_reload_notify(s);
4399
a335debb
PX
4400 ret = 0;
4401out:
bf269906 4402 g_free(le_bitmap);
a335debb
PX
4403 return ret;
4404}
4405
edd090c7
PX
4406static int ram_resume_prepare(MigrationState *s, void *opaque)
4407{
4408 RAMState *rs = *(RAMState **)opaque;
08614f34 4409 int ret;
edd090c7 4410
08614f34
PX
4411 ret = ram_dirty_bitmap_sync_all(s, rs);
4412 if (ret) {
4413 return ret;
4414 }
4415
4416 ram_state_resume_prepare(rs, s->to_dst_file);
4417
4418 return 0;
edd090c7
PX
4419}
4420
56e93d26 4421static SaveVMHandlers savevm_ram_handlers = {
9907e842 4422 .save_setup = ram_save_setup,
56e93d26 4423 .save_live_iterate = ram_save_iterate,
763c906b 4424 .save_live_complete_postcopy = ram_save_complete,
a3e06c3d 4425 .save_live_complete_precopy = ram_save_complete,
c6467627 4426 .has_postcopy = ram_has_postcopy,
56e93d26
JQ
4427 .save_live_pending = ram_save_pending,
4428 .load_state = ram_load,
f265e0e4
JQ
4429 .save_cleanup = ram_save_cleanup,
4430 .load_setup = ram_load_setup,
4431 .load_cleanup = ram_load_cleanup,
edd090c7 4432 .resume_prepare = ram_resume_prepare,
56e93d26
JQ
4433};
4434
4435void ram_mig_init(void)
4436{
4437 qemu_mutex_init(&XBZRLE.lock);
6f37bb8b 4438 register_savevm_live(NULL, "ram", 0, 4, &savevm_ram_handlers, &ram_state);
56e93d26 4439}