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