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