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