monitor: Fix QMP ABI breakage around "id"
[qemu.git] / arch_init.c
blobb5d90a41fa2495b6648b1fbac83003973150ae2e
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <stdint.h>
25 #include <stdarg.h>
26 #include <stdlib.h>
27 #include <zlib.h>
28 #ifndef _WIN32
29 #include <sys/types.h>
30 #include <sys/mman.h>
31 #endif
32 #include "config.h"
33 #include "monitor/monitor.h"
34 #include "sysemu/sysemu.h"
35 #include "qemu/bitops.h"
36 #include "qemu/bitmap.h"
37 #include "sysemu/arch_init.h"
38 #include "audio/audio.h"
39 #include "hw/i386/pc.h"
40 #include "hw/pci/pci.h"
41 #include "hw/audio/audio.h"
42 #include "sysemu/kvm.h"
43 #include "migration/migration.h"
44 #include "hw/i386/smbios.h"
45 #include "exec/address-spaces.h"
46 #include "hw/audio/pcspk.h"
47 #include "migration/page_cache.h"
48 #include "qemu/config-file.h"
49 #include "qemu/error-report.h"
50 #include "qmp-commands.h"
51 #include "trace.h"
52 #include "exec/cpu-all.h"
53 #include "exec/ram_addr.h"
54 #include "hw/acpi/acpi.h"
55 #include "qemu/host-utils.h"
56 #include "qemu/rcu_queue.h"
58 #ifdef DEBUG_ARCH_INIT
59 #define DPRINTF(fmt, ...) \
60 do { fprintf(stdout, "arch_init: " fmt, ## __VA_ARGS__); } while (0)
61 #else
62 #define DPRINTF(fmt, ...) \
63 do { } while (0)
64 #endif
66 #ifdef TARGET_SPARC
67 int graphic_width = 1024;
68 int graphic_height = 768;
69 int graphic_depth = 8;
70 #else
71 int graphic_width = 800;
72 int graphic_height = 600;
73 int graphic_depth = 32;
74 #endif
77 #if defined(TARGET_ALPHA)
78 #define QEMU_ARCH QEMU_ARCH_ALPHA
79 #elif defined(TARGET_ARM)
80 #define QEMU_ARCH QEMU_ARCH_ARM
81 #elif defined(TARGET_CRIS)
82 #define QEMU_ARCH QEMU_ARCH_CRIS
83 #elif defined(TARGET_I386)
84 #define QEMU_ARCH QEMU_ARCH_I386
85 #elif defined(TARGET_M68K)
86 #define QEMU_ARCH QEMU_ARCH_M68K
87 #elif defined(TARGET_LM32)
88 #define QEMU_ARCH QEMU_ARCH_LM32
89 #elif defined(TARGET_MICROBLAZE)
90 #define QEMU_ARCH QEMU_ARCH_MICROBLAZE
91 #elif defined(TARGET_MIPS)
92 #define QEMU_ARCH QEMU_ARCH_MIPS
93 #elif defined(TARGET_MOXIE)
94 #define QEMU_ARCH QEMU_ARCH_MOXIE
95 #elif defined(TARGET_OPENRISC)
96 #define QEMU_ARCH QEMU_ARCH_OPENRISC
97 #elif defined(TARGET_PPC)
98 #define QEMU_ARCH QEMU_ARCH_PPC
99 #elif defined(TARGET_S390X)
100 #define QEMU_ARCH QEMU_ARCH_S390X
101 #elif defined(TARGET_SH4)
102 #define QEMU_ARCH QEMU_ARCH_SH4
103 #elif defined(TARGET_SPARC)
104 #define QEMU_ARCH QEMU_ARCH_SPARC
105 #elif defined(TARGET_XTENSA)
106 #define QEMU_ARCH QEMU_ARCH_XTENSA
107 #elif defined(TARGET_UNICORE32)
108 #define QEMU_ARCH QEMU_ARCH_UNICORE32
109 #elif defined(TARGET_TRICORE)
110 #define QEMU_ARCH QEMU_ARCH_TRICORE
111 #endif
113 const uint32_t arch_type = QEMU_ARCH;
114 static bool mig_throttle_on;
115 static int dirty_rate_high_cnt;
116 static void check_guest_throttling(void);
118 static uint64_t bitmap_sync_count;
120 /***********************************************************/
121 /* ram save/restore */
123 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
124 #define RAM_SAVE_FLAG_COMPRESS 0x02
125 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
126 #define RAM_SAVE_FLAG_PAGE 0x08
127 #define RAM_SAVE_FLAG_EOS 0x10
128 #define RAM_SAVE_FLAG_CONTINUE 0x20
129 #define RAM_SAVE_FLAG_XBZRLE 0x40
130 /* 0x80 is reserved in migration.h start with 0x100 next */
131 #define RAM_SAVE_FLAG_COMPRESS_PAGE 0x100
133 static struct defconfig_file {
134 const char *filename;
135 /* Indicates it is an user config file (disabled by -no-user-config) */
136 bool userconfig;
137 } default_config_files[] = {
138 { CONFIG_QEMU_CONFDIR "/qemu.conf", true },
139 { NULL }, /* end of list */
142 static const uint8_t ZERO_TARGET_PAGE[TARGET_PAGE_SIZE];
144 int qemu_read_default_config_files(bool userconfig)
146 int ret;
147 struct defconfig_file *f;
149 for (f = default_config_files; f->filename; f++) {
150 if (!userconfig && f->userconfig) {
151 continue;
153 ret = qemu_read_config_file(f->filename);
154 if (ret < 0 && ret != -ENOENT) {
155 return ret;
159 return 0;
162 static inline bool is_zero_range(uint8_t *p, uint64_t size)
164 return buffer_find_nonzero_offset(p, size) == size;
167 /* struct contains XBZRLE cache and a static page
168 used by the compression */
169 static struct {
170 /* buffer used for XBZRLE encoding */
171 uint8_t *encoded_buf;
172 /* buffer for storing page content */
173 uint8_t *current_buf;
174 /* Cache for XBZRLE, Protected by lock. */
175 PageCache *cache;
176 QemuMutex lock;
177 } XBZRLE;
179 /* buffer used for XBZRLE decoding */
180 static uint8_t *xbzrle_decoded_buf;
182 static void XBZRLE_cache_lock(void)
184 if (migrate_use_xbzrle())
185 qemu_mutex_lock(&XBZRLE.lock);
188 static void XBZRLE_cache_unlock(void)
190 if (migrate_use_xbzrle())
191 qemu_mutex_unlock(&XBZRLE.lock);
195 * called from qmp_migrate_set_cache_size in main thread, possibly while
196 * a migration is in progress.
197 * A running migration maybe using the cache and might finish during this
198 * call, hence changes to the cache are protected by XBZRLE.lock().
200 int64_t xbzrle_cache_resize(int64_t new_size)
202 PageCache *new_cache;
203 int64_t ret;
205 if (new_size < TARGET_PAGE_SIZE) {
206 return -1;
209 XBZRLE_cache_lock();
211 if (XBZRLE.cache != NULL) {
212 if (pow2floor(new_size) == migrate_xbzrle_cache_size()) {
213 goto out_new_size;
215 new_cache = cache_init(new_size / TARGET_PAGE_SIZE,
216 TARGET_PAGE_SIZE);
217 if (!new_cache) {
218 error_report("Error creating cache");
219 ret = -1;
220 goto out;
223 cache_fini(XBZRLE.cache);
224 XBZRLE.cache = new_cache;
227 out_new_size:
228 ret = pow2floor(new_size);
229 out:
230 XBZRLE_cache_unlock();
231 return ret;
234 /* accounting for migration statistics */
235 typedef struct AccountingInfo {
236 uint64_t dup_pages;
237 uint64_t skipped_pages;
238 uint64_t norm_pages;
239 uint64_t iterations;
240 uint64_t xbzrle_bytes;
241 uint64_t xbzrle_pages;
242 uint64_t xbzrle_cache_miss;
243 double xbzrle_cache_miss_rate;
244 uint64_t xbzrle_overflows;
245 } AccountingInfo;
247 static AccountingInfo acct_info;
249 static void acct_clear(void)
251 memset(&acct_info, 0, sizeof(acct_info));
254 uint64_t dup_mig_bytes_transferred(void)
256 return acct_info.dup_pages * TARGET_PAGE_SIZE;
259 uint64_t dup_mig_pages_transferred(void)
261 return acct_info.dup_pages;
264 uint64_t skipped_mig_bytes_transferred(void)
266 return acct_info.skipped_pages * TARGET_PAGE_SIZE;
269 uint64_t skipped_mig_pages_transferred(void)
271 return acct_info.skipped_pages;
274 uint64_t norm_mig_bytes_transferred(void)
276 return acct_info.norm_pages * TARGET_PAGE_SIZE;
279 uint64_t norm_mig_pages_transferred(void)
281 return acct_info.norm_pages;
284 uint64_t xbzrle_mig_bytes_transferred(void)
286 return acct_info.xbzrle_bytes;
289 uint64_t xbzrle_mig_pages_transferred(void)
291 return acct_info.xbzrle_pages;
294 uint64_t xbzrle_mig_pages_cache_miss(void)
296 return acct_info.xbzrle_cache_miss;
299 double xbzrle_mig_cache_miss_rate(void)
301 return acct_info.xbzrle_cache_miss_rate;
304 uint64_t xbzrle_mig_pages_overflow(void)
306 return acct_info.xbzrle_overflows;
309 /* This is the last block that we have visited serching for dirty pages
311 static RAMBlock *last_seen_block;
312 /* This is the last block from where we have sent data */
313 static RAMBlock *last_sent_block;
314 static ram_addr_t last_offset;
315 static unsigned long *migration_bitmap;
316 static uint64_t migration_dirty_pages;
317 static uint32_t last_version;
318 static bool ram_bulk_stage;
320 struct CompressParam {
321 bool start;
322 bool done;
323 QEMUFile *file;
324 QemuMutex mutex;
325 QemuCond cond;
326 RAMBlock *block;
327 ram_addr_t offset;
329 typedef struct CompressParam CompressParam;
331 struct DecompressParam {
332 bool start;
333 QemuMutex mutex;
334 QemuCond cond;
335 void *des;
336 uint8 *compbuf;
337 int len;
339 typedef struct DecompressParam DecompressParam;
341 static CompressParam *comp_param;
342 static QemuThread *compress_threads;
343 /* comp_done_cond is used to wake up the migration thread when
344 * one of the compression threads has finished the compression.
345 * comp_done_lock is used to co-work with comp_done_cond.
347 static QemuMutex *comp_done_lock;
348 static QemuCond *comp_done_cond;
349 /* The empty QEMUFileOps will be used by file in CompressParam */
350 static const QEMUFileOps empty_ops = { };
352 static bool compression_switch;
353 static bool quit_comp_thread;
354 static bool quit_decomp_thread;
355 static DecompressParam *decomp_param;
356 static QemuThread *decompress_threads;
357 static uint8_t *compressed_data_buf;
359 static int do_compress_ram_page(CompressParam *param);
361 static void *do_data_compress(void *opaque)
363 CompressParam *param = opaque;
365 while (!quit_comp_thread) {
366 qemu_mutex_lock(&param->mutex);
367 /* Re-check the quit_comp_thread in case of
368 * terminate_compression_threads is called just before
369 * qemu_mutex_lock(&param->mutex) and after
370 * while(!quit_comp_thread), re-check it here can make
371 * sure the compression thread terminate as expected.
373 while (!param->start && !quit_comp_thread) {
374 qemu_cond_wait(&param->cond, &param->mutex);
376 if (!quit_comp_thread) {
377 do_compress_ram_page(param);
379 param->start = false;
380 qemu_mutex_unlock(&param->mutex);
382 qemu_mutex_lock(comp_done_lock);
383 param->done = true;
384 qemu_cond_signal(comp_done_cond);
385 qemu_mutex_unlock(comp_done_lock);
388 return NULL;
391 static inline void terminate_compression_threads(void)
393 int idx, thread_count;
395 thread_count = migrate_compress_threads();
396 quit_comp_thread = true;
397 for (idx = 0; idx < thread_count; idx++) {
398 qemu_mutex_lock(&comp_param[idx].mutex);
399 qemu_cond_signal(&comp_param[idx].cond);
400 qemu_mutex_unlock(&comp_param[idx].mutex);
404 void migrate_compress_threads_join(void)
406 int i, thread_count;
408 if (!migrate_use_compression()) {
409 return;
411 terminate_compression_threads();
412 thread_count = migrate_compress_threads();
413 for (i = 0; i < thread_count; i++) {
414 qemu_thread_join(compress_threads + i);
415 qemu_fclose(comp_param[i].file);
416 qemu_mutex_destroy(&comp_param[i].mutex);
417 qemu_cond_destroy(&comp_param[i].cond);
419 qemu_mutex_destroy(comp_done_lock);
420 qemu_cond_destroy(comp_done_cond);
421 g_free(compress_threads);
422 g_free(comp_param);
423 g_free(comp_done_cond);
424 g_free(comp_done_lock);
425 compress_threads = NULL;
426 comp_param = NULL;
427 comp_done_cond = NULL;
428 comp_done_lock = NULL;
431 void migrate_compress_threads_create(void)
433 int i, thread_count;
435 if (!migrate_use_compression()) {
436 return;
438 quit_comp_thread = false;
439 compression_switch = true;
440 thread_count = migrate_compress_threads();
441 compress_threads = g_new0(QemuThread, thread_count);
442 comp_param = g_new0(CompressParam, thread_count);
443 comp_done_cond = g_new0(QemuCond, 1);
444 comp_done_lock = g_new0(QemuMutex, 1);
445 qemu_cond_init(comp_done_cond);
446 qemu_mutex_init(comp_done_lock);
447 for (i = 0; i < thread_count; i++) {
448 /* com_param[i].file is just used as a dummy buffer to save data, set
449 * it's ops to empty.
451 comp_param[i].file = qemu_fopen_ops(NULL, &empty_ops);
452 comp_param[i].done = true;
453 qemu_mutex_init(&comp_param[i].mutex);
454 qemu_cond_init(&comp_param[i].cond);
455 qemu_thread_create(compress_threads + i, "compress",
456 do_data_compress, comp_param + i,
457 QEMU_THREAD_JOINABLE);
462 * save_page_header: Write page header to wire
464 * If this is the 1st block, it also writes the block identification
466 * Returns: Number of bytes written
468 * @f: QEMUFile where to send the data
469 * @block: block that contains the page we want to send
470 * @offset: offset inside the block for the page
471 * in the lower bits, it contains flags
473 static size_t save_page_header(QEMUFile *f, RAMBlock *block, ram_addr_t offset)
475 size_t size;
477 qemu_put_be64(f, offset);
478 size = 8;
480 if (!(offset & RAM_SAVE_FLAG_CONTINUE)) {
481 qemu_put_byte(f, strlen(block->idstr));
482 qemu_put_buffer(f, (uint8_t *)block->idstr,
483 strlen(block->idstr));
484 size += 1 + strlen(block->idstr);
486 return size;
489 /* Update the xbzrle cache to reflect a page that's been sent as all 0.
490 * The important thing is that a stale (not-yet-0'd) page be replaced
491 * by the new data.
492 * As a bonus, if the page wasn't in the cache it gets added so that
493 * when a small write is made into the 0'd page it gets XBZRLE sent
495 static void xbzrle_cache_zero_page(ram_addr_t current_addr)
497 if (ram_bulk_stage || !migrate_use_xbzrle()) {
498 return;
501 /* We don't care if this fails to allocate a new cache page
502 * as long as it updated an old one */
503 cache_insert(XBZRLE.cache, current_addr, ZERO_TARGET_PAGE,
504 bitmap_sync_count);
507 #define ENCODING_FLAG_XBZRLE 0x1
510 * save_xbzrle_page: compress and send current page
512 * Returns: 1 means that we wrote the page
513 * 0 means that page is identical to the one already sent
514 * -1 means that xbzrle would be longer than normal
516 * @f: QEMUFile where to send the data
517 * @current_data:
518 * @current_addr:
519 * @block: block that contains the page we want to send
520 * @offset: offset inside the block for the page
521 * @last_stage: if we are at the completion stage
522 * @bytes_transferred: increase it with the number of transferred bytes
524 static int save_xbzrle_page(QEMUFile *f, uint8_t **current_data,
525 ram_addr_t current_addr, RAMBlock *block,
526 ram_addr_t offset, bool last_stage,
527 uint64_t *bytes_transferred)
529 int encoded_len = 0, bytes_xbzrle;
530 uint8_t *prev_cached_page;
532 if (!cache_is_cached(XBZRLE.cache, current_addr, bitmap_sync_count)) {
533 acct_info.xbzrle_cache_miss++;
534 if (!last_stage) {
535 if (cache_insert(XBZRLE.cache, current_addr, *current_data,
536 bitmap_sync_count) == -1) {
537 return -1;
538 } else {
539 /* update *current_data when the page has been
540 inserted into cache */
541 *current_data = get_cached_data(XBZRLE.cache, current_addr);
544 return -1;
547 prev_cached_page = get_cached_data(XBZRLE.cache, current_addr);
549 /* save current buffer into memory */
550 memcpy(XBZRLE.current_buf, *current_data, TARGET_PAGE_SIZE);
552 /* XBZRLE encoding (if there is no overflow) */
553 encoded_len = xbzrle_encode_buffer(prev_cached_page, XBZRLE.current_buf,
554 TARGET_PAGE_SIZE, XBZRLE.encoded_buf,
555 TARGET_PAGE_SIZE);
556 if (encoded_len == 0) {
557 DPRINTF("Skipping unmodified page\n");
558 return 0;
559 } else if (encoded_len == -1) {
560 DPRINTF("Overflow\n");
561 acct_info.xbzrle_overflows++;
562 /* update data in the cache */
563 if (!last_stage) {
564 memcpy(prev_cached_page, *current_data, TARGET_PAGE_SIZE);
565 *current_data = prev_cached_page;
567 return -1;
570 /* we need to update the data in the cache, in order to get the same data */
571 if (!last_stage) {
572 memcpy(prev_cached_page, XBZRLE.current_buf, TARGET_PAGE_SIZE);
575 /* Send XBZRLE based compressed page */
576 bytes_xbzrle = save_page_header(f, block, offset | RAM_SAVE_FLAG_XBZRLE);
577 qemu_put_byte(f, ENCODING_FLAG_XBZRLE);
578 qemu_put_be16(f, encoded_len);
579 qemu_put_buffer(f, XBZRLE.encoded_buf, encoded_len);
580 bytes_xbzrle += encoded_len + 1 + 2;
581 acct_info.xbzrle_pages++;
582 acct_info.xbzrle_bytes += bytes_xbzrle;
583 *bytes_transferred += bytes_xbzrle;
585 return 1;
588 static inline
589 ram_addr_t migration_bitmap_find_and_reset_dirty(MemoryRegion *mr,
590 ram_addr_t start)
592 unsigned long base = mr->ram_addr >> TARGET_PAGE_BITS;
593 unsigned long nr = base + (start >> TARGET_PAGE_BITS);
594 uint64_t mr_size = TARGET_PAGE_ALIGN(memory_region_size(mr));
595 unsigned long size = base + (mr_size >> TARGET_PAGE_BITS);
597 unsigned long next;
599 if (ram_bulk_stage && nr > base) {
600 next = nr + 1;
601 } else {
602 next = find_next_bit(migration_bitmap, size, nr);
605 if (next < size) {
606 clear_bit(next, migration_bitmap);
607 migration_dirty_pages--;
609 return (next - base) << TARGET_PAGE_BITS;
612 static inline bool migration_bitmap_set_dirty(ram_addr_t addr)
614 bool ret;
615 int nr = addr >> TARGET_PAGE_BITS;
617 ret = test_and_set_bit(nr, migration_bitmap);
619 if (!ret) {
620 migration_dirty_pages++;
622 return ret;
625 static void migration_bitmap_sync_range(ram_addr_t start, ram_addr_t length)
627 ram_addr_t addr;
628 unsigned long page = BIT_WORD(start >> TARGET_PAGE_BITS);
630 /* start address is aligned at the start of a word? */
631 if (((page * BITS_PER_LONG) << TARGET_PAGE_BITS) == start) {
632 int k;
633 int nr = BITS_TO_LONGS(length >> TARGET_PAGE_BITS);
634 unsigned long *src = ram_list.dirty_memory[DIRTY_MEMORY_MIGRATION];
636 for (k = page; k < page + nr; k++) {
637 if (src[k]) {
638 unsigned long new_dirty;
639 new_dirty = ~migration_bitmap[k];
640 migration_bitmap[k] |= src[k];
641 new_dirty &= src[k];
642 migration_dirty_pages += ctpopl(new_dirty);
643 src[k] = 0;
646 } else {
647 for (addr = 0; addr < length; addr += TARGET_PAGE_SIZE) {
648 if (cpu_physical_memory_get_dirty(start + addr,
649 TARGET_PAGE_SIZE,
650 DIRTY_MEMORY_MIGRATION)) {
651 cpu_physical_memory_reset_dirty(start + addr,
652 TARGET_PAGE_SIZE,
653 DIRTY_MEMORY_MIGRATION);
654 migration_bitmap_set_dirty(start + addr);
661 /* Fix me: there are too many global variables used in migration process. */
662 static int64_t start_time;
663 static int64_t bytes_xfer_prev;
664 static int64_t num_dirty_pages_period;
665 static uint64_t xbzrle_cache_miss_prev;
666 static uint64_t iterations_prev;
668 static void migration_bitmap_sync_init(void)
670 start_time = 0;
671 bytes_xfer_prev = 0;
672 num_dirty_pages_period = 0;
673 xbzrle_cache_miss_prev = 0;
674 iterations_prev = 0;
677 /* Called with iothread lock held, to protect ram_list.dirty_memory[] */
678 static void migration_bitmap_sync(void)
680 RAMBlock *block;
681 uint64_t num_dirty_pages_init = migration_dirty_pages;
682 MigrationState *s = migrate_get_current();
683 int64_t end_time;
684 int64_t bytes_xfer_now;
686 bitmap_sync_count++;
688 if (!bytes_xfer_prev) {
689 bytes_xfer_prev = ram_bytes_transferred();
692 if (!start_time) {
693 start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
696 trace_migration_bitmap_sync_start();
697 address_space_sync_dirty_bitmap(&address_space_memory);
699 rcu_read_lock();
700 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
701 migration_bitmap_sync_range(block->mr->ram_addr, block->used_length);
703 rcu_read_unlock();
705 trace_migration_bitmap_sync_end(migration_dirty_pages
706 - num_dirty_pages_init);
707 num_dirty_pages_period += migration_dirty_pages - num_dirty_pages_init;
708 end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
710 /* more than 1 second = 1000 millisecons */
711 if (end_time > start_time + 1000) {
712 if (migrate_auto_converge()) {
713 /* The following detection logic can be refined later. For now:
714 Check to see if the dirtied bytes is 50% more than the approx.
715 amount of bytes that just got transferred since the last time we
716 were in this routine. If that happens >N times (for now N==4)
717 we turn on the throttle down logic */
718 bytes_xfer_now = ram_bytes_transferred();
719 if (s->dirty_pages_rate &&
720 (num_dirty_pages_period * TARGET_PAGE_SIZE >
721 (bytes_xfer_now - bytes_xfer_prev)/2) &&
722 (dirty_rate_high_cnt++ > 4)) {
723 trace_migration_throttle();
724 mig_throttle_on = true;
725 dirty_rate_high_cnt = 0;
727 bytes_xfer_prev = bytes_xfer_now;
728 } else {
729 mig_throttle_on = false;
731 if (migrate_use_xbzrle()) {
732 if (iterations_prev != acct_info.iterations) {
733 acct_info.xbzrle_cache_miss_rate =
734 (double)(acct_info.xbzrle_cache_miss -
735 xbzrle_cache_miss_prev) /
736 (acct_info.iterations - iterations_prev);
738 iterations_prev = acct_info.iterations;
739 xbzrle_cache_miss_prev = acct_info.xbzrle_cache_miss;
741 s->dirty_pages_rate = num_dirty_pages_period * 1000
742 / (end_time - start_time);
743 s->dirty_bytes_rate = s->dirty_pages_rate * TARGET_PAGE_SIZE;
744 start_time = end_time;
745 num_dirty_pages_period = 0;
747 s->dirty_sync_count = bitmap_sync_count;
751 * save_zero_page: Send the zero page to the stream
753 * Returns: Number of pages written.
755 * @f: QEMUFile where to send the data
756 * @block: block that contains the page we want to send
757 * @offset: offset inside the block for the page
758 * @p: pointer to the page
759 * @bytes_transferred: increase it with the number of transferred bytes
761 static int save_zero_page(QEMUFile *f, RAMBlock *block, ram_addr_t offset,
762 uint8_t *p, uint64_t *bytes_transferred)
764 int pages = -1;
766 if (is_zero_range(p, TARGET_PAGE_SIZE)) {
767 acct_info.dup_pages++;
768 *bytes_transferred += save_page_header(f, block,
769 offset | RAM_SAVE_FLAG_COMPRESS);
770 qemu_put_byte(f, 0);
771 *bytes_transferred += 1;
772 pages = 1;
775 return pages;
779 * ram_save_page: Send the given page to the stream
781 * Returns: Number of pages written.
783 * @f: QEMUFile where to send the data
784 * @block: block that contains the page we want to send
785 * @offset: offset inside the block for the page
786 * @last_stage: if we are at the completion stage
787 * @bytes_transferred: increase it with the number of transferred bytes
789 static int ram_save_page(QEMUFile *f, RAMBlock* block, ram_addr_t offset,
790 bool last_stage, uint64_t *bytes_transferred)
792 int pages = -1;
793 uint64_t bytes_xmit;
794 ram_addr_t current_addr;
795 MemoryRegion *mr = block->mr;
796 uint8_t *p;
797 int ret;
798 bool send_async = true;
800 p = memory_region_get_ram_ptr(mr) + offset;
802 /* In doubt sent page as normal */
803 bytes_xmit = 0;
804 ret = ram_control_save_page(f, block->offset,
805 offset, TARGET_PAGE_SIZE, &bytes_xmit);
806 if (bytes_xmit) {
807 *bytes_transferred += bytes_xmit;
808 pages = 1;
811 XBZRLE_cache_lock();
813 current_addr = block->offset + offset;
815 if (block == last_sent_block) {
816 offset |= RAM_SAVE_FLAG_CONTINUE;
818 if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {
819 if (ret != RAM_SAVE_CONTROL_DELAYED) {
820 if (bytes_xmit > 0) {
821 acct_info.norm_pages++;
822 } else if (bytes_xmit == 0) {
823 acct_info.dup_pages++;
826 } else {
827 pages = save_zero_page(f, block, offset, p, bytes_transferred);
828 if (pages > 0) {
829 /* Must let xbzrle know, otherwise a previous (now 0'd) cached
830 * page would be stale
832 xbzrle_cache_zero_page(current_addr);
833 } else if (!ram_bulk_stage && migrate_use_xbzrle()) {
834 pages = save_xbzrle_page(f, &p, current_addr, block,
835 offset, last_stage, bytes_transferred);
836 if (!last_stage) {
837 /* Can't send this cached data async, since the cache page
838 * might get updated before it gets to the wire
840 send_async = false;
845 /* XBZRLE overflow or normal page */
846 if (pages == -1) {
847 *bytes_transferred += save_page_header(f, block,
848 offset | RAM_SAVE_FLAG_PAGE);
849 if (send_async) {
850 qemu_put_buffer_async(f, p, TARGET_PAGE_SIZE);
851 } else {
852 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
854 *bytes_transferred += TARGET_PAGE_SIZE;
855 pages = 1;
856 acct_info.norm_pages++;
859 XBZRLE_cache_unlock();
861 return pages;
864 static int do_compress_ram_page(CompressParam *param)
866 int bytes_sent, blen;
867 uint8_t *p;
868 RAMBlock *block = param->block;
869 ram_addr_t offset = param->offset;
871 p = memory_region_get_ram_ptr(block->mr) + (offset & TARGET_PAGE_MASK);
873 bytes_sent = save_page_header(param->file, block, offset |
874 RAM_SAVE_FLAG_COMPRESS_PAGE);
875 blen = qemu_put_compression_data(param->file, p, TARGET_PAGE_SIZE,
876 migrate_compress_level());
877 bytes_sent += blen;
879 return bytes_sent;
882 static inline void start_compression(CompressParam *param)
884 param->done = false;
885 qemu_mutex_lock(&param->mutex);
886 param->start = true;
887 qemu_cond_signal(&param->cond);
888 qemu_mutex_unlock(&param->mutex);
891 static inline void start_decompression(DecompressParam *param)
893 qemu_mutex_lock(&param->mutex);
894 param->start = true;
895 qemu_cond_signal(&param->cond);
896 qemu_mutex_unlock(&param->mutex);
899 static uint64_t bytes_transferred;
901 static void flush_compressed_data(QEMUFile *f)
903 int idx, len, thread_count;
905 if (!migrate_use_compression()) {
906 return;
908 thread_count = migrate_compress_threads();
909 for (idx = 0; idx < thread_count; idx++) {
910 if (!comp_param[idx].done) {
911 qemu_mutex_lock(comp_done_lock);
912 while (!comp_param[idx].done && !quit_comp_thread) {
913 qemu_cond_wait(comp_done_cond, comp_done_lock);
915 qemu_mutex_unlock(comp_done_lock);
917 if (!quit_comp_thread) {
918 len = qemu_put_qemu_file(f, comp_param[idx].file);
919 bytes_transferred += len;
924 static inline void set_compress_params(CompressParam *param, RAMBlock *block,
925 ram_addr_t offset)
927 param->block = block;
928 param->offset = offset;
931 static int compress_page_with_multi_thread(QEMUFile *f, RAMBlock *block,
932 ram_addr_t offset,
933 uint64_t *bytes_transferred)
935 int idx, thread_count, bytes_xmit = -1, pages = -1;
937 thread_count = migrate_compress_threads();
938 qemu_mutex_lock(comp_done_lock);
939 while (true) {
940 for (idx = 0; idx < thread_count; idx++) {
941 if (comp_param[idx].done) {
942 bytes_xmit = qemu_put_qemu_file(f, comp_param[idx].file);
943 set_compress_params(&comp_param[idx], block, offset);
944 start_compression(&comp_param[idx]);
945 pages = 1;
946 acct_info.norm_pages++;
947 *bytes_transferred += bytes_xmit;
948 break;
951 if (pages > 0) {
952 break;
953 } else {
954 qemu_cond_wait(comp_done_cond, comp_done_lock);
957 qemu_mutex_unlock(comp_done_lock);
959 return pages;
963 * ram_save_compressed_page: compress the given page and send it to the stream
965 * Returns: Number of pages written.
967 * @f: QEMUFile where to send the data
968 * @block: block that contains the page we want to send
969 * @offset: offset inside the block for the page
970 * @last_stage: if we are at the completion stage
971 * @bytes_transferred: increase it with the number of transferred bytes
973 static int ram_save_compressed_page(QEMUFile *f, RAMBlock *block,
974 ram_addr_t offset, bool last_stage,
975 uint64_t *bytes_transferred)
977 int pages = -1;
978 uint64_t bytes_xmit;
979 MemoryRegion *mr = block->mr;
980 uint8_t *p;
981 int ret;
983 p = memory_region_get_ram_ptr(mr) + offset;
985 bytes_xmit = 0;
986 ret = ram_control_save_page(f, block->offset,
987 offset, TARGET_PAGE_SIZE, &bytes_xmit);
988 if (bytes_xmit) {
989 *bytes_transferred += bytes_xmit;
990 pages = 1;
992 if (block == last_sent_block) {
993 offset |= RAM_SAVE_FLAG_CONTINUE;
995 if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {
996 if (ret != RAM_SAVE_CONTROL_DELAYED) {
997 if (bytes_xmit > 0) {
998 acct_info.norm_pages++;
999 } else if (bytes_xmit == 0) {
1000 acct_info.dup_pages++;
1003 } else {
1004 /* When starting the process of a new block, the first page of
1005 * the block should be sent out before other pages in the same
1006 * block, and all the pages in last block should have been sent
1007 * out, keeping this order is important, because the 'cont' flag
1008 * is used to avoid resending the block name.
1010 if (block != last_sent_block) {
1011 flush_compressed_data(f);
1012 pages = save_zero_page(f, block, offset, p, bytes_transferred);
1013 if (pages == -1) {
1014 set_compress_params(&comp_param[0], block, offset);
1015 /* Use the qemu thread to compress the data to make sure the
1016 * first page is sent out before other pages
1018 bytes_xmit = do_compress_ram_page(&comp_param[0]);
1019 acct_info.norm_pages++;
1020 qemu_put_qemu_file(f, comp_param[0].file);
1021 *bytes_transferred += bytes_xmit;
1022 pages = 1;
1024 } else {
1025 pages = save_zero_page(f, block, offset, p, bytes_transferred);
1026 if (pages == -1) {
1027 pages = compress_page_with_multi_thread(f, block, offset,
1028 bytes_transferred);
1033 return pages;
1037 * ram_find_and_save_block: Finds a dirty page and sends it to f
1039 * Called within an RCU critical section.
1041 * Returns: The number of pages written
1042 * 0 means no dirty pages
1044 * @f: QEMUFile where to send the data
1045 * @last_stage: if we are at the completion stage
1046 * @bytes_transferred: increase it with the number of transferred bytes
1049 static int ram_find_and_save_block(QEMUFile *f, bool last_stage,
1050 uint64_t *bytes_transferred)
1052 RAMBlock *block = last_seen_block;
1053 ram_addr_t offset = last_offset;
1054 bool complete_round = false;
1055 int pages = 0;
1056 MemoryRegion *mr;
1058 if (!block)
1059 block = QLIST_FIRST_RCU(&ram_list.blocks);
1061 while (true) {
1062 mr = block->mr;
1063 offset = migration_bitmap_find_and_reset_dirty(mr, offset);
1064 if (complete_round && block == last_seen_block &&
1065 offset >= last_offset) {
1066 break;
1068 if (offset >= block->used_length) {
1069 offset = 0;
1070 block = QLIST_NEXT_RCU(block, next);
1071 if (!block) {
1072 block = QLIST_FIRST_RCU(&ram_list.blocks);
1073 complete_round = true;
1074 ram_bulk_stage = false;
1075 if (migrate_use_xbzrle()) {
1076 /* If xbzrle is on, stop using the data compression at this
1077 * point. In theory, xbzrle can do better than compression.
1079 flush_compressed_data(f);
1080 compression_switch = false;
1083 } else {
1084 if (compression_switch && migrate_use_compression()) {
1085 pages = ram_save_compressed_page(f, block, offset, last_stage,
1086 bytes_transferred);
1087 } else {
1088 pages = ram_save_page(f, block, offset, last_stage,
1089 bytes_transferred);
1092 /* if page is unmodified, continue to the next */
1093 if (pages > 0) {
1094 last_sent_block = block;
1095 break;
1100 last_seen_block = block;
1101 last_offset = offset;
1103 return pages;
1106 void acct_update_position(QEMUFile *f, size_t size, bool zero)
1108 uint64_t pages = size / TARGET_PAGE_SIZE;
1109 if (zero) {
1110 acct_info.dup_pages += pages;
1111 } else {
1112 acct_info.norm_pages += pages;
1113 bytes_transferred += size;
1114 qemu_update_position(f, size);
1118 static ram_addr_t ram_save_remaining(void)
1120 return migration_dirty_pages;
1123 uint64_t ram_bytes_remaining(void)
1125 return ram_save_remaining() * TARGET_PAGE_SIZE;
1128 uint64_t ram_bytes_transferred(void)
1130 return bytes_transferred;
1133 uint64_t ram_bytes_total(void)
1135 RAMBlock *block;
1136 uint64_t total = 0;
1138 rcu_read_lock();
1139 QLIST_FOREACH_RCU(block, &ram_list.blocks, next)
1140 total += block->used_length;
1141 rcu_read_unlock();
1142 return total;
1145 void free_xbzrle_decoded_buf(void)
1147 g_free(xbzrle_decoded_buf);
1148 xbzrle_decoded_buf = NULL;
1151 static void migration_end(void)
1153 if (migration_bitmap) {
1154 memory_global_dirty_log_stop();
1155 g_free(migration_bitmap);
1156 migration_bitmap = NULL;
1159 XBZRLE_cache_lock();
1160 if (XBZRLE.cache) {
1161 cache_fini(XBZRLE.cache);
1162 g_free(XBZRLE.encoded_buf);
1163 g_free(XBZRLE.current_buf);
1164 XBZRLE.cache = NULL;
1165 XBZRLE.encoded_buf = NULL;
1166 XBZRLE.current_buf = NULL;
1168 XBZRLE_cache_unlock();
1171 static void ram_migration_cancel(void *opaque)
1173 migration_end();
1176 static void reset_ram_globals(void)
1178 last_seen_block = NULL;
1179 last_sent_block = NULL;
1180 last_offset = 0;
1181 last_version = ram_list.version;
1182 ram_bulk_stage = true;
1185 #define MAX_WAIT 50 /* ms, half buffered_file limit */
1188 /* Each of ram_save_setup, ram_save_iterate and ram_save_complete has
1189 * long-running RCU critical section. When rcu-reclaims in the code
1190 * start to become numerous it will be necessary to reduce the
1191 * granularity of these critical sections.
1194 static int ram_save_setup(QEMUFile *f, void *opaque)
1196 RAMBlock *block;
1197 int64_t ram_bitmap_pages; /* Size of bitmap in pages, including gaps */
1199 mig_throttle_on = false;
1200 dirty_rate_high_cnt = 0;
1201 bitmap_sync_count = 0;
1202 migration_bitmap_sync_init();
1204 if (migrate_use_xbzrle()) {
1205 XBZRLE_cache_lock();
1206 XBZRLE.cache = cache_init(migrate_xbzrle_cache_size() /
1207 TARGET_PAGE_SIZE,
1208 TARGET_PAGE_SIZE);
1209 if (!XBZRLE.cache) {
1210 XBZRLE_cache_unlock();
1211 error_report("Error creating cache");
1212 return -1;
1214 XBZRLE_cache_unlock();
1216 /* We prefer not to abort if there is no memory */
1217 XBZRLE.encoded_buf = g_try_malloc0(TARGET_PAGE_SIZE);
1218 if (!XBZRLE.encoded_buf) {
1219 error_report("Error allocating encoded_buf");
1220 return -1;
1223 XBZRLE.current_buf = g_try_malloc(TARGET_PAGE_SIZE);
1224 if (!XBZRLE.current_buf) {
1225 error_report("Error allocating current_buf");
1226 g_free(XBZRLE.encoded_buf);
1227 XBZRLE.encoded_buf = NULL;
1228 return -1;
1231 acct_clear();
1234 /* iothread lock needed for ram_list.dirty_memory[] */
1235 qemu_mutex_lock_iothread();
1236 qemu_mutex_lock_ramlist();
1237 rcu_read_lock();
1238 bytes_transferred = 0;
1239 reset_ram_globals();
1241 ram_bitmap_pages = last_ram_offset() >> TARGET_PAGE_BITS;
1242 migration_bitmap = bitmap_new(ram_bitmap_pages);
1243 bitmap_set(migration_bitmap, 0, ram_bitmap_pages);
1246 * Count the total number of pages used by ram blocks not including any
1247 * gaps due to alignment or unplugs.
1249 migration_dirty_pages = ram_bytes_total() >> TARGET_PAGE_BITS;
1251 memory_global_dirty_log_start();
1252 migration_bitmap_sync();
1253 qemu_mutex_unlock_ramlist();
1254 qemu_mutex_unlock_iothread();
1256 qemu_put_be64(f, ram_bytes_total() | RAM_SAVE_FLAG_MEM_SIZE);
1258 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1259 qemu_put_byte(f, strlen(block->idstr));
1260 qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));
1261 qemu_put_be64(f, block->used_length);
1264 rcu_read_unlock();
1266 ram_control_before_iterate(f, RAM_CONTROL_SETUP);
1267 ram_control_after_iterate(f, RAM_CONTROL_SETUP);
1269 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1271 return 0;
1274 static int ram_save_iterate(QEMUFile *f, void *opaque)
1276 int ret;
1277 int i;
1278 int64_t t0;
1279 int pages_sent = 0;
1281 rcu_read_lock();
1282 if (ram_list.version != last_version) {
1283 reset_ram_globals();
1286 /* Read version before ram_list.blocks */
1287 smp_rmb();
1289 ram_control_before_iterate(f, RAM_CONTROL_ROUND);
1291 t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1292 i = 0;
1293 while ((ret = qemu_file_rate_limit(f)) == 0) {
1294 int pages;
1296 pages = ram_find_and_save_block(f, false, &bytes_transferred);
1297 /* no more pages to sent */
1298 if (pages == 0) {
1299 break;
1301 pages_sent += pages;
1302 acct_info.iterations++;
1303 check_guest_throttling();
1304 /* we want to check in the 1st loop, just in case it was the 1st time
1305 and we had to sync the dirty bitmap.
1306 qemu_get_clock_ns() is a bit expensive, so we only check each some
1307 iterations
1309 if ((i & 63) == 0) {
1310 uint64_t t1 = (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - t0) / 1000000;
1311 if (t1 > MAX_WAIT) {
1312 DPRINTF("big wait: %" PRIu64 " milliseconds, %d iterations\n",
1313 t1, i);
1314 break;
1317 i++;
1319 flush_compressed_data(f);
1320 rcu_read_unlock();
1323 * Must occur before EOS (or any QEMUFile operation)
1324 * because of RDMA protocol.
1326 ram_control_after_iterate(f, RAM_CONTROL_ROUND);
1328 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1329 bytes_transferred += 8;
1331 ret = qemu_file_get_error(f);
1332 if (ret < 0) {
1333 return ret;
1336 return pages_sent;
1339 /* Called with iothread lock */
1340 static int ram_save_complete(QEMUFile *f, void *opaque)
1342 rcu_read_lock();
1344 migration_bitmap_sync();
1346 ram_control_before_iterate(f, RAM_CONTROL_FINISH);
1348 /* try transferring iterative blocks of memory */
1350 /* flush all remaining blocks regardless of rate limiting */
1351 while (true) {
1352 int pages;
1354 pages = ram_find_and_save_block(f, true, &bytes_transferred);
1355 /* no more blocks to sent */
1356 if (pages == 0) {
1357 break;
1361 flush_compressed_data(f);
1362 ram_control_after_iterate(f, RAM_CONTROL_FINISH);
1363 migration_end();
1365 rcu_read_unlock();
1366 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1368 return 0;
1371 static uint64_t ram_save_pending(QEMUFile *f, void *opaque, uint64_t max_size)
1373 uint64_t remaining_size;
1375 remaining_size = ram_save_remaining() * TARGET_PAGE_SIZE;
1377 if (remaining_size < max_size) {
1378 qemu_mutex_lock_iothread();
1379 rcu_read_lock();
1380 migration_bitmap_sync();
1381 rcu_read_unlock();
1382 qemu_mutex_unlock_iothread();
1383 remaining_size = ram_save_remaining() * TARGET_PAGE_SIZE;
1385 return remaining_size;
1388 static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host)
1390 unsigned int xh_len;
1391 int xh_flags;
1393 if (!xbzrle_decoded_buf) {
1394 xbzrle_decoded_buf = g_malloc(TARGET_PAGE_SIZE);
1397 /* extract RLE header */
1398 xh_flags = qemu_get_byte(f);
1399 xh_len = qemu_get_be16(f);
1401 if (xh_flags != ENCODING_FLAG_XBZRLE) {
1402 error_report("Failed to load XBZRLE page - wrong compression!");
1403 return -1;
1406 if (xh_len > TARGET_PAGE_SIZE) {
1407 error_report("Failed to load XBZRLE page - len overflow!");
1408 return -1;
1410 /* load data and decode */
1411 qemu_get_buffer(f, xbzrle_decoded_buf, xh_len);
1413 /* decode RLE */
1414 if (xbzrle_decode_buffer(xbzrle_decoded_buf, xh_len, host,
1415 TARGET_PAGE_SIZE) == -1) {
1416 error_report("Failed to load XBZRLE page - decode error!");
1417 return -1;
1420 return 0;
1423 /* Must be called from within a rcu critical section.
1424 * Returns a pointer from within the RCU-protected ram_list.
1426 static inline void *host_from_stream_offset(QEMUFile *f,
1427 ram_addr_t offset,
1428 int flags)
1430 static RAMBlock *block = NULL;
1431 char id[256];
1432 uint8_t len;
1434 if (flags & RAM_SAVE_FLAG_CONTINUE) {
1435 if (!block || block->max_length <= offset) {
1436 error_report("Ack, bad migration stream!");
1437 return NULL;
1440 return memory_region_get_ram_ptr(block->mr) + offset;
1443 len = qemu_get_byte(f);
1444 qemu_get_buffer(f, (uint8_t *)id, len);
1445 id[len] = 0;
1447 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1448 if (!strncmp(id, block->idstr, sizeof(id)) &&
1449 block->max_length > offset) {
1450 return memory_region_get_ram_ptr(block->mr) + offset;
1454 error_report("Can't find block %s!", id);
1455 return NULL;
1459 * If a page (or a whole RDMA chunk) has been
1460 * determined to be zero, then zap it.
1462 void ram_handle_compressed(void *host, uint8_t ch, uint64_t size)
1464 if (ch != 0 || !is_zero_range(host, size)) {
1465 memset(host, ch, size);
1469 static void *do_data_decompress(void *opaque)
1471 DecompressParam *param = opaque;
1472 unsigned long pagesize;
1474 while (!quit_decomp_thread) {
1475 qemu_mutex_lock(&param->mutex);
1476 while (!param->start && !quit_decomp_thread) {
1477 qemu_cond_wait(&param->cond, &param->mutex);
1478 pagesize = TARGET_PAGE_SIZE;
1479 if (!quit_decomp_thread) {
1480 /* uncompress() will return failed in some case, especially
1481 * when the page is dirted when doing the compression, it's
1482 * not a problem because the dirty page will be retransferred
1483 * and uncompress() won't break the data in other pages.
1485 uncompress((Bytef *)param->des, &pagesize,
1486 (const Bytef *)param->compbuf, param->len);
1488 param->start = false;
1490 qemu_mutex_unlock(&param->mutex);
1493 return NULL;
1496 void migrate_decompress_threads_create(void)
1498 int i, thread_count;
1500 thread_count = migrate_decompress_threads();
1501 decompress_threads = g_new0(QemuThread, thread_count);
1502 decomp_param = g_new0(DecompressParam, thread_count);
1503 compressed_data_buf = g_malloc0(compressBound(TARGET_PAGE_SIZE));
1504 quit_decomp_thread = false;
1505 for (i = 0; i < thread_count; i++) {
1506 qemu_mutex_init(&decomp_param[i].mutex);
1507 qemu_cond_init(&decomp_param[i].cond);
1508 decomp_param[i].compbuf = g_malloc0(compressBound(TARGET_PAGE_SIZE));
1509 qemu_thread_create(decompress_threads + i, "decompress",
1510 do_data_decompress, decomp_param + i,
1511 QEMU_THREAD_JOINABLE);
1515 void migrate_decompress_threads_join(void)
1517 int i, thread_count;
1519 quit_decomp_thread = true;
1520 thread_count = migrate_decompress_threads();
1521 for (i = 0; i < thread_count; i++) {
1522 qemu_mutex_lock(&decomp_param[i].mutex);
1523 qemu_cond_signal(&decomp_param[i].cond);
1524 qemu_mutex_unlock(&decomp_param[i].mutex);
1526 for (i = 0; i < thread_count; i++) {
1527 qemu_thread_join(decompress_threads + i);
1528 qemu_mutex_destroy(&decomp_param[i].mutex);
1529 qemu_cond_destroy(&decomp_param[i].cond);
1530 g_free(decomp_param[i].compbuf);
1532 g_free(decompress_threads);
1533 g_free(decomp_param);
1534 g_free(compressed_data_buf);
1535 decompress_threads = NULL;
1536 decomp_param = NULL;
1537 compressed_data_buf = NULL;
1540 static void decompress_data_with_multi_threads(uint8_t *compbuf,
1541 void *host, int len)
1543 int idx, thread_count;
1545 thread_count = migrate_decompress_threads();
1546 while (true) {
1547 for (idx = 0; idx < thread_count; idx++) {
1548 if (!decomp_param[idx].start) {
1549 memcpy(decomp_param[idx].compbuf, compbuf, len);
1550 decomp_param[idx].des = host;
1551 decomp_param[idx].len = len;
1552 start_decompression(&decomp_param[idx]);
1553 break;
1556 if (idx < thread_count) {
1557 break;
1562 static int ram_load(QEMUFile *f, void *opaque, int version_id)
1564 int flags = 0, ret = 0;
1565 static uint64_t seq_iter;
1566 int len = 0;
1568 seq_iter++;
1570 if (version_id != 4) {
1571 ret = -EINVAL;
1574 /* This RCU critical section can be very long running.
1575 * When RCU reclaims in the code start to become numerous,
1576 * it will be necessary to reduce the granularity of this
1577 * critical section.
1579 rcu_read_lock();
1580 while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
1581 ram_addr_t addr, total_ram_bytes;
1582 void *host;
1583 uint8_t ch;
1585 addr = qemu_get_be64(f);
1586 flags = addr & ~TARGET_PAGE_MASK;
1587 addr &= TARGET_PAGE_MASK;
1589 switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
1590 case RAM_SAVE_FLAG_MEM_SIZE:
1591 /* Synchronize RAM block list */
1592 total_ram_bytes = addr;
1593 while (!ret && total_ram_bytes) {
1594 RAMBlock *block;
1595 uint8_t len;
1596 char id[256];
1597 ram_addr_t length;
1599 len = qemu_get_byte(f);
1600 qemu_get_buffer(f, (uint8_t *)id, len);
1601 id[len] = 0;
1602 length = qemu_get_be64(f);
1604 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1605 if (!strncmp(id, block->idstr, sizeof(id))) {
1606 if (length != block->used_length) {
1607 Error *local_err = NULL;
1609 ret = qemu_ram_resize(block->offset, length, &local_err);
1610 if (local_err) {
1611 error_report_err(local_err);
1614 break;
1618 if (!block) {
1619 error_report("Unknown ramblock \"%s\", cannot "
1620 "accept migration", id);
1621 ret = -EINVAL;
1624 total_ram_bytes -= length;
1626 break;
1627 case RAM_SAVE_FLAG_COMPRESS:
1628 host = host_from_stream_offset(f, addr, flags);
1629 if (!host) {
1630 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
1631 ret = -EINVAL;
1632 break;
1634 ch = qemu_get_byte(f);
1635 ram_handle_compressed(host, ch, TARGET_PAGE_SIZE);
1636 break;
1637 case RAM_SAVE_FLAG_PAGE:
1638 host = host_from_stream_offset(f, addr, flags);
1639 if (!host) {
1640 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
1641 ret = -EINVAL;
1642 break;
1644 qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
1645 break;
1646 case RAM_SAVE_FLAG_COMPRESS_PAGE:
1647 host = host_from_stream_offset(f, addr, flags);
1648 if (!host) {
1649 error_report("Invalid RAM offset " RAM_ADDR_FMT, addr);
1650 ret = -EINVAL;
1651 break;
1654 len = qemu_get_be32(f);
1655 if (len < 0 || len > compressBound(TARGET_PAGE_SIZE)) {
1656 error_report("Invalid compressed data length: %d", len);
1657 ret = -EINVAL;
1658 break;
1660 qemu_get_buffer(f, compressed_data_buf, len);
1661 decompress_data_with_multi_threads(compressed_data_buf, host, len);
1662 break;
1663 case RAM_SAVE_FLAG_XBZRLE:
1664 host = host_from_stream_offset(f, addr, flags);
1665 if (!host) {
1666 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
1667 ret = -EINVAL;
1668 break;
1670 if (load_xbzrle(f, addr, host) < 0) {
1671 error_report("Failed to decompress XBZRLE page at "
1672 RAM_ADDR_FMT, addr);
1673 ret = -EINVAL;
1674 break;
1676 break;
1677 case RAM_SAVE_FLAG_EOS:
1678 /* normal exit */
1679 break;
1680 default:
1681 if (flags & RAM_SAVE_FLAG_HOOK) {
1682 ram_control_load_hook(f, flags);
1683 } else {
1684 error_report("Unknown combination of migration flags: %#x",
1685 flags);
1686 ret = -EINVAL;
1689 if (!ret) {
1690 ret = qemu_file_get_error(f);
1694 rcu_read_unlock();
1695 DPRINTF("Completed load of VM with exit code %d seq iteration "
1696 "%" PRIu64 "\n", ret, seq_iter);
1697 return ret;
1700 static SaveVMHandlers savevm_ram_handlers = {
1701 .save_live_setup = ram_save_setup,
1702 .save_live_iterate = ram_save_iterate,
1703 .save_live_complete = ram_save_complete,
1704 .save_live_pending = ram_save_pending,
1705 .load_state = ram_load,
1706 .cancel = ram_migration_cancel,
1709 void ram_mig_init(void)
1711 qemu_mutex_init(&XBZRLE.lock);
1712 register_savevm_live(NULL, "ram", 0, 4, &savevm_ram_handlers, NULL);
1715 struct soundhw {
1716 const char *name;
1717 const char *descr;
1718 int enabled;
1719 int isa;
1720 union {
1721 int (*init_isa) (ISABus *bus);
1722 int (*init_pci) (PCIBus *bus);
1723 } init;
1726 static struct soundhw soundhw[9];
1727 static int soundhw_count;
1729 void isa_register_soundhw(const char *name, const char *descr,
1730 int (*init_isa)(ISABus *bus))
1732 assert(soundhw_count < ARRAY_SIZE(soundhw) - 1);
1733 soundhw[soundhw_count].name = name;
1734 soundhw[soundhw_count].descr = descr;
1735 soundhw[soundhw_count].isa = 1;
1736 soundhw[soundhw_count].init.init_isa = init_isa;
1737 soundhw_count++;
1740 void pci_register_soundhw(const char *name, const char *descr,
1741 int (*init_pci)(PCIBus *bus))
1743 assert(soundhw_count < ARRAY_SIZE(soundhw) - 1);
1744 soundhw[soundhw_count].name = name;
1745 soundhw[soundhw_count].descr = descr;
1746 soundhw[soundhw_count].isa = 0;
1747 soundhw[soundhw_count].init.init_pci = init_pci;
1748 soundhw_count++;
1751 void select_soundhw(const char *optarg)
1753 struct soundhw *c;
1755 if (is_help_option(optarg)) {
1756 show_valid_cards:
1758 if (soundhw_count) {
1759 printf("Valid sound card names (comma separated):\n");
1760 for (c = soundhw; c->name; ++c) {
1761 printf ("%-11s %s\n", c->name, c->descr);
1763 printf("\n-soundhw all will enable all of the above\n");
1764 } else {
1765 printf("Machine has no user-selectable audio hardware "
1766 "(it may or may not have always-present audio hardware).\n");
1768 exit(!is_help_option(optarg));
1770 else {
1771 size_t l;
1772 const char *p;
1773 char *e;
1774 int bad_card = 0;
1776 if (!strcmp(optarg, "all")) {
1777 for (c = soundhw; c->name; ++c) {
1778 c->enabled = 1;
1780 return;
1783 p = optarg;
1784 while (*p) {
1785 e = strchr(p, ',');
1786 l = !e ? strlen(p) : (size_t) (e - p);
1788 for (c = soundhw; c->name; ++c) {
1789 if (!strncmp(c->name, p, l) && !c->name[l]) {
1790 c->enabled = 1;
1791 break;
1795 if (!c->name) {
1796 if (l > 80) {
1797 error_report("Unknown sound card name (too big to show)");
1799 else {
1800 error_report("Unknown sound card name `%.*s'",
1801 (int) l, p);
1803 bad_card = 1;
1805 p += l + (e != NULL);
1808 if (bad_card) {
1809 goto show_valid_cards;
1814 void audio_init(void)
1816 struct soundhw *c;
1817 ISABus *isa_bus = (ISABus *) object_resolve_path_type("", TYPE_ISA_BUS, NULL);
1818 PCIBus *pci_bus = (PCIBus *) object_resolve_path_type("", TYPE_PCI_BUS, NULL);
1820 for (c = soundhw; c->name; ++c) {
1821 if (c->enabled) {
1822 if (c->isa) {
1823 if (!isa_bus) {
1824 error_report("ISA bus not available for %s", c->name);
1825 exit(1);
1827 c->init.init_isa(isa_bus);
1828 } else {
1829 if (!pci_bus) {
1830 error_report("PCI bus not available for %s", c->name);
1831 exit(1);
1833 c->init.init_pci(pci_bus);
1839 int qemu_uuid_parse(const char *str, uint8_t *uuid)
1841 int ret;
1843 if (strlen(str) != 36) {
1844 return -1;
1847 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
1848 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
1849 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14],
1850 &uuid[15]);
1852 if (ret != 16) {
1853 return -1;
1855 return 0;
1858 void do_acpitable_option(const QemuOpts *opts)
1860 #ifdef TARGET_I386
1861 Error *err = NULL;
1863 acpi_table_add(opts, &err);
1864 if (err) {
1865 error_report("Wrong acpi table provided: %s",
1866 error_get_pretty(err));
1867 error_free(err);
1868 exit(1);
1870 #endif
1873 void do_smbios_option(QemuOpts *opts)
1875 #ifdef TARGET_I386
1876 smbios_entry_add(opts);
1877 #endif
1880 void cpudef_init(void)
1882 #if defined(cpudef_setup)
1883 cpudef_setup(); /* parse cpu definitions in target config file */
1884 #endif
1887 int kvm_available(void)
1889 #ifdef CONFIG_KVM
1890 return 1;
1891 #else
1892 return 0;
1893 #endif
1896 int xen_available(void)
1898 #ifdef CONFIG_XEN
1899 return 1;
1900 #else
1901 return 0;
1902 #endif
1906 TargetInfo *qmp_query_target(Error **errp)
1908 TargetInfo *info = g_malloc0(sizeof(*info));
1910 info->arch = g_strdup(TARGET_NAME);
1912 return info;
1915 /* Stub function that's gets run on the vcpu when its brought out of the
1916 VM to run inside qemu via async_run_on_cpu()*/
1917 static void mig_sleep_cpu(void *opq)
1919 qemu_mutex_unlock_iothread();
1920 g_usleep(30*1000);
1921 qemu_mutex_lock_iothread();
1924 /* To reduce the dirty rate explicitly disallow the VCPUs from spending
1925 much time in the VM. The migration thread will try to catchup.
1926 Workload will experience a performance drop.
1928 static void mig_throttle_guest_down(void)
1930 CPUState *cpu;
1932 qemu_mutex_lock_iothread();
1933 CPU_FOREACH(cpu) {
1934 async_run_on_cpu(cpu, mig_sleep_cpu, NULL);
1936 qemu_mutex_unlock_iothread();
1939 static void check_guest_throttling(void)
1941 static int64_t t0;
1942 int64_t t1;
1944 if (!mig_throttle_on) {
1945 return;
1948 if (!t0) {
1949 t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1950 return;
1953 t1 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1955 /* If it has been more than 40 ms since the last time the guest
1956 * was throttled then do it again.
1958 if (40 < (t1-t0)/1000000) {
1959 mig_throttle_guest_down();
1960 t0 = t1;