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