xref: /qemu/migration/ram.c (revision b103cc6e74ac92f070a0e004bd84334e845c20b5)
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 "system/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     /* Hand over to RDMA first */
1968     if (control_save_page(pss, offset, &res)) {
1969         return res;
1970     }
1971 
1972     if (!migrate_multifd()
1973         || migrate_zero_page_detection() == ZERO_PAGE_DETECTION_LEGACY) {
1974         if (save_zero_page(rs, pss, offset)) {
1975             return 1;
1976         }
1977     }
1978 
1979     if (migrate_multifd()) {
1980         RAMBlock *block = pss->block;
1981         return ram_save_multifd_page(block, offset);
1982     }
1983 
1984     return ram_save_page(rs, pss);
1985 }
1986 
1987 /* Should be called before sending a host page */
1988 static void pss_host_page_prepare(PageSearchStatus *pss)
1989 {
1990     /* How many guest pages are there in one host page? */
1991     size_t guest_pfns = qemu_ram_pagesize(pss->block) >> TARGET_PAGE_BITS;
1992 
1993     pss->host_page_sending = true;
1994     if (guest_pfns <= 1) {
1995         /*
1996          * This covers both when guest psize == host psize, or when guest
1997          * has larger psize than the host (guest_pfns==0).
1998          *
1999          * For the latter, we always send one whole guest page per
2000          * iteration of the host page (example: an Alpha VM on x86 host
2001          * will have guest psize 8K while host psize 4K).
2002          */
2003         pss->host_page_start = pss->page;
2004         pss->host_page_end = pss->page + 1;
2005     } else {
2006         /*
2007          * The host page spans over multiple guest pages, we send them
2008          * within the same host page iteration.
2009          */
2010         pss->host_page_start = ROUND_DOWN(pss->page, guest_pfns);
2011         pss->host_page_end = ROUND_UP(pss->page + 1, guest_pfns);
2012     }
2013 }
2014 
2015 /*
2016  * Whether the page pointed by PSS is within the host page being sent.
2017  * Must be called after a previous pss_host_page_prepare().
2018  */
2019 static bool pss_within_range(PageSearchStatus *pss)
2020 {
2021     ram_addr_t ram_addr;
2022 
2023     assert(pss->host_page_sending);
2024 
2025     /* Over host-page boundary? */
2026     if (pss->page >= pss->host_page_end) {
2027         return false;
2028     }
2029 
2030     ram_addr = ((ram_addr_t)pss->page) << TARGET_PAGE_BITS;
2031 
2032     return offset_in_ramblock(pss->block, ram_addr);
2033 }
2034 
2035 static void pss_host_page_finish(PageSearchStatus *pss)
2036 {
2037     pss->host_page_sending = false;
2038     /* This is not needed, but just to reset it */
2039     pss->host_page_start = pss->host_page_end = 0;
2040 }
2041 
2042 /*
2043  * Send an urgent host page specified by `pss'.  Need to be called with
2044  * bitmap_mutex held.
2045  *
2046  * Returns 0 if save host page succeeded, false otherwise.
2047  */
2048 static int ram_save_host_page_urgent(PageSearchStatus *pss)
2049 {
2050     bool page_dirty, sent = false;
2051     RAMState *rs = ram_state;
2052     int ret = 0;
2053 
2054     trace_postcopy_preempt_send_host_page(pss->block->idstr, pss->page);
2055     pss_host_page_prepare(pss);
2056 
2057     /*
2058      * If precopy is sending the same page, let it be done in precopy, or
2059      * we could send the same page in two channels and none of them will
2060      * receive the whole page.
2061      */
2062     if (pss_overlap(pss, &ram_state->pss[RAM_CHANNEL_PRECOPY])) {
2063         trace_postcopy_preempt_hit(pss->block->idstr,
2064                                    pss->page << TARGET_PAGE_BITS);
2065         return 0;
2066     }
2067 
2068     do {
2069         page_dirty = migration_bitmap_clear_dirty(rs, pss->block, pss->page);
2070 
2071         if (page_dirty) {
2072             /* Be strict to return code; it must be 1, or what else? */
2073             if (ram_save_target_page(rs, pss) != 1) {
2074                 error_report_once("%s: ram_save_target_page failed", __func__);
2075                 ret = -1;
2076                 goto out;
2077             }
2078             sent = true;
2079         }
2080         pss_find_next_dirty(pss);
2081     } while (pss_within_range(pss));
2082 out:
2083     pss_host_page_finish(pss);
2084     /* For urgent requests, flush immediately if sent */
2085     if (sent) {
2086         qemu_fflush(pss->pss_channel);
2087     }
2088     return ret;
2089 }
2090 
2091 /**
2092  * ram_save_host_page: save a whole host page
2093  *
2094  * Starting at *offset send pages up to the end of the current host
2095  * page. It's valid for the initial offset to point into the middle of
2096  * a host page in which case the remainder of the hostpage is sent.
2097  * Only dirty target pages are sent. Note that the host page size may
2098  * be a huge page for this block.
2099  *
2100  * The saving stops at the boundary of the used_length of the block
2101  * if the RAMBlock isn't a multiple of the host page size.
2102  *
2103  * The caller must be with ram_state.bitmap_mutex held to call this
2104  * function.  Note that this function can temporarily release the lock, but
2105  * when the function is returned it'll make sure the lock is still held.
2106  *
2107  * Returns the number of pages written or negative on error
2108  *
2109  * @rs: current RAM state
2110  * @pss: data about the page we want to send
2111  */
2112 static int ram_save_host_page(RAMState *rs, PageSearchStatus *pss)
2113 {
2114     bool page_dirty, preempt_active = postcopy_preempt_active();
2115     int tmppages, pages = 0;
2116     size_t pagesize_bits =
2117         qemu_ram_pagesize(pss->block) >> TARGET_PAGE_BITS;
2118     unsigned long start_page = pss->page;
2119     int res;
2120 
2121     if (migrate_ram_is_ignored(pss->block)) {
2122         error_report("block %s should not be migrated !", pss->block->idstr);
2123         return 0;
2124     }
2125 
2126     /* Update host page boundary information */
2127     pss_host_page_prepare(pss);
2128 
2129     do {
2130         page_dirty = migration_bitmap_clear_dirty(rs, pss->block, pss->page);
2131 
2132         /* Check the pages is dirty and if it is send it */
2133         if (page_dirty) {
2134             /*
2135              * Properly yield the lock only in postcopy preempt mode
2136              * because both migration thread and rp-return thread can
2137              * operate on the bitmaps.
2138              */
2139             if (preempt_active) {
2140                 qemu_mutex_unlock(&rs->bitmap_mutex);
2141             }
2142             tmppages = ram_save_target_page(rs, pss);
2143             if (tmppages >= 0) {
2144                 pages += tmppages;
2145                 /*
2146                  * Allow rate limiting to happen in the middle of huge pages if
2147                  * something is sent in the current iteration.
2148                  */
2149                 if (pagesize_bits > 1 && tmppages > 0) {
2150                     migration_rate_limit();
2151                 }
2152             }
2153             if (preempt_active) {
2154                 qemu_mutex_lock(&rs->bitmap_mutex);
2155             }
2156         } else {
2157             tmppages = 0;
2158         }
2159 
2160         if (tmppages < 0) {
2161             pss_host_page_finish(pss);
2162             return tmppages;
2163         }
2164 
2165         pss_find_next_dirty(pss);
2166     } while (pss_within_range(pss));
2167 
2168     pss_host_page_finish(pss);
2169 
2170     res = ram_save_release_protection(rs, pss, start_page);
2171     return (res < 0 ? res : pages);
2172 }
2173 
2174 /**
2175  * ram_find_and_save_block: finds a dirty page and sends it to f
2176  *
2177  * Called within an RCU critical section.
2178  *
2179  * Returns the number of pages written where zero means no dirty pages,
2180  * or negative on error
2181  *
2182  * @rs: current RAM state
2183  *
2184  * On systems where host-page-size > target-page-size it will send all the
2185  * pages in a host page that are dirty.
2186  */
2187 static int ram_find_and_save_block(RAMState *rs)
2188 {
2189     PageSearchStatus *pss = &rs->pss[RAM_CHANNEL_PRECOPY];
2190     int pages = 0;
2191 
2192     /* No dirty page as there is zero RAM */
2193     if (!rs->ram_bytes_total) {
2194         return pages;
2195     }
2196 
2197     /*
2198      * Always keep last_seen_block/last_page valid during this procedure,
2199      * because find_dirty_block() relies on these values (e.g., we compare
2200      * last_seen_block with pss.block to see whether we searched all the
2201      * ramblocks) to detect the completion of migration.  Having NULL value
2202      * of last_seen_block can conditionally cause below loop to run forever.
2203      */
2204     if (!rs->last_seen_block) {
2205         rs->last_seen_block = QLIST_FIRST_RCU(&ram_list.blocks);
2206         rs->last_page = 0;
2207     }
2208 
2209     pss_init(pss, rs->last_seen_block, rs->last_page);
2210 
2211     while (true){
2212         if (!get_queued_page(rs, pss)) {
2213             /* priority queue empty, so just search for something dirty */
2214             int res = find_dirty_block(rs, pss);
2215             if (res != PAGE_DIRTY_FOUND) {
2216                 if (res == PAGE_ALL_CLEAN) {
2217                     break;
2218                 } else if (res == PAGE_TRY_AGAIN) {
2219                     continue;
2220                 } else if (res < 0) {
2221                     pages = res;
2222                     break;
2223                 }
2224             }
2225         }
2226         pages = ram_save_host_page(rs, pss);
2227         if (pages) {
2228             break;
2229         }
2230     }
2231 
2232     rs->last_seen_block = pss->block;
2233     rs->last_page = pss->page;
2234 
2235     return pages;
2236 }
2237 
2238 static uint64_t ram_bytes_total_with_ignored(void)
2239 {
2240     RAMBlock *block;
2241     uint64_t total = 0;
2242 
2243     RCU_READ_LOCK_GUARD();
2244 
2245     RAMBLOCK_FOREACH_MIGRATABLE(block) {
2246         total += block->used_length;
2247     }
2248     return total;
2249 }
2250 
2251 uint64_t ram_bytes_total(void)
2252 {
2253     RAMBlock *block;
2254     uint64_t total = 0;
2255 
2256     RCU_READ_LOCK_GUARD();
2257 
2258     RAMBLOCK_FOREACH_NOT_IGNORED(block) {
2259         total += block->used_length;
2260     }
2261     return total;
2262 }
2263 
2264 static void xbzrle_load_setup(void)
2265 {
2266     XBZRLE.decoded_buf = g_malloc(TARGET_PAGE_SIZE);
2267 }
2268 
2269 static void xbzrle_load_cleanup(void)
2270 {
2271     g_free(XBZRLE.decoded_buf);
2272     XBZRLE.decoded_buf = NULL;
2273 }
2274 
2275 static void ram_state_cleanup(RAMState **rsp)
2276 {
2277     if (*rsp) {
2278         migration_page_queue_free(*rsp);
2279         qemu_mutex_destroy(&(*rsp)->bitmap_mutex);
2280         qemu_mutex_destroy(&(*rsp)->src_page_req_mutex);
2281         g_free(*rsp);
2282         *rsp = NULL;
2283     }
2284 }
2285 
2286 static void xbzrle_cleanup(void)
2287 {
2288     XBZRLE_cache_lock();
2289     if (XBZRLE.cache) {
2290         cache_fini(XBZRLE.cache);
2291         g_free(XBZRLE.encoded_buf);
2292         g_free(XBZRLE.current_buf);
2293         g_free(XBZRLE.zero_target_page);
2294         XBZRLE.cache = NULL;
2295         XBZRLE.encoded_buf = NULL;
2296         XBZRLE.current_buf = NULL;
2297         XBZRLE.zero_target_page = NULL;
2298     }
2299     XBZRLE_cache_unlock();
2300 }
2301 
2302 static void ram_bitmaps_destroy(void)
2303 {
2304     RAMBlock *block;
2305 
2306     RAMBLOCK_FOREACH_NOT_IGNORED(block) {
2307         g_free(block->clear_bmap);
2308         block->clear_bmap = NULL;
2309         g_free(block->bmap);
2310         block->bmap = NULL;
2311         g_free(block->file_bmap);
2312         block->file_bmap = NULL;
2313     }
2314 }
2315 
2316 static void ram_save_cleanup(void *opaque)
2317 {
2318     RAMState **rsp = opaque;
2319 
2320     /* We don't use dirty log with background snapshots */
2321     if (!migrate_background_snapshot()) {
2322         /* caller have hold BQL or is in a bh, so there is
2323          * no writing race against the migration bitmap
2324          */
2325         if (global_dirty_tracking & GLOBAL_DIRTY_MIGRATION) {
2326             /*
2327              * do not stop dirty log without starting it, since
2328              * memory_global_dirty_log_stop will assert that
2329              * memory_global_dirty_log_start/stop used in pairs
2330              */
2331             memory_global_dirty_log_stop(GLOBAL_DIRTY_MIGRATION);
2332         }
2333     }
2334 
2335     ram_bitmaps_destroy();
2336 
2337     xbzrle_cleanup();
2338     multifd_ram_save_cleanup();
2339     ram_state_cleanup(rsp);
2340 }
2341 
2342 static void ram_state_reset(RAMState *rs)
2343 {
2344     int i;
2345 
2346     for (i = 0; i < RAM_CHANNEL_MAX; i++) {
2347         rs->pss[i].last_sent_block = NULL;
2348     }
2349 
2350     rs->last_seen_block = NULL;
2351     rs->last_page = 0;
2352     rs->last_version = ram_list.version;
2353     rs->xbzrle_started = false;
2354 }
2355 
2356 #define MAX_WAIT 50 /* ms, half buffered_file limit */
2357 
2358 /* **** functions for postcopy ***** */
2359 
2360 void ram_postcopy_migrated_memory_release(MigrationState *ms)
2361 {
2362     struct RAMBlock *block;
2363 
2364     RAMBLOCK_FOREACH_NOT_IGNORED(block) {
2365         unsigned long *bitmap = block->bmap;
2366         unsigned long range = block->used_length >> TARGET_PAGE_BITS;
2367         unsigned long run_start = find_next_zero_bit(bitmap, range, 0);
2368 
2369         while (run_start < range) {
2370             unsigned long run_end = find_next_bit(bitmap, range, run_start + 1);
2371             ram_discard_range(block->idstr,
2372                               ((ram_addr_t)run_start) << TARGET_PAGE_BITS,
2373                               ((ram_addr_t)(run_end - run_start))
2374                                 << TARGET_PAGE_BITS);
2375             run_start = find_next_zero_bit(bitmap, range, run_end + 1);
2376         }
2377     }
2378 }
2379 
2380 /**
2381  * postcopy_send_discard_bm_ram: discard a RAMBlock
2382  *
2383  * Callback from postcopy_each_ram_send_discard for each RAMBlock
2384  *
2385  * @ms: current migration state
2386  * @block: RAMBlock to discard
2387  */
2388 static void postcopy_send_discard_bm_ram(MigrationState *ms, RAMBlock *block)
2389 {
2390     unsigned long end = block->used_length >> TARGET_PAGE_BITS;
2391     unsigned long current;
2392     unsigned long *bitmap = block->bmap;
2393 
2394     for (current = 0; current < end; ) {
2395         unsigned long one = find_next_bit(bitmap, end, current);
2396         unsigned long zero, discard_length;
2397 
2398         if (one >= end) {
2399             break;
2400         }
2401 
2402         zero = find_next_zero_bit(bitmap, end, one + 1);
2403 
2404         if (zero >= end) {
2405             discard_length = end - one;
2406         } else {
2407             discard_length = zero - one;
2408         }
2409         postcopy_discard_send_range(ms, one, discard_length);
2410         current = one + discard_length;
2411     }
2412 }
2413 
2414 static void postcopy_chunk_hostpages_pass(MigrationState *ms, RAMBlock *block);
2415 
2416 /**
2417  * postcopy_each_ram_send_discard: discard all RAMBlocks
2418  *
2419  * Utility for the outgoing postcopy code.
2420  *   Calls postcopy_send_discard_bm_ram for each RAMBlock
2421  *   passing it bitmap indexes and name.
2422  * (qemu_ram_foreach_block ends up passing unscaled lengths
2423  *  which would mean postcopy code would have to deal with target page)
2424  *
2425  * @ms: current migration state
2426  */
2427 static void postcopy_each_ram_send_discard(MigrationState *ms)
2428 {
2429     struct RAMBlock *block;
2430 
2431     RAMBLOCK_FOREACH_NOT_IGNORED(block) {
2432         postcopy_discard_send_init(ms, block->idstr);
2433 
2434         /*
2435          * Deal with TPS != HPS and huge pages.  It discard any partially sent
2436          * host-page size chunks, mark any partially dirty host-page size
2437          * chunks as all dirty.  In this case the host-page is the host-page
2438          * for the particular RAMBlock, i.e. it might be a huge page.
2439          */
2440         postcopy_chunk_hostpages_pass(ms, block);
2441 
2442         /*
2443          * Postcopy sends chunks of bitmap over the wire, but it
2444          * just needs indexes at this point, avoids it having
2445          * target page specific code.
2446          */
2447         postcopy_send_discard_bm_ram(ms, block);
2448         postcopy_discard_send_finish(ms);
2449     }
2450 }
2451 
2452 /**
2453  * postcopy_chunk_hostpages_pass: canonicalize bitmap in hostpages
2454  *
2455  * Helper for postcopy_chunk_hostpages; it's called twice to
2456  * canonicalize the two bitmaps, that are similar, but one is
2457  * inverted.
2458  *
2459  * Postcopy requires that all target pages in a hostpage are dirty or
2460  * clean, not a mix.  This function canonicalizes the bitmaps.
2461  *
2462  * @ms: current migration state
2463  * @block: block that contains the page we want to canonicalize
2464  */
2465 static void postcopy_chunk_hostpages_pass(MigrationState *ms, RAMBlock *block)
2466 {
2467     RAMState *rs = ram_state;
2468     unsigned long *bitmap = block->bmap;
2469     unsigned int host_ratio = block->page_size / TARGET_PAGE_SIZE;
2470     unsigned long pages = block->used_length >> TARGET_PAGE_BITS;
2471     unsigned long run_start;
2472 
2473     if (block->page_size == TARGET_PAGE_SIZE) {
2474         /* Easy case - TPS==HPS for a non-huge page RAMBlock */
2475         return;
2476     }
2477 
2478     /* Find a dirty page */
2479     run_start = find_next_bit(bitmap, pages, 0);
2480 
2481     while (run_start < pages) {
2482 
2483         /*
2484          * If the start of this run of pages is in the middle of a host
2485          * page, then we need to fixup this host page.
2486          */
2487         if (QEMU_IS_ALIGNED(run_start, host_ratio)) {
2488             /* Find the end of this run */
2489             run_start = find_next_zero_bit(bitmap, pages, run_start + 1);
2490             /*
2491              * If the end isn't at the start of a host page, then the
2492              * run doesn't finish at the end of a host page
2493              * and we need to discard.
2494              */
2495         }
2496 
2497         if (!QEMU_IS_ALIGNED(run_start, host_ratio)) {
2498             unsigned long page;
2499             unsigned long fixup_start_addr = QEMU_ALIGN_DOWN(run_start,
2500                                                              host_ratio);
2501             run_start = QEMU_ALIGN_UP(run_start, host_ratio);
2502 
2503             /* Clean up the bitmap */
2504             for (page = fixup_start_addr;
2505                  page < fixup_start_addr + host_ratio; page++) {
2506                 /*
2507                  * Remark them as dirty, updating the count for any pages
2508                  * that weren't previously dirty.
2509                  */
2510                 rs->migration_dirty_pages += !test_and_set_bit(page, bitmap);
2511             }
2512         }
2513 
2514         /* Find the next dirty page for the next iteration */
2515         run_start = find_next_bit(bitmap, pages, run_start);
2516     }
2517 }
2518 
2519 /**
2520  * ram_postcopy_send_discard_bitmap: transmit the discard bitmap
2521  *
2522  * Transmit the set of pages to be discarded after precopy to the target
2523  * these are pages that:
2524  *     a) Have been previously transmitted but are now dirty again
2525  *     b) Pages that have never been transmitted, this ensures that
2526  *        any pages on the destination that have been mapped by background
2527  *        tasks get discarded (transparent huge pages is the specific concern)
2528  * Hopefully this is pretty sparse
2529  *
2530  * @ms: current migration state
2531  */
2532 void ram_postcopy_send_discard_bitmap(MigrationState *ms)
2533 {
2534     RAMState *rs = ram_state;
2535 
2536     RCU_READ_LOCK_GUARD();
2537 
2538     /* This should be our last sync, the src is now paused */
2539     migration_bitmap_sync(rs, false);
2540 
2541     /* Easiest way to make sure we don't resume in the middle of a host-page */
2542     rs->pss[RAM_CHANNEL_PRECOPY].last_sent_block = NULL;
2543     rs->last_seen_block = NULL;
2544     rs->last_page = 0;
2545 
2546     postcopy_each_ram_send_discard(ms);
2547 
2548     trace_ram_postcopy_send_discard_bitmap();
2549 }
2550 
2551 /**
2552  * ram_discard_range: discard dirtied pages at the beginning of postcopy
2553  *
2554  * Returns zero on success
2555  *
2556  * @rbname: name of the RAMBlock of the request. NULL means the
2557  *          same that last one.
2558  * @start: RAMBlock starting page
2559  * @length: RAMBlock size
2560  */
2561 int ram_discard_range(const char *rbname, uint64_t start, size_t length)
2562 {
2563     trace_ram_discard_range(rbname, start, length);
2564 
2565     RCU_READ_LOCK_GUARD();
2566     RAMBlock *rb = qemu_ram_block_by_name(rbname);
2567 
2568     if (!rb) {
2569         error_report("ram_discard_range: Failed to find block '%s'", rbname);
2570         return -1;
2571     }
2572 
2573     /*
2574      * On source VM, we don't need to update the received bitmap since
2575      * we don't even have one.
2576      */
2577     if (rb->receivedmap) {
2578         bitmap_clear(rb->receivedmap, start >> qemu_target_page_bits(),
2579                      length >> qemu_target_page_bits());
2580     }
2581 
2582     return ram_block_discard_range(rb, start, length);
2583 }
2584 
2585 /*
2586  * For every allocation, we will try not to crash the VM if the
2587  * allocation failed.
2588  */
2589 static bool xbzrle_init(Error **errp)
2590 {
2591     if (!migrate_xbzrle()) {
2592         return true;
2593     }
2594 
2595     XBZRLE_cache_lock();
2596 
2597     XBZRLE.zero_target_page = g_try_malloc0(TARGET_PAGE_SIZE);
2598     if (!XBZRLE.zero_target_page) {
2599         error_setg(errp, "%s: Error allocating zero page", __func__);
2600         goto err_out;
2601     }
2602 
2603     XBZRLE.cache = cache_init(migrate_xbzrle_cache_size(),
2604                               TARGET_PAGE_SIZE, errp);
2605     if (!XBZRLE.cache) {
2606         goto free_zero_page;
2607     }
2608 
2609     XBZRLE.encoded_buf = g_try_malloc0(TARGET_PAGE_SIZE);
2610     if (!XBZRLE.encoded_buf) {
2611         error_setg(errp, "%s: Error allocating encoded_buf", __func__);
2612         goto free_cache;
2613     }
2614 
2615     XBZRLE.current_buf = g_try_malloc(TARGET_PAGE_SIZE);
2616     if (!XBZRLE.current_buf) {
2617         error_setg(errp, "%s: Error allocating current_buf", __func__);
2618         goto free_encoded_buf;
2619     }
2620 
2621     /* We are all good */
2622     XBZRLE_cache_unlock();
2623     return true;
2624 
2625 free_encoded_buf:
2626     g_free(XBZRLE.encoded_buf);
2627     XBZRLE.encoded_buf = NULL;
2628 free_cache:
2629     cache_fini(XBZRLE.cache);
2630     XBZRLE.cache = NULL;
2631 free_zero_page:
2632     g_free(XBZRLE.zero_target_page);
2633     XBZRLE.zero_target_page = NULL;
2634 err_out:
2635     XBZRLE_cache_unlock();
2636     return false;
2637 }
2638 
2639 static bool ram_state_init(RAMState **rsp, Error **errp)
2640 {
2641     *rsp = g_try_new0(RAMState, 1);
2642 
2643     if (!*rsp) {
2644         error_setg(errp, "%s: Init ramstate fail", __func__);
2645         return false;
2646     }
2647 
2648     qemu_mutex_init(&(*rsp)->bitmap_mutex);
2649     qemu_mutex_init(&(*rsp)->src_page_req_mutex);
2650     QSIMPLEQ_INIT(&(*rsp)->src_page_requests);
2651     (*rsp)->ram_bytes_total = ram_bytes_total();
2652 
2653     /*
2654      * Count the total number of pages used by ram blocks not including any
2655      * gaps due to alignment or unplugs.
2656      * This must match with the initial values of dirty bitmap.
2657      */
2658     (*rsp)->migration_dirty_pages = (*rsp)->ram_bytes_total >> TARGET_PAGE_BITS;
2659     ram_state_reset(*rsp);
2660 
2661     return true;
2662 }
2663 
2664 static void ram_list_init_bitmaps(void)
2665 {
2666     MigrationState *ms = migrate_get_current();
2667     RAMBlock *block;
2668     unsigned long pages;
2669     uint8_t shift;
2670 
2671     /* Skip setting bitmap if there is no RAM */
2672     if (ram_bytes_total()) {
2673         shift = ms->clear_bitmap_shift;
2674         if (shift > CLEAR_BITMAP_SHIFT_MAX) {
2675             error_report("clear_bitmap_shift (%u) too big, using "
2676                          "max value (%u)", shift, CLEAR_BITMAP_SHIFT_MAX);
2677             shift = CLEAR_BITMAP_SHIFT_MAX;
2678         } else if (shift < CLEAR_BITMAP_SHIFT_MIN) {
2679             error_report("clear_bitmap_shift (%u) too small, using "
2680                          "min value (%u)", shift, CLEAR_BITMAP_SHIFT_MIN);
2681             shift = CLEAR_BITMAP_SHIFT_MIN;
2682         }
2683 
2684         RAMBLOCK_FOREACH_NOT_IGNORED(block) {
2685             pages = block->max_length >> TARGET_PAGE_BITS;
2686             /*
2687              * The initial dirty bitmap for migration must be set with all
2688              * ones to make sure we'll migrate every guest RAM page to
2689              * destination.
2690              * Here we set RAMBlock.bmap all to 1 because when rebegin a
2691              * new migration after a failed migration, ram_list.
2692              * dirty_memory[DIRTY_MEMORY_MIGRATION] don't include the whole
2693              * guest memory.
2694              */
2695             block->bmap = bitmap_new(pages);
2696             bitmap_set(block->bmap, 0, pages);
2697             if (migrate_mapped_ram()) {
2698                 block->file_bmap = bitmap_new(pages);
2699             }
2700             block->clear_bmap_shift = shift;
2701             block->clear_bmap = bitmap_new(clear_bmap_size(pages, shift));
2702         }
2703     }
2704 }
2705 
2706 static void migration_bitmap_clear_discarded_pages(RAMState *rs)
2707 {
2708     unsigned long pages;
2709     RAMBlock *rb;
2710 
2711     RCU_READ_LOCK_GUARD();
2712 
2713     RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
2714             pages = ramblock_dirty_bitmap_clear_discarded_pages(rb);
2715             rs->migration_dirty_pages -= pages;
2716     }
2717 }
2718 
2719 static bool ram_init_bitmaps(RAMState *rs, Error **errp)
2720 {
2721     bool ret = true;
2722 
2723     qemu_mutex_lock_ramlist();
2724 
2725     WITH_RCU_READ_LOCK_GUARD() {
2726         ram_list_init_bitmaps();
2727         /* We don't use dirty log with background snapshots */
2728         if (!migrate_background_snapshot()) {
2729             ret = memory_global_dirty_log_start(GLOBAL_DIRTY_MIGRATION, errp);
2730             if (!ret) {
2731                 goto out_unlock;
2732             }
2733             migration_bitmap_sync_precopy(false);
2734         }
2735     }
2736 out_unlock:
2737     qemu_mutex_unlock_ramlist();
2738 
2739     if (!ret) {
2740         ram_bitmaps_destroy();
2741         return false;
2742     }
2743 
2744     /*
2745      * After an eventual first bitmap sync, fixup the initial bitmap
2746      * containing all 1s to exclude any discarded pages from migration.
2747      */
2748     migration_bitmap_clear_discarded_pages(rs);
2749     return true;
2750 }
2751 
2752 static int ram_init_all(RAMState **rsp, Error **errp)
2753 {
2754     if (!ram_state_init(rsp, errp)) {
2755         return -1;
2756     }
2757 
2758     if (!xbzrle_init(errp)) {
2759         ram_state_cleanup(rsp);
2760         return -1;
2761     }
2762 
2763     if (!ram_init_bitmaps(*rsp, errp)) {
2764         return -1;
2765     }
2766 
2767     return 0;
2768 }
2769 
2770 static void ram_state_resume_prepare(RAMState *rs, QEMUFile *out)
2771 {
2772     RAMBlock *block;
2773     uint64_t pages = 0;
2774 
2775     /*
2776      * Postcopy is not using xbzrle/compression, so no need for that.
2777      * Also, since source are already halted, we don't need to care
2778      * about dirty page logging as well.
2779      */
2780 
2781     RAMBLOCK_FOREACH_NOT_IGNORED(block) {
2782         pages += bitmap_count_one(block->bmap,
2783                                   block->used_length >> TARGET_PAGE_BITS);
2784     }
2785 
2786     /* This may not be aligned with current bitmaps. Recalculate. */
2787     rs->migration_dirty_pages = pages;
2788 
2789     ram_state_reset(rs);
2790 
2791     /* Update RAMState cache of output QEMUFile */
2792     rs->pss[RAM_CHANNEL_PRECOPY].pss_channel = out;
2793 
2794     trace_ram_state_resume_prepare(pages);
2795 }
2796 
2797 /*
2798  * This function clears bits of the free pages reported by the caller from the
2799  * migration dirty bitmap. @addr is the host address corresponding to the
2800  * start of the continuous guest free pages, and @len is the total bytes of
2801  * those pages.
2802  */
2803 void qemu_guest_free_page_hint(void *addr, size_t len)
2804 {
2805     RAMBlock *block;
2806     ram_addr_t offset;
2807     size_t used_len, start, npages;
2808 
2809     /* This function is currently expected to be used during live migration */
2810     if (!migration_is_running()) {
2811         return;
2812     }
2813 
2814     for (; len > 0; len -= used_len, addr += used_len) {
2815         block = qemu_ram_block_from_host(addr, false, &offset);
2816         if (unlikely(!block || offset >= block->used_length)) {
2817             /*
2818              * The implementation might not support RAMBlock resize during
2819              * live migration, but it could happen in theory with future
2820              * updates. So we add a check here to capture that case.
2821              */
2822             error_report_once("%s unexpected error", __func__);
2823             return;
2824         }
2825 
2826         if (len <= block->used_length - offset) {
2827             used_len = len;
2828         } else {
2829             used_len = block->used_length - offset;
2830         }
2831 
2832         start = offset >> TARGET_PAGE_BITS;
2833         npages = used_len >> TARGET_PAGE_BITS;
2834 
2835         qemu_mutex_lock(&ram_state->bitmap_mutex);
2836         /*
2837          * The skipped free pages are equavalent to be sent from clear_bmap's
2838          * perspective, so clear the bits from the memory region bitmap which
2839          * are initially set. Otherwise those skipped pages will be sent in
2840          * the next round after syncing from the memory region bitmap.
2841          */
2842         migration_clear_memory_region_dirty_bitmap_range(block, start, npages);
2843         ram_state->migration_dirty_pages -=
2844                       bitmap_count_one_with_offset(block->bmap, start, npages);
2845         bitmap_clear(block->bmap, start, npages);
2846         qemu_mutex_unlock(&ram_state->bitmap_mutex);
2847     }
2848 }
2849 
2850 #define MAPPED_RAM_HDR_VERSION 1
2851 struct MappedRamHeader {
2852     uint32_t version;
2853     /*
2854      * The target's page size, so we know how many pages are in the
2855      * bitmap.
2856      */
2857     uint64_t page_size;
2858     /*
2859      * The offset in the migration file where the pages bitmap is
2860      * stored.
2861      */
2862     uint64_t bitmap_offset;
2863     /*
2864      * The offset in the migration file where the actual pages (data)
2865      * are stored.
2866      */
2867     uint64_t pages_offset;
2868 } QEMU_PACKED;
2869 typedef struct MappedRamHeader MappedRamHeader;
2870 
2871 static void mapped_ram_setup_ramblock(QEMUFile *file, RAMBlock *block)
2872 {
2873     g_autofree MappedRamHeader *header = NULL;
2874     size_t header_size, bitmap_size;
2875     long num_pages;
2876 
2877     header = g_new0(MappedRamHeader, 1);
2878     header_size = sizeof(MappedRamHeader);
2879 
2880     num_pages = block->used_length >> TARGET_PAGE_BITS;
2881     bitmap_size = BITS_TO_LONGS(num_pages) * sizeof(unsigned long);
2882 
2883     /*
2884      * Save the file offsets of where the bitmap and the pages should
2885      * go as they are written at the end of migration and during the
2886      * iterative phase, respectively.
2887      */
2888     block->bitmap_offset = qemu_get_offset(file) + header_size;
2889     block->pages_offset = ROUND_UP(block->bitmap_offset +
2890                                    bitmap_size,
2891                                    MAPPED_RAM_FILE_OFFSET_ALIGNMENT);
2892 
2893     header->version = cpu_to_be32(MAPPED_RAM_HDR_VERSION);
2894     header->page_size = cpu_to_be64(TARGET_PAGE_SIZE);
2895     header->bitmap_offset = cpu_to_be64(block->bitmap_offset);
2896     header->pages_offset = cpu_to_be64(block->pages_offset);
2897 
2898     qemu_put_buffer(file, (uint8_t *) header, header_size);
2899 
2900     /* prepare offset for next ramblock */
2901     qemu_set_offset(file, block->pages_offset + block->used_length, SEEK_SET);
2902 }
2903 
2904 static bool mapped_ram_read_header(QEMUFile *file, MappedRamHeader *header,
2905                                    Error **errp)
2906 {
2907     size_t ret, header_size = sizeof(MappedRamHeader);
2908 
2909     ret = qemu_get_buffer(file, (uint8_t *)header, header_size);
2910     if (ret != header_size) {
2911         error_setg(errp, "Could not read whole mapped-ram migration header "
2912                    "(expected %zd, got %zd bytes)", header_size, ret);
2913         return false;
2914     }
2915 
2916     /* migration stream is big-endian */
2917     header->version = be32_to_cpu(header->version);
2918 
2919     if (header->version > MAPPED_RAM_HDR_VERSION) {
2920         error_setg(errp, "Migration mapped-ram capability version not "
2921                    "supported (expected <= %d, got %d)", MAPPED_RAM_HDR_VERSION,
2922                    header->version);
2923         return false;
2924     }
2925 
2926     header->page_size = be64_to_cpu(header->page_size);
2927     header->bitmap_offset = be64_to_cpu(header->bitmap_offset);
2928     header->pages_offset = be64_to_cpu(header->pages_offset);
2929 
2930     return true;
2931 }
2932 
2933 /*
2934  * Each of ram_save_setup, ram_save_iterate and ram_save_complete has
2935  * long-running RCU critical section.  When rcu-reclaims in the code
2936  * start to become numerous it will be necessary to reduce the
2937  * granularity of these critical sections.
2938  */
2939 
2940 /**
2941  * ram_save_setup: Setup RAM for migration
2942  *
2943  * Returns zero to indicate success and negative for error
2944  *
2945  * @f: QEMUFile where to send the data
2946  * @opaque: RAMState pointer
2947  * @errp: pointer to Error*, to store an error if it happens.
2948  */
2949 static int ram_save_setup(QEMUFile *f, void *opaque, Error **errp)
2950 {
2951     RAMState **rsp = opaque;
2952     RAMBlock *block;
2953     int ret, max_hg_page_size;
2954 
2955     /* migration has already setup the bitmap, reuse it. */
2956     if (!migration_in_colo_state()) {
2957         if (ram_init_all(rsp, errp) != 0) {
2958             return -1;
2959         }
2960     }
2961     (*rsp)->pss[RAM_CHANNEL_PRECOPY].pss_channel = f;
2962 
2963     /*
2964      * ??? Mirrors the previous value of qemu_host_page_size,
2965      * but is this really what was intended for the migration?
2966      */
2967     max_hg_page_size = MAX(qemu_real_host_page_size(), TARGET_PAGE_SIZE);
2968 
2969     WITH_RCU_READ_LOCK_GUARD() {
2970         qemu_put_be64(f, ram_bytes_total_with_ignored()
2971                          | RAM_SAVE_FLAG_MEM_SIZE);
2972 
2973         RAMBLOCK_FOREACH_MIGRATABLE(block) {
2974             qemu_put_byte(f, strlen(block->idstr));
2975             qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));
2976             qemu_put_be64(f, block->used_length);
2977             if (migrate_postcopy_ram() &&
2978                 block->page_size != max_hg_page_size) {
2979                 qemu_put_be64(f, block->page_size);
2980             }
2981             if (migrate_ignore_shared()) {
2982                 qemu_put_be64(f, block->mr->addr);
2983             }
2984 
2985             if (migrate_mapped_ram()) {
2986                 mapped_ram_setup_ramblock(f, block);
2987             }
2988         }
2989     }
2990 
2991     ret = rdma_registration_start(f, RAM_CONTROL_SETUP);
2992     if (ret < 0) {
2993         error_setg(errp, "%s: failed to start RDMA registration", __func__);
2994         qemu_file_set_error(f, ret);
2995         return ret;
2996     }
2997 
2998     ret = rdma_registration_stop(f, RAM_CONTROL_SETUP);
2999     if (ret < 0) {
3000         error_setg(errp, "%s: failed to stop RDMA registration", __func__);
3001         qemu_file_set_error(f, ret);
3002         return ret;
3003     }
3004 
3005     if (migrate_multifd()) {
3006         multifd_ram_save_setup();
3007     }
3008 
3009     /*
3010      * This operation is unfortunate..
3011      *
3012      * For legacy QEMUs using per-section sync
3013      * =======================================
3014      *
3015      * This must exist because the EOS below requires the SYNC messages
3016      * per-channel to work.
3017      *
3018      * For modern QEMUs using per-round sync
3019      * =====================================
3020      *
3021      * Logically such sync is not needed, and recv threads should not run
3022      * until setup ready (using things like channels_ready on src).  Then
3023      * we should be all fine.
3024      *
3025      * However even if we add channels_ready to recv side in new QEMUs, old
3026      * QEMU won't have them so this sync will still be needed to make sure
3027      * multifd recv threads won't start processing guest pages early before
3028      * ram_load_setup() is properly done.
3029      *
3030      * Let's stick with this.  Fortunately the overhead is low to sync
3031      * during setup because the VM is running, so at least it's not
3032      * accounted as part of downtime.
3033      */
3034     bql_unlock();
3035     ret = multifd_ram_flush_and_sync(f);
3036     bql_lock();
3037     if (ret < 0) {
3038         error_setg(errp, "%s: multifd synchronization failed", __func__);
3039         return ret;
3040     }
3041 
3042     qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3043     ret = qemu_fflush(f);
3044     if (ret < 0) {
3045         error_setg_errno(errp, -ret, "%s failed", __func__);
3046     }
3047     return ret;
3048 }
3049 
3050 static void ram_save_file_bmap(QEMUFile *f)
3051 {
3052     RAMBlock *block;
3053 
3054     RAMBLOCK_FOREACH_MIGRATABLE(block) {
3055         long num_pages = block->used_length >> TARGET_PAGE_BITS;
3056         long bitmap_size = BITS_TO_LONGS(num_pages) * sizeof(unsigned long);
3057 
3058         qemu_put_buffer_at(f, (uint8_t *)block->file_bmap, bitmap_size,
3059                            block->bitmap_offset);
3060         ram_transferred_add(bitmap_size);
3061 
3062         /*
3063          * Free the bitmap here to catch any synchronization issues
3064          * with multifd channels. No channels should be sending pages
3065          * after we've written the bitmap to file.
3066          */
3067         g_free(block->file_bmap);
3068         block->file_bmap = NULL;
3069     }
3070 }
3071 
3072 void ramblock_set_file_bmap_atomic(RAMBlock *block, ram_addr_t offset, bool set)
3073 {
3074     if (set) {
3075         set_bit_atomic(offset >> TARGET_PAGE_BITS, block->file_bmap);
3076     } else {
3077         clear_bit_atomic(offset >> TARGET_PAGE_BITS, block->file_bmap);
3078     }
3079 }
3080 
3081 /**
3082  * ram_save_iterate: iterative stage for migration
3083  *
3084  * Returns zero to indicate success and negative for error
3085  *
3086  * @f: QEMUFile where to send the data
3087  * @opaque: RAMState pointer
3088  */
3089 static int ram_save_iterate(QEMUFile *f, void *opaque)
3090 {
3091     RAMState **temp = opaque;
3092     RAMState *rs = *temp;
3093     int ret = 0;
3094     int i;
3095     int64_t t0;
3096     int done = 0;
3097 
3098     /*
3099      * We'll take this lock a little bit long, but it's okay for two reasons.
3100      * Firstly, the only possible other thread to take it is who calls
3101      * qemu_guest_free_page_hint(), which should be rare; secondly, see
3102      * MAX_WAIT (if curious, further see commit 4508bd9ed8053ce) below, which
3103      * guarantees that we'll at least released it in a regular basis.
3104      */
3105     WITH_QEMU_LOCK_GUARD(&rs->bitmap_mutex) {
3106         WITH_RCU_READ_LOCK_GUARD() {
3107             if (ram_list.version != rs->last_version) {
3108                 ram_state_reset(rs);
3109             }
3110 
3111             /* Read version before ram_list.blocks */
3112             smp_rmb();
3113 
3114             ret = rdma_registration_start(f, RAM_CONTROL_ROUND);
3115             if (ret < 0) {
3116                 qemu_file_set_error(f, ret);
3117                 goto out;
3118             }
3119 
3120             t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
3121             i = 0;
3122             while ((ret = migration_rate_exceeded(f)) == 0 ||
3123                    postcopy_has_request(rs)) {
3124                 int pages;
3125 
3126                 if (qemu_file_get_error(f)) {
3127                     break;
3128                 }
3129 
3130                 pages = ram_find_and_save_block(rs);
3131                 /* no more pages to sent */
3132                 if (pages == 0) {
3133                     done = 1;
3134                     break;
3135                 }
3136 
3137                 if (pages < 0) {
3138                     qemu_file_set_error(f, pages);
3139                     break;
3140                 }
3141 
3142                 rs->target_page_count += pages;
3143 
3144                 /*
3145                  * we want to check in the 1st loop, just in case it was the 1st
3146                  * time and we had to sync the dirty bitmap.
3147                  * qemu_clock_get_ns() is a bit expensive, so we only check each
3148                  * some iterations
3149                  */
3150                 if ((i & 63) == 0) {
3151                     uint64_t t1 = (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - t0) /
3152                         1000000;
3153                     if (t1 > MAX_WAIT) {
3154                         trace_ram_save_iterate_big_wait(t1, i);
3155                         break;
3156                     }
3157                 }
3158                 i++;
3159             }
3160         }
3161     }
3162 
3163     /*
3164      * Must occur before EOS (or any QEMUFile operation)
3165      * because of RDMA protocol.
3166      */
3167     ret = rdma_registration_stop(f, RAM_CONTROL_ROUND);
3168     if (ret < 0) {
3169         qemu_file_set_error(f, ret);
3170     }
3171 
3172 out:
3173     if (ret >= 0 && migration_is_running()) {
3174         if (multifd_ram_sync_per_section()) {
3175             ret = multifd_ram_flush_and_sync(f);
3176             if (ret < 0) {
3177                 return ret;
3178             }
3179         }
3180 
3181         qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3182         ram_transferred_add(8);
3183         ret = qemu_fflush(f);
3184     }
3185     if (ret < 0) {
3186         return ret;
3187     }
3188 
3189     return done;
3190 }
3191 
3192 /**
3193  * ram_save_complete: function called to send the remaining amount of ram
3194  *
3195  * Returns zero to indicate success or negative on error
3196  *
3197  * Called with the BQL
3198  *
3199  * @f: QEMUFile where to send the data
3200  * @opaque: RAMState pointer
3201  */
3202 static int ram_save_complete(QEMUFile *f, void *opaque)
3203 {
3204     RAMState **temp = opaque;
3205     RAMState *rs = *temp;
3206     int ret = 0;
3207 
3208     rs->last_stage = !migration_in_colo_state();
3209 
3210     WITH_RCU_READ_LOCK_GUARD() {
3211         if (!migration_in_postcopy()) {
3212             migration_bitmap_sync_precopy(true);
3213         }
3214 
3215         ret = rdma_registration_start(f, RAM_CONTROL_FINISH);
3216         if (ret < 0) {
3217             qemu_file_set_error(f, ret);
3218             return ret;
3219         }
3220 
3221         /* try transferring iterative blocks of memory */
3222 
3223         /* flush all remaining blocks regardless of rate limiting */
3224         qemu_mutex_lock(&rs->bitmap_mutex);
3225         while (true) {
3226             int pages;
3227 
3228             pages = ram_find_and_save_block(rs);
3229             /* no more blocks to sent */
3230             if (pages == 0) {
3231                 break;
3232             }
3233             if (pages < 0) {
3234                 qemu_mutex_unlock(&rs->bitmap_mutex);
3235                 return pages;
3236             }
3237         }
3238         qemu_mutex_unlock(&rs->bitmap_mutex);
3239 
3240         ret = rdma_registration_stop(f, RAM_CONTROL_FINISH);
3241         if (ret < 0) {
3242             qemu_file_set_error(f, ret);
3243             return ret;
3244         }
3245     }
3246 
3247     if (multifd_ram_sync_per_section()) {
3248         /*
3249          * Only the old dest QEMU will need this sync, because each EOS
3250          * will require one SYNC message on each channel.
3251          */
3252         ret = multifd_ram_flush_and_sync(f);
3253         if (ret < 0) {
3254             return ret;
3255         }
3256     }
3257 
3258     if (migrate_mapped_ram()) {
3259         ram_save_file_bmap(f);
3260 
3261         if (qemu_file_get_error(f)) {
3262             Error *local_err = NULL;
3263             int err = qemu_file_get_error_obj(f, &local_err);
3264 
3265             error_reportf_err(local_err, "Failed to write bitmap to file: ");
3266             return -err;
3267         }
3268     }
3269 
3270     qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3271     return qemu_fflush(f);
3272 }
3273 
3274 static void ram_state_pending_estimate(void *opaque, uint64_t *must_precopy,
3275                                        uint64_t *can_postcopy)
3276 {
3277     RAMState **temp = opaque;
3278     RAMState *rs = *temp;
3279 
3280     uint64_t remaining_size = rs->migration_dirty_pages * TARGET_PAGE_SIZE;
3281 
3282     if (migrate_postcopy_ram()) {
3283         /* We can do postcopy, and all the data is postcopiable */
3284         *can_postcopy += remaining_size;
3285     } else {
3286         *must_precopy += remaining_size;
3287     }
3288 }
3289 
3290 static void ram_state_pending_exact(void *opaque, uint64_t *must_precopy,
3291                                     uint64_t *can_postcopy)
3292 {
3293     RAMState **temp = opaque;
3294     RAMState *rs = *temp;
3295     uint64_t remaining_size;
3296 
3297     if (!migration_in_postcopy()) {
3298         bql_lock();
3299         WITH_RCU_READ_LOCK_GUARD() {
3300             migration_bitmap_sync_precopy(false);
3301         }
3302         bql_unlock();
3303     }
3304 
3305     remaining_size = rs->migration_dirty_pages * TARGET_PAGE_SIZE;
3306 
3307     if (migrate_postcopy_ram()) {
3308         /* We can do postcopy, and all the data is postcopiable */
3309         *can_postcopy += remaining_size;
3310     } else {
3311         *must_precopy += remaining_size;
3312     }
3313 }
3314 
3315 static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host)
3316 {
3317     unsigned int xh_len;
3318     int xh_flags;
3319     uint8_t *loaded_data;
3320 
3321     /* extract RLE header */
3322     xh_flags = qemu_get_byte(f);
3323     xh_len = qemu_get_be16(f);
3324 
3325     if (xh_flags != ENCODING_FLAG_XBZRLE) {
3326         error_report("Failed to load XBZRLE page - wrong compression!");
3327         return -1;
3328     }
3329 
3330     if (xh_len > TARGET_PAGE_SIZE) {
3331         error_report("Failed to load XBZRLE page - len overflow!");
3332         return -1;
3333     }
3334     loaded_data = XBZRLE.decoded_buf;
3335     /* load data and decode */
3336     /* it can change loaded_data to point to an internal buffer */
3337     qemu_get_buffer_in_place(f, &loaded_data, xh_len);
3338 
3339     /* decode RLE */
3340     if (xbzrle_decode_buffer(loaded_data, xh_len, host,
3341                              TARGET_PAGE_SIZE) == -1) {
3342         error_report("Failed to load XBZRLE page - decode error!");
3343         return -1;
3344     }
3345 
3346     return 0;
3347 }
3348 
3349 /**
3350  * ram_block_from_stream: read a RAMBlock id from the migration stream
3351  *
3352  * Must be called from within a rcu critical section.
3353  *
3354  * Returns a pointer from within the RCU-protected ram_list.
3355  *
3356  * @mis: the migration incoming state pointer
3357  * @f: QEMUFile where to read the data from
3358  * @flags: Page flags (mostly to see if it's a continuation of previous block)
3359  * @channel: the channel we're using
3360  */
3361 static inline RAMBlock *ram_block_from_stream(MigrationIncomingState *mis,
3362                                               QEMUFile *f, int flags,
3363                                               int channel)
3364 {
3365     RAMBlock *block = mis->last_recv_block[channel];
3366     char id[256];
3367     uint8_t len;
3368 
3369     if (flags & RAM_SAVE_FLAG_CONTINUE) {
3370         if (!block) {
3371             error_report("Ack, bad migration stream!");
3372             return NULL;
3373         }
3374         return block;
3375     }
3376 
3377     len = qemu_get_byte(f);
3378     qemu_get_buffer(f, (uint8_t *)id, len);
3379     id[len] = 0;
3380 
3381     block = qemu_ram_block_by_name(id);
3382     if (!block) {
3383         error_report("Can't find block %s", id);
3384         return NULL;
3385     }
3386 
3387     if (migrate_ram_is_ignored(block)) {
3388         error_report("block %s should not be migrated !", id);
3389         return NULL;
3390     }
3391 
3392     mis->last_recv_block[channel] = block;
3393 
3394     return block;
3395 }
3396 
3397 static inline void *host_from_ram_block_offset(RAMBlock *block,
3398                                                ram_addr_t offset)
3399 {
3400     if (!offset_in_ramblock(block, offset)) {
3401         return NULL;
3402     }
3403 
3404     return block->host + offset;
3405 }
3406 
3407 static void *host_page_from_ram_block_offset(RAMBlock *block,
3408                                              ram_addr_t offset)
3409 {
3410     /* Note: Explicitly no check against offset_in_ramblock(). */
3411     return (void *)QEMU_ALIGN_DOWN((uintptr_t)(block->host + offset),
3412                                    block->page_size);
3413 }
3414 
3415 static ram_addr_t host_page_offset_from_ram_block_offset(RAMBlock *block,
3416                                                          ram_addr_t offset)
3417 {
3418     return ((uintptr_t)block->host + offset) & (block->page_size - 1);
3419 }
3420 
3421 void colo_record_bitmap(RAMBlock *block, ram_addr_t *normal, uint32_t pages)
3422 {
3423     qemu_mutex_lock(&ram_state->bitmap_mutex);
3424     for (int i = 0; i < pages; i++) {
3425         ram_addr_t offset = normal[i];
3426         ram_state->migration_dirty_pages += !test_and_set_bit(
3427                                                 offset >> TARGET_PAGE_BITS,
3428                                                 block->bmap);
3429     }
3430     qemu_mutex_unlock(&ram_state->bitmap_mutex);
3431 }
3432 
3433 static inline void *colo_cache_from_block_offset(RAMBlock *block,
3434                              ram_addr_t offset, bool record_bitmap)
3435 {
3436     if (!offset_in_ramblock(block, offset)) {
3437         return NULL;
3438     }
3439     if (!block->colo_cache) {
3440         error_report("%s: colo_cache is NULL in block :%s",
3441                      __func__, block->idstr);
3442         return NULL;
3443     }
3444 
3445     /*
3446     * During colo checkpoint, we need bitmap of these migrated pages.
3447     * It help us to decide which pages in ram cache should be flushed
3448     * into VM's RAM later.
3449     */
3450     if (record_bitmap) {
3451         colo_record_bitmap(block, &offset, 1);
3452     }
3453     return block->colo_cache + offset;
3454 }
3455 
3456 /**
3457  * ram_handle_zero: handle the zero page case
3458  *
3459  * If a page (or a whole RDMA chunk) has been
3460  * determined to be zero, then zap it.
3461  *
3462  * @host: host address for the zero page
3463  * @ch: what the page is filled from.  We only support zero
3464  * @size: size of the zero page
3465  */
3466 void ram_handle_zero(void *host, uint64_t size)
3467 {
3468     if (!buffer_is_zero(host, size)) {
3469         memset(host, 0, size);
3470     }
3471 }
3472 
3473 static void colo_init_ram_state(void)
3474 {
3475     Error *local_err = NULL;
3476 
3477     if (!ram_state_init(&ram_state, &local_err)) {
3478         error_report_err(local_err);
3479     }
3480 }
3481 
3482 /*
3483  * colo cache: this is for secondary VM, we cache the whole
3484  * memory of the secondary VM, it is need to hold the global lock
3485  * to call this helper.
3486  */
3487 int colo_init_ram_cache(void)
3488 {
3489     RAMBlock *block;
3490 
3491     WITH_RCU_READ_LOCK_GUARD() {
3492         RAMBLOCK_FOREACH_NOT_IGNORED(block) {
3493             block->colo_cache = qemu_anon_ram_alloc(block->used_length,
3494                                                     NULL, false, false);
3495             if (!block->colo_cache) {
3496                 error_report("%s: Can't alloc memory for COLO cache of block %s,"
3497                              "size 0x" RAM_ADDR_FMT, __func__, block->idstr,
3498                              block->used_length);
3499                 RAMBLOCK_FOREACH_NOT_IGNORED(block) {
3500                     if (block->colo_cache) {
3501                         qemu_anon_ram_free(block->colo_cache, block->used_length);
3502                         block->colo_cache = NULL;
3503                     }
3504                 }
3505                 return -errno;
3506             }
3507             if (!machine_dump_guest_core(current_machine)) {
3508                 qemu_madvise(block->colo_cache, block->used_length,
3509                              QEMU_MADV_DONTDUMP);
3510             }
3511         }
3512     }
3513 
3514     /*
3515     * Record the dirty pages that sent by PVM, we use this dirty bitmap together
3516     * with to decide which page in cache should be flushed into SVM's RAM. Here
3517     * we use the same name 'ram_bitmap' as for migration.
3518     */
3519     if (ram_bytes_total()) {
3520         RAMBLOCK_FOREACH_NOT_IGNORED(block) {
3521             unsigned long pages = block->max_length >> TARGET_PAGE_BITS;
3522             block->bmap = bitmap_new(pages);
3523         }
3524     }
3525 
3526     colo_init_ram_state();
3527     return 0;
3528 }
3529 
3530 /* TODO: duplicated with ram_init_bitmaps */
3531 void colo_incoming_start_dirty_log(void)
3532 {
3533     RAMBlock *block = NULL;
3534     Error *local_err = NULL;
3535 
3536     /* For memory_global_dirty_log_start below. */
3537     bql_lock();
3538     qemu_mutex_lock_ramlist();
3539 
3540     memory_global_dirty_log_sync(false);
3541     WITH_RCU_READ_LOCK_GUARD() {
3542         RAMBLOCK_FOREACH_NOT_IGNORED(block) {
3543             ramblock_sync_dirty_bitmap(ram_state, block);
3544             /* Discard this dirty bitmap record */
3545             bitmap_zero(block->bmap, block->max_length >> TARGET_PAGE_BITS);
3546         }
3547         if (!memory_global_dirty_log_start(GLOBAL_DIRTY_MIGRATION,
3548                                            &local_err)) {
3549             error_report_err(local_err);
3550         }
3551     }
3552     ram_state->migration_dirty_pages = 0;
3553     qemu_mutex_unlock_ramlist();
3554     bql_unlock();
3555 }
3556 
3557 /* It is need to hold the global lock to call this helper */
3558 void colo_release_ram_cache(void)
3559 {
3560     RAMBlock *block;
3561 
3562     memory_global_dirty_log_stop(GLOBAL_DIRTY_MIGRATION);
3563     RAMBLOCK_FOREACH_NOT_IGNORED(block) {
3564         g_free(block->bmap);
3565         block->bmap = NULL;
3566     }
3567 
3568     WITH_RCU_READ_LOCK_GUARD() {
3569         RAMBLOCK_FOREACH_NOT_IGNORED(block) {
3570             if (block->colo_cache) {
3571                 qemu_anon_ram_free(block->colo_cache, block->used_length);
3572                 block->colo_cache = NULL;
3573             }
3574         }
3575     }
3576     ram_state_cleanup(&ram_state);
3577 }
3578 
3579 /**
3580  * ram_load_setup: Setup RAM for migration incoming side
3581  *
3582  * Returns zero to indicate success and negative for error
3583  *
3584  * @f: QEMUFile where to receive the data
3585  * @opaque: RAMState pointer
3586  * @errp: pointer to Error*, to store an error if it happens.
3587  */
3588 static int ram_load_setup(QEMUFile *f, void *opaque, Error **errp)
3589 {
3590     xbzrle_load_setup();
3591     ramblock_recv_map_init();
3592 
3593     return 0;
3594 }
3595 
3596 static int ram_load_cleanup(void *opaque)
3597 {
3598     RAMBlock *rb;
3599 
3600     RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
3601         qemu_ram_block_writeback(rb);
3602     }
3603 
3604     xbzrle_load_cleanup();
3605 
3606     RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
3607         g_free(rb->receivedmap);
3608         rb->receivedmap = NULL;
3609     }
3610 
3611     return 0;
3612 }
3613 
3614 /**
3615  * ram_postcopy_incoming_init: allocate postcopy data structures
3616  *
3617  * Returns 0 for success and negative if there was one error
3618  *
3619  * @mis: current migration incoming state
3620  *
3621  * Allocate data structures etc needed by incoming migration with
3622  * postcopy-ram. postcopy-ram's similarly names
3623  * postcopy_ram_incoming_init does the work.
3624  */
3625 int ram_postcopy_incoming_init(MigrationIncomingState *mis)
3626 {
3627     return postcopy_ram_incoming_init(mis);
3628 }
3629 
3630 /**
3631  * ram_load_postcopy: load a page in postcopy case
3632  *
3633  * Returns 0 for success or -errno in case of error
3634  *
3635  * Called in postcopy mode by ram_load().
3636  * rcu_read_lock is taken prior to this being called.
3637  *
3638  * @f: QEMUFile where to send the data
3639  * @channel: the channel to use for loading
3640  */
3641 int ram_load_postcopy(QEMUFile *f, int channel)
3642 {
3643     int flags = 0, ret = 0;
3644     bool place_needed = false;
3645     bool matches_target_page_size = false;
3646     MigrationIncomingState *mis = migration_incoming_get_current();
3647     PostcopyTmpPage *tmp_page = &mis->postcopy_tmp_pages[channel];
3648 
3649     while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
3650         ram_addr_t addr;
3651         void *page_buffer = NULL;
3652         void *place_source = NULL;
3653         RAMBlock *block = NULL;
3654         uint8_t ch;
3655 
3656         addr = qemu_get_be64(f);
3657 
3658         /*
3659          * If qemu file error, we should stop here, and then "addr"
3660          * may be invalid
3661          */
3662         ret = qemu_file_get_error(f);
3663         if (ret) {
3664             break;
3665         }
3666 
3667         flags = addr & ~TARGET_PAGE_MASK;
3668         addr &= TARGET_PAGE_MASK;
3669 
3670         trace_ram_load_postcopy_loop(channel, (uint64_t)addr, flags);
3671         if (flags & (RAM_SAVE_FLAG_ZERO | RAM_SAVE_FLAG_PAGE)) {
3672             block = ram_block_from_stream(mis, f, flags, channel);
3673             if (!block) {
3674                 ret = -EINVAL;
3675                 break;
3676             }
3677 
3678             /*
3679              * Relying on used_length is racy and can result in false positives.
3680              * We might place pages beyond used_length in case RAM was shrunk
3681              * while in postcopy, which is fine - trying to place via
3682              * UFFDIO_COPY/UFFDIO_ZEROPAGE will never segfault.
3683              */
3684             if (!block->host || addr >= block->postcopy_length) {
3685                 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
3686                 ret = -EINVAL;
3687                 break;
3688             }
3689             tmp_page->target_pages++;
3690             matches_target_page_size = block->page_size == TARGET_PAGE_SIZE;
3691             /*
3692              * Postcopy requires that we place whole host pages atomically;
3693              * these may be huge pages for RAMBlocks that are backed by
3694              * hugetlbfs.
3695              * To make it atomic, the data is read into a temporary page
3696              * that's moved into place later.
3697              * The migration protocol uses,  possibly smaller, target-pages
3698              * however the source ensures it always sends all the components
3699              * of a host page in one chunk.
3700              */
3701             page_buffer = tmp_page->tmp_huge_page +
3702                           host_page_offset_from_ram_block_offset(block, addr);
3703             /* If all TP are zero then we can optimise the place */
3704             if (tmp_page->target_pages == 1) {
3705                 tmp_page->host_addr =
3706                     host_page_from_ram_block_offset(block, addr);
3707             } else if (tmp_page->host_addr !=
3708                        host_page_from_ram_block_offset(block, addr)) {
3709                 /* not the 1st TP within the HP */
3710                 error_report("Non-same host page detected on channel %d: "
3711                              "Target host page %p, received host page %p "
3712                              "(rb %s offset 0x"RAM_ADDR_FMT" target_pages %d)",
3713                              channel, tmp_page->host_addr,
3714                              host_page_from_ram_block_offset(block, addr),
3715                              block->idstr, addr, tmp_page->target_pages);
3716                 ret = -EINVAL;
3717                 break;
3718             }
3719 
3720             /*
3721              * If it's the last part of a host page then we place the host
3722              * page
3723              */
3724             if (tmp_page->target_pages ==
3725                 (block->page_size / TARGET_PAGE_SIZE)) {
3726                 place_needed = true;
3727             }
3728             place_source = tmp_page->tmp_huge_page;
3729         }
3730 
3731         switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
3732         case RAM_SAVE_FLAG_ZERO:
3733             ch = qemu_get_byte(f);
3734             if (ch != 0) {
3735                 error_report("Found a zero page with value %d", ch);
3736                 ret = -EINVAL;
3737                 break;
3738             }
3739             /*
3740              * Can skip to set page_buffer when
3741              * this is a zero page and (block->page_size == TARGET_PAGE_SIZE).
3742              */
3743             if (!matches_target_page_size) {
3744                 memset(page_buffer, ch, TARGET_PAGE_SIZE);
3745             }
3746             break;
3747 
3748         case RAM_SAVE_FLAG_PAGE:
3749             tmp_page->all_zero = false;
3750             if (!matches_target_page_size) {
3751                 /* For huge pages, we always use temporary buffer */
3752                 qemu_get_buffer(f, page_buffer, TARGET_PAGE_SIZE);
3753             } else {
3754                 /*
3755                  * For small pages that matches target page size, we
3756                  * avoid the qemu_file copy.  Instead we directly use
3757                  * the buffer of QEMUFile to place the page.  Note: we
3758                  * cannot do any QEMUFile operation before using that
3759                  * buffer to make sure the buffer is valid when
3760                  * placing the page.
3761                  */
3762                 qemu_get_buffer_in_place(f, (uint8_t **)&place_source,
3763                                          TARGET_PAGE_SIZE);
3764             }
3765             break;
3766         case RAM_SAVE_FLAG_EOS:
3767             break;
3768         default:
3769             error_report("Unknown combination of migration flags: 0x%x"
3770                          " (postcopy mode)", flags);
3771             ret = -EINVAL;
3772             break;
3773         }
3774 
3775         /* Detect for any possible file errors */
3776         if (!ret && qemu_file_get_error(f)) {
3777             ret = qemu_file_get_error(f);
3778         }
3779 
3780         if (!ret && place_needed) {
3781             if (tmp_page->all_zero) {
3782                 ret = postcopy_place_page_zero(mis, tmp_page->host_addr, block);
3783             } else {
3784                 ret = postcopy_place_page(mis, tmp_page->host_addr,
3785                                           place_source, block);
3786             }
3787             place_needed = false;
3788             postcopy_temp_page_reset(tmp_page);
3789         }
3790     }
3791 
3792     return ret;
3793 }
3794 
3795 static bool postcopy_is_running(void)
3796 {
3797     PostcopyState ps = postcopy_state_get();
3798     return ps >= POSTCOPY_INCOMING_LISTENING && ps < POSTCOPY_INCOMING_END;
3799 }
3800 
3801 /*
3802  * Flush content of RAM cache into SVM's memory.
3803  * Only flush the pages that be dirtied by PVM or SVM or both.
3804  */
3805 void colo_flush_ram_cache(void)
3806 {
3807     RAMBlock *block = NULL;
3808     void *dst_host;
3809     void *src_host;
3810     unsigned long offset = 0;
3811 
3812     memory_global_dirty_log_sync(false);
3813     qemu_mutex_lock(&ram_state->bitmap_mutex);
3814     WITH_RCU_READ_LOCK_GUARD() {
3815         RAMBLOCK_FOREACH_NOT_IGNORED(block) {
3816             ramblock_sync_dirty_bitmap(ram_state, block);
3817         }
3818     }
3819 
3820     trace_colo_flush_ram_cache_begin(ram_state->migration_dirty_pages);
3821     WITH_RCU_READ_LOCK_GUARD() {
3822         block = QLIST_FIRST_RCU(&ram_list.blocks);
3823 
3824         while (block) {
3825             unsigned long num = 0;
3826 
3827             offset = colo_bitmap_find_dirty(ram_state, block, offset, &num);
3828             if (!offset_in_ramblock(block,
3829                                     ((ram_addr_t)offset) << TARGET_PAGE_BITS)) {
3830                 offset = 0;
3831                 num = 0;
3832                 block = QLIST_NEXT_RCU(block, next);
3833             } else {
3834                 unsigned long i = 0;
3835 
3836                 for (i = 0; i < num; i++) {
3837                     migration_bitmap_clear_dirty(ram_state, block, offset + i);
3838                 }
3839                 dst_host = block->host
3840                          + (((ram_addr_t)offset) << TARGET_PAGE_BITS);
3841                 src_host = block->colo_cache
3842                          + (((ram_addr_t)offset) << TARGET_PAGE_BITS);
3843                 memcpy(dst_host, src_host, TARGET_PAGE_SIZE * num);
3844                 offset += num;
3845             }
3846         }
3847     }
3848     qemu_mutex_unlock(&ram_state->bitmap_mutex);
3849     trace_colo_flush_ram_cache_end();
3850 }
3851 
3852 static size_t ram_load_multifd_pages(void *host_addr, size_t size,
3853                                      uint64_t offset)
3854 {
3855     MultiFDRecvData *data = multifd_get_recv_data();
3856 
3857     data->opaque = host_addr;
3858     data->file_offset = offset;
3859     data->size = size;
3860 
3861     if (!multifd_recv()) {
3862         return 0;
3863     }
3864 
3865     return size;
3866 }
3867 
3868 static bool read_ramblock_mapped_ram(QEMUFile *f, RAMBlock *block,
3869                                      long num_pages, unsigned long *bitmap,
3870                                      Error **errp)
3871 {
3872     ERRP_GUARD();
3873     unsigned long set_bit_idx, clear_bit_idx;
3874     ram_addr_t offset;
3875     void *host;
3876     size_t read, unread, size;
3877 
3878     for (set_bit_idx = find_first_bit(bitmap, num_pages);
3879          set_bit_idx < num_pages;
3880          set_bit_idx = find_next_bit(bitmap, num_pages, clear_bit_idx + 1)) {
3881 
3882         clear_bit_idx = find_next_zero_bit(bitmap, num_pages, set_bit_idx + 1);
3883 
3884         unread = TARGET_PAGE_SIZE * (clear_bit_idx - set_bit_idx);
3885         offset = set_bit_idx << TARGET_PAGE_BITS;
3886 
3887         while (unread > 0) {
3888             host = host_from_ram_block_offset(block, offset);
3889             if (!host) {
3890                 error_setg(errp, "page outside of ramblock %s range",
3891                            block->idstr);
3892                 return false;
3893             }
3894 
3895             size = MIN(unread, MAPPED_RAM_LOAD_BUF_SIZE);
3896 
3897             if (migrate_multifd()) {
3898                 read = ram_load_multifd_pages(host, size,
3899                                               block->pages_offset + offset);
3900             } else {
3901                 read = qemu_get_buffer_at(f, host, size,
3902                                           block->pages_offset + offset);
3903             }
3904 
3905             if (!read) {
3906                 goto err;
3907             }
3908             offset += read;
3909             unread -= read;
3910         }
3911     }
3912 
3913     return true;
3914 
3915 err:
3916     qemu_file_get_error_obj(f, errp);
3917     error_prepend(errp, "(%s) failed to read page " RAM_ADDR_FMT
3918                   "from file offset %" PRIx64 ": ", block->idstr, offset,
3919                   block->pages_offset + offset);
3920     return false;
3921 }
3922 
3923 static void parse_ramblock_mapped_ram(QEMUFile *f, RAMBlock *block,
3924                                       ram_addr_t length, Error **errp)
3925 {
3926     g_autofree unsigned long *bitmap = NULL;
3927     MappedRamHeader header;
3928     size_t bitmap_size;
3929     long num_pages;
3930 
3931     if (!mapped_ram_read_header(f, &header, errp)) {
3932         return;
3933     }
3934 
3935     block->pages_offset = header.pages_offset;
3936 
3937     /*
3938      * Check the alignment of the file region that contains pages. We
3939      * don't enforce MAPPED_RAM_FILE_OFFSET_ALIGNMENT to allow that
3940      * value to change in the future. Do only a sanity check with page
3941      * size alignment.
3942      */
3943     if (!QEMU_IS_ALIGNED(block->pages_offset, TARGET_PAGE_SIZE)) {
3944         error_setg(errp,
3945                    "Error reading ramblock %s pages, region has bad alignment",
3946                    block->idstr);
3947         return;
3948     }
3949 
3950     num_pages = length / header.page_size;
3951     bitmap_size = BITS_TO_LONGS(num_pages) * sizeof(unsigned long);
3952 
3953     bitmap = g_malloc0(bitmap_size);
3954     if (qemu_get_buffer_at(f, (uint8_t *)bitmap, bitmap_size,
3955                            header.bitmap_offset) != bitmap_size) {
3956         error_setg(errp, "Error reading dirty bitmap");
3957         return;
3958     }
3959 
3960     if (!read_ramblock_mapped_ram(f, block, num_pages, bitmap, errp)) {
3961         return;
3962     }
3963 
3964     /* Skip pages array */
3965     qemu_set_offset(f, block->pages_offset + length, SEEK_SET);
3966 
3967     return;
3968 }
3969 
3970 static int parse_ramblock(QEMUFile *f, RAMBlock *block, ram_addr_t length)
3971 {
3972     int ret = 0;
3973     /* ADVISE is earlier, it shows the source has the postcopy capability on */
3974     bool postcopy_advised = migration_incoming_postcopy_advised();
3975     int max_hg_page_size;
3976     Error *local_err = NULL;
3977 
3978     assert(block);
3979 
3980     if (migrate_mapped_ram()) {
3981         parse_ramblock_mapped_ram(f, block, length, &local_err);
3982         if (local_err) {
3983             error_report_err(local_err);
3984             return -EINVAL;
3985         }
3986         return 0;
3987     }
3988 
3989     if (!qemu_ram_is_migratable(block)) {
3990         error_report("block %s should not be migrated !", block->idstr);
3991         return -EINVAL;
3992     }
3993 
3994     if (length != block->used_length) {
3995         ret = qemu_ram_resize(block, length, &local_err);
3996         if (local_err) {
3997             error_report_err(local_err);
3998             return ret;
3999         }
4000     }
4001 
4002     /*
4003      * ??? Mirrors the previous value of qemu_host_page_size,
4004      * but is this really what was intended for the migration?
4005      */
4006     max_hg_page_size = MAX(qemu_real_host_page_size(), TARGET_PAGE_SIZE);
4007 
4008     /* For postcopy we need to check hugepage sizes match */
4009     if (postcopy_advised && migrate_postcopy_ram() &&
4010         block->page_size != max_hg_page_size) {
4011         uint64_t remote_page_size = qemu_get_be64(f);
4012         if (remote_page_size != block->page_size) {
4013             error_report("Mismatched RAM page size %s "
4014                          "(local) %zd != %" PRId64, block->idstr,
4015                          block->page_size, remote_page_size);
4016             return -EINVAL;
4017         }
4018     }
4019     if (migrate_ignore_shared()) {
4020         hwaddr addr = qemu_get_be64(f);
4021         if (migrate_ram_is_ignored(block) &&
4022             block->mr->addr != addr) {
4023             error_report("Mismatched GPAs for block %s "
4024                          "%" PRId64 "!= %" PRId64, block->idstr,
4025                          (uint64_t)addr, (uint64_t)block->mr->addr);
4026             return -EINVAL;
4027         }
4028     }
4029     ret = rdma_block_notification_handle(f, block->idstr);
4030     if (ret < 0) {
4031         qemu_file_set_error(f, ret);
4032     }
4033 
4034     return ret;
4035 }
4036 
4037 static int parse_ramblocks(QEMUFile *f, ram_addr_t total_ram_bytes)
4038 {
4039     int ret = 0;
4040 
4041     /* Synchronize RAM block list */
4042     while (!ret && total_ram_bytes) {
4043         RAMBlock *block;
4044         char id[256];
4045         ram_addr_t length;
4046         int len = qemu_get_byte(f);
4047 
4048         qemu_get_buffer(f, (uint8_t *)id, len);
4049         id[len] = 0;
4050         length = qemu_get_be64(f);
4051 
4052         block = qemu_ram_block_by_name(id);
4053         if (block) {
4054             ret = parse_ramblock(f, block, length);
4055         } else {
4056             error_report("Unknown ramblock \"%s\", cannot accept "
4057                          "migration", id);
4058             ret = -EINVAL;
4059         }
4060         total_ram_bytes -= length;
4061     }
4062 
4063     return ret;
4064 }
4065 
4066 /**
4067  * ram_load_precopy: load pages in precopy case
4068  *
4069  * Returns 0 for success or -errno in case of error
4070  *
4071  * Called in precopy mode by ram_load().
4072  * rcu_read_lock is taken prior to this being called.
4073  *
4074  * @f: QEMUFile where to send the data
4075  */
4076 static int ram_load_precopy(QEMUFile *f)
4077 {
4078     MigrationIncomingState *mis = migration_incoming_get_current();
4079     int flags = 0, ret = 0, invalid_flags = 0, i = 0;
4080 
4081     if (migrate_mapped_ram()) {
4082         invalid_flags |= (RAM_SAVE_FLAG_HOOK | RAM_SAVE_FLAG_MULTIFD_FLUSH |
4083                           RAM_SAVE_FLAG_PAGE | RAM_SAVE_FLAG_XBZRLE |
4084                           RAM_SAVE_FLAG_ZERO);
4085     }
4086 
4087     while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
4088         ram_addr_t addr;
4089         void *host = NULL, *host_bak = NULL;
4090         uint8_t ch;
4091 
4092         /*
4093          * Yield periodically to let main loop run, but an iteration of
4094          * the main loop is expensive, so do it each some iterations
4095          */
4096         if ((i & 32767) == 0 && qemu_in_coroutine()) {
4097             aio_co_schedule(qemu_get_current_aio_context(),
4098                             qemu_coroutine_self());
4099             qemu_coroutine_yield();
4100         }
4101         i++;
4102 
4103         addr = qemu_get_be64(f);
4104         ret = qemu_file_get_error(f);
4105         if (ret) {
4106             error_report("Getting RAM address failed");
4107             break;
4108         }
4109 
4110         flags = addr & ~TARGET_PAGE_MASK;
4111         addr &= TARGET_PAGE_MASK;
4112 
4113         if (flags & invalid_flags) {
4114             error_report("Unexpected RAM flags: %d", flags & invalid_flags);
4115 
4116             ret = -EINVAL;
4117             break;
4118         }
4119 
4120         if (flags & (RAM_SAVE_FLAG_ZERO | RAM_SAVE_FLAG_PAGE |
4121                      RAM_SAVE_FLAG_XBZRLE)) {
4122             RAMBlock *block = ram_block_from_stream(mis, f, flags,
4123                                                     RAM_CHANNEL_PRECOPY);
4124 
4125             host = host_from_ram_block_offset(block, addr);
4126             /*
4127              * After going into COLO stage, we should not load the page
4128              * into SVM's memory directly, we put them into colo_cache firstly.
4129              * NOTE: We need to keep a copy of SVM's ram in colo_cache.
4130              * Previously, we copied all these memory in preparing stage of COLO
4131              * while we need to stop VM, which is a time-consuming process.
4132              * Here we optimize it by a trick, back-up every page while in
4133              * migration process while COLO is enabled, though it affects the
4134              * speed of the migration, but it obviously reduce the downtime of
4135              * back-up all SVM'S memory in COLO preparing stage.
4136              */
4137             if (migration_incoming_colo_enabled()) {
4138                 if (migration_incoming_in_colo_state()) {
4139                     /* In COLO stage, put all pages into cache temporarily */
4140                     host = colo_cache_from_block_offset(block, addr, true);
4141                 } else {
4142                    /*
4143                     * In migration stage but before COLO stage,
4144                     * Put all pages into both cache and SVM's memory.
4145                     */
4146                     host_bak = colo_cache_from_block_offset(block, addr, false);
4147                 }
4148             }
4149             if (!host) {
4150                 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
4151                 ret = -EINVAL;
4152                 break;
4153             }
4154             if (!migration_incoming_in_colo_state()) {
4155                 ramblock_recv_bitmap_set(block, host);
4156             }
4157 
4158             trace_ram_load_loop(block->idstr, (uint64_t)addr, flags, host);
4159         }
4160 
4161         switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
4162         case RAM_SAVE_FLAG_MEM_SIZE:
4163             ret = parse_ramblocks(f, addr);
4164             /*
4165              * For mapped-ram migration (to a file) using multifd, we sync
4166              * once and for all here to make sure all tasks we queued to
4167              * multifd threads are completed, so that all the ramblocks
4168              * (including all the guest memory pages within) are fully
4169              * loaded after this sync returns.
4170              */
4171             if (migrate_mapped_ram()) {
4172                 multifd_recv_sync_main();
4173             }
4174             break;
4175 
4176         case RAM_SAVE_FLAG_ZERO:
4177             ch = qemu_get_byte(f);
4178             if (ch != 0) {
4179                 error_report("Found a zero page with value %d", ch);
4180                 ret = -EINVAL;
4181                 break;
4182             }
4183             ram_handle_zero(host, TARGET_PAGE_SIZE);
4184             break;
4185 
4186         case RAM_SAVE_FLAG_PAGE:
4187             qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
4188             break;
4189 
4190         case RAM_SAVE_FLAG_XBZRLE:
4191             if (load_xbzrle(f, addr, host) < 0) {
4192                 error_report("Failed to decompress XBZRLE page at "
4193                              RAM_ADDR_FMT, addr);
4194                 ret = -EINVAL;
4195                 break;
4196             }
4197             break;
4198         case RAM_SAVE_FLAG_MULTIFD_FLUSH:
4199             multifd_recv_sync_main();
4200             break;
4201         case RAM_SAVE_FLAG_EOS:
4202             /* normal exit */
4203             if (migrate_multifd() &&
4204                 migrate_multifd_flush_after_each_section() &&
4205                 /*
4206                  * Mapped-ram migration flushes once and for all after
4207                  * parsing ramblocks. Always ignore EOS for it.
4208                  */
4209                 !migrate_mapped_ram()) {
4210                 multifd_recv_sync_main();
4211             }
4212             break;
4213         case RAM_SAVE_FLAG_HOOK:
4214             ret = rdma_registration_handle(f);
4215             if (ret < 0) {
4216                 qemu_file_set_error(f, ret);
4217             }
4218             break;
4219         default:
4220             error_report("Unknown combination of migration flags: 0x%x", flags);
4221             ret = -EINVAL;
4222         }
4223         if (!ret) {
4224             ret = qemu_file_get_error(f);
4225         }
4226         if (!ret && host_bak) {
4227             memcpy(host_bak, host, TARGET_PAGE_SIZE);
4228         }
4229     }
4230 
4231     return ret;
4232 }
4233 
4234 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4235 {
4236     int ret = 0;
4237     static uint64_t seq_iter;
4238     /*
4239      * If system is running in postcopy mode, page inserts to host memory must
4240      * be atomic
4241      */
4242     bool postcopy_running = postcopy_is_running();
4243 
4244     seq_iter++;
4245 
4246     if (version_id != 4) {
4247         return -EINVAL;
4248     }
4249 
4250     /*
4251      * This RCU critical section can be very long running.
4252      * When RCU reclaims in the code start to become numerous,
4253      * it will be necessary to reduce the granularity of this
4254      * critical section.
4255      */
4256     trace_ram_load_start();
4257     WITH_RCU_READ_LOCK_GUARD() {
4258         if (postcopy_running) {
4259             /*
4260              * Note!  Here RAM_CHANNEL_PRECOPY is the precopy channel of
4261              * postcopy migration, we have another RAM_CHANNEL_POSTCOPY to
4262              * service fast page faults.
4263              */
4264             ret = ram_load_postcopy(f, RAM_CHANNEL_PRECOPY);
4265         } else {
4266             ret = ram_load_precopy(f);
4267         }
4268     }
4269     trace_ram_load_complete(ret, seq_iter);
4270 
4271     return ret;
4272 }
4273 
4274 static bool ram_has_postcopy(void *opaque)
4275 {
4276     RAMBlock *rb;
4277     RAMBLOCK_FOREACH_NOT_IGNORED(rb) {
4278         if (ramblock_is_pmem(rb)) {
4279             info_report("Block: %s, host: %p is a nvdimm memory, postcopy"
4280                          "is not supported now!", rb->idstr, rb->host);
4281             return false;
4282         }
4283     }
4284 
4285     return migrate_postcopy_ram();
4286 }
4287 
4288 /* Sync all the dirty bitmap with destination VM.  */
4289 static int ram_dirty_bitmap_sync_all(MigrationState *s, RAMState *rs)
4290 {
4291     RAMBlock *block;
4292     QEMUFile *file = s->to_dst_file;
4293 
4294     trace_ram_dirty_bitmap_sync_start();
4295 
4296     qatomic_set(&rs->postcopy_bmap_sync_requested, 0);
4297     RAMBLOCK_FOREACH_NOT_IGNORED(block) {
4298         qemu_savevm_send_recv_bitmap(file, block->idstr);
4299         trace_ram_dirty_bitmap_request(block->idstr);
4300         qatomic_inc(&rs->postcopy_bmap_sync_requested);
4301     }
4302 
4303     trace_ram_dirty_bitmap_sync_wait();
4304 
4305     /* Wait until all the ramblocks' dirty bitmap synced */
4306     while (qatomic_read(&rs->postcopy_bmap_sync_requested)) {
4307         if (migration_rp_wait(s)) {
4308             return -1;
4309         }
4310     }
4311 
4312     trace_ram_dirty_bitmap_sync_complete();
4313 
4314     return 0;
4315 }
4316 
4317 /*
4318  * Read the received bitmap, revert it as the initial dirty bitmap.
4319  * This is only used when the postcopy migration is paused but wants
4320  * to resume from a middle point.
4321  *
4322  * Returns true if succeeded, false for errors.
4323  */
4324 bool ram_dirty_bitmap_reload(MigrationState *s, RAMBlock *block, Error **errp)
4325 {
4326     /* from_dst_file is always valid because we're within rp_thread */
4327     QEMUFile *file = s->rp_state.from_dst_file;
4328     g_autofree unsigned long *le_bitmap = NULL;
4329     unsigned long nbits = block->used_length >> TARGET_PAGE_BITS;
4330     uint64_t local_size = DIV_ROUND_UP(nbits, 8);
4331     uint64_t size, end_mark;
4332     RAMState *rs = ram_state;
4333 
4334     trace_ram_dirty_bitmap_reload_begin(block->idstr);
4335 
4336     if (s->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
4337         error_setg(errp, "Reload bitmap in incorrect state %s",
4338                    MigrationStatus_str(s->state));
4339         return false;
4340     }
4341 
4342     /*
4343      * Note: see comments in ramblock_recv_bitmap_send() on why we
4344      * need the endianness conversion, and the paddings.
4345      */
4346     local_size = ROUND_UP(local_size, 8);
4347 
4348     /* Add paddings */
4349     le_bitmap = bitmap_new(nbits + BITS_PER_LONG);
4350 
4351     size = qemu_get_be64(file);
4352 
4353     /* The size of the bitmap should match with our ramblock */
4354     if (size != local_size) {
4355         error_setg(errp, "ramblock '%s' bitmap size mismatch (0x%"PRIx64
4356                    " != 0x%"PRIx64")", block->idstr, size, local_size);
4357         return false;
4358     }
4359 
4360     size = qemu_get_buffer(file, (uint8_t *)le_bitmap, local_size);
4361     end_mark = qemu_get_be64(file);
4362 
4363     if (qemu_file_get_error(file) || size != local_size) {
4364         error_setg(errp, "read bitmap failed for ramblock '%s': "
4365                    "(size 0x%"PRIx64", got: 0x%"PRIx64")",
4366                    block->idstr, local_size, size);
4367         return false;
4368     }
4369 
4370     if (end_mark != RAMBLOCK_RECV_BITMAP_ENDING) {
4371         error_setg(errp, "ramblock '%s' end mark incorrect: 0x%"PRIx64,
4372                    block->idstr, end_mark);
4373         return false;
4374     }
4375 
4376     /*
4377      * Endianness conversion. We are during postcopy (though paused).
4378      * The dirty bitmap won't change. We can directly modify it.
4379      */
4380     bitmap_from_le(block->bmap, le_bitmap, nbits);
4381 
4382     /*
4383      * What we received is "received bitmap". Revert it as the initial
4384      * dirty bitmap for this ramblock.
4385      */
4386     bitmap_complement(block->bmap, block->bmap, nbits);
4387 
4388     /* Clear dirty bits of discarded ranges that we don't want to migrate. */
4389     ramblock_dirty_bitmap_clear_discarded_pages(block);
4390 
4391     /* We'll recalculate migration_dirty_pages in ram_state_resume_prepare(). */
4392     trace_ram_dirty_bitmap_reload_complete(block->idstr);
4393 
4394     qatomic_dec(&rs->postcopy_bmap_sync_requested);
4395 
4396     /*
4397      * We succeeded to sync bitmap for current ramblock. Always kick the
4398      * migration thread to check whether all requested bitmaps are
4399      * reloaded.  NOTE: it's racy to only kick when requested==0, because
4400      * we don't know whether the migration thread may still be increasing
4401      * it.
4402      */
4403     migration_rp_kick(s);
4404 
4405     return true;
4406 }
4407 
4408 static int ram_resume_prepare(MigrationState *s, void *opaque)
4409 {
4410     RAMState *rs = *(RAMState **)opaque;
4411     int ret;
4412 
4413     ret = ram_dirty_bitmap_sync_all(s, rs);
4414     if (ret) {
4415         return ret;
4416     }
4417 
4418     ram_state_resume_prepare(rs, s->to_dst_file);
4419 
4420     return 0;
4421 }
4422 
4423 void postcopy_preempt_shutdown_file(MigrationState *s)
4424 {
4425     qemu_put_be64(s->postcopy_qemufile_src, RAM_SAVE_FLAG_EOS);
4426     qemu_fflush(s->postcopy_qemufile_src);
4427 }
4428 
4429 static SaveVMHandlers savevm_ram_handlers = {
4430     .save_setup = ram_save_setup,
4431     .save_live_iterate = ram_save_iterate,
4432     .save_live_complete_postcopy = ram_save_complete,
4433     .save_live_complete_precopy = ram_save_complete,
4434     .has_postcopy = ram_has_postcopy,
4435     .state_pending_exact = ram_state_pending_exact,
4436     .state_pending_estimate = ram_state_pending_estimate,
4437     .load_state = ram_load,
4438     .save_cleanup = ram_save_cleanup,
4439     .load_setup = ram_load_setup,
4440     .load_cleanup = ram_load_cleanup,
4441     .resume_prepare = ram_resume_prepare,
4442 };
4443 
4444 static void ram_mig_ram_block_resized(RAMBlockNotifier *n, void *host,
4445                                       size_t old_size, size_t new_size)
4446 {
4447     PostcopyState ps = postcopy_state_get();
4448     ram_addr_t offset;
4449     RAMBlock *rb = qemu_ram_block_from_host(host, false, &offset);
4450     Error *err = NULL;
4451 
4452     if (!rb) {
4453         error_report("RAM block not found");
4454         return;
4455     }
4456 
4457     if (migrate_ram_is_ignored(rb)) {
4458         return;
4459     }
4460 
4461     if (migration_is_running()) {
4462         /*
4463          * Precopy code on the source cannot deal with the size of RAM blocks
4464          * changing at random points in time - especially after sending the
4465          * RAM block sizes in the migration stream, they must no longer change.
4466          * Abort and indicate a proper reason.
4467          */
4468         error_setg(&err, "RAM block '%s' resized during precopy.", rb->idstr);
4469         migrate_set_error(migrate_get_current(), err);
4470         error_free(err);
4471 
4472         migration_cancel();
4473     }
4474 
4475     switch (ps) {
4476     case POSTCOPY_INCOMING_ADVISE:
4477         /*
4478          * Update what ram_postcopy_incoming_init()->init_range() does at the
4479          * time postcopy was advised. Syncing RAM blocks with the source will
4480          * result in RAM resizes.
4481          */
4482         if (old_size < new_size) {
4483             if (ram_discard_range(rb->idstr, old_size, new_size - old_size)) {
4484                 error_report("RAM block '%s' discard of resized RAM failed",
4485                              rb->idstr);
4486             }
4487         }
4488         rb->postcopy_length = new_size;
4489         break;
4490     case POSTCOPY_INCOMING_NONE:
4491     case POSTCOPY_INCOMING_RUNNING:
4492     case POSTCOPY_INCOMING_END:
4493         /*
4494          * Once our guest is running, postcopy does no longer care about
4495          * resizes. When growing, the new memory was not available on the
4496          * source, no handler needed.
4497          */
4498         break;
4499     default:
4500         error_report("RAM block '%s' resized during postcopy state: %d",
4501                      rb->idstr, ps);
4502         exit(-1);
4503     }
4504 }
4505 
4506 static RAMBlockNotifier ram_mig_ram_notifier = {
4507     .ram_block_resized = ram_mig_ram_block_resized,
4508 };
4509 
4510 void ram_mig_init(void)
4511 {
4512     qemu_mutex_init(&XBZRLE.lock);
4513     register_savevm_live("ram", 0, 4, &savevm_ram_handlers, &ram_state);
4514     ram_block_notifier_add(&ram_mig_ram_notifier);
4515 }
4516