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