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