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