xref: /qemu/system/arch_init.c (revision 73bab2fc2adeb18b26752937f3cf60afa9658a9c)
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 #include <stdint.h>
25 #include <stdarg.h>
26 #include <stdlib.h>
27 #ifndef _WIN32
28 #include <sys/types.h>
29 #include <sys/mman.h>
30 #endif
31 #include "config.h"
32 #include "monitor/monitor.h"
33 #include "sysemu/sysemu.h"
34 #include "qemu/bitops.h"
35 #include "qemu/bitmap.h"
36 #include "sysemu/arch_init.h"
37 #include "audio/audio.h"
38 #include "hw/i386/pc.h"
39 #include "hw/pci/pci.h"
40 #include "hw/audio/audio.h"
41 #include "sysemu/kvm.h"
42 #include "migration/migration.h"
43 #include "hw/i386/smbios.h"
44 #include "exec/address-spaces.h"
45 #include "hw/audio/pcspk.h"
46 #include "migration/page_cache.h"
47 #include "qemu/config-file.h"
48 #include "qemu/error-report.h"
49 #include "qmp-commands.h"
50 #include "trace.h"
51 #include "exec/cpu-all.h"
52 #include "exec/ram_addr.h"
53 #include "hw/acpi/acpi.h"
54 #include "qemu/host-utils.h"
55 #include "qemu/rcu_queue.h"
56 
57 #ifdef DEBUG_ARCH_INIT
58 #define DPRINTF(fmt, ...) \
59     do { fprintf(stdout, "arch_init: " fmt, ## __VA_ARGS__); } while (0)
60 #else
61 #define DPRINTF(fmt, ...) \
62     do { } while (0)
63 #endif
64 
65 #ifdef TARGET_SPARC
66 int graphic_width = 1024;
67 int graphic_height = 768;
68 int graphic_depth = 8;
69 #else
70 int graphic_width = 800;
71 int graphic_height = 600;
72 int graphic_depth = 32;
73 #endif
74 
75 
76 #if defined(TARGET_ALPHA)
77 #define QEMU_ARCH QEMU_ARCH_ALPHA
78 #elif defined(TARGET_ARM)
79 #define QEMU_ARCH QEMU_ARCH_ARM
80 #elif defined(TARGET_CRIS)
81 #define QEMU_ARCH QEMU_ARCH_CRIS
82 #elif defined(TARGET_I386)
83 #define QEMU_ARCH QEMU_ARCH_I386
84 #elif defined(TARGET_M68K)
85 #define QEMU_ARCH QEMU_ARCH_M68K
86 #elif defined(TARGET_LM32)
87 #define QEMU_ARCH QEMU_ARCH_LM32
88 #elif defined(TARGET_MICROBLAZE)
89 #define QEMU_ARCH QEMU_ARCH_MICROBLAZE
90 #elif defined(TARGET_MIPS)
91 #define QEMU_ARCH QEMU_ARCH_MIPS
92 #elif defined(TARGET_MOXIE)
93 #define QEMU_ARCH QEMU_ARCH_MOXIE
94 #elif defined(TARGET_OPENRISC)
95 #define QEMU_ARCH QEMU_ARCH_OPENRISC
96 #elif defined(TARGET_PPC)
97 #define QEMU_ARCH QEMU_ARCH_PPC
98 #elif defined(TARGET_S390X)
99 #define QEMU_ARCH QEMU_ARCH_S390X
100 #elif defined(TARGET_SH4)
101 #define QEMU_ARCH QEMU_ARCH_SH4
102 #elif defined(TARGET_SPARC)
103 #define QEMU_ARCH QEMU_ARCH_SPARC
104 #elif defined(TARGET_XTENSA)
105 #define QEMU_ARCH QEMU_ARCH_XTENSA
106 #elif defined(TARGET_UNICORE32)
107 #define QEMU_ARCH QEMU_ARCH_UNICORE32
108 #elif defined(TARGET_TRICORE)
109 #define QEMU_ARCH QEMU_ARCH_TRICORE
110 #endif
111 
112 const uint32_t arch_type = QEMU_ARCH;
113 static bool mig_throttle_on;
114 static int dirty_rate_high_cnt;
115 static void check_guest_throttling(void);
116 
117 static uint64_t bitmap_sync_count;
118 
119 /***********************************************************/
120 /* ram save/restore */
121 
122 #define RAM_SAVE_FLAG_FULL     0x01 /* Obsolete, not used anymore */
123 #define RAM_SAVE_FLAG_COMPRESS 0x02
124 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
125 #define RAM_SAVE_FLAG_PAGE     0x08
126 #define RAM_SAVE_FLAG_EOS      0x10
127 #define RAM_SAVE_FLAG_CONTINUE 0x20
128 #define RAM_SAVE_FLAG_XBZRLE   0x40
129 /* 0x80 is reserved in migration.h start with 0x100 next */
130 
131 static struct defconfig_file {
132     const char *filename;
133     /* Indicates it is an user config file (disabled by -no-user-config) */
134     bool userconfig;
135 } default_config_files[] = {
136     { CONFIG_QEMU_CONFDIR "/qemu.conf",                   true },
137     { CONFIG_QEMU_CONFDIR "/target-" TARGET_NAME ".conf", true },
138     { NULL }, /* end of list */
139 };
140 
141 static const uint8_t ZERO_TARGET_PAGE[TARGET_PAGE_SIZE];
142 
143 int qemu_read_default_config_files(bool userconfig)
144 {
145     int ret;
146     struct defconfig_file *f;
147 
148     for (f = default_config_files; f->filename; f++) {
149         if (!userconfig && f->userconfig) {
150             continue;
151         }
152         ret = qemu_read_config_file(f->filename);
153         if (ret < 0 && ret != -ENOENT) {
154             return ret;
155         }
156     }
157 
158     return 0;
159 }
160 
161 static inline bool is_zero_range(uint8_t *p, uint64_t size)
162 {
163     return buffer_find_nonzero_offset(p, size) == size;
164 }
165 
166 /* struct contains XBZRLE cache and a static page
167    used by the compression */
168 static struct {
169     /* buffer used for XBZRLE encoding */
170     uint8_t *encoded_buf;
171     /* buffer for storing page content */
172     uint8_t *current_buf;
173     /* Cache for XBZRLE, Protected by lock. */
174     PageCache *cache;
175     QemuMutex lock;
176 } XBZRLE;
177 
178 /* buffer used for XBZRLE decoding */
179 static uint8_t *xbzrle_decoded_buf;
180 
181 static void XBZRLE_cache_lock(void)
182 {
183     if (migrate_use_xbzrle())
184         qemu_mutex_lock(&XBZRLE.lock);
185 }
186 
187 static void XBZRLE_cache_unlock(void)
188 {
189     if (migrate_use_xbzrle())
190         qemu_mutex_unlock(&XBZRLE.lock);
191 }
192 
193 /*
194  * called from qmp_migrate_set_cache_size in main thread, possibly while
195  * a migration is in progress.
196  * A running migration maybe using the cache and might finish during this
197  * call, hence changes to the cache are protected by XBZRLE.lock().
198  */
199 int64_t xbzrle_cache_resize(int64_t new_size)
200 {
201     PageCache *new_cache;
202     int64_t ret;
203 
204     if (new_size < TARGET_PAGE_SIZE) {
205         return -1;
206     }
207 
208     XBZRLE_cache_lock();
209 
210     if (XBZRLE.cache != NULL) {
211         if (pow2floor(new_size) == migrate_xbzrle_cache_size()) {
212             goto out_new_size;
213         }
214         new_cache = cache_init(new_size / TARGET_PAGE_SIZE,
215                                         TARGET_PAGE_SIZE);
216         if (!new_cache) {
217             error_report("Error creating cache");
218             ret = -1;
219             goto out;
220         }
221 
222         cache_fini(XBZRLE.cache);
223         XBZRLE.cache = new_cache;
224     }
225 
226 out_new_size:
227     ret = pow2floor(new_size);
228 out:
229     XBZRLE_cache_unlock();
230     return ret;
231 }
232 
233 /* accounting for migration statistics */
234 typedef struct AccountingInfo {
235     uint64_t dup_pages;
236     uint64_t skipped_pages;
237     uint64_t norm_pages;
238     uint64_t iterations;
239     uint64_t xbzrle_bytes;
240     uint64_t xbzrle_pages;
241     uint64_t xbzrle_cache_miss;
242     double xbzrle_cache_miss_rate;
243     uint64_t xbzrle_overflows;
244 } AccountingInfo;
245 
246 static AccountingInfo acct_info;
247 
248 static void acct_clear(void)
249 {
250     memset(&acct_info, 0, sizeof(acct_info));
251 }
252 
253 uint64_t dup_mig_bytes_transferred(void)
254 {
255     return acct_info.dup_pages * TARGET_PAGE_SIZE;
256 }
257 
258 uint64_t dup_mig_pages_transferred(void)
259 {
260     return acct_info.dup_pages;
261 }
262 
263 uint64_t skipped_mig_bytes_transferred(void)
264 {
265     return acct_info.skipped_pages * TARGET_PAGE_SIZE;
266 }
267 
268 uint64_t skipped_mig_pages_transferred(void)
269 {
270     return acct_info.skipped_pages;
271 }
272 
273 uint64_t norm_mig_bytes_transferred(void)
274 {
275     return acct_info.norm_pages * TARGET_PAGE_SIZE;
276 }
277 
278 uint64_t norm_mig_pages_transferred(void)
279 {
280     return acct_info.norm_pages;
281 }
282 
283 uint64_t xbzrle_mig_bytes_transferred(void)
284 {
285     return acct_info.xbzrle_bytes;
286 }
287 
288 uint64_t xbzrle_mig_pages_transferred(void)
289 {
290     return acct_info.xbzrle_pages;
291 }
292 
293 uint64_t xbzrle_mig_pages_cache_miss(void)
294 {
295     return acct_info.xbzrle_cache_miss;
296 }
297 
298 double xbzrle_mig_cache_miss_rate(void)
299 {
300     return acct_info.xbzrle_cache_miss_rate;
301 }
302 
303 uint64_t xbzrle_mig_pages_overflow(void)
304 {
305     return acct_info.xbzrle_overflows;
306 }
307 
308 /* This is the last block that we have visited serching for dirty pages
309  */
310 static RAMBlock *last_seen_block;
311 /* This is the last block from where we have sent data */
312 static RAMBlock *last_sent_block;
313 static ram_addr_t last_offset;
314 static unsigned long *migration_bitmap;
315 static uint64_t migration_dirty_pages;
316 static uint32_t last_version;
317 static bool ram_bulk_stage;
318 
319 static size_t save_block_hdr(QEMUFile *f, RAMBlock *block, ram_addr_t offset,
320                              int flag)
321 {
322     size_t size;
323 
324     if (block == last_sent_block) {
325         offset |= RAM_SAVE_FLAG_CONTINUE;
326     }
327 
328     qemu_put_be64(f, offset | flag);
329     size = 8;
330 
331     if (block != last_sent_block) {
332         qemu_put_byte(f, strlen(block->idstr));
333         qemu_put_buffer(f, (uint8_t *)block->idstr,
334                         strlen(block->idstr));
335         size += 1 + strlen(block->idstr);
336         last_sent_block = block;
337     }
338     return size;
339 }
340 
341 /* Update the xbzrle cache to reflect a page that's been sent as all 0.
342  * The important thing is that a stale (not-yet-0'd) page be replaced
343  * by the new data.
344  * As a bonus, if the page wasn't in the cache it gets added so that
345  * when a small write is made into the 0'd page it gets XBZRLE sent
346  */
347 static void xbzrle_cache_zero_page(ram_addr_t current_addr)
348 {
349     if (ram_bulk_stage || !migrate_use_xbzrle()) {
350         return;
351     }
352 
353     /* We don't care if this fails to allocate a new cache page
354      * as long as it updated an old one */
355     cache_insert(XBZRLE.cache, current_addr, ZERO_TARGET_PAGE,
356                  bitmap_sync_count);
357 }
358 
359 #define ENCODING_FLAG_XBZRLE 0x1
360 
361 /**
362  * save_xbzrle_page: compress and send current page
363  *
364  * Returns: 1 means that we wrote the page
365  *          0 means that page is identical to the one already sent
366  *          -1 means that xbzrle would be longer than normal
367  *
368  * @f: QEMUFile where to send the data
369  * @current_data:
370  * @current_addr:
371  * @block: block that contains the page we want to send
372  * @offset: offset inside the block for the page
373  * @last_stage: if we are at the completion stage
374  * @bytes_transferred: increase it with the number of transferred bytes
375  */
376 static int save_xbzrle_page(QEMUFile *f, uint8_t **current_data,
377                             ram_addr_t current_addr, RAMBlock *block,
378                             ram_addr_t offset, bool last_stage,
379                             uint64_t *bytes_transferred)
380 {
381     int encoded_len = 0, bytes_xbzrle;
382     uint8_t *prev_cached_page;
383 
384     if (!cache_is_cached(XBZRLE.cache, current_addr, bitmap_sync_count)) {
385         acct_info.xbzrle_cache_miss++;
386         if (!last_stage) {
387             if (cache_insert(XBZRLE.cache, current_addr, *current_data,
388                              bitmap_sync_count) == -1) {
389                 return -1;
390             } else {
391                 /* update *current_data when the page has been
392                    inserted into cache */
393                 *current_data = get_cached_data(XBZRLE.cache, current_addr);
394             }
395         }
396         return -1;
397     }
398 
399     prev_cached_page = get_cached_data(XBZRLE.cache, current_addr);
400 
401     /* save current buffer into memory */
402     memcpy(XBZRLE.current_buf, *current_data, TARGET_PAGE_SIZE);
403 
404     /* XBZRLE encoding (if there is no overflow) */
405     encoded_len = xbzrle_encode_buffer(prev_cached_page, XBZRLE.current_buf,
406                                        TARGET_PAGE_SIZE, XBZRLE.encoded_buf,
407                                        TARGET_PAGE_SIZE);
408     if (encoded_len == 0) {
409         DPRINTF("Skipping unmodified page\n");
410         return 0;
411     } else if (encoded_len == -1) {
412         DPRINTF("Overflow\n");
413         acct_info.xbzrle_overflows++;
414         /* update data in the cache */
415         if (!last_stage) {
416             memcpy(prev_cached_page, *current_data, TARGET_PAGE_SIZE);
417             *current_data = prev_cached_page;
418         }
419         return -1;
420     }
421 
422     /* we need to update the data in the cache, in order to get the same data */
423     if (!last_stage) {
424         memcpy(prev_cached_page, XBZRLE.current_buf, TARGET_PAGE_SIZE);
425     }
426 
427     /* Send XBZRLE based compressed page */
428     bytes_xbzrle = save_block_hdr(f, block, offset, RAM_SAVE_FLAG_XBZRLE);
429     qemu_put_byte(f, ENCODING_FLAG_XBZRLE);
430     qemu_put_be16(f, encoded_len);
431     qemu_put_buffer(f, XBZRLE.encoded_buf, encoded_len);
432     bytes_xbzrle += encoded_len + 1 + 2;
433     acct_info.xbzrle_pages++;
434     acct_info.xbzrle_bytes += bytes_xbzrle;
435     *bytes_transferred += bytes_xbzrle;
436 
437     return 1;
438 }
439 
440 static inline
441 ram_addr_t migration_bitmap_find_and_reset_dirty(MemoryRegion *mr,
442                                                  ram_addr_t start)
443 {
444     unsigned long base = mr->ram_addr >> TARGET_PAGE_BITS;
445     unsigned long nr = base + (start >> TARGET_PAGE_BITS);
446     uint64_t mr_size = TARGET_PAGE_ALIGN(memory_region_size(mr));
447     unsigned long size = base + (mr_size >> TARGET_PAGE_BITS);
448 
449     unsigned long next;
450 
451     if (ram_bulk_stage && nr > base) {
452         next = nr + 1;
453     } else {
454         next = find_next_bit(migration_bitmap, size, nr);
455     }
456 
457     if (next < size) {
458         clear_bit(next, migration_bitmap);
459         migration_dirty_pages--;
460     }
461     return (next - base) << TARGET_PAGE_BITS;
462 }
463 
464 static inline bool migration_bitmap_set_dirty(ram_addr_t addr)
465 {
466     bool ret;
467     int nr = addr >> TARGET_PAGE_BITS;
468 
469     ret = test_and_set_bit(nr, migration_bitmap);
470 
471     if (!ret) {
472         migration_dirty_pages++;
473     }
474     return ret;
475 }
476 
477 static void migration_bitmap_sync_range(ram_addr_t start, ram_addr_t length)
478 {
479     ram_addr_t addr;
480     unsigned long page = BIT_WORD(start >> TARGET_PAGE_BITS);
481 
482     /* start address is aligned at the start of a word? */
483     if (((page * BITS_PER_LONG) << TARGET_PAGE_BITS) == start) {
484         int k;
485         int nr = BITS_TO_LONGS(length >> TARGET_PAGE_BITS);
486         unsigned long *src = ram_list.dirty_memory[DIRTY_MEMORY_MIGRATION];
487 
488         for (k = page; k < page + nr; k++) {
489             if (src[k]) {
490                 unsigned long new_dirty;
491                 new_dirty = ~migration_bitmap[k];
492                 migration_bitmap[k] |= src[k];
493                 new_dirty &= src[k];
494                 migration_dirty_pages += ctpopl(new_dirty);
495                 src[k] = 0;
496             }
497         }
498     } else {
499         for (addr = 0; addr < length; addr += TARGET_PAGE_SIZE) {
500             if (cpu_physical_memory_get_dirty(start + addr,
501                                               TARGET_PAGE_SIZE,
502                                               DIRTY_MEMORY_MIGRATION)) {
503                 cpu_physical_memory_reset_dirty(start + addr,
504                                                 TARGET_PAGE_SIZE,
505                                                 DIRTY_MEMORY_MIGRATION);
506                 migration_bitmap_set_dirty(start + addr);
507             }
508         }
509     }
510 }
511 
512 
513 /* Fix me: there are too many global variables used in migration process. */
514 static int64_t start_time;
515 static int64_t bytes_xfer_prev;
516 static int64_t num_dirty_pages_period;
517 
518 static void migration_bitmap_sync_init(void)
519 {
520     start_time = 0;
521     bytes_xfer_prev = 0;
522     num_dirty_pages_period = 0;
523 }
524 
525 /* Called with iothread lock held, to protect ram_list.dirty_memory[] */
526 static void migration_bitmap_sync(void)
527 {
528     RAMBlock *block;
529     uint64_t num_dirty_pages_init = migration_dirty_pages;
530     MigrationState *s = migrate_get_current();
531     int64_t end_time;
532     int64_t bytes_xfer_now;
533     static uint64_t xbzrle_cache_miss_prev;
534     static uint64_t iterations_prev;
535 
536     bitmap_sync_count++;
537 
538     if (!bytes_xfer_prev) {
539         bytes_xfer_prev = ram_bytes_transferred();
540     }
541 
542     if (!start_time) {
543         start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
544     }
545 
546     trace_migration_bitmap_sync_start();
547     address_space_sync_dirty_bitmap(&address_space_memory);
548 
549     rcu_read_lock();
550     QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
551         migration_bitmap_sync_range(block->mr->ram_addr, block->used_length);
552     }
553     rcu_read_unlock();
554 
555     trace_migration_bitmap_sync_end(migration_dirty_pages
556                                     - num_dirty_pages_init);
557     num_dirty_pages_period += migration_dirty_pages - num_dirty_pages_init;
558     end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
559 
560     /* more than 1 second = 1000 millisecons */
561     if (end_time > start_time + 1000) {
562         if (migrate_auto_converge()) {
563             /* The following detection logic can be refined later. For now:
564                Check to see if the dirtied bytes is 50% more than the approx.
565                amount of bytes that just got transferred since the last time we
566                were in this routine. If that happens >N times (for now N==4)
567                we turn on the throttle down logic */
568             bytes_xfer_now = ram_bytes_transferred();
569             if (s->dirty_pages_rate &&
570                (num_dirty_pages_period * TARGET_PAGE_SIZE >
571                    (bytes_xfer_now - bytes_xfer_prev)/2) &&
572                (dirty_rate_high_cnt++ > 4)) {
573                     trace_migration_throttle();
574                     mig_throttle_on = true;
575                     dirty_rate_high_cnt = 0;
576              }
577              bytes_xfer_prev = bytes_xfer_now;
578         } else {
579              mig_throttle_on = false;
580         }
581         if (migrate_use_xbzrle()) {
582             if (iterations_prev != 0) {
583                 acct_info.xbzrle_cache_miss_rate =
584                    (double)(acct_info.xbzrle_cache_miss -
585                             xbzrle_cache_miss_prev) /
586                    (acct_info.iterations - iterations_prev);
587             }
588             iterations_prev = acct_info.iterations;
589             xbzrle_cache_miss_prev = acct_info.xbzrle_cache_miss;
590         }
591         s->dirty_pages_rate = num_dirty_pages_period * 1000
592             / (end_time - start_time);
593         s->dirty_bytes_rate = s->dirty_pages_rate * TARGET_PAGE_SIZE;
594         start_time = end_time;
595         num_dirty_pages_period = 0;
596         s->dirty_sync_count = bitmap_sync_count;
597     }
598 }
599 
600 /**
601  * ram_save_page: Send the given page to the stream
602  *
603  * Returns: Number of pages written.
604  *
605  * @f: QEMUFile where to send the data
606  * @block: block that contains the page we want to send
607  * @offset: offset inside the block for the page
608  * @last_stage: if we are at the completion stage
609  * @bytes_transferred: increase it with the number of transferred bytes
610  */
611 static int ram_save_page(QEMUFile *f, RAMBlock* block, ram_addr_t offset,
612                          bool last_stage, uint64_t *bytes_transferred)
613 {
614     int pages = -1;
615     uint64_t bytes_xmit;
616     ram_addr_t current_addr;
617     MemoryRegion *mr = block->mr;
618     uint8_t *p;
619     int ret;
620     bool send_async = true;
621 
622     p = memory_region_get_ram_ptr(mr) + offset;
623 
624     /* In doubt sent page as normal */
625     bytes_xmit = 0;
626     ret = ram_control_save_page(f, block->offset,
627                            offset, TARGET_PAGE_SIZE, &bytes_xmit);
628     if (bytes_xmit) {
629         *bytes_transferred += bytes_xmit;
630         pages = 1;
631     }
632 
633     XBZRLE_cache_lock();
634 
635     current_addr = block->offset + offset;
636     if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {
637         if (ret != RAM_SAVE_CONTROL_DELAYED) {
638             if (bytes_xmit > 0) {
639                 acct_info.norm_pages++;
640             } else if (bytes_xmit == 0) {
641                 acct_info.dup_pages++;
642             }
643         }
644     } else if (is_zero_range(p, TARGET_PAGE_SIZE)) {
645         acct_info.dup_pages++;
646         *bytes_transferred += save_block_hdr(f, block, offset,
647                                              RAM_SAVE_FLAG_COMPRESS);
648         qemu_put_byte(f, 0);
649         *bytes_transferred += 1;
650         pages = 1;
651         /* Must let xbzrle know, otherwise a previous (now 0'd) cached
652          * page would be stale
653          */
654         xbzrle_cache_zero_page(current_addr);
655     } else if (!ram_bulk_stage && migrate_use_xbzrle()) {
656         pages = save_xbzrle_page(f, &p, current_addr, block,
657                                  offset, last_stage, bytes_transferred);
658         if (!last_stage) {
659             /* Can't send this cached data async, since the cache page
660              * might get updated before it gets to the wire
661              */
662             send_async = false;
663         }
664     }
665 
666     /* XBZRLE overflow or normal page */
667     if (pages == -1) {
668         *bytes_transferred += save_block_hdr(f, block, offset,
669                                              RAM_SAVE_FLAG_PAGE);
670         if (send_async) {
671             qemu_put_buffer_async(f, p, TARGET_PAGE_SIZE);
672         } else {
673             qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
674         }
675         *bytes_transferred += TARGET_PAGE_SIZE;
676         pages = 1;
677         acct_info.norm_pages++;
678     }
679 
680     XBZRLE_cache_unlock();
681 
682     return pages;
683 }
684 
685 /**
686  * ram_find_and_save_block: Finds a dirty page and sends it to f
687  *
688  * Called within an RCU critical section.
689  *
690  * Returns:  The number of pages written
691  *           0 means no dirty pages
692  *
693  * @f: QEMUFile where to send the data
694  * @last_stage: if we are at the completion stage
695  * @bytes_transferred: increase it with the number of transferred bytes
696  */
697 
698 static int ram_find_and_save_block(QEMUFile *f, bool last_stage,
699                                    uint64_t *bytes_transferred)
700 {
701     RAMBlock *block = last_seen_block;
702     ram_addr_t offset = last_offset;
703     bool complete_round = false;
704     int pages = 0;
705     MemoryRegion *mr;
706 
707     if (!block)
708         block = QLIST_FIRST_RCU(&ram_list.blocks);
709 
710     while (true) {
711         mr = block->mr;
712         offset = migration_bitmap_find_and_reset_dirty(mr, offset);
713         if (complete_round && block == last_seen_block &&
714             offset >= last_offset) {
715             break;
716         }
717         if (offset >= block->used_length) {
718             offset = 0;
719             block = QLIST_NEXT_RCU(block, next);
720             if (!block) {
721                 block = QLIST_FIRST_RCU(&ram_list.blocks);
722                 complete_round = true;
723                 ram_bulk_stage = false;
724             }
725         } else {
726             pages = ram_save_page(f, block, offset, last_stage,
727                                   bytes_transferred);
728 
729             /* if page is unmodified, continue to the next */
730             if (pages > 0) {
731                 break;
732             }
733         }
734     }
735 
736     last_seen_block = block;
737     last_offset = offset;
738 
739     return pages;
740 }
741 
742 static uint64_t bytes_transferred;
743 
744 void acct_update_position(QEMUFile *f, size_t size, bool zero)
745 {
746     uint64_t pages = size / TARGET_PAGE_SIZE;
747     if (zero) {
748         acct_info.dup_pages += pages;
749     } else {
750         acct_info.norm_pages += pages;
751         bytes_transferred += size;
752         qemu_update_position(f, size);
753     }
754 }
755 
756 static ram_addr_t ram_save_remaining(void)
757 {
758     return migration_dirty_pages;
759 }
760 
761 uint64_t ram_bytes_remaining(void)
762 {
763     return ram_save_remaining() * TARGET_PAGE_SIZE;
764 }
765 
766 uint64_t ram_bytes_transferred(void)
767 {
768     return bytes_transferred;
769 }
770 
771 uint64_t ram_bytes_total(void)
772 {
773     RAMBlock *block;
774     uint64_t total = 0;
775 
776     rcu_read_lock();
777     QLIST_FOREACH_RCU(block, &ram_list.blocks, next)
778         total += block->used_length;
779     rcu_read_unlock();
780     return total;
781 }
782 
783 void free_xbzrle_decoded_buf(void)
784 {
785     g_free(xbzrle_decoded_buf);
786     xbzrle_decoded_buf = NULL;
787 }
788 
789 static void migration_end(void)
790 {
791     if (migration_bitmap) {
792         memory_global_dirty_log_stop();
793         g_free(migration_bitmap);
794         migration_bitmap = NULL;
795     }
796 
797     XBZRLE_cache_lock();
798     if (XBZRLE.cache) {
799         cache_fini(XBZRLE.cache);
800         g_free(XBZRLE.encoded_buf);
801         g_free(XBZRLE.current_buf);
802         XBZRLE.cache = NULL;
803         XBZRLE.encoded_buf = NULL;
804         XBZRLE.current_buf = NULL;
805     }
806     XBZRLE_cache_unlock();
807 }
808 
809 static void ram_migration_cancel(void *opaque)
810 {
811     migration_end();
812 }
813 
814 static void reset_ram_globals(void)
815 {
816     last_seen_block = NULL;
817     last_sent_block = NULL;
818     last_offset = 0;
819     last_version = ram_list.version;
820     ram_bulk_stage = true;
821 }
822 
823 #define MAX_WAIT 50 /* ms, half buffered_file limit */
824 
825 
826 /* Each of ram_save_setup, ram_save_iterate and ram_save_complete has
827  * long-running RCU critical section.  When rcu-reclaims in the code
828  * start to become numerous it will be necessary to reduce the
829  * granularity of these critical sections.
830  */
831 
832 static int ram_save_setup(QEMUFile *f, void *opaque)
833 {
834     RAMBlock *block;
835     int64_t ram_bitmap_pages; /* Size of bitmap in pages, including gaps */
836 
837     mig_throttle_on = false;
838     dirty_rate_high_cnt = 0;
839     bitmap_sync_count = 0;
840     migration_bitmap_sync_init();
841 
842     if (migrate_use_xbzrle()) {
843         XBZRLE_cache_lock();
844         XBZRLE.cache = cache_init(migrate_xbzrle_cache_size() /
845                                   TARGET_PAGE_SIZE,
846                                   TARGET_PAGE_SIZE);
847         if (!XBZRLE.cache) {
848             XBZRLE_cache_unlock();
849             error_report("Error creating cache");
850             return -1;
851         }
852         XBZRLE_cache_unlock();
853 
854         /* We prefer not to abort if there is no memory */
855         XBZRLE.encoded_buf = g_try_malloc0(TARGET_PAGE_SIZE);
856         if (!XBZRLE.encoded_buf) {
857             error_report("Error allocating encoded_buf");
858             return -1;
859         }
860 
861         XBZRLE.current_buf = g_try_malloc(TARGET_PAGE_SIZE);
862         if (!XBZRLE.current_buf) {
863             error_report("Error allocating current_buf");
864             g_free(XBZRLE.encoded_buf);
865             XBZRLE.encoded_buf = NULL;
866             return -1;
867         }
868 
869         acct_clear();
870     }
871 
872     /* iothread lock needed for ram_list.dirty_memory[] */
873     qemu_mutex_lock_iothread();
874     qemu_mutex_lock_ramlist();
875     rcu_read_lock();
876     bytes_transferred = 0;
877     reset_ram_globals();
878 
879     ram_bitmap_pages = last_ram_offset() >> TARGET_PAGE_BITS;
880     migration_bitmap = bitmap_new(ram_bitmap_pages);
881     bitmap_set(migration_bitmap, 0, ram_bitmap_pages);
882 
883     /*
884      * Count the total number of pages used by ram blocks not including any
885      * gaps due to alignment or unplugs.
886      */
887     migration_dirty_pages = 0;
888     QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
889         uint64_t block_pages;
890 
891         block_pages = block->used_length >> TARGET_PAGE_BITS;
892         migration_dirty_pages += block_pages;
893     }
894 
895     memory_global_dirty_log_start();
896     migration_bitmap_sync();
897     qemu_mutex_unlock_ramlist();
898     qemu_mutex_unlock_iothread();
899 
900     qemu_put_be64(f, ram_bytes_total() | RAM_SAVE_FLAG_MEM_SIZE);
901 
902     QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
903         qemu_put_byte(f, strlen(block->idstr));
904         qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));
905         qemu_put_be64(f, block->used_length);
906     }
907 
908     rcu_read_unlock();
909 
910     ram_control_before_iterate(f, RAM_CONTROL_SETUP);
911     ram_control_after_iterate(f, RAM_CONTROL_SETUP);
912 
913     qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
914 
915     return 0;
916 }
917 
918 static int ram_save_iterate(QEMUFile *f, void *opaque)
919 {
920     int ret;
921     int i;
922     int64_t t0;
923     int pages_sent = 0;
924 
925     rcu_read_lock();
926     if (ram_list.version != last_version) {
927         reset_ram_globals();
928     }
929 
930     /* Read version before ram_list.blocks */
931     smp_rmb();
932 
933     ram_control_before_iterate(f, RAM_CONTROL_ROUND);
934 
935     t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
936     i = 0;
937     while ((ret = qemu_file_rate_limit(f)) == 0) {
938         int pages;
939 
940         pages = ram_find_and_save_block(f, false, &bytes_transferred);
941         /* no more pages to sent */
942         if (pages == 0) {
943             break;
944         }
945         pages_sent += pages;
946         acct_info.iterations++;
947         check_guest_throttling();
948         /* we want to check in the 1st loop, just in case it was the 1st time
949            and we had to sync the dirty bitmap.
950            qemu_get_clock_ns() is a bit expensive, so we only check each some
951            iterations
952         */
953         if ((i & 63) == 0) {
954             uint64_t t1 = (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - t0) / 1000000;
955             if (t1 > MAX_WAIT) {
956                 DPRINTF("big wait: %" PRIu64 " milliseconds, %d iterations\n",
957                         t1, i);
958                 break;
959             }
960         }
961         i++;
962     }
963     rcu_read_unlock();
964 
965     /*
966      * Must occur before EOS (or any QEMUFile operation)
967      * because of RDMA protocol.
968      */
969     ram_control_after_iterate(f, RAM_CONTROL_ROUND);
970 
971     qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
972     bytes_transferred += 8;
973 
974     ret = qemu_file_get_error(f);
975     if (ret < 0) {
976         return ret;
977     }
978 
979     return pages_sent;
980 }
981 
982 /* Called with iothread lock */
983 static int ram_save_complete(QEMUFile *f, void *opaque)
984 {
985     rcu_read_lock();
986 
987     migration_bitmap_sync();
988 
989     ram_control_before_iterate(f, RAM_CONTROL_FINISH);
990 
991     /* try transferring iterative blocks of memory */
992 
993     /* flush all remaining blocks regardless of rate limiting */
994     while (true) {
995         int pages;
996 
997         pages = ram_find_and_save_block(f, true, &bytes_transferred);
998         /* no more blocks to sent */
999         if (pages == 0) {
1000             break;
1001         }
1002     }
1003 
1004     ram_control_after_iterate(f, RAM_CONTROL_FINISH);
1005     migration_end();
1006 
1007     rcu_read_unlock();
1008     qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1009 
1010     return 0;
1011 }
1012 
1013 static uint64_t ram_save_pending(QEMUFile *f, void *opaque, uint64_t max_size)
1014 {
1015     uint64_t remaining_size;
1016 
1017     remaining_size = ram_save_remaining() * TARGET_PAGE_SIZE;
1018 
1019     if (remaining_size < max_size) {
1020         qemu_mutex_lock_iothread();
1021         rcu_read_lock();
1022         migration_bitmap_sync();
1023         rcu_read_unlock();
1024         qemu_mutex_unlock_iothread();
1025         remaining_size = ram_save_remaining() * TARGET_PAGE_SIZE;
1026     }
1027     return remaining_size;
1028 }
1029 
1030 static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host)
1031 {
1032     unsigned int xh_len;
1033     int xh_flags;
1034 
1035     if (!xbzrle_decoded_buf) {
1036         xbzrle_decoded_buf = g_malloc(TARGET_PAGE_SIZE);
1037     }
1038 
1039     /* extract RLE header */
1040     xh_flags = qemu_get_byte(f);
1041     xh_len = qemu_get_be16(f);
1042 
1043     if (xh_flags != ENCODING_FLAG_XBZRLE) {
1044         error_report("Failed to load XBZRLE page - wrong compression!");
1045         return -1;
1046     }
1047 
1048     if (xh_len > TARGET_PAGE_SIZE) {
1049         error_report("Failed to load XBZRLE page - len overflow!");
1050         return -1;
1051     }
1052     /* load data and decode */
1053     qemu_get_buffer(f, xbzrle_decoded_buf, xh_len);
1054 
1055     /* decode RLE */
1056     if (xbzrle_decode_buffer(xbzrle_decoded_buf, xh_len, host,
1057                              TARGET_PAGE_SIZE) == -1) {
1058         error_report("Failed to load XBZRLE page - decode error!");
1059         return -1;
1060     }
1061 
1062     return 0;
1063 }
1064 
1065 /* Must be called from within a rcu critical section.
1066  * Returns a pointer from within the RCU-protected ram_list.
1067  */
1068 static inline void *host_from_stream_offset(QEMUFile *f,
1069                                             ram_addr_t offset,
1070                                             int flags)
1071 {
1072     static RAMBlock *block = NULL;
1073     char id[256];
1074     uint8_t len;
1075 
1076     if (flags & RAM_SAVE_FLAG_CONTINUE) {
1077         if (!block || block->max_length <= offset) {
1078             error_report("Ack, bad migration stream!");
1079             return NULL;
1080         }
1081 
1082         return memory_region_get_ram_ptr(block->mr) + offset;
1083     }
1084 
1085     len = qemu_get_byte(f);
1086     qemu_get_buffer(f, (uint8_t *)id, len);
1087     id[len] = 0;
1088 
1089     QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1090         if (!strncmp(id, block->idstr, sizeof(id)) &&
1091             block->max_length > offset) {
1092             return memory_region_get_ram_ptr(block->mr) + offset;
1093         }
1094     }
1095 
1096     error_report("Can't find block %s!", id);
1097     return NULL;
1098 }
1099 
1100 /*
1101  * If a page (or a whole RDMA chunk) has been
1102  * determined to be zero, then zap it.
1103  */
1104 void ram_handle_compressed(void *host, uint8_t ch, uint64_t size)
1105 {
1106     if (ch != 0 || !is_zero_range(host, size)) {
1107         memset(host, ch, size);
1108     }
1109 }
1110 
1111 static int ram_load(QEMUFile *f, void *opaque, int version_id)
1112 {
1113     int flags = 0, ret = 0;
1114     static uint64_t seq_iter;
1115 
1116     seq_iter++;
1117 
1118     if (version_id != 4) {
1119         ret = -EINVAL;
1120     }
1121 
1122     /* This RCU critical section can be very long running.
1123      * When RCU reclaims in the code start to become numerous,
1124      * it will be necessary to reduce the granularity of this
1125      * critical section.
1126      */
1127     rcu_read_lock();
1128     while (!ret && !(flags & RAM_SAVE_FLAG_EOS)) {
1129         ram_addr_t addr, total_ram_bytes;
1130         void *host;
1131         uint8_t ch;
1132 
1133         addr = qemu_get_be64(f);
1134         flags = addr & ~TARGET_PAGE_MASK;
1135         addr &= TARGET_PAGE_MASK;
1136 
1137         switch (flags & ~RAM_SAVE_FLAG_CONTINUE) {
1138         case RAM_SAVE_FLAG_MEM_SIZE:
1139             /* Synchronize RAM block list */
1140             total_ram_bytes = addr;
1141             while (!ret && total_ram_bytes) {
1142                 RAMBlock *block;
1143                 uint8_t len;
1144                 char id[256];
1145                 ram_addr_t length;
1146 
1147                 len = qemu_get_byte(f);
1148                 qemu_get_buffer(f, (uint8_t *)id, len);
1149                 id[len] = 0;
1150                 length = qemu_get_be64(f);
1151 
1152                 QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {
1153                     if (!strncmp(id, block->idstr, sizeof(id))) {
1154                         if (length != block->used_length) {
1155                             Error *local_err = NULL;
1156 
1157                             ret = qemu_ram_resize(block->offset, length, &local_err);
1158                             if (local_err) {
1159                                 error_report_err(local_err);
1160                             }
1161                         }
1162                         break;
1163                     }
1164                 }
1165 
1166                 if (!block) {
1167                     error_report("Unknown ramblock \"%s\", cannot "
1168                                  "accept migration", id);
1169                     ret = -EINVAL;
1170                 }
1171 
1172                 total_ram_bytes -= length;
1173             }
1174             break;
1175         case RAM_SAVE_FLAG_COMPRESS:
1176             host = host_from_stream_offset(f, addr, flags);
1177             if (!host) {
1178                 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
1179                 ret = -EINVAL;
1180                 break;
1181             }
1182             ch = qemu_get_byte(f);
1183             ram_handle_compressed(host, ch, TARGET_PAGE_SIZE);
1184             break;
1185         case RAM_SAVE_FLAG_PAGE:
1186             host = host_from_stream_offset(f, addr, flags);
1187             if (!host) {
1188                 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
1189                 ret = -EINVAL;
1190                 break;
1191             }
1192             qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
1193             break;
1194         case RAM_SAVE_FLAG_XBZRLE:
1195             host = host_from_stream_offset(f, addr, flags);
1196             if (!host) {
1197                 error_report("Illegal RAM offset " RAM_ADDR_FMT, addr);
1198                 ret = -EINVAL;
1199                 break;
1200             }
1201             if (load_xbzrle(f, addr, host) < 0) {
1202                 error_report("Failed to decompress XBZRLE page at "
1203                              RAM_ADDR_FMT, addr);
1204                 ret = -EINVAL;
1205                 break;
1206             }
1207             break;
1208         case RAM_SAVE_FLAG_EOS:
1209             /* normal exit */
1210             break;
1211         default:
1212             if (flags & RAM_SAVE_FLAG_HOOK) {
1213                 ram_control_load_hook(f, flags);
1214             } else {
1215                 error_report("Unknown combination of migration flags: %#x",
1216                              flags);
1217                 ret = -EINVAL;
1218             }
1219         }
1220         if (!ret) {
1221             ret = qemu_file_get_error(f);
1222         }
1223     }
1224 
1225     rcu_read_unlock();
1226     DPRINTF("Completed load of VM with exit code %d seq iteration "
1227             "%" PRIu64 "\n", ret, seq_iter);
1228     return ret;
1229 }
1230 
1231 static SaveVMHandlers savevm_ram_handlers = {
1232     .save_live_setup = ram_save_setup,
1233     .save_live_iterate = ram_save_iterate,
1234     .save_live_complete = ram_save_complete,
1235     .save_live_pending = ram_save_pending,
1236     .load_state = ram_load,
1237     .cancel = ram_migration_cancel,
1238 };
1239 
1240 void ram_mig_init(void)
1241 {
1242     qemu_mutex_init(&XBZRLE.lock);
1243     register_savevm_live(NULL, "ram", 0, 4, &savevm_ram_handlers, NULL);
1244 }
1245 
1246 struct soundhw {
1247     const char *name;
1248     const char *descr;
1249     int enabled;
1250     int isa;
1251     union {
1252         int (*init_isa) (ISABus *bus);
1253         int (*init_pci) (PCIBus *bus);
1254     } init;
1255 };
1256 
1257 static struct soundhw soundhw[9];
1258 static int soundhw_count;
1259 
1260 void isa_register_soundhw(const char *name, const char *descr,
1261                           int (*init_isa)(ISABus *bus))
1262 {
1263     assert(soundhw_count < ARRAY_SIZE(soundhw) - 1);
1264     soundhw[soundhw_count].name = name;
1265     soundhw[soundhw_count].descr = descr;
1266     soundhw[soundhw_count].isa = 1;
1267     soundhw[soundhw_count].init.init_isa = init_isa;
1268     soundhw_count++;
1269 }
1270 
1271 void pci_register_soundhw(const char *name, const char *descr,
1272                           int (*init_pci)(PCIBus *bus))
1273 {
1274     assert(soundhw_count < ARRAY_SIZE(soundhw) - 1);
1275     soundhw[soundhw_count].name = name;
1276     soundhw[soundhw_count].descr = descr;
1277     soundhw[soundhw_count].isa = 0;
1278     soundhw[soundhw_count].init.init_pci = init_pci;
1279     soundhw_count++;
1280 }
1281 
1282 void select_soundhw(const char *optarg)
1283 {
1284     struct soundhw *c;
1285 
1286     if (is_help_option(optarg)) {
1287     show_valid_cards:
1288 
1289         if (soundhw_count) {
1290              printf("Valid sound card names (comma separated):\n");
1291              for (c = soundhw; c->name; ++c) {
1292                  printf ("%-11s %s\n", c->name, c->descr);
1293              }
1294              printf("\n-soundhw all will enable all of the above\n");
1295         } else {
1296              printf("Machine has no user-selectable audio hardware "
1297                     "(it may or may not have always-present audio hardware).\n");
1298         }
1299         exit(!is_help_option(optarg));
1300     }
1301     else {
1302         size_t l;
1303         const char *p;
1304         char *e;
1305         int bad_card = 0;
1306 
1307         if (!strcmp(optarg, "all")) {
1308             for (c = soundhw; c->name; ++c) {
1309                 c->enabled = 1;
1310             }
1311             return;
1312         }
1313 
1314         p = optarg;
1315         while (*p) {
1316             e = strchr(p, ',');
1317             l = !e ? strlen(p) : (size_t) (e - p);
1318 
1319             for (c = soundhw; c->name; ++c) {
1320                 if (!strncmp(c->name, p, l) && !c->name[l]) {
1321                     c->enabled = 1;
1322                     break;
1323                 }
1324             }
1325 
1326             if (!c->name) {
1327                 if (l > 80) {
1328                     error_report("Unknown sound card name (too big to show)");
1329                 }
1330                 else {
1331                     error_report("Unknown sound card name `%.*s'",
1332                                  (int) l, p);
1333                 }
1334                 bad_card = 1;
1335             }
1336             p += l + (e != NULL);
1337         }
1338 
1339         if (bad_card) {
1340             goto show_valid_cards;
1341         }
1342     }
1343 }
1344 
1345 void audio_init(void)
1346 {
1347     struct soundhw *c;
1348     ISABus *isa_bus = (ISABus *) object_resolve_path_type("", TYPE_ISA_BUS, NULL);
1349     PCIBus *pci_bus = (PCIBus *) object_resolve_path_type("", TYPE_PCI_BUS, NULL);
1350 
1351     for (c = soundhw; c->name; ++c) {
1352         if (c->enabled) {
1353             if (c->isa) {
1354                 if (!isa_bus) {
1355                     error_report("ISA bus not available for %s", c->name);
1356                     exit(1);
1357                 }
1358                 c->init.init_isa(isa_bus);
1359             } else {
1360                 if (!pci_bus) {
1361                     error_report("PCI bus not available for %s", c->name);
1362                     exit(1);
1363                 }
1364                 c->init.init_pci(pci_bus);
1365             }
1366         }
1367     }
1368 }
1369 
1370 int qemu_uuid_parse(const char *str, uint8_t *uuid)
1371 {
1372     int ret;
1373 
1374     if (strlen(str) != 36) {
1375         return -1;
1376     }
1377 
1378     ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
1379                  &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
1380                  &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14],
1381                  &uuid[15]);
1382 
1383     if (ret != 16) {
1384         return -1;
1385     }
1386     return 0;
1387 }
1388 
1389 void do_acpitable_option(const QemuOpts *opts)
1390 {
1391 #ifdef TARGET_I386
1392     Error *err = NULL;
1393 
1394     acpi_table_add(opts, &err);
1395     if (err) {
1396         error_report("Wrong acpi table provided: %s",
1397                      error_get_pretty(err));
1398         error_free(err);
1399         exit(1);
1400     }
1401 #endif
1402 }
1403 
1404 void do_smbios_option(QemuOpts *opts)
1405 {
1406 #ifdef TARGET_I386
1407     smbios_entry_add(opts);
1408 #endif
1409 }
1410 
1411 void cpudef_init(void)
1412 {
1413 #if defined(cpudef_setup)
1414     cpudef_setup(); /* parse cpu definitions in target config file */
1415 #endif
1416 }
1417 
1418 int kvm_available(void)
1419 {
1420 #ifdef CONFIG_KVM
1421     return 1;
1422 #else
1423     return 0;
1424 #endif
1425 }
1426 
1427 int xen_available(void)
1428 {
1429 #ifdef CONFIG_XEN
1430     return 1;
1431 #else
1432     return 0;
1433 #endif
1434 }
1435 
1436 
1437 TargetInfo *qmp_query_target(Error **errp)
1438 {
1439     TargetInfo *info = g_malloc0(sizeof(*info));
1440 
1441     info->arch = g_strdup(TARGET_NAME);
1442 
1443     return info;
1444 }
1445 
1446 /* Stub function that's gets run on the vcpu when its brought out of the
1447    VM to run inside qemu via async_run_on_cpu()*/
1448 static void mig_sleep_cpu(void *opq)
1449 {
1450     qemu_mutex_unlock_iothread();
1451     g_usleep(30*1000);
1452     qemu_mutex_lock_iothread();
1453 }
1454 
1455 /* To reduce the dirty rate explicitly disallow the VCPUs from spending
1456    much time in the VM. The migration thread will try to catchup.
1457    Workload will experience a performance drop.
1458 */
1459 static void mig_throttle_guest_down(void)
1460 {
1461     CPUState *cpu;
1462 
1463     qemu_mutex_lock_iothread();
1464     CPU_FOREACH(cpu) {
1465         async_run_on_cpu(cpu, mig_sleep_cpu, NULL);
1466     }
1467     qemu_mutex_unlock_iothread();
1468 }
1469 
1470 static void check_guest_throttling(void)
1471 {
1472     static int64_t t0;
1473     int64_t        t1;
1474 
1475     if (!mig_throttle_on) {
1476         return;
1477     }
1478 
1479     if (!t0)  {
1480         t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1481         return;
1482     }
1483 
1484     t1 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1485 
1486     /* If it has been more than 40 ms since the last time the guest
1487      * was throttled then do it again.
1488      */
1489     if (40 < (t1-t0)/1000000) {
1490         mig_throttle_guest_down();
1491         t0 = t1;
1492     }
1493 }
1494