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