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