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