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