]> Git Repo - qemu.git/blob - arch_init.c
ram: split function that synchronizes a range
[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 #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 "qmp-commands.h"
49 #include "trace.h"
50 #include "exec/cpu-all.h"
51 #include "exec/ram_addr.h"
52 #include "hw/acpi/acpi.h"
53
54 #ifdef DEBUG_ARCH_INIT
55 #define DPRINTF(fmt, ...) \
56     do { fprintf(stdout, "arch_init: " fmt, ## __VA_ARGS__); } while (0)
57 #else
58 #define DPRINTF(fmt, ...) \
59     do { } while (0)
60 #endif
61
62 #ifdef TARGET_SPARC
63 int graphic_width = 1024;
64 int graphic_height = 768;
65 int graphic_depth = 8;
66 #else
67 int graphic_width = 800;
68 int graphic_height = 600;
69 int graphic_depth = 32;
70 #endif
71
72
73 #if defined(TARGET_ALPHA)
74 #define QEMU_ARCH QEMU_ARCH_ALPHA
75 #elif defined(TARGET_ARM)
76 #define QEMU_ARCH QEMU_ARCH_ARM
77 #elif defined(TARGET_CRIS)
78 #define QEMU_ARCH QEMU_ARCH_CRIS
79 #elif defined(TARGET_I386)
80 #define QEMU_ARCH QEMU_ARCH_I386
81 #elif defined(TARGET_M68K)
82 #define QEMU_ARCH QEMU_ARCH_M68K
83 #elif defined(TARGET_LM32)
84 #define QEMU_ARCH QEMU_ARCH_LM32
85 #elif defined(TARGET_MICROBLAZE)
86 #define QEMU_ARCH QEMU_ARCH_MICROBLAZE
87 #elif defined(TARGET_MIPS)
88 #define QEMU_ARCH QEMU_ARCH_MIPS
89 #elif defined(TARGET_MOXIE)
90 #define QEMU_ARCH QEMU_ARCH_MOXIE
91 #elif defined(TARGET_OPENRISC)
92 #define QEMU_ARCH QEMU_ARCH_OPENRISC
93 #elif defined(TARGET_PPC)
94 #define QEMU_ARCH QEMU_ARCH_PPC
95 #elif defined(TARGET_S390X)
96 #define QEMU_ARCH QEMU_ARCH_S390X
97 #elif defined(TARGET_SH4)
98 #define QEMU_ARCH QEMU_ARCH_SH4
99 #elif defined(TARGET_SPARC)
100 #define QEMU_ARCH QEMU_ARCH_SPARC
101 #elif defined(TARGET_XTENSA)
102 #define QEMU_ARCH QEMU_ARCH_XTENSA
103 #elif defined(TARGET_UNICORE32)
104 #define QEMU_ARCH QEMU_ARCH_UNICORE32
105 #endif
106
107 const uint32_t arch_type = QEMU_ARCH;
108 static bool mig_throttle_on;
109 static int dirty_rate_high_cnt;
110 static void check_guest_throttling(void);
111
112 /***********************************************************/
113 /* ram save/restore */
114
115 #define RAM_SAVE_FLAG_FULL     0x01 /* Obsolete, not used anymore */
116 #define RAM_SAVE_FLAG_COMPRESS 0x02
117 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
118 #define RAM_SAVE_FLAG_PAGE     0x08
119 #define RAM_SAVE_FLAG_EOS      0x10
120 #define RAM_SAVE_FLAG_CONTINUE 0x20
121 #define RAM_SAVE_FLAG_XBZRLE   0x40
122 /* 0x80 is reserved in migration.h start with 0x100 next */
123
124
125 static struct defconfig_file {
126     const char *filename;
127     /* Indicates it is an user config file (disabled by -no-user-config) */
128     bool userconfig;
129 } default_config_files[] = {
130     { CONFIG_QEMU_CONFDIR "/qemu.conf",                   true },
131     { CONFIG_QEMU_CONFDIR "/target-" TARGET_NAME ".conf", true },
132     { NULL }, /* end of list */
133 };
134
135
136 int qemu_read_default_config_files(bool userconfig)
137 {
138     int ret;
139     struct defconfig_file *f;
140
141     for (f = default_config_files; f->filename; f++) {
142         if (!userconfig && f->userconfig) {
143             continue;
144         }
145         ret = qemu_read_config_file(f->filename);
146         if (ret < 0 && ret != -ENOENT) {
147             return ret;
148         }
149     }
150
151     return 0;
152 }
153
154 static inline bool is_zero_range(uint8_t *p, uint64_t size)
155 {
156     return buffer_find_nonzero_offset(p, size) == size;
157 }
158
159 /* struct contains XBZRLE cache and a static page
160    used by the compression */
161 static struct {
162     /* buffer used for XBZRLE encoding */
163     uint8_t *encoded_buf;
164     /* buffer for storing page content */
165     uint8_t *current_buf;
166     /* buffer used for XBZRLE decoding */
167     uint8_t *decoded_buf;
168     /* Cache for XBZRLE */
169     PageCache *cache;
170 } XBZRLE = {
171     .encoded_buf = NULL,
172     .current_buf = NULL,
173     .decoded_buf = NULL,
174     .cache = NULL,
175 };
176
177
178 int64_t xbzrle_cache_resize(int64_t new_size)
179 {
180     if (XBZRLE.cache != NULL) {
181         return cache_resize(XBZRLE.cache, new_size / TARGET_PAGE_SIZE) *
182             TARGET_PAGE_SIZE;
183     }
184     return pow2floor(new_size);
185 }
186
187 /* accounting for migration statistics */
188 typedef struct AccountingInfo {
189     uint64_t dup_pages;
190     uint64_t skipped_pages;
191     uint64_t norm_pages;
192     uint64_t iterations;
193     uint64_t xbzrle_bytes;
194     uint64_t xbzrle_pages;
195     uint64_t xbzrle_cache_miss;
196     uint64_t xbzrle_overflows;
197 } AccountingInfo;
198
199 static AccountingInfo acct_info;
200
201 static void acct_clear(void)
202 {
203     memset(&acct_info, 0, sizeof(acct_info));
204 }
205
206 uint64_t dup_mig_bytes_transferred(void)
207 {
208     return acct_info.dup_pages * TARGET_PAGE_SIZE;
209 }
210
211 uint64_t dup_mig_pages_transferred(void)
212 {
213     return acct_info.dup_pages;
214 }
215
216 uint64_t skipped_mig_bytes_transferred(void)
217 {
218     return acct_info.skipped_pages * TARGET_PAGE_SIZE;
219 }
220
221 uint64_t skipped_mig_pages_transferred(void)
222 {
223     return acct_info.skipped_pages;
224 }
225
226 uint64_t norm_mig_bytes_transferred(void)
227 {
228     return acct_info.norm_pages * TARGET_PAGE_SIZE;
229 }
230
231 uint64_t norm_mig_pages_transferred(void)
232 {
233     return acct_info.norm_pages;
234 }
235
236 uint64_t xbzrle_mig_bytes_transferred(void)
237 {
238     return acct_info.xbzrle_bytes;
239 }
240
241 uint64_t xbzrle_mig_pages_transferred(void)
242 {
243     return acct_info.xbzrle_pages;
244 }
245
246 uint64_t xbzrle_mig_pages_cache_miss(void)
247 {
248     return acct_info.xbzrle_cache_miss;
249 }
250
251 uint64_t xbzrle_mig_pages_overflow(void)
252 {
253     return acct_info.xbzrle_overflows;
254 }
255
256 static size_t save_block_hdr(QEMUFile *f, RAMBlock *block, ram_addr_t offset,
257                              int cont, int flag)
258 {
259     size_t size;
260
261     qemu_put_be64(f, offset | cont | flag);
262     size = 8;
263
264     if (!cont) {
265         qemu_put_byte(f, strlen(block->idstr));
266         qemu_put_buffer(f, (uint8_t *)block->idstr,
267                         strlen(block->idstr));
268         size += 1 + strlen(block->idstr);
269     }
270     return size;
271 }
272
273 #define ENCODING_FLAG_XBZRLE 0x1
274
275 static int save_xbzrle_page(QEMUFile *f, uint8_t *current_data,
276                             ram_addr_t current_addr, RAMBlock *block,
277                             ram_addr_t offset, int cont, bool last_stage)
278 {
279     int encoded_len = 0, bytes_sent = -1;
280     uint8_t *prev_cached_page;
281
282     if (!cache_is_cached(XBZRLE.cache, current_addr)) {
283         if (!last_stage) {
284             cache_insert(XBZRLE.cache, current_addr, current_data);
285         }
286         acct_info.xbzrle_cache_miss++;
287         return -1;
288     }
289
290     prev_cached_page = get_cached_data(XBZRLE.cache, current_addr);
291
292     /* save current buffer into memory */
293     memcpy(XBZRLE.current_buf, current_data, TARGET_PAGE_SIZE);
294
295     /* XBZRLE encoding (if there is no overflow) */
296     encoded_len = xbzrle_encode_buffer(prev_cached_page, XBZRLE.current_buf,
297                                        TARGET_PAGE_SIZE, XBZRLE.encoded_buf,
298                                        TARGET_PAGE_SIZE);
299     if (encoded_len == 0) {
300         DPRINTF("Skipping unmodified page\n");
301         return 0;
302     } else if (encoded_len == -1) {
303         DPRINTF("Overflow\n");
304         acct_info.xbzrle_overflows++;
305         /* update data in the cache */
306         memcpy(prev_cached_page, current_data, TARGET_PAGE_SIZE);
307         return -1;
308     }
309
310     /* we need to update the data in the cache, in order to get the same data */
311     if (!last_stage) {
312         memcpy(prev_cached_page, XBZRLE.current_buf, TARGET_PAGE_SIZE);
313     }
314
315     /* Send XBZRLE based compressed page */
316     bytes_sent = save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_XBZRLE);
317     qemu_put_byte(f, ENCODING_FLAG_XBZRLE);
318     qemu_put_be16(f, encoded_len);
319     qemu_put_buffer(f, XBZRLE.encoded_buf, encoded_len);
320     bytes_sent += encoded_len + 1 + 2;
321     acct_info.xbzrle_pages++;
322     acct_info.xbzrle_bytes += bytes_sent;
323
324     return bytes_sent;
325 }
326
327
328 /* This is the last block that we have visited serching for dirty pages
329  */
330 static RAMBlock *last_seen_block;
331 /* This is the last block from where we have sent data */
332 static RAMBlock *last_sent_block;
333 static ram_addr_t last_offset;
334 static unsigned long *migration_bitmap;
335 static uint64_t migration_dirty_pages;
336 static uint32_t last_version;
337 static bool ram_bulk_stage;
338
339 static inline
340 ram_addr_t migration_bitmap_find_and_reset_dirty(MemoryRegion *mr,
341                                                  ram_addr_t start)
342 {
343     unsigned long base = mr->ram_addr >> TARGET_PAGE_BITS;
344     unsigned long nr = base + (start >> TARGET_PAGE_BITS);
345     uint64_t mr_size = TARGET_PAGE_ALIGN(memory_region_size(mr));
346     unsigned long size = base + (mr_size >> TARGET_PAGE_BITS);
347
348     unsigned long next;
349
350     if (ram_bulk_stage && nr > base) {
351         next = nr + 1;
352     } else {
353         next = find_next_bit(migration_bitmap, size, nr);
354     }
355
356     if (next < size) {
357         clear_bit(next, migration_bitmap);
358         migration_dirty_pages--;
359     }
360     return (next - base) << TARGET_PAGE_BITS;
361 }
362
363 static inline bool migration_bitmap_set_dirty(ram_addr_t addr)
364 {
365     bool ret;
366     int nr = addr >> TARGET_PAGE_BITS;
367
368     ret = test_and_set_bit(nr, migration_bitmap);
369
370     if (!ret) {
371         migration_dirty_pages++;
372     }
373     return ret;
374 }
375
376 static void migration_bitmap_sync_range(ram_addr_t start, ram_addr_t length)
377 {
378     ram_addr_t addr;
379
380     for (addr = 0; addr < length; addr += TARGET_PAGE_SIZE) {
381         if (cpu_physical_memory_get_dirty(start + addr,
382                                           TARGET_PAGE_SIZE,
383                                           DIRTY_MEMORY_MIGRATION)) {
384             cpu_physical_memory_reset_dirty(start + addr,
385                                             TARGET_PAGE_SIZE,
386                                             DIRTY_MEMORY_MIGRATION);
387             migration_bitmap_set_dirty(start + addr);
388         }
389     }
390 }
391
392
393 /* Needs iothread lock! */
394
395 static void migration_bitmap_sync(void)
396 {
397     RAMBlock *block;
398     uint64_t num_dirty_pages_init = migration_dirty_pages;
399     MigrationState *s = migrate_get_current();
400     static int64_t start_time;
401     static int64_t bytes_xfer_prev;
402     static int64_t num_dirty_pages_period;
403     int64_t end_time;
404     int64_t bytes_xfer_now;
405
406     if (!bytes_xfer_prev) {
407         bytes_xfer_prev = ram_bytes_transferred();
408     }
409
410     if (!start_time) {
411         start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
412     }
413
414     trace_migration_bitmap_sync_start();
415     address_space_sync_dirty_bitmap(&address_space_memory);
416
417     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
418         migration_bitmap_sync_range(block->mr->ram_addr, block->length);
419     }
420     trace_migration_bitmap_sync_end(migration_dirty_pages
421                                     - num_dirty_pages_init);
422     num_dirty_pages_period += migration_dirty_pages - num_dirty_pages_init;
423     end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
424
425     /* more than 1 second = 1000 millisecons */
426     if (end_time > start_time + 1000) {
427         if (migrate_auto_converge()) {
428             /* The following detection logic can be refined later. For now:
429                Check to see if the dirtied bytes is 50% more than the approx.
430                amount of bytes that just got transferred since the last time we
431                were in this routine. If that happens >N times (for now N==4)
432                we turn on the throttle down logic */
433             bytes_xfer_now = ram_bytes_transferred();
434             if (s->dirty_pages_rate &&
435                (num_dirty_pages_period * TARGET_PAGE_SIZE >
436                    (bytes_xfer_now - bytes_xfer_prev)/2) &&
437                (dirty_rate_high_cnt++ > 4)) {
438                     trace_migration_throttle();
439                     mig_throttle_on = true;
440                     dirty_rate_high_cnt = 0;
441              }
442              bytes_xfer_prev = bytes_xfer_now;
443         } else {
444              mig_throttle_on = false;
445         }
446         s->dirty_pages_rate = num_dirty_pages_period * 1000
447             / (end_time - start_time);
448         s->dirty_bytes_rate = s->dirty_pages_rate * TARGET_PAGE_SIZE;
449         start_time = end_time;
450         num_dirty_pages_period = 0;
451     }
452 }
453
454 /*
455  * ram_save_block: Writes a page of memory to the stream f
456  *
457  * Returns:  The number of bytes written.
458  *           0 means no dirty pages
459  */
460
461 static int ram_save_block(QEMUFile *f, bool last_stage)
462 {
463     RAMBlock *block = last_seen_block;
464     ram_addr_t offset = last_offset;
465     bool complete_round = false;
466     int bytes_sent = 0;
467     MemoryRegion *mr;
468     ram_addr_t current_addr;
469
470     if (!block)
471         block = QTAILQ_FIRST(&ram_list.blocks);
472
473     while (true) {
474         mr = block->mr;
475         offset = migration_bitmap_find_and_reset_dirty(mr, offset);
476         if (complete_round && block == last_seen_block &&
477             offset >= last_offset) {
478             break;
479         }
480         if (offset >= block->length) {
481             offset = 0;
482             block = QTAILQ_NEXT(block, next);
483             if (!block) {
484                 block = QTAILQ_FIRST(&ram_list.blocks);
485                 complete_round = true;
486                 ram_bulk_stage = false;
487             }
488         } else {
489             int ret;
490             uint8_t *p;
491             int cont = (block == last_sent_block) ?
492                 RAM_SAVE_FLAG_CONTINUE : 0;
493
494             p = memory_region_get_ram_ptr(mr) + offset;
495
496             /* In doubt sent page as normal */
497             bytes_sent = -1;
498             ret = ram_control_save_page(f, block->offset,
499                                offset, TARGET_PAGE_SIZE, &bytes_sent);
500
501             if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {
502                 if (ret != RAM_SAVE_CONTROL_DELAYED) {
503                     if (bytes_sent > 0) {
504                         acct_info.norm_pages++;
505                     } else if (bytes_sent == 0) {
506                         acct_info.dup_pages++;
507                     }
508                 }
509             } else if (is_zero_range(p, TARGET_PAGE_SIZE)) {
510                 acct_info.dup_pages++;
511                 bytes_sent = save_block_hdr(f, block, offset, cont,
512                                             RAM_SAVE_FLAG_COMPRESS);
513                 qemu_put_byte(f, 0);
514                 bytes_sent++;
515             } else if (!ram_bulk_stage && migrate_use_xbzrle()) {
516                 current_addr = block->offset + offset;
517                 bytes_sent = save_xbzrle_page(f, p, current_addr, block,
518                                               offset, cont, last_stage);
519                 if (!last_stage) {
520                     p = get_cached_data(XBZRLE.cache, current_addr);
521                 }
522             }
523
524             /* XBZRLE overflow or normal page */
525             if (bytes_sent == -1) {
526                 bytes_sent = save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_PAGE);
527                 qemu_put_buffer_async(f, p, TARGET_PAGE_SIZE);
528                 bytes_sent += TARGET_PAGE_SIZE;
529                 acct_info.norm_pages++;
530             }
531
532             /* if page is unmodified, continue to the next */
533             if (bytes_sent > 0) {
534                 last_sent_block = block;
535                 break;
536             }
537         }
538     }
539     last_seen_block = block;
540     last_offset = offset;
541
542     return bytes_sent;
543 }
544
545 static uint64_t bytes_transferred;
546
547 void acct_update_position(QEMUFile *f, size_t size, bool zero)
548 {
549     uint64_t pages = size / TARGET_PAGE_SIZE;
550     if (zero) {
551         acct_info.dup_pages += pages;
552     } else {
553         acct_info.norm_pages += pages;
554         bytes_transferred += size;
555         qemu_update_position(f, size);
556     }
557 }
558
559 static ram_addr_t ram_save_remaining(void)
560 {
561     return migration_dirty_pages;
562 }
563
564 uint64_t ram_bytes_remaining(void)
565 {
566     return ram_save_remaining() * TARGET_PAGE_SIZE;
567 }
568
569 uint64_t ram_bytes_transferred(void)
570 {
571     return bytes_transferred;
572 }
573
574 uint64_t ram_bytes_total(void)
575 {
576     RAMBlock *block;
577     uint64_t total = 0;
578
579     QTAILQ_FOREACH(block, &ram_list.blocks, next)
580         total += block->length;
581
582     return total;
583 }
584
585 static void migration_end(void)
586 {
587     if (migration_bitmap) {
588         memory_global_dirty_log_stop();
589         g_free(migration_bitmap);
590         migration_bitmap = NULL;
591     }
592
593     if (XBZRLE.cache) {
594         cache_fini(XBZRLE.cache);
595         g_free(XBZRLE.cache);
596         g_free(XBZRLE.encoded_buf);
597         g_free(XBZRLE.current_buf);
598         g_free(XBZRLE.decoded_buf);
599         XBZRLE.cache = NULL;
600     }
601 }
602
603 static void ram_migration_cancel(void *opaque)
604 {
605     migration_end();
606 }
607
608 static void reset_ram_globals(void)
609 {
610     last_seen_block = NULL;
611     last_sent_block = NULL;
612     last_offset = 0;
613     last_version = ram_list.version;
614     ram_bulk_stage = true;
615 }
616
617 #define MAX_WAIT 50 /* ms, half buffered_file limit */
618
619 static int ram_save_setup(QEMUFile *f, void *opaque)
620 {
621     RAMBlock *block;
622     int64_t ram_pages = last_ram_offset() >> TARGET_PAGE_BITS;
623
624     migration_bitmap = bitmap_new(ram_pages);
625     bitmap_set(migration_bitmap, 0, ram_pages);
626     migration_dirty_pages = ram_pages;
627     mig_throttle_on = false;
628     dirty_rate_high_cnt = 0;
629
630     if (migrate_use_xbzrle()) {
631         XBZRLE.cache = cache_init(migrate_xbzrle_cache_size() /
632                                   TARGET_PAGE_SIZE,
633                                   TARGET_PAGE_SIZE);
634         if (!XBZRLE.cache) {
635             DPRINTF("Error creating cache\n");
636             return -1;
637         }
638         XBZRLE.encoded_buf = g_malloc0(TARGET_PAGE_SIZE);
639         XBZRLE.current_buf = g_malloc(TARGET_PAGE_SIZE);
640         acct_clear();
641     }
642
643     qemu_mutex_lock_iothread();
644     qemu_mutex_lock_ramlist();
645     bytes_transferred = 0;
646     reset_ram_globals();
647
648     memory_global_dirty_log_start();
649     migration_bitmap_sync();
650     qemu_mutex_unlock_iothread();
651
652     qemu_put_be64(f, ram_bytes_total() | RAM_SAVE_FLAG_MEM_SIZE);
653
654     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
655         qemu_put_byte(f, strlen(block->idstr));
656         qemu_put_buffer(f, (uint8_t *)block->idstr, strlen(block->idstr));
657         qemu_put_be64(f, block->length);
658     }
659
660     qemu_mutex_unlock_ramlist();
661
662     ram_control_before_iterate(f, RAM_CONTROL_SETUP);
663     ram_control_after_iterate(f, RAM_CONTROL_SETUP);
664
665     qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
666
667     return 0;
668 }
669
670 static int ram_save_iterate(QEMUFile *f, void *opaque)
671 {
672     int ret;
673     int i;
674     int64_t t0;
675     int total_sent = 0;
676
677     qemu_mutex_lock_ramlist();
678
679     if (ram_list.version != last_version) {
680         reset_ram_globals();
681     }
682
683     ram_control_before_iterate(f, RAM_CONTROL_ROUND);
684
685     t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
686     i = 0;
687     while ((ret = qemu_file_rate_limit(f)) == 0) {
688         int bytes_sent;
689
690         bytes_sent = ram_save_block(f, false);
691         /* no more blocks to sent */
692         if (bytes_sent == 0) {
693             break;
694         }
695         total_sent += bytes_sent;
696         acct_info.iterations++;
697         check_guest_throttling();
698         /* we want to check in the 1st loop, just in case it was the 1st time
699            and we had to sync the dirty bitmap.
700            qemu_get_clock_ns() is a bit expensive, so we only check each some
701            iterations
702         */
703         if ((i & 63) == 0) {
704             uint64_t t1 = (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - t0) / 1000000;
705             if (t1 > MAX_WAIT) {
706                 DPRINTF("big wait: %" PRIu64 " milliseconds, %d iterations\n",
707                         t1, i);
708                 break;
709             }
710         }
711         i++;
712     }
713
714     qemu_mutex_unlock_ramlist();
715
716     /*
717      * Must occur before EOS (or any QEMUFile operation)
718      * because of RDMA protocol.
719      */
720     ram_control_after_iterate(f, RAM_CONTROL_ROUND);
721
722     bytes_transferred += total_sent;
723
724     /*
725      * Do not count these 8 bytes into total_sent, so that we can
726      * return 0 if no page had been dirtied.
727      */
728     qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
729     bytes_transferred += 8;
730
731     ret = qemu_file_get_error(f);
732     if (ret < 0) {
733         return ret;
734     }
735
736     return total_sent;
737 }
738
739 static int ram_save_complete(QEMUFile *f, void *opaque)
740 {
741     qemu_mutex_lock_ramlist();
742     migration_bitmap_sync();
743
744     ram_control_before_iterate(f, RAM_CONTROL_FINISH);
745
746     /* try transferring iterative blocks of memory */
747
748     /* flush all remaining blocks regardless of rate limiting */
749     while (true) {
750         int bytes_sent;
751
752         bytes_sent = ram_save_block(f, true);
753         /* no more blocks to sent */
754         if (bytes_sent == 0) {
755             break;
756         }
757         bytes_transferred += bytes_sent;
758     }
759
760     ram_control_after_iterate(f, RAM_CONTROL_FINISH);
761     migration_end();
762
763     qemu_mutex_unlock_ramlist();
764     qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
765
766     return 0;
767 }
768
769 static uint64_t ram_save_pending(QEMUFile *f, void *opaque, uint64_t max_size)
770 {
771     uint64_t remaining_size;
772
773     remaining_size = ram_save_remaining() * TARGET_PAGE_SIZE;
774
775     if (remaining_size < max_size) {
776         qemu_mutex_lock_iothread();
777         migration_bitmap_sync();
778         qemu_mutex_unlock_iothread();
779         remaining_size = ram_save_remaining() * TARGET_PAGE_SIZE;
780     }
781     return remaining_size;
782 }
783
784 static int load_xbzrle(QEMUFile *f, ram_addr_t addr, void *host)
785 {
786     int ret, rc = 0;
787     unsigned int xh_len;
788     int xh_flags;
789
790     if (!XBZRLE.decoded_buf) {
791         XBZRLE.decoded_buf = g_malloc(TARGET_PAGE_SIZE);
792     }
793
794     /* extract RLE header */
795     xh_flags = qemu_get_byte(f);
796     xh_len = qemu_get_be16(f);
797
798     if (xh_flags != ENCODING_FLAG_XBZRLE) {
799         fprintf(stderr, "Failed to load XBZRLE page - wrong compression!\n");
800         return -1;
801     }
802
803     if (xh_len > TARGET_PAGE_SIZE) {
804         fprintf(stderr, "Failed to load XBZRLE page - len overflow!\n");
805         return -1;
806     }
807     /* load data and decode */
808     qemu_get_buffer(f, XBZRLE.decoded_buf, xh_len);
809
810     /* decode RLE */
811     ret = xbzrle_decode_buffer(XBZRLE.decoded_buf, xh_len, host,
812                                TARGET_PAGE_SIZE);
813     if (ret == -1) {
814         fprintf(stderr, "Failed to load XBZRLE page - decode error!\n");
815         rc = -1;
816     } else  if (ret > TARGET_PAGE_SIZE) {
817         fprintf(stderr, "Failed to load XBZRLE page - size %d exceeds %d!\n",
818                 ret, TARGET_PAGE_SIZE);
819         abort();
820     }
821
822     return rc;
823 }
824
825 static inline void *host_from_stream_offset(QEMUFile *f,
826                                             ram_addr_t offset,
827                                             int flags)
828 {
829     static RAMBlock *block = NULL;
830     char id[256];
831     uint8_t len;
832
833     if (flags & RAM_SAVE_FLAG_CONTINUE) {
834         if (!block) {
835             fprintf(stderr, "Ack, bad migration stream!\n");
836             return NULL;
837         }
838
839         return memory_region_get_ram_ptr(block->mr) + offset;
840     }
841
842     len = qemu_get_byte(f);
843     qemu_get_buffer(f, (uint8_t *)id, len);
844     id[len] = 0;
845
846     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
847         if (!strncmp(id, block->idstr, sizeof(id)))
848             return memory_region_get_ram_ptr(block->mr) + offset;
849     }
850
851     fprintf(stderr, "Can't find block %s!\n", id);
852     return NULL;
853 }
854
855 /*
856  * If a page (or a whole RDMA chunk) has been
857  * determined to be zero, then zap it.
858  */
859 void ram_handle_compressed(void *host, uint8_t ch, uint64_t size)
860 {
861     if (ch != 0 || !is_zero_range(host, size)) {
862         memset(host, ch, size);
863     }
864 }
865
866 static int ram_load(QEMUFile *f, void *opaque, int version_id)
867 {
868     ram_addr_t addr;
869     int flags, ret = 0;
870     int error;
871     static uint64_t seq_iter;
872
873     seq_iter++;
874
875     if (version_id < 4 || version_id > 4) {
876         return -EINVAL;
877     }
878
879     do {
880         addr = qemu_get_be64(f);
881
882         flags = addr & ~TARGET_PAGE_MASK;
883         addr &= TARGET_PAGE_MASK;
884
885         if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
886             if (version_id == 4) {
887                 /* Synchronize RAM block list */
888                 char id[256];
889                 ram_addr_t length;
890                 ram_addr_t total_ram_bytes = addr;
891
892                 while (total_ram_bytes) {
893                     RAMBlock *block;
894                     uint8_t len;
895
896                     len = qemu_get_byte(f);
897                     qemu_get_buffer(f, (uint8_t *)id, len);
898                     id[len] = 0;
899                     length = qemu_get_be64(f);
900
901                     QTAILQ_FOREACH(block, &ram_list.blocks, next) {
902                         if (!strncmp(id, block->idstr, sizeof(id))) {
903                             if (block->length != length) {
904                                 fprintf(stderr,
905                                         "Length mismatch: %s: " RAM_ADDR_FMT
906                                         " in != " RAM_ADDR_FMT "\n", id, length,
907                                         block->length);
908                                 ret =  -EINVAL;
909                                 goto done;
910                             }
911                             break;
912                         }
913                     }
914
915                     if (!block) {
916                         fprintf(stderr, "Unknown ramblock \"%s\", cannot "
917                                 "accept migration\n", id);
918                         ret = -EINVAL;
919                         goto done;
920                     }
921
922                     total_ram_bytes -= length;
923                 }
924             }
925         }
926
927         if (flags & RAM_SAVE_FLAG_COMPRESS) {
928             void *host;
929             uint8_t ch;
930
931             host = host_from_stream_offset(f, addr, flags);
932             if (!host) {
933                 return -EINVAL;
934             }
935
936             ch = qemu_get_byte(f);
937             ram_handle_compressed(host, ch, TARGET_PAGE_SIZE);
938         } else if (flags & RAM_SAVE_FLAG_PAGE) {
939             void *host;
940
941             host = host_from_stream_offset(f, addr, flags);
942             if (!host) {
943                 return -EINVAL;
944             }
945
946             qemu_get_buffer(f, host, TARGET_PAGE_SIZE);
947         } else if (flags & RAM_SAVE_FLAG_XBZRLE) {
948             void *host = host_from_stream_offset(f, addr, flags);
949             if (!host) {
950                 return -EINVAL;
951             }
952
953             if (load_xbzrle(f, addr, host) < 0) {
954                 ret = -EINVAL;
955                 goto done;
956             }
957         } else if (flags & RAM_SAVE_FLAG_HOOK) {
958             ram_control_load_hook(f, flags);
959         }
960         error = qemu_file_get_error(f);
961         if (error) {
962             ret = error;
963             goto done;
964         }
965     } while (!(flags & RAM_SAVE_FLAG_EOS));
966
967 done:
968     DPRINTF("Completed load of VM with exit code %d seq iteration "
969             "%" PRIu64 "\n", ret, seq_iter);
970     return ret;
971 }
972
973 SaveVMHandlers savevm_ram_handlers = {
974     .save_live_setup = ram_save_setup,
975     .save_live_iterate = ram_save_iterate,
976     .save_live_complete = ram_save_complete,
977     .save_live_pending = ram_save_pending,
978     .load_state = ram_load,
979     .cancel = ram_migration_cancel,
980 };
981
982 struct soundhw {
983     const char *name;
984     const char *descr;
985     int enabled;
986     int isa;
987     union {
988         int (*init_isa) (ISABus *bus);
989         int (*init_pci) (PCIBus *bus);
990     } init;
991 };
992
993 static struct soundhw soundhw[9];
994 static int soundhw_count;
995
996 void isa_register_soundhw(const char *name, const char *descr,
997                           int (*init_isa)(ISABus *bus))
998 {
999     assert(soundhw_count < ARRAY_SIZE(soundhw) - 1);
1000     soundhw[soundhw_count].name = name;
1001     soundhw[soundhw_count].descr = descr;
1002     soundhw[soundhw_count].isa = 1;
1003     soundhw[soundhw_count].init.init_isa = init_isa;
1004     soundhw_count++;
1005 }
1006
1007 void pci_register_soundhw(const char *name, const char *descr,
1008                           int (*init_pci)(PCIBus *bus))
1009 {
1010     assert(soundhw_count < ARRAY_SIZE(soundhw) - 1);
1011     soundhw[soundhw_count].name = name;
1012     soundhw[soundhw_count].descr = descr;
1013     soundhw[soundhw_count].isa = 0;
1014     soundhw[soundhw_count].init.init_pci = init_pci;
1015     soundhw_count++;
1016 }
1017
1018 void select_soundhw(const char *optarg)
1019 {
1020     struct soundhw *c;
1021
1022     if (is_help_option(optarg)) {
1023     show_valid_cards:
1024
1025         if (soundhw_count) {
1026              printf("Valid sound card names (comma separated):\n");
1027              for (c = soundhw; c->name; ++c) {
1028                  printf ("%-11s %s\n", c->name, c->descr);
1029              }
1030              printf("\n-soundhw all will enable all of the above\n");
1031         } else {
1032              printf("Machine has no user-selectable audio hardware "
1033                     "(it may or may not have always-present audio hardware).\n");
1034         }
1035         exit(!is_help_option(optarg));
1036     }
1037     else {
1038         size_t l;
1039         const char *p;
1040         char *e;
1041         int bad_card = 0;
1042
1043         if (!strcmp(optarg, "all")) {
1044             for (c = soundhw; c->name; ++c) {
1045                 c->enabled = 1;
1046             }
1047             return;
1048         }
1049
1050         p = optarg;
1051         while (*p) {
1052             e = strchr(p, ',');
1053             l = !e ? strlen(p) : (size_t) (e - p);
1054
1055             for (c = soundhw; c->name; ++c) {
1056                 if (!strncmp(c->name, p, l) && !c->name[l]) {
1057                     c->enabled = 1;
1058                     break;
1059                 }
1060             }
1061
1062             if (!c->name) {
1063                 if (l > 80) {
1064                     fprintf(stderr,
1065                             "Unknown sound card name (too big to show)\n");
1066                 }
1067                 else {
1068                     fprintf(stderr, "Unknown sound card name `%.*s'\n",
1069                             (int) l, p);
1070                 }
1071                 bad_card = 1;
1072             }
1073             p += l + (e != NULL);
1074         }
1075
1076         if (bad_card) {
1077             goto show_valid_cards;
1078         }
1079     }
1080 }
1081
1082 void audio_init(void)
1083 {
1084     struct soundhw *c;
1085     ISABus *isa_bus = (ISABus *) object_resolve_path_type("", TYPE_ISA_BUS, NULL);
1086     PCIBus *pci_bus = (PCIBus *) object_resolve_path_type("", TYPE_PCI_BUS, NULL);
1087
1088     for (c = soundhw; c->name; ++c) {
1089         if (c->enabled) {
1090             if (c->isa) {
1091                 if (!isa_bus) {
1092                     fprintf(stderr, "ISA bus not available for %s\n", c->name);
1093                     exit(1);
1094                 }
1095                 c->init.init_isa(isa_bus);
1096             } else {
1097                 if (!pci_bus) {
1098                     fprintf(stderr, "PCI bus not available for %s\n", c->name);
1099                     exit(1);
1100                 }
1101                 c->init.init_pci(pci_bus);
1102             }
1103         }
1104     }
1105 }
1106
1107 int qemu_uuid_parse(const char *str, uint8_t *uuid)
1108 {
1109     int ret;
1110
1111     if (strlen(str) != 36) {
1112         return -1;
1113     }
1114
1115     ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
1116                  &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
1117                  &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14],
1118                  &uuid[15]);
1119
1120     if (ret != 16) {
1121         return -1;
1122     }
1123     return 0;
1124 }
1125
1126 void do_acpitable_option(const QemuOpts *opts)
1127 {
1128 #ifdef TARGET_I386
1129     Error *err = NULL;
1130
1131     acpi_table_add(opts, &err);
1132     if (err) {
1133         error_report("Wrong acpi table provided: %s",
1134                      error_get_pretty(err));
1135         error_free(err);
1136         exit(1);
1137     }
1138 #endif
1139 }
1140
1141 void do_smbios_option(QemuOpts *opts)
1142 {
1143 #ifdef TARGET_I386
1144     smbios_entry_add(opts);
1145 #endif
1146 }
1147
1148 void cpudef_init(void)
1149 {
1150 #if defined(cpudef_setup)
1151     cpudef_setup(); /* parse cpu definitions in target config file */
1152 #endif
1153 }
1154
1155 int tcg_available(void)
1156 {
1157     return 1;
1158 }
1159
1160 int kvm_available(void)
1161 {
1162 #ifdef CONFIG_KVM
1163     return 1;
1164 #else
1165     return 0;
1166 #endif
1167 }
1168
1169 int xen_available(void)
1170 {
1171 #ifdef CONFIG_XEN
1172     return 1;
1173 #else
1174     return 0;
1175 #endif
1176 }
1177
1178
1179 TargetInfo *qmp_query_target(Error **errp)
1180 {
1181     TargetInfo *info = g_malloc0(sizeof(*info));
1182
1183     info->arch = g_strdup(TARGET_NAME);
1184
1185     return info;
1186 }
1187
1188 /* Stub function that's gets run on the vcpu when its brought out of the
1189    VM to run inside qemu via async_run_on_cpu()*/
1190 static void mig_sleep_cpu(void *opq)
1191 {
1192     qemu_mutex_unlock_iothread();
1193     g_usleep(30*1000);
1194     qemu_mutex_lock_iothread();
1195 }
1196
1197 /* To reduce the dirty rate explicitly disallow the VCPUs from spending
1198    much time in the VM. The migration thread will try to catchup.
1199    Workload will experience a performance drop.
1200 */
1201 static void mig_throttle_guest_down(void)
1202 {
1203     CPUState *cpu;
1204
1205     qemu_mutex_lock_iothread();
1206     CPU_FOREACH(cpu) {
1207         async_run_on_cpu(cpu, mig_sleep_cpu, NULL);
1208     }
1209     qemu_mutex_unlock_iothread();
1210 }
1211
1212 static void check_guest_throttling(void)
1213 {
1214     static int64_t t0;
1215     int64_t        t1;
1216
1217     if (!mig_throttle_on) {
1218         return;
1219     }
1220
1221     if (!t0)  {
1222         t0 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1223         return;
1224     }
1225
1226     t1 = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1227
1228     /* If it has been more than 40 ms since the last time the guest
1229      * was throttled then do it again.
1230      */
1231     if (40 < (t1-t0)/1000000) {
1232         mig_throttle_guest_down();
1233         t0 = t1;
1234     }
1235 }
This page took 0.089488 seconds and 4 git commands to generate.