Merge commit 'c9f398e53fedb88df243e32eb9bc50fda4ec44d0' into upstream-merge
[qemu/qemu-dev-zwu.git] / vl.c
blob0eca166b86f9b15b080cb50fec9c2bd513fe7d58
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <libgen.h>
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #include <arpa/inet.h>
48 #include <dirent.h>
49 #include <netdb.h>
50 #include <sys/select.h>
51 #ifdef CONFIG_BSD
52 #include <sys/stat.h>
53 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
54 #include <libutil.h>
55 #else
56 #include <util.h>
57 #endif
58 #else
59 #ifdef __linux__
60 #include <pty.h>
61 #include <malloc.h>
62 #include <linux/rtc.h>
63 #include <sys/prctl.h>
65 /* For the benefit of older linux systems which don't supply it,
66 we use a local copy of hpet.h. */
67 /* #include <linux/hpet.h> */
68 #include "hpet.h"
70 #include <linux/ppdev.h>
71 #include <linux/parport.h>
72 #endif
73 #ifdef __sun__
74 #include <sys/stat.h>
75 #include <sys/ethernet.h>
76 #include <sys/sockio.h>
77 #include <netinet/arp.h>
78 #include <netinet/in.h>
79 #include <netinet/in_systm.h>
80 #include <netinet/ip.h>
81 #include <netinet/ip_icmp.h> // must come after ip.h
82 #include <netinet/udp.h>
83 #include <netinet/tcp.h>
84 #include <net/if.h>
85 #include <syslog.h>
86 #include <stropts.h>
87 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
88 discussion about Solaris header problems */
89 extern int madvise(caddr_t, size_t, int);
90 #endif
91 #endif
92 #endif
94 #if defined(__OpenBSD__)
95 #include <util.h>
96 #endif
98 #if defined(CONFIG_VDE)
99 #include <libvdeplug.h>
100 #endif
102 #ifdef _WIN32
103 #include <windows.h>
104 #include <mmsystem.h>
105 #endif
107 #ifdef CONFIG_SDL
108 #if defined(__APPLE__) || defined(main)
109 #include <SDL.h>
110 int qemu_main(int argc, char **argv, char **envp);
111 int main(int argc, char **argv)
113 return qemu_main(argc, argv, NULL);
115 #undef main
116 #define main qemu_main
117 #endif
118 #endif /* CONFIG_SDL */
120 #ifdef CONFIG_COCOA
121 #undef main
122 #define main qemu_main
123 #endif /* CONFIG_COCOA */
125 #include "hw/hw.h"
126 #include "hw/boards.h"
127 #include "hw/usb.h"
128 #include "hw/pcmcia.h"
129 #include "hw/pc.h"
130 #include "hw/audiodev.h"
131 #include "hw/isa.h"
132 #include "hw/baum.h"
133 #include "hw/bt.h"
134 #include "hw/watchdog.h"
135 #include "hw/smbios.h"
136 #include "hw/xen.h"
137 #include "hw/qdev.h"
138 #include "hw/loader.h"
139 #include "bt-host.h"
140 #include "net.h"
141 #include "net/slirp.h"
142 #include "monitor.h"
143 #include "console.h"
144 #include "sysemu.h"
145 #include "gdbstub.h"
146 #include "qemu-timer.h"
147 #include "qemu-char.h"
148 #include "cache-utils.h"
149 #include "block.h"
150 #include "block_int.h"
151 #include "block-migration.h"
152 #include "dma.h"
153 #include "audio/audio.h"
154 #include "migration.h"
155 #include "kvm.h"
156 #include "balloon.h"
157 #include "qemu-option.h"
158 #include "qemu-config.h"
159 #include "qemu-objects.h"
160 #include "qemu-kvm.h"
161 #include "hw/device-assignment.h"
163 #include "disas.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #include "slirp/libslirp.h"
171 #include "qemu-queue.h"
173 //#define DEBUG_NET
174 //#define DEBUG_SLIRP
176 #define DEFAULT_RAM_SIZE 128
178 static const char *data_dir;
179 const char *bios_name = NULL;
180 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181 to store the VM snapshots */
182 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
183 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
184 DriveInfo *extboot_drive = NULL;
185 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
186 static DisplayState *display_state;
187 DisplayType display_type = DT_DEFAULT;
188 const char* keyboard_layout = NULL;
189 ram_addr_t ram_size;
190 int nb_nics;
191 NICInfo nd_table[MAX_NICS];
192 int vm_running;
193 int autostart;
194 static int rtc_utc = 1;
195 static int rtc_date_offset = -1; /* -1 means no change */
196 QEMUClock *rtc_clock;
197 int vga_interface_type = VGA_NONE;
198 #ifdef TARGET_SPARC
199 int graphic_width = 1024;
200 int graphic_height = 768;
201 int graphic_depth = 8;
202 #else
203 int graphic_width = 800;
204 int graphic_height = 600;
205 int graphic_depth = 15;
206 #endif
207 static int full_screen = 0;
208 #ifdef CONFIG_SDL
209 static int no_frame = 0;
210 #endif
211 int no_quit = 0;
212 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
213 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
214 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
215 #ifdef TARGET_I386
216 int win2k_install_hack = 0;
217 int rtc_td_hack = 0;
218 #endif
219 int usb_enabled = 0;
220 int singlestep = 0;
221 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
222 int assigned_devices_index;
223 int smp_cpus = 1;
224 int max_cpus = 0;
225 int smp_cores = 1;
226 int smp_threads = 1;
227 const char *vnc_display;
228 int acpi_enabled = 1;
229 #ifdef TARGET_I386
230 int no_hpet = 0;
231 #endif
232 int fd_bootchk = 1;
233 int no_reboot = 0;
234 int no_shutdown = 0;
235 int cursor_hide = 1;
236 int graphic_rotate = 0;
237 uint8_t irq0override = 1;
238 #ifndef _WIN32
239 int daemonize = 0;
240 #endif
241 const char *watchdog;
242 const char *option_rom[MAX_OPTION_ROMS];
243 int nb_option_roms;
244 int semihosting_enabled = 0;
245 int time_drift_fix = 0;
246 unsigned int kvm_shadow_memory = 0;
247 const char *mem_path = NULL;
248 #ifdef MAP_POPULATE
249 int mem_prealloc = 1; /* force preallocation of physical target memory */
250 #endif
251 #ifdef TARGET_ARM
252 int old_param = 0;
253 #endif
254 const char *qemu_name;
255 int alt_grab = 0;
256 int ctrl_grab = 0;
257 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
258 unsigned int nb_prom_envs = 0;
259 const char *prom_envs[MAX_PROM_ENVS];
260 #endif
261 const char *nvram = NULL;
262 int boot_menu;
264 int nb_numa_nodes;
265 uint64_t node_mem[MAX_NODES];
266 uint64_t node_cpumask[MAX_NODES];
268 static CPUState *cur_cpu;
269 static CPUState *next_cpu;
270 static int timer_alarm_pending = 1;
271 /* Conversion factor from emulated instructions to virtual clock ticks. */
272 static int icount_time_shift;
273 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
274 #define MAX_ICOUNT_SHIFT 10
275 /* Compensate for varying guest execution speed. */
276 static int64_t qemu_icount_bias;
277 static QEMUTimer *icount_rt_timer;
278 static QEMUTimer *icount_vm_timer;
279 static QEMUTimer *nographic_timer;
281 uint8_t qemu_uuid[16];
283 static QEMUBootSetHandler *boot_set_handler;
284 static void *boot_set_opaque;
286 static int default_serial = 1;
287 static int default_parallel = 1;
288 static int default_virtcon = 1;
289 static int default_monitor = 1;
290 static int default_vga = 1;
291 static int default_floppy = 1;
292 static int default_cdrom = 1;
293 static int default_sdcard = 1;
295 static struct {
296 const char *driver;
297 int *flag;
298 } default_list[] = {
299 { .driver = "isa-serial", .flag = &default_serial },
300 { .driver = "isa-parallel", .flag = &default_parallel },
301 { .driver = "isa-fdc", .flag = &default_floppy },
302 { .driver = "ide-drive", .flag = &default_cdrom },
303 { .driver = "virtio-console-pci", .flag = &default_virtcon },
304 { .driver = "virtio-console-s390", .flag = &default_virtcon },
305 { .driver = "VGA", .flag = &default_vga },
306 { .driver = "cirrus-vga", .flag = &default_vga },
307 { .driver = "vmware-svga", .flag = &default_vga },
310 static int default_driver_check(QemuOpts *opts, void *opaque)
312 const char *driver = qemu_opt_get(opts, "driver");
313 int i;
315 if (!driver)
316 return 0;
317 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
318 if (strcmp(default_list[i].driver, driver) != 0)
319 continue;
320 *(default_list[i].flag) = 0;
322 return 0;
325 /***********************************************************/
326 /* x86 ISA bus support */
328 target_phys_addr_t isa_mem_base = 0;
329 PicState2 *isa_pic;
331 /***********************************************************/
332 void hw_error(const char *fmt, ...)
334 va_list ap;
335 CPUState *env;
337 va_start(ap, fmt);
338 fprintf(stderr, "qemu: hardware error: ");
339 vfprintf(stderr, fmt, ap);
340 fprintf(stderr, "\n");
341 for(env = first_cpu; env != NULL; env = env->next_cpu) {
342 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
343 #ifdef TARGET_I386
344 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
345 #else
346 cpu_dump_state(env, stderr, fprintf, 0);
347 #endif
349 va_end(ap);
350 abort();
353 static void set_proc_name(const char *s)
355 #if defined(__linux__) && defined(PR_SET_NAME)
356 char name[16];
357 if (!s)
358 return;
359 name[sizeof(name) - 1] = 0;
360 strncpy(name, s, sizeof(name));
361 /* Could rewrite argv[0] too, but that's a bit more complicated.
362 This simple way is enough for `top'. */
363 prctl(PR_SET_NAME, name);
364 #endif
367 /***************/
368 /* ballooning */
370 static QEMUBalloonEvent *qemu_balloon_event;
371 void *qemu_balloon_event_opaque;
373 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
375 qemu_balloon_event = func;
376 qemu_balloon_event_opaque = opaque;
379 void qemu_balloon(ram_addr_t target)
381 if (qemu_balloon_event)
382 qemu_balloon_event(qemu_balloon_event_opaque, target);
385 ram_addr_t qemu_balloon_status(void)
387 if (qemu_balloon_event)
388 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
389 return 0;
392 /***********************************************************/
393 /* keyboard/mouse */
395 static QEMUPutKBDEvent *qemu_put_kbd_event;
396 static void *qemu_put_kbd_event_opaque;
397 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
398 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
400 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
402 qemu_put_kbd_event_opaque = opaque;
403 qemu_put_kbd_event = func;
406 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
407 void *opaque, int absolute,
408 const char *name)
410 QEMUPutMouseEntry *s, *cursor;
412 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
414 s->qemu_put_mouse_event = func;
415 s->qemu_put_mouse_event_opaque = opaque;
416 s->qemu_put_mouse_event_absolute = absolute;
417 s->qemu_put_mouse_event_name = qemu_strdup(name);
418 s->next = NULL;
420 if (!qemu_put_mouse_event_head) {
421 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
422 return s;
425 cursor = qemu_put_mouse_event_head;
426 while (cursor->next != NULL)
427 cursor = cursor->next;
429 cursor->next = s;
430 qemu_put_mouse_event_current = s;
432 return s;
435 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
437 QEMUPutMouseEntry *prev = NULL, *cursor;
439 if (!qemu_put_mouse_event_head || entry == NULL)
440 return;
442 cursor = qemu_put_mouse_event_head;
443 while (cursor != NULL && cursor != entry) {
444 prev = cursor;
445 cursor = cursor->next;
448 if (cursor == NULL) // does not exist or list empty
449 return;
450 else if (prev == NULL) { // entry is head
451 qemu_put_mouse_event_head = cursor->next;
452 if (qemu_put_mouse_event_current == entry)
453 qemu_put_mouse_event_current = cursor->next;
454 qemu_free(entry->qemu_put_mouse_event_name);
455 qemu_free(entry);
456 return;
459 prev->next = entry->next;
461 if (qemu_put_mouse_event_current == entry)
462 qemu_put_mouse_event_current = prev;
464 qemu_free(entry->qemu_put_mouse_event_name);
465 qemu_free(entry);
468 void kbd_put_keycode(int keycode)
470 if (qemu_put_kbd_event) {
471 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
475 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
477 QEMUPutMouseEvent *mouse_event;
478 void *mouse_event_opaque;
479 int width;
481 if (!qemu_put_mouse_event_current) {
482 return;
485 mouse_event =
486 qemu_put_mouse_event_current->qemu_put_mouse_event;
487 mouse_event_opaque =
488 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
490 if (mouse_event) {
491 if (graphic_rotate) {
492 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
493 width = 0x7fff;
494 else
495 width = graphic_width - 1;
496 mouse_event(mouse_event_opaque,
497 width - dy, dx, dz, buttons_state);
498 } else
499 mouse_event(mouse_event_opaque,
500 dx, dy, dz, buttons_state);
504 int kbd_mouse_is_absolute(void)
506 if (!qemu_put_mouse_event_current)
507 return 0;
509 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
512 static void info_mice_iter(QObject *data, void *opaque)
514 QDict *mouse;
515 Monitor *mon = opaque;
517 mouse = qobject_to_qdict(data);
518 monitor_printf(mon, "%c Mouse #%" PRId64 ": %s\n",
519 (qdict_get_bool(mouse, "current") ? '*' : ' '),
520 qdict_get_int(mouse, "index"), qdict_get_str(mouse, "name"));
523 void do_info_mice_print(Monitor *mon, const QObject *data)
525 QList *mice_list;
527 mice_list = qobject_to_qlist(data);
528 if (qlist_empty(mice_list)) {
529 monitor_printf(mon, "No mouse devices connected\n");
530 return;
533 qlist_iter(mice_list, info_mice_iter, mon);
537 * do_info_mice(): Show VM mice information
539 * Each mouse is represented by a QDict, the returned QObject is a QList of
540 * all mice.
542 * The mouse QDict contains the following:
544 * - "name": mouse's name
545 * - "index": mouse's index
546 * - "current": true if this mouse is receiving events, false otherwise
548 * Example:
550 * [ { "name": "QEMU Microsoft Mouse", "index": 0, "current": false },
551 * { "name": "QEMU PS/2 Mouse", "index": 1, "current": true } ]
553 void do_info_mice(Monitor *mon, QObject **ret_data)
555 QEMUPutMouseEntry *cursor;
556 QList *mice_list;
557 int index = 0;
559 mice_list = qlist_new();
561 if (!qemu_put_mouse_event_head) {
562 goto out;
565 cursor = qemu_put_mouse_event_head;
566 while (cursor != NULL) {
567 QObject *obj;
568 obj = qobject_from_jsonf("{ 'name': %s, 'index': %d, 'current': %i }",
569 cursor->qemu_put_mouse_event_name,
570 index, cursor == qemu_put_mouse_event_current);
571 qlist_append_obj(mice_list, obj);
572 index++;
573 cursor = cursor->next;
576 out:
577 *ret_data = QOBJECT(mice_list);
580 void do_mouse_set(Monitor *mon, const QDict *qdict)
582 QEMUPutMouseEntry *cursor;
583 int i = 0;
584 int index = qdict_get_int(qdict, "index");
586 if (!qemu_put_mouse_event_head) {
587 monitor_printf(mon, "No mouse devices connected\n");
588 return;
591 cursor = qemu_put_mouse_event_head;
592 while (cursor != NULL && index != i) {
593 i++;
594 cursor = cursor->next;
597 if (cursor != NULL)
598 qemu_put_mouse_event_current = cursor;
599 else
600 monitor_printf(mon, "Mouse at given index not found\n");
603 /* compute with 96 bit intermediate result: (a*b)/c */
604 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
606 union {
607 uint64_t ll;
608 struct {
609 #ifdef HOST_WORDS_BIGENDIAN
610 uint32_t high, low;
611 #else
612 uint32_t low, high;
613 #endif
614 } l;
615 } u, res;
616 uint64_t rl, rh;
618 u.ll = a;
619 rl = (uint64_t)u.l.low * (uint64_t)b;
620 rh = (uint64_t)u.l.high * (uint64_t)b;
621 rh += (rl >> 32);
622 res.l.high = rh / c;
623 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
624 return res.ll;
627 /***********************************************************/
628 /* real time host monotonic timer */
630 static int64_t get_clock_realtime(void)
632 struct timeval tv;
634 gettimeofday(&tv, NULL);
635 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
638 #ifdef WIN32
640 static int64_t clock_freq;
642 static void init_get_clock(void)
644 LARGE_INTEGER freq;
645 int ret;
646 ret = QueryPerformanceFrequency(&freq);
647 if (ret == 0) {
648 fprintf(stderr, "Could not calibrate ticks\n");
649 exit(1);
651 clock_freq = freq.QuadPart;
654 static int64_t get_clock(void)
656 LARGE_INTEGER ti;
657 QueryPerformanceCounter(&ti);
658 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
661 #else
663 static int use_rt_clock;
665 static void init_get_clock(void)
667 use_rt_clock = 0;
668 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
669 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
671 struct timespec ts;
672 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
673 use_rt_clock = 1;
676 #endif
679 static int64_t get_clock(void)
681 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
682 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
683 if (use_rt_clock) {
684 struct timespec ts;
685 clock_gettime(CLOCK_MONOTONIC, &ts);
686 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
687 } else
688 #endif
690 /* XXX: using gettimeofday leads to problems if the date
691 changes, so it should be avoided. */
692 return get_clock_realtime();
695 #endif
697 /* Return the virtual CPU time, based on the instruction counter. */
698 static int64_t cpu_get_icount(void)
700 int64_t icount;
701 CPUState *env = cpu_single_env;;
702 icount = qemu_icount;
703 if (env) {
704 if (!can_do_io(env))
705 fprintf(stderr, "Bad clock read\n");
706 icount -= (env->icount_decr.u16.low + env->icount_extra);
708 return qemu_icount_bias + (icount << icount_time_shift);
711 /***********************************************************/
712 /* guest cycle counter */
714 typedef struct TimersState {
715 int64_t cpu_ticks_prev;
716 int64_t cpu_ticks_offset;
717 int64_t cpu_clock_offset;
718 int32_t cpu_ticks_enabled;
719 int64_t dummy;
720 } TimersState;
722 TimersState timers_state;
724 /* return the host CPU cycle counter and handle stop/restart */
725 int64_t cpu_get_ticks(void)
727 if (use_icount) {
728 return cpu_get_icount();
730 if (!timers_state.cpu_ticks_enabled) {
731 return timers_state.cpu_ticks_offset;
732 } else {
733 int64_t ticks;
734 ticks = cpu_get_real_ticks();
735 if (timers_state.cpu_ticks_prev > ticks) {
736 /* Note: non increasing ticks may happen if the host uses
737 software suspend */
738 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
740 timers_state.cpu_ticks_prev = ticks;
741 return ticks + timers_state.cpu_ticks_offset;
745 /* return the host CPU monotonic timer and handle stop/restart */
746 static int64_t cpu_get_clock(void)
748 int64_t ti;
749 if (!timers_state.cpu_ticks_enabled) {
750 return timers_state.cpu_clock_offset;
751 } else {
752 ti = get_clock();
753 return ti + timers_state.cpu_clock_offset;
757 /* enable cpu_get_ticks() */
758 void cpu_enable_ticks(void)
760 if (!timers_state.cpu_ticks_enabled) {
761 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
762 timers_state.cpu_clock_offset -= get_clock();
763 timers_state.cpu_ticks_enabled = 1;
767 /* disable cpu_get_ticks() : the clock is stopped. You must not call
768 cpu_get_ticks() after that. */
769 void cpu_disable_ticks(void)
771 if (timers_state.cpu_ticks_enabled) {
772 timers_state.cpu_ticks_offset = cpu_get_ticks();
773 timers_state.cpu_clock_offset = cpu_get_clock();
774 timers_state.cpu_ticks_enabled = 0;
778 /***********************************************************/
779 /* timers */
781 #define QEMU_CLOCK_REALTIME 0
782 #define QEMU_CLOCK_VIRTUAL 1
783 #define QEMU_CLOCK_HOST 2
785 struct QEMUClock {
786 int type;
787 /* XXX: add frequency */
790 struct QEMUTimer {
791 QEMUClock *clock;
792 int64_t expire_time;
793 QEMUTimerCB *cb;
794 void *opaque;
795 struct QEMUTimer *next;
798 struct qemu_alarm_timer {
799 char const *name;
800 unsigned int flags;
802 int (*start)(struct qemu_alarm_timer *t);
803 void (*stop)(struct qemu_alarm_timer *t);
804 void (*rearm)(struct qemu_alarm_timer *t);
805 void *priv;
808 #define ALARM_FLAG_DYNTICKS 0x1
809 #define ALARM_FLAG_EXPIRED 0x2
811 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
813 return t && (t->flags & ALARM_FLAG_DYNTICKS);
816 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
818 if (!alarm_has_dynticks(t))
819 return;
821 t->rearm(t);
824 /* TODO: MIN_TIMER_REARM_US should be optimized */
825 #define MIN_TIMER_REARM_US 250
827 static struct qemu_alarm_timer *alarm_timer;
829 #ifdef _WIN32
831 struct qemu_alarm_win32 {
832 MMRESULT timerId;
833 unsigned int period;
834 } alarm_win32_data = {0, -1};
836 static int win32_start_timer(struct qemu_alarm_timer *t);
837 static void win32_stop_timer(struct qemu_alarm_timer *t);
838 static void win32_rearm_timer(struct qemu_alarm_timer *t);
840 #else
842 static int unix_start_timer(struct qemu_alarm_timer *t);
843 static void unix_stop_timer(struct qemu_alarm_timer *t);
845 #ifdef __linux__
847 static int dynticks_start_timer(struct qemu_alarm_timer *t);
848 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
849 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
851 static int hpet_start_timer(struct qemu_alarm_timer *t);
852 static void hpet_stop_timer(struct qemu_alarm_timer *t);
854 static int rtc_start_timer(struct qemu_alarm_timer *t);
855 static void rtc_stop_timer(struct qemu_alarm_timer *t);
857 #endif /* __linux__ */
859 #endif /* _WIN32 */
861 /* Correlation between real and virtual time is always going to be
862 fairly approximate, so ignore small variation.
863 When the guest is idle real and virtual time will be aligned in
864 the IO wait loop. */
865 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
867 static void icount_adjust(void)
869 int64_t cur_time;
870 int64_t cur_icount;
871 int64_t delta;
872 static int64_t last_delta;
873 /* If the VM is not running, then do nothing. */
874 if (!vm_running)
875 return;
877 cur_time = cpu_get_clock();
878 cur_icount = qemu_get_clock(vm_clock);
879 delta = cur_icount - cur_time;
880 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
881 if (delta > 0
882 && last_delta + ICOUNT_WOBBLE < delta * 2
883 && icount_time_shift > 0) {
884 /* The guest is getting too far ahead. Slow time down. */
885 icount_time_shift--;
887 if (delta < 0
888 && last_delta - ICOUNT_WOBBLE > delta * 2
889 && icount_time_shift < MAX_ICOUNT_SHIFT) {
890 /* The guest is getting too far behind. Speed time up. */
891 icount_time_shift++;
893 last_delta = delta;
894 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
897 static void icount_adjust_rt(void * opaque)
899 qemu_mod_timer(icount_rt_timer,
900 qemu_get_clock(rt_clock) + 1000);
901 icount_adjust();
904 static void icount_adjust_vm(void * opaque)
906 qemu_mod_timer(icount_vm_timer,
907 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
908 icount_adjust();
911 static void init_icount_adjust(void)
913 /* Have both realtime and virtual time triggers for speed adjustment.
914 The realtime trigger catches emulated time passing too slowly,
915 the virtual time trigger catches emulated time passing too fast.
916 Realtime triggers occur even when idle, so use them less frequently
917 than VM triggers. */
918 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
919 qemu_mod_timer(icount_rt_timer,
920 qemu_get_clock(rt_clock) + 1000);
921 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
922 qemu_mod_timer(icount_vm_timer,
923 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
926 static struct qemu_alarm_timer alarm_timers[] = {
927 #ifndef _WIN32
928 #ifdef __linux__
929 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
930 dynticks_stop_timer, dynticks_rearm_timer, NULL},
931 /* HPET - if available - is preferred */
932 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
933 /* ...otherwise try RTC */
934 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
935 #endif
936 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
937 #else
938 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
939 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
940 {"win32", 0, win32_start_timer,
941 win32_stop_timer, NULL, &alarm_win32_data},
942 #endif
943 {NULL, }
946 static void show_available_alarms(void)
948 int i;
950 printf("Available alarm timers, in order of precedence:\n");
951 for (i = 0; alarm_timers[i].name; i++)
952 printf("%s\n", alarm_timers[i].name);
955 static void configure_alarms(char const *opt)
957 int i;
958 int cur = 0;
959 int count = ARRAY_SIZE(alarm_timers) - 1;
960 char *arg;
961 char *name;
962 struct qemu_alarm_timer tmp;
964 if (!strcmp(opt, "?")) {
965 show_available_alarms();
966 exit(0);
969 arg = qemu_strdup(opt);
971 /* Reorder the array */
972 name = strtok(arg, ",");
973 while (name) {
974 for (i = 0; i < count && alarm_timers[i].name; i++) {
975 if (!strcmp(alarm_timers[i].name, name))
976 break;
979 if (i == count) {
980 fprintf(stderr, "Unknown clock %s\n", name);
981 goto next;
984 if (i < cur)
985 /* Ignore */
986 goto next;
988 /* Swap */
989 tmp = alarm_timers[i];
990 alarm_timers[i] = alarm_timers[cur];
991 alarm_timers[cur] = tmp;
993 cur++;
994 next:
995 name = strtok(NULL, ",");
998 qemu_free(arg);
1000 if (cur) {
1001 /* Disable remaining timers */
1002 for (i = cur; i < count; i++)
1003 alarm_timers[i].name = NULL;
1004 } else {
1005 show_available_alarms();
1006 exit(1);
1010 #define QEMU_NUM_CLOCKS 3
1012 QEMUClock *rt_clock;
1013 QEMUClock *vm_clock;
1014 QEMUClock *host_clock;
1016 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
1018 static QEMUClock *qemu_new_clock(int type)
1020 QEMUClock *clock;
1021 clock = qemu_mallocz(sizeof(QEMUClock));
1022 clock->type = type;
1023 return clock;
1026 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1028 QEMUTimer *ts;
1030 ts = qemu_mallocz(sizeof(QEMUTimer));
1031 ts->clock = clock;
1032 ts->cb = cb;
1033 ts->opaque = opaque;
1034 return ts;
1037 void qemu_free_timer(QEMUTimer *ts)
1039 qemu_free(ts);
1042 /* stop a timer, but do not dealloc it */
1043 void qemu_del_timer(QEMUTimer *ts)
1045 QEMUTimer **pt, *t;
1047 /* NOTE: this code must be signal safe because
1048 qemu_timer_expired() can be called from a signal. */
1049 pt = &active_timers[ts->clock->type];
1050 for(;;) {
1051 t = *pt;
1052 if (!t)
1053 break;
1054 if (t == ts) {
1055 *pt = t->next;
1056 break;
1058 pt = &t->next;
1062 /* modify the current timer so that it will be fired when current_time
1063 >= expire_time. The corresponding callback will be called. */
1064 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1066 QEMUTimer **pt, *t;
1068 qemu_del_timer(ts);
1070 /* add the timer in the sorted list */
1071 /* NOTE: this code must be signal safe because
1072 qemu_timer_expired() can be called from a signal. */
1073 pt = &active_timers[ts->clock->type];
1074 for(;;) {
1075 t = *pt;
1076 if (!t)
1077 break;
1078 if (t->expire_time > expire_time)
1079 break;
1080 pt = &t->next;
1082 ts->expire_time = expire_time;
1083 ts->next = *pt;
1084 *pt = ts;
1086 /* Rearm if necessary */
1087 if (pt == &active_timers[ts->clock->type]) {
1088 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1089 qemu_rearm_alarm_timer(alarm_timer);
1091 /* Interrupt execution to force deadline recalculation. */
1092 if (use_icount)
1093 qemu_notify_event();
1097 int qemu_timer_pending(QEMUTimer *ts)
1099 QEMUTimer *t;
1100 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1101 if (t == ts)
1102 return 1;
1104 return 0;
1107 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1109 if (!timer_head)
1110 return 0;
1111 return (timer_head->expire_time <= current_time);
1114 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1116 QEMUTimer *ts;
1118 for(;;) {
1119 ts = *ptimer_head;
1120 if (!ts || ts->expire_time > current_time)
1121 break;
1122 /* remove timer from the list before calling the callback */
1123 *ptimer_head = ts->next;
1124 ts->next = NULL;
1126 /* run the callback (the timer list can be modified) */
1127 ts->cb(ts->opaque);
1131 int64_t qemu_get_clock(QEMUClock *clock)
1133 switch(clock->type) {
1134 case QEMU_CLOCK_REALTIME:
1135 return get_clock() / 1000000;
1136 default:
1137 case QEMU_CLOCK_VIRTUAL:
1138 if (use_icount) {
1139 return cpu_get_icount();
1140 } else {
1141 return cpu_get_clock();
1143 case QEMU_CLOCK_HOST:
1144 return get_clock_realtime();
1148 static void init_clocks(void)
1150 init_get_clock();
1151 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
1152 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
1153 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
1155 rtc_clock = host_clock;
1158 /* save a timer */
1159 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1161 uint64_t expire_time;
1163 if (qemu_timer_pending(ts)) {
1164 expire_time = ts->expire_time;
1165 } else {
1166 expire_time = -1;
1168 qemu_put_be64(f, expire_time);
1171 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1173 uint64_t expire_time;
1175 expire_time = qemu_get_be64(f);
1176 if (expire_time != -1) {
1177 qemu_mod_timer(ts, expire_time);
1178 } else {
1179 qemu_del_timer(ts);
1183 static const VMStateDescription vmstate_timers = {
1184 .name = "timer",
1185 .version_id = 2,
1186 .minimum_version_id = 1,
1187 .minimum_version_id_old = 1,
1188 .fields = (VMStateField []) {
1189 VMSTATE_INT64(cpu_ticks_offset, TimersState),
1190 VMSTATE_INT64(dummy, TimersState),
1191 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1192 VMSTATE_END_OF_LIST()
1196 static void qemu_event_increment(void);
1198 #ifdef _WIN32
1199 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1200 DWORD_PTR dwUser, DWORD_PTR dw1,
1201 DWORD_PTR dw2)
1202 #else
1203 static void host_alarm_handler(int host_signum)
1204 #endif
1206 #if 0
1207 #define DISP_FREQ 1000
1209 static int64_t delta_min = INT64_MAX;
1210 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1211 static int count;
1212 ti = qemu_get_clock(vm_clock);
1213 if (last_clock != 0) {
1214 delta = ti - last_clock;
1215 if (delta < delta_min)
1216 delta_min = delta;
1217 if (delta > delta_max)
1218 delta_max = delta;
1219 delta_cum += delta;
1220 if (++count == DISP_FREQ) {
1221 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1222 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1223 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1224 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1225 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1226 count = 0;
1227 delta_min = INT64_MAX;
1228 delta_max = 0;
1229 delta_cum = 0;
1232 last_clock = ti;
1234 #endif
1235 if (alarm_has_dynticks(alarm_timer) ||
1236 (!use_icount &&
1237 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1238 qemu_get_clock(vm_clock))) ||
1239 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1240 qemu_get_clock(rt_clock)) ||
1241 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1242 qemu_get_clock(host_clock))) {
1243 qemu_event_increment();
1244 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1246 #ifndef CONFIG_IOTHREAD
1247 if (next_cpu) {
1248 /* stop the currently executing cpu because a timer occured */
1249 cpu_exit(next_cpu);
1251 #endif
1252 timer_alarm_pending = 1;
1253 qemu_notify_event();
1257 static int64_t qemu_next_deadline(void)
1259 /* To avoid problems with overflow limit this to 2^32. */
1260 int64_t delta = INT32_MAX;
1262 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1263 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1264 qemu_get_clock(vm_clock);
1266 if (active_timers[QEMU_CLOCK_HOST]) {
1267 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1268 qemu_get_clock(host_clock);
1269 if (hdelta < delta)
1270 delta = hdelta;
1273 if (delta < 0)
1274 delta = 0;
1276 return delta;
1279 #if defined(__linux__)
1280 static uint64_t qemu_next_deadline_dyntick(void)
1282 int64_t delta;
1283 int64_t rtdelta;
1285 if (use_icount)
1286 delta = INT32_MAX;
1287 else
1288 delta = (qemu_next_deadline() + 999) / 1000;
1290 if (active_timers[QEMU_CLOCK_REALTIME]) {
1291 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1292 qemu_get_clock(rt_clock))*1000;
1293 if (rtdelta < delta)
1294 delta = rtdelta;
1297 if (delta < MIN_TIMER_REARM_US)
1298 delta = MIN_TIMER_REARM_US;
1300 return delta;
1302 #endif
1304 #ifndef _WIN32
1306 /* Sets a specific flag */
1307 static int fcntl_setfl(int fd, int flag)
1309 int flags;
1311 flags = fcntl(fd, F_GETFL);
1312 if (flags == -1)
1313 return -errno;
1315 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1316 return -errno;
1318 return 0;
1321 #if defined(__linux__)
1323 #define RTC_FREQ 1024
1325 static void enable_sigio_timer(int fd)
1327 struct sigaction act;
1329 /* timer signal */
1330 sigfillset(&act.sa_mask);
1331 act.sa_flags = 0;
1332 act.sa_handler = host_alarm_handler;
1334 sigaction(SIGIO, &act, NULL);
1335 fcntl_setfl(fd, O_ASYNC);
1336 fcntl(fd, F_SETOWN, getpid());
1339 static int hpet_start_timer(struct qemu_alarm_timer *t)
1341 struct hpet_info info;
1342 int r, fd;
1344 fd = qemu_open("/dev/hpet", O_RDONLY);
1345 if (fd < 0)
1346 return -1;
1348 /* Set frequency */
1349 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1350 if (r < 0) {
1351 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1352 "error, but for better emulation accuracy type:\n"
1353 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1354 goto fail;
1357 /* Check capabilities */
1358 r = ioctl(fd, HPET_INFO, &info);
1359 if (r < 0)
1360 goto fail;
1362 /* Enable periodic mode */
1363 r = ioctl(fd, HPET_EPI, 0);
1364 if (info.hi_flags && (r < 0))
1365 goto fail;
1367 /* Enable interrupt */
1368 r = ioctl(fd, HPET_IE_ON, 0);
1369 if (r < 0)
1370 goto fail;
1372 enable_sigio_timer(fd);
1373 t->priv = (void *)(long)fd;
1375 return 0;
1376 fail:
1377 close(fd);
1378 return -1;
1381 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1383 int fd = (long)t->priv;
1385 close(fd);
1388 static int rtc_start_timer(struct qemu_alarm_timer *t)
1390 int rtc_fd;
1391 unsigned long current_rtc_freq = 0;
1393 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1394 if (rtc_fd < 0)
1395 return -1;
1396 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1397 if (current_rtc_freq != RTC_FREQ &&
1398 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1399 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1400 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1401 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1402 goto fail;
1404 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1405 fail:
1406 close(rtc_fd);
1407 return -1;
1410 enable_sigio_timer(rtc_fd);
1412 t->priv = (void *)(long)rtc_fd;
1414 return 0;
1417 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1419 int rtc_fd = (long)t->priv;
1421 close(rtc_fd);
1424 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1426 struct sigevent ev;
1427 timer_t host_timer;
1428 struct sigaction act;
1430 sigfillset(&act.sa_mask);
1431 act.sa_flags = 0;
1432 act.sa_handler = host_alarm_handler;
1434 sigaction(SIGALRM, &act, NULL);
1437 * Initialize ev struct to 0 to avoid valgrind complaining
1438 * about uninitialized data in timer_create call
1440 memset(&ev, 0, sizeof(ev));
1441 ev.sigev_value.sival_int = 0;
1442 ev.sigev_notify = SIGEV_SIGNAL;
1443 ev.sigev_signo = SIGALRM;
1445 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1446 perror("timer_create");
1448 /* disable dynticks */
1449 fprintf(stderr, "Dynamic Ticks disabled\n");
1451 return -1;
1454 t->priv = (void *)(long)host_timer;
1456 return 0;
1459 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1461 timer_t host_timer = (timer_t)(long)t->priv;
1463 timer_delete(host_timer);
1466 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1468 timer_t host_timer = (timer_t)(long)t->priv;
1469 struct itimerspec timeout;
1470 int64_t nearest_delta_us = INT64_MAX;
1471 int64_t current_us;
1473 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1474 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1475 !active_timers[QEMU_CLOCK_HOST])
1476 return;
1478 nearest_delta_us = qemu_next_deadline_dyntick();
1480 /* check whether a timer is already running */
1481 if (timer_gettime(host_timer, &timeout)) {
1482 perror("gettime");
1483 fprintf(stderr, "Internal timer error: aborting\n");
1484 exit(1);
1486 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1487 if (current_us && current_us <= nearest_delta_us)
1488 return;
1490 timeout.it_interval.tv_sec = 0;
1491 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1492 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1493 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1494 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1495 perror("settime");
1496 fprintf(stderr, "Internal timer error: aborting\n");
1497 exit(1);
1501 #endif /* defined(__linux__) */
1503 static int unix_start_timer(struct qemu_alarm_timer *t)
1505 struct sigaction act;
1506 struct itimerval itv;
1507 int err;
1509 /* timer signal */
1510 sigfillset(&act.sa_mask);
1511 act.sa_flags = 0;
1512 act.sa_handler = host_alarm_handler;
1514 sigaction(SIGALRM, &act, NULL);
1516 itv.it_interval.tv_sec = 0;
1517 /* for i386 kernel 2.6 to get 1 ms */
1518 itv.it_interval.tv_usec = 999;
1519 itv.it_value.tv_sec = 0;
1520 itv.it_value.tv_usec = 10 * 1000;
1522 err = setitimer(ITIMER_REAL, &itv, NULL);
1523 if (err)
1524 return -1;
1526 return 0;
1529 static void unix_stop_timer(struct qemu_alarm_timer *t)
1531 struct itimerval itv;
1533 memset(&itv, 0, sizeof(itv));
1534 setitimer(ITIMER_REAL, &itv, NULL);
1537 #endif /* !defined(_WIN32) */
1540 #ifdef _WIN32
1542 static int win32_start_timer(struct qemu_alarm_timer *t)
1544 TIMECAPS tc;
1545 struct qemu_alarm_win32 *data = t->priv;
1546 UINT flags;
1548 memset(&tc, 0, sizeof(tc));
1549 timeGetDevCaps(&tc, sizeof(tc));
1551 if (data->period < tc.wPeriodMin)
1552 data->period = tc.wPeriodMin;
1554 timeBeginPeriod(data->period);
1556 flags = TIME_CALLBACK_FUNCTION;
1557 if (alarm_has_dynticks(t))
1558 flags |= TIME_ONESHOT;
1559 else
1560 flags |= TIME_PERIODIC;
1562 data->timerId = timeSetEvent(1, // interval (ms)
1563 data->period, // resolution
1564 host_alarm_handler, // function
1565 (DWORD)t, // parameter
1566 flags);
1568 if (!data->timerId) {
1569 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1570 GetLastError());
1571 timeEndPeriod(data->period);
1572 return -1;
1575 return 0;
1578 static void win32_stop_timer(struct qemu_alarm_timer *t)
1580 struct qemu_alarm_win32 *data = t->priv;
1582 timeKillEvent(data->timerId);
1583 timeEndPeriod(data->period);
1586 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1588 struct qemu_alarm_win32 *data = t->priv;
1590 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1591 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1592 !active_timers[QEMU_CLOCK_HOST])
1593 return;
1595 timeKillEvent(data->timerId);
1597 data->timerId = timeSetEvent(1,
1598 data->period,
1599 host_alarm_handler,
1600 (DWORD)t,
1601 TIME_ONESHOT | TIME_PERIODIC);
1603 if (!data->timerId) {
1604 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1605 GetLastError());
1607 timeEndPeriod(data->period);
1608 exit(1);
1612 #endif /* _WIN32 */
1614 static int init_timer_alarm(void)
1616 struct qemu_alarm_timer *t = NULL;
1617 int i, err = -1;
1619 for (i = 0; alarm_timers[i].name; i++) {
1620 t = &alarm_timers[i];
1622 err = t->start(t);
1623 if (!err)
1624 break;
1627 if (err) {
1628 err = -ENOENT;
1629 goto fail;
1632 alarm_timer = t;
1634 return 0;
1636 fail:
1637 return err;
1640 static void quit_timers(void)
1642 alarm_timer->stop(alarm_timer);
1643 alarm_timer = NULL;
1646 /***********************************************************/
1647 /* host time/date access */
1648 void qemu_get_timedate(struct tm *tm, int offset)
1650 time_t ti;
1651 struct tm *ret;
1653 time(&ti);
1654 ti += offset;
1655 if (rtc_date_offset == -1) {
1656 if (rtc_utc)
1657 ret = gmtime(&ti);
1658 else
1659 ret = localtime(&ti);
1660 } else {
1661 ti -= rtc_date_offset;
1662 ret = gmtime(&ti);
1665 memcpy(tm, ret, sizeof(struct tm));
1668 int qemu_timedate_diff(struct tm *tm)
1670 time_t seconds;
1672 if (rtc_date_offset == -1)
1673 if (rtc_utc)
1674 seconds = mktimegm(tm);
1675 else
1676 seconds = mktime(tm);
1677 else
1678 seconds = mktimegm(tm) + rtc_date_offset;
1680 return seconds - time(NULL);
1683 static void configure_rtc_date_offset(const char *startdate, int legacy)
1685 time_t rtc_start_date;
1686 struct tm tm;
1688 if (!strcmp(startdate, "now") && legacy) {
1689 rtc_date_offset = -1;
1690 } else {
1691 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1692 &tm.tm_year,
1693 &tm.tm_mon,
1694 &tm.tm_mday,
1695 &tm.tm_hour,
1696 &tm.tm_min,
1697 &tm.tm_sec) == 6) {
1698 /* OK */
1699 } else if (sscanf(startdate, "%d-%d-%d",
1700 &tm.tm_year,
1701 &tm.tm_mon,
1702 &tm.tm_mday) == 3) {
1703 tm.tm_hour = 0;
1704 tm.tm_min = 0;
1705 tm.tm_sec = 0;
1706 } else {
1707 goto date_fail;
1709 tm.tm_year -= 1900;
1710 tm.tm_mon--;
1711 rtc_start_date = mktimegm(&tm);
1712 if (rtc_start_date == -1) {
1713 date_fail:
1714 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1715 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1716 exit(1);
1718 rtc_date_offset = time(NULL) - rtc_start_date;
1722 static void configure_rtc(QemuOpts *opts)
1724 const char *value;
1726 value = qemu_opt_get(opts, "base");
1727 if (value) {
1728 if (!strcmp(value, "utc")) {
1729 rtc_utc = 1;
1730 } else if (!strcmp(value, "localtime")) {
1731 rtc_utc = 0;
1732 } else {
1733 configure_rtc_date_offset(value, 0);
1736 value = qemu_opt_get(opts, "clock");
1737 if (value) {
1738 if (!strcmp(value, "host")) {
1739 rtc_clock = host_clock;
1740 } else if (!strcmp(value, "vm")) {
1741 rtc_clock = vm_clock;
1742 } else {
1743 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1744 exit(1);
1747 #ifdef CONFIG_TARGET_I386
1748 value = qemu_opt_get(opts, "driftfix");
1749 if (value) {
1750 if (!strcmp(buf, "slew")) {
1751 rtc_td_hack = 1;
1752 } else if (!strcmp(buf, "none")) {
1753 rtc_td_hack = 0;
1754 } else {
1755 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1756 exit(1);
1759 #endif
1762 #ifdef _WIN32
1763 static void socket_cleanup(void)
1765 WSACleanup();
1768 static int socket_init(void)
1770 WSADATA Data;
1771 int ret, err;
1773 ret = WSAStartup(MAKEWORD(2,2), &Data);
1774 if (ret != 0) {
1775 err = WSAGetLastError();
1776 fprintf(stderr, "WSAStartup: %d\n", err);
1777 return -1;
1779 atexit(socket_cleanup);
1780 return 0;
1782 #endif
1784 /***********************************************************/
1785 /* Bluetooth support */
1786 static int nb_hcis;
1787 static int cur_hci;
1788 static struct HCIInfo *hci_table[MAX_NICS];
1790 static struct bt_vlan_s {
1791 struct bt_scatternet_s net;
1792 int id;
1793 struct bt_vlan_s *next;
1794 } *first_bt_vlan;
1796 /* find or alloc a new bluetooth "VLAN" */
1797 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1799 struct bt_vlan_s **pvlan, *vlan;
1800 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1801 if (vlan->id == id)
1802 return &vlan->net;
1804 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1805 vlan->id = id;
1806 pvlan = &first_bt_vlan;
1807 while (*pvlan != NULL)
1808 pvlan = &(*pvlan)->next;
1809 *pvlan = vlan;
1810 return &vlan->net;
1813 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1817 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1819 return -ENOTSUP;
1822 static struct HCIInfo null_hci = {
1823 .cmd_send = null_hci_send,
1824 .sco_send = null_hci_send,
1825 .acl_send = null_hci_send,
1826 .bdaddr_set = null_hci_addr_set,
1829 struct HCIInfo *qemu_next_hci(void)
1831 if (cur_hci == nb_hcis)
1832 return &null_hci;
1834 return hci_table[cur_hci++];
1837 static struct HCIInfo *hci_init(const char *str)
1839 char *endp;
1840 struct bt_scatternet_s *vlan = 0;
1842 if (!strcmp(str, "null"))
1843 /* null */
1844 return &null_hci;
1845 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1846 /* host[:hciN] */
1847 return bt_host_hci(str[4] ? str + 5 : "hci0");
1848 else if (!strncmp(str, "hci", 3)) {
1849 /* hci[,vlan=n] */
1850 if (str[3]) {
1851 if (!strncmp(str + 3, ",vlan=", 6)) {
1852 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1853 if (*endp)
1854 vlan = 0;
1856 } else
1857 vlan = qemu_find_bt_vlan(0);
1858 if (vlan)
1859 return bt_new_hci(vlan);
1862 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1864 return 0;
1867 static int bt_hci_parse(const char *str)
1869 struct HCIInfo *hci;
1870 bdaddr_t bdaddr;
1872 if (nb_hcis >= MAX_NICS) {
1873 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1874 return -1;
1877 hci = hci_init(str);
1878 if (!hci)
1879 return -1;
1881 bdaddr.b[0] = 0x52;
1882 bdaddr.b[1] = 0x54;
1883 bdaddr.b[2] = 0x00;
1884 bdaddr.b[3] = 0x12;
1885 bdaddr.b[4] = 0x34;
1886 bdaddr.b[5] = 0x56 + nb_hcis;
1887 hci->bdaddr_set(hci, bdaddr.b);
1889 hci_table[nb_hcis++] = hci;
1891 return 0;
1894 static void bt_vhci_add(int vlan_id)
1896 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1898 if (!vlan->slave)
1899 fprintf(stderr, "qemu: warning: adding a VHCI to "
1900 "an empty scatternet %i\n", vlan_id);
1902 bt_vhci_init(bt_new_hci(vlan));
1905 static struct bt_device_s *bt_device_add(const char *opt)
1907 struct bt_scatternet_s *vlan;
1908 int vlan_id = 0;
1909 char *endp = strstr(opt, ",vlan=");
1910 int len = (endp ? endp - opt : strlen(opt)) + 1;
1911 char devname[10];
1913 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1915 if (endp) {
1916 vlan_id = strtol(endp + 6, &endp, 0);
1917 if (*endp) {
1918 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1919 return 0;
1923 vlan = qemu_find_bt_vlan(vlan_id);
1925 if (!vlan->slave)
1926 fprintf(stderr, "qemu: warning: adding a slave device to "
1927 "an empty scatternet %i\n", vlan_id);
1929 if (!strcmp(devname, "keyboard"))
1930 return bt_keyboard_init(vlan);
1932 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1933 return 0;
1936 static int bt_parse(const char *opt)
1938 const char *endp, *p;
1939 int vlan;
1941 if (strstart(opt, "hci", &endp)) {
1942 if (!*endp || *endp == ',') {
1943 if (*endp)
1944 if (!strstart(endp, ",vlan=", 0))
1945 opt = endp + 1;
1947 return bt_hci_parse(opt);
1949 } else if (strstart(opt, "vhci", &endp)) {
1950 if (!*endp || *endp == ',') {
1951 if (*endp) {
1952 if (strstart(endp, ",vlan=", &p)) {
1953 vlan = strtol(p, (char **) &endp, 0);
1954 if (*endp) {
1955 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1956 return 1;
1958 } else {
1959 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1960 return 1;
1962 } else
1963 vlan = 0;
1965 bt_vhci_add(vlan);
1966 return 0;
1968 } else if (strstart(opt, "device:", &endp))
1969 return !bt_device_add(endp);
1971 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1972 return 1;
1975 /***********************************************************/
1976 /* QEMU Block devices */
1978 #define HD_ALIAS "index=%d,media=disk"
1979 #define CDROM_ALIAS "index=2,media=cdrom"
1980 #define FD_ALIAS "index=%d,if=floppy"
1981 #define PFLASH_ALIAS "if=pflash"
1982 #define MTD_ALIAS "if=mtd"
1983 #define SD_ALIAS "index=0,if=sd"
1985 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1987 va_list ap;
1988 char optstr[1024];
1989 QemuOpts *opts;
1991 va_start(ap, fmt);
1992 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1993 va_end(ap);
1995 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1996 if (!opts) {
1997 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1998 __FUNCTION__, optstr);
1999 return NULL;
2001 if (file)
2002 qemu_opt_set(opts, "file", file);
2003 return opts;
2006 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
2008 DriveInfo *dinfo;
2010 /* seek interface, bus and unit */
2012 QTAILQ_FOREACH(dinfo, &drives, next) {
2013 if (dinfo->type == type &&
2014 dinfo->bus == bus &&
2015 dinfo->unit == unit)
2016 return dinfo;
2019 return NULL;
2022 DriveInfo *drive_get_by_id(const char *id)
2024 DriveInfo *dinfo;
2026 QTAILQ_FOREACH(dinfo, &drives, next) {
2027 if (strcmp(id, dinfo->id))
2028 continue;
2029 return dinfo;
2031 return NULL;
2034 int drive_get_max_bus(BlockInterfaceType type)
2036 int max_bus;
2037 DriveInfo *dinfo;
2039 max_bus = -1;
2040 QTAILQ_FOREACH(dinfo, &drives, next) {
2041 if(dinfo->type == type &&
2042 dinfo->bus > max_bus)
2043 max_bus = dinfo->bus;
2045 return max_bus;
2048 const char *drive_get_serial(BlockDriverState *bdrv)
2050 DriveInfo *dinfo;
2052 QTAILQ_FOREACH(dinfo, &drives, next) {
2053 if (dinfo->bdrv == bdrv)
2054 return dinfo->serial;
2057 return "\0";
2060 BlockInterfaceErrorAction drive_get_on_error(
2061 BlockDriverState *bdrv, int is_read)
2063 DriveInfo *dinfo;
2065 QTAILQ_FOREACH(dinfo, &drives, next) {
2066 if (dinfo->bdrv == bdrv)
2067 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
2070 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
2073 static void bdrv_format_print(void *opaque, const char *name)
2075 fprintf(stderr, " %s", name);
2078 void drive_uninit(DriveInfo *dinfo)
2080 qemu_opts_del(dinfo->opts);
2081 bdrv_delete(dinfo->bdrv);
2082 QTAILQ_REMOVE(&drives, dinfo, next);
2083 qemu_free(dinfo);
2086 static int parse_block_error_action(const char *buf, int is_read)
2088 if (!strcmp(buf, "ignore")) {
2089 return BLOCK_ERR_IGNORE;
2090 } else if (!is_read && !strcmp(buf, "enospc")) {
2091 return BLOCK_ERR_STOP_ENOSPC;
2092 } else if (!strcmp(buf, "stop")) {
2093 return BLOCK_ERR_STOP_ANY;
2094 } else if (!strcmp(buf, "report")) {
2095 return BLOCK_ERR_REPORT;
2096 } else {
2097 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
2098 buf, is_read ? "read" : "write");
2099 return -1;
2103 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
2104 int *fatal_error)
2106 const char *buf;
2107 const char *file = NULL;
2108 char devname[128];
2109 const char *serial;
2110 const char *mediastr = "";
2111 BlockInterfaceType type;
2112 enum { MEDIA_DISK, MEDIA_CDROM } media;
2113 int bus_id, unit_id;
2114 int cyls, heads, secs, translation;
2115 BlockDriver *drv = NULL;
2116 QEMUMachine *machine = opaque;
2117 int max_devs;
2118 int index;
2119 int cache;
2120 int aio = 0;
2121 int ro = 0;
2122 int bdrv_flags;
2123 int on_read_error, on_write_error;
2124 const char *devaddr;
2125 DriveInfo *dinfo;
2126 int is_extboot = 0;
2127 int snapshot = 0;
2129 *fatal_error = 1;
2131 translation = BIOS_ATA_TRANSLATION_AUTO;
2132 cache = 1;
2134 if (machine && machine->use_scsi) {
2135 type = IF_SCSI;
2136 max_devs = MAX_SCSI_DEVS;
2137 pstrcpy(devname, sizeof(devname), "scsi");
2138 } else {
2139 type = IF_IDE;
2140 max_devs = MAX_IDE_DEVS;
2141 pstrcpy(devname, sizeof(devname), "ide");
2143 media = MEDIA_DISK;
2145 /* extract parameters */
2146 bus_id = qemu_opt_get_number(opts, "bus", 0);
2147 unit_id = qemu_opt_get_number(opts, "unit", -1);
2148 index = qemu_opt_get_number(opts, "index", -1);
2150 cyls = qemu_opt_get_number(opts, "cyls", 0);
2151 heads = qemu_opt_get_number(opts, "heads", 0);
2152 secs = qemu_opt_get_number(opts, "secs", 0);
2154 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2155 ro = qemu_opt_get_bool(opts, "readonly", 0);
2157 file = qemu_opt_get(opts, "file");
2158 serial = qemu_opt_get(opts, "serial");
2160 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2161 pstrcpy(devname, sizeof(devname), buf);
2162 if (!strcmp(buf, "ide")) {
2163 type = IF_IDE;
2164 max_devs = MAX_IDE_DEVS;
2165 } else if (!strcmp(buf, "scsi")) {
2166 type = IF_SCSI;
2167 max_devs = MAX_SCSI_DEVS;
2168 } else if (!strcmp(buf, "floppy")) {
2169 type = IF_FLOPPY;
2170 max_devs = 0;
2171 } else if (!strcmp(buf, "pflash")) {
2172 type = IF_PFLASH;
2173 max_devs = 0;
2174 } else if (!strcmp(buf, "mtd")) {
2175 type = IF_MTD;
2176 max_devs = 0;
2177 } else if (!strcmp(buf, "sd")) {
2178 type = IF_SD;
2179 max_devs = 0;
2180 } else if (!strcmp(buf, "virtio")) {
2181 type = IF_VIRTIO;
2182 max_devs = 0;
2183 } else if (!strcmp(buf, "xen")) {
2184 type = IF_XEN;
2185 max_devs = 0;
2186 } else if (!strcmp(buf, "none")) {
2187 type = IF_NONE;
2188 max_devs = 0;
2189 } else {
2190 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2191 return NULL;
2195 if (cyls || heads || secs) {
2196 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2197 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2198 return NULL;
2200 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2201 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2202 return NULL;
2204 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2205 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2206 return NULL;
2210 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2211 if (!cyls) {
2212 fprintf(stderr,
2213 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2214 buf);
2215 return NULL;
2217 if (!strcmp(buf, "none"))
2218 translation = BIOS_ATA_TRANSLATION_NONE;
2219 else if (!strcmp(buf, "lba"))
2220 translation = BIOS_ATA_TRANSLATION_LBA;
2221 else if (!strcmp(buf, "auto"))
2222 translation = BIOS_ATA_TRANSLATION_AUTO;
2223 else {
2224 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2225 return NULL;
2229 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2230 if (!strcmp(buf, "disk")) {
2231 media = MEDIA_DISK;
2232 } else if (!strcmp(buf, "cdrom")) {
2233 if (cyls || secs || heads) {
2234 fprintf(stderr,
2235 "qemu: '%s' invalid physical CHS format\n", buf);
2236 return NULL;
2238 media = MEDIA_CDROM;
2239 } else {
2240 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2241 return NULL;
2245 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2246 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2247 cache = 0;
2248 else if (!strcmp(buf, "writethrough"))
2249 cache = 1;
2250 else if (!strcmp(buf, "writeback"))
2251 cache = 2;
2252 else {
2253 fprintf(stderr, "qemu: invalid cache option\n");
2254 return NULL;
2258 #ifdef CONFIG_LINUX_AIO
2259 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2260 if (!strcmp(buf, "threads"))
2261 aio = 0;
2262 else if (!strcmp(buf, "native"))
2263 aio = 1;
2264 else {
2265 fprintf(stderr, "qemu: invalid aio option\n");
2266 return NULL;
2269 #endif
2271 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2272 if (strcmp(buf, "?") == 0) {
2273 fprintf(stderr, "qemu: Supported formats:");
2274 bdrv_iterate_format(bdrv_format_print, NULL);
2275 fprintf(stderr, "\n");
2276 return NULL;
2278 drv = bdrv_find_whitelisted_format(buf);
2279 if (!drv) {
2280 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2281 return NULL;
2285 is_extboot = qemu_opt_get_bool(opts, "boot", 0);
2286 if (is_extboot && extboot_drive) {
2287 fprintf(stderr, "qemu: two bootable drives specified\n");
2288 return NULL;
2291 on_write_error = BLOCK_ERR_STOP_ENOSPC;
2292 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2293 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2294 fprintf(stderr, "werror is no supported by this format\n");
2295 return NULL;
2298 on_write_error = parse_block_error_action(buf, 0);
2299 if (on_write_error < 0) {
2300 return NULL;
2304 on_read_error = BLOCK_ERR_REPORT;
2305 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2306 if (type != IF_IDE && type != IF_VIRTIO) {
2307 fprintf(stderr, "rerror is no supported by this format\n");
2308 return NULL;
2311 on_read_error = parse_block_error_action(buf, 1);
2312 if (on_read_error < 0) {
2313 return NULL;
2317 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2318 if (type != IF_VIRTIO) {
2319 fprintf(stderr, "addr is not supported\n");
2320 return NULL;
2324 /* compute bus and unit according index */
2326 if (index != -1) {
2327 if (bus_id != 0 || unit_id != -1) {
2328 fprintf(stderr,
2329 "qemu: index cannot be used with bus and unit\n");
2330 return NULL;
2332 if (max_devs == 0)
2334 unit_id = index;
2335 bus_id = 0;
2336 } else {
2337 unit_id = index % max_devs;
2338 bus_id = index / max_devs;
2342 /* if user doesn't specify a unit_id,
2343 * try to find the first free
2346 if (unit_id == -1) {
2347 unit_id = 0;
2348 while (drive_get(type, bus_id, unit_id) != NULL) {
2349 unit_id++;
2350 if (max_devs && unit_id >= max_devs) {
2351 unit_id -= max_devs;
2352 bus_id++;
2357 /* check unit id */
2359 if (max_devs && unit_id >= max_devs) {
2360 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2361 unit_id, max_devs - 1);
2362 return NULL;
2366 * ignore multiple definitions
2369 if (drive_get(type, bus_id, unit_id) != NULL) {
2370 *fatal_error = 0;
2371 return NULL;
2374 /* init */
2376 dinfo = qemu_mallocz(sizeof(*dinfo));
2377 if ((buf = qemu_opts_id(opts)) != NULL) {
2378 dinfo->id = qemu_strdup(buf);
2379 } else {
2380 /* no id supplied -> create one */
2381 dinfo->id = qemu_mallocz(32);
2382 if (type == IF_IDE || type == IF_SCSI)
2383 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2384 if (max_devs)
2385 snprintf(dinfo->id, 32, "%s%i%s%i",
2386 devname, bus_id, mediastr, unit_id);
2387 else
2388 snprintf(dinfo->id, 32, "%s%s%i",
2389 devname, mediastr, unit_id);
2391 dinfo->bdrv = bdrv_new(dinfo->id);
2392 dinfo->devaddr = devaddr;
2393 dinfo->type = type;
2394 dinfo->bus = bus_id;
2395 dinfo->unit = unit_id;
2396 dinfo->on_read_error = on_read_error;
2397 dinfo->on_write_error = on_write_error;
2398 dinfo->opts = opts;
2399 if (serial)
2400 strncpy(dinfo->serial, serial, sizeof(serial));
2401 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2402 if (is_extboot) {
2403 extboot_drive = dinfo;
2406 switch(type) {
2407 case IF_IDE:
2408 case IF_SCSI:
2409 case IF_XEN:
2410 case IF_NONE:
2411 switch(media) {
2412 case MEDIA_DISK:
2413 if (cyls != 0) {
2414 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2415 bdrv_set_translation_hint(dinfo->bdrv, translation);
2417 break;
2418 case MEDIA_CDROM:
2419 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2420 break;
2422 break;
2423 case IF_SD:
2424 /* FIXME: This isn't really a floppy, but it's a reasonable
2425 approximation. */
2426 case IF_FLOPPY:
2427 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2428 break;
2429 case IF_PFLASH:
2430 case IF_MTD:
2431 break;
2432 case IF_VIRTIO:
2433 /* add virtio block device */
2434 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2435 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2436 qemu_opt_set(opts, "drive", dinfo->id);
2437 if (devaddr)
2438 qemu_opt_set(opts, "addr", devaddr);
2439 break;
2440 case IF_COUNT:
2441 abort();
2443 if (!file) {
2444 *fatal_error = 0;
2445 return NULL;
2447 bdrv_flags = 0;
2448 if (snapshot) {
2449 bdrv_flags |= BDRV_O_SNAPSHOT;
2450 cache = 2; /* always use write-back with snapshot */
2452 if (cache == 0) /* no caching */
2453 bdrv_flags |= BDRV_O_NOCACHE;
2454 else if (cache == 2) /* write-back */
2455 bdrv_flags |= BDRV_O_CACHE_WB;
2457 if (aio == 1) {
2458 bdrv_flags |= BDRV_O_NATIVE_AIO;
2459 } else {
2460 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2463 if (ro == 1) {
2464 if (type == IF_IDE) {
2465 fprintf(stderr, "qemu: readonly flag not supported for drive with ide interface\n");
2466 return NULL;
2468 (void)bdrv_set_read_only(dinfo->bdrv, 1);
2471 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2472 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2473 file, strerror(errno));
2474 return NULL;
2477 if (bdrv_key_required(dinfo->bdrv))
2478 autostart = 0;
2479 *fatal_error = 0;
2480 return dinfo;
2483 static int drive_init_func(QemuOpts *opts, void *opaque)
2485 QEMUMachine *machine = opaque;
2486 int fatal_error = 0;
2488 if (drive_init(opts, machine, &fatal_error) == NULL) {
2489 if (fatal_error)
2490 return 1;
2492 return 0;
2495 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2497 if (NULL == qemu_opt_get(opts, "snapshot")) {
2498 qemu_opt_set(opts, "snapshot", "on");
2500 return 0;
2503 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2505 boot_set_handler = func;
2506 boot_set_opaque = opaque;
2509 int qemu_boot_set(const char *boot_devices)
2511 if (!boot_set_handler) {
2512 return -EINVAL;
2514 return boot_set_handler(boot_set_opaque, boot_devices);
2517 static int parse_bootdevices(char *devices)
2519 /* We just do some generic consistency checks */
2520 const char *p;
2521 int bitmap = 0;
2523 for (p = devices; *p != '\0'; p++) {
2524 /* Allowed boot devices are:
2525 * a-b: floppy disk drives
2526 * c-f: IDE disk drives
2527 * g-m: machine implementation dependant drives
2528 * n-p: network devices
2529 * It's up to each machine implementation to check if the given boot
2530 * devices match the actual hardware implementation and firmware
2531 * features.
2533 if (*p < 'a' || *p > 'p') {
2534 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2535 exit(1);
2537 if (bitmap & (1 << (*p - 'a'))) {
2538 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2539 exit(1);
2541 bitmap |= 1 << (*p - 'a');
2543 return bitmap;
2546 static void restore_boot_devices(void *opaque)
2548 char *standard_boot_devices = opaque;
2550 qemu_boot_set(standard_boot_devices);
2552 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2553 qemu_free(standard_boot_devices);
2556 static void numa_add(const char *optarg)
2558 char option[128];
2559 char *endptr;
2560 unsigned long long value, endvalue;
2561 int nodenr;
2563 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2564 if (!strcmp(option, "node")) {
2565 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2566 nodenr = nb_numa_nodes;
2567 } else {
2568 nodenr = strtoull(option, NULL, 10);
2571 if (get_param_value(option, 128, "mem", optarg) == 0) {
2572 node_mem[nodenr] = 0;
2573 } else {
2574 value = strtoull(option, &endptr, 0);
2575 switch (*endptr) {
2576 case 0: case 'M': case 'm':
2577 value <<= 20;
2578 break;
2579 case 'G': case 'g':
2580 value <<= 30;
2581 break;
2583 node_mem[nodenr] = value;
2585 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2586 node_cpumask[nodenr] = 0;
2587 } else {
2588 value = strtoull(option, &endptr, 10);
2589 if (value >= 64) {
2590 value = 63;
2591 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2592 } else {
2593 if (*endptr == '-') {
2594 endvalue = strtoull(endptr+1, &endptr, 10);
2595 if (endvalue >= 63) {
2596 endvalue = 62;
2597 fprintf(stderr,
2598 "only 63 CPUs in NUMA mode supported.\n");
2600 value = (1 << (endvalue + 1)) - (1 << value);
2601 } else {
2602 value = 1 << value;
2605 node_cpumask[nodenr] = value;
2607 nb_numa_nodes++;
2609 return;
2612 static void smp_parse(const char *optarg)
2614 int smp, sockets = 0, threads = 0, cores = 0;
2615 char *endptr;
2616 char option[128];
2618 smp = strtoul(optarg, &endptr, 10);
2619 if (endptr != optarg) {
2620 if (*endptr == ',') {
2621 endptr++;
2624 if (get_param_value(option, 128, "sockets", endptr) != 0)
2625 sockets = strtoull(option, NULL, 10);
2626 if (get_param_value(option, 128, "cores", endptr) != 0)
2627 cores = strtoull(option, NULL, 10);
2628 if (get_param_value(option, 128, "threads", endptr) != 0)
2629 threads = strtoull(option, NULL, 10);
2630 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2631 max_cpus = strtoull(option, NULL, 10);
2633 /* compute missing values, prefer sockets over cores over threads */
2634 if (smp == 0 || sockets == 0) {
2635 sockets = sockets > 0 ? sockets : 1;
2636 cores = cores > 0 ? cores : 1;
2637 threads = threads > 0 ? threads : 1;
2638 if (smp == 0) {
2639 smp = cores * threads * sockets;
2640 } else {
2641 sockets = smp / (cores * threads);
2643 } else {
2644 if (cores == 0) {
2645 threads = threads > 0 ? threads : 1;
2646 cores = smp / (sockets * threads);
2647 } else {
2648 if (sockets == 0) {
2649 sockets = smp / (cores * threads);
2650 } else {
2651 threads = smp / (cores * sockets);
2655 smp_cpus = smp;
2656 smp_cores = cores > 0 ? cores : 1;
2657 smp_threads = threads > 0 ? threads : 1;
2658 if (max_cpus == 0)
2659 max_cpus = smp_cpus;
2662 /***********************************************************/
2663 /* USB devices */
2665 static int usb_device_add(const char *devname, int is_hotplug)
2667 const char *p;
2668 USBDevice *dev = NULL;
2670 if (!usb_enabled)
2671 return -1;
2673 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2674 dev = usbdevice_create(devname);
2675 if (dev)
2676 goto done;
2678 /* the other ones */
2679 if (strstart(devname, "host:", &p)) {
2680 dev = usb_host_device_open(p);
2681 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2682 dev = usb_bt_init(devname[2] ? hci_init(p) :
2683 bt_new_hci(qemu_find_bt_vlan(0)));
2684 } else {
2685 return -1;
2687 if (!dev)
2688 return -1;
2690 done:
2691 return 0;
2694 static int usb_device_del(const char *devname)
2696 int bus_num, addr;
2697 const char *p;
2699 if (strstart(devname, "host:", &p))
2700 return usb_host_device_close(p);
2702 if (!usb_enabled)
2703 return -1;
2705 p = strchr(devname, '.');
2706 if (!p)
2707 return -1;
2708 bus_num = strtoul(devname, NULL, 0);
2709 addr = strtoul(p + 1, NULL, 0);
2711 return usb_device_delete_addr(bus_num, addr);
2714 static int usb_parse(const char *cmdline)
2716 int r;
2717 r = usb_device_add(cmdline, 0);
2718 if (r < 0) {
2719 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2721 return r;
2724 void do_usb_add(Monitor *mon, const QDict *qdict)
2726 const char *devname = qdict_get_str(qdict, "devname");
2727 if (usb_device_add(devname, 1) < 0) {
2728 qemu_error("could not add USB device '%s'\n", devname);
2732 void do_usb_del(Monitor *mon, const QDict *qdict)
2734 const char *devname = qdict_get_str(qdict, "devname");
2735 if (usb_device_del(devname) < 0) {
2736 qemu_error("could not delete USB device '%s'\n", devname);
2740 /***********************************************************/
2741 /* PCMCIA/Cardbus */
2743 static struct pcmcia_socket_entry_s {
2744 PCMCIASocket *socket;
2745 struct pcmcia_socket_entry_s *next;
2746 } *pcmcia_sockets = 0;
2748 void pcmcia_socket_register(PCMCIASocket *socket)
2750 struct pcmcia_socket_entry_s *entry;
2752 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2753 entry->socket = socket;
2754 entry->next = pcmcia_sockets;
2755 pcmcia_sockets = entry;
2758 void pcmcia_socket_unregister(PCMCIASocket *socket)
2760 struct pcmcia_socket_entry_s *entry, **ptr;
2762 ptr = &pcmcia_sockets;
2763 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2764 if (entry->socket == socket) {
2765 *ptr = entry->next;
2766 qemu_free(entry);
2770 void pcmcia_info(Monitor *mon)
2772 struct pcmcia_socket_entry_s *iter;
2774 if (!pcmcia_sockets)
2775 monitor_printf(mon, "No PCMCIA sockets\n");
2777 for (iter = pcmcia_sockets; iter; iter = iter->next)
2778 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2779 iter->socket->attached ? iter->socket->card_string :
2780 "Empty");
2783 /***********************************************************/
2784 /* register display */
2786 struct DisplayAllocator default_allocator = {
2787 defaultallocator_create_displaysurface,
2788 defaultallocator_resize_displaysurface,
2789 defaultallocator_free_displaysurface
2792 void register_displaystate(DisplayState *ds)
2794 DisplayState **s;
2795 s = &display_state;
2796 while (*s != NULL)
2797 s = &(*s)->next;
2798 ds->next = NULL;
2799 *s = ds;
2802 DisplayState *get_displaystate(void)
2804 return display_state;
2807 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2809 if(ds->allocator == &default_allocator) ds->allocator = da;
2810 return ds->allocator;
2813 /* dumb display */
2815 static void dumb_display_init(void)
2817 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2818 ds->allocator = &default_allocator;
2819 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2820 register_displaystate(ds);
2823 /***********************************************************/
2824 /* I/O handling */
2826 typedef struct IOHandlerRecord {
2827 int fd;
2828 IOCanRWHandler *fd_read_poll;
2829 IOHandler *fd_read;
2830 IOHandler *fd_write;
2831 int deleted;
2832 void *opaque;
2833 /* temporary data */
2834 struct pollfd *ufd;
2835 struct IOHandlerRecord *next;
2836 } IOHandlerRecord;
2838 static IOHandlerRecord *first_io_handler;
2840 /* XXX: fd_read_poll should be suppressed, but an API change is
2841 necessary in the character devices to suppress fd_can_read(). */
2842 int qemu_set_fd_handler2(int fd,
2843 IOCanRWHandler *fd_read_poll,
2844 IOHandler *fd_read,
2845 IOHandler *fd_write,
2846 void *opaque)
2848 IOHandlerRecord **pioh, *ioh;
2850 if (!fd_read && !fd_write) {
2851 pioh = &first_io_handler;
2852 for(;;) {
2853 ioh = *pioh;
2854 if (ioh == NULL)
2855 break;
2856 if (ioh->fd == fd) {
2857 ioh->deleted = 1;
2858 break;
2860 pioh = &ioh->next;
2862 } else {
2863 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2864 if (ioh->fd == fd)
2865 goto found;
2867 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2868 ioh->next = first_io_handler;
2869 first_io_handler = ioh;
2870 found:
2871 ioh->fd = fd;
2872 ioh->fd_read_poll = fd_read_poll;
2873 ioh->fd_read = fd_read;
2874 ioh->fd_write = fd_write;
2875 ioh->opaque = opaque;
2876 ioh->deleted = 0;
2878 qemu_notify_event();
2879 return 0;
2882 int qemu_set_fd_handler(int fd,
2883 IOHandler *fd_read,
2884 IOHandler *fd_write,
2885 void *opaque)
2887 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2890 #ifdef _WIN32
2891 /***********************************************************/
2892 /* Polling handling */
2894 typedef struct PollingEntry {
2895 PollingFunc *func;
2896 void *opaque;
2897 struct PollingEntry *next;
2898 } PollingEntry;
2900 static PollingEntry *first_polling_entry;
2902 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2904 PollingEntry **ppe, *pe;
2905 pe = qemu_mallocz(sizeof(PollingEntry));
2906 pe->func = func;
2907 pe->opaque = opaque;
2908 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2909 *ppe = pe;
2910 return 0;
2913 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2915 PollingEntry **ppe, *pe;
2916 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2917 pe = *ppe;
2918 if (pe->func == func && pe->opaque == opaque) {
2919 *ppe = pe->next;
2920 qemu_free(pe);
2921 break;
2926 /***********************************************************/
2927 /* Wait objects support */
2928 typedef struct WaitObjects {
2929 int num;
2930 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2931 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2932 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2933 } WaitObjects;
2935 static WaitObjects wait_objects = {0};
2937 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2939 WaitObjects *w = &wait_objects;
2941 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2942 return -1;
2943 w->events[w->num] = handle;
2944 w->func[w->num] = func;
2945 w->opaque[w->num] = opaque;
2946 w->num++;
2947 return 0;
2950 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2952 int i, found;
2953 WaitObjects *w = &wait_objects;
2955 found = 0;
2956 for (i = 0; i < w->num; i++) {
2957 if (w->events[i] == handle)
2958 found = 1;
2959 if (found) {
2960 w->events[i] = w->events[i + 1];
2961 w->func[i] = w->func[i + 1];
2962 w->opaque[i] = w->opaque[i + 1];
2965 if (found)
2966 w->num--;
2968 #endif
2970 /***********************************************************/
2971 /* ram save/restore */
2973 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2974 #define RAM_SAVE_FLAG_COMPRESS 0x02
2975 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2976 #define RAM_SAVE_FLAG_PAGE 0x08
2977 #define RAM_SAVE_FLAG_EOS 0x10
2979 static int is_dup_page(uint8_t *page, uint8_t ch)
2981 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2982 uint32_t *array = (uint32_t *)page;
2983 int i;
2985 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2986 if (array[i] != val)
2987 return 0;
2990 return 1;
2993 static int ram_save_block(QEMUFile *f)
2995 static ram_addr_t current_addr = 0;
2996 ram_addr_t saved_addr = current_addr;
2997 ram_addr_t addr = 0;
2998 int found = 0;
3000 while (addr < last_ram_offset) {
3001 if (kvm_enabled() && current_addr == 0) {
3002 int r;
3003 r = kvm_update_dirty_pages_log();
3004 if (r) {
3005 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3006 qemu_file_set_error(f);
3007 return 0;
3010 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3011 uint8_t *p;
3013 cpu_physical_memory_reset_dirty(current_addr,
3014 current_addr + TARGET_PAGE_SIZE,
3015 MIGRATION_DIRTY_FLAG);
3017 p = qemu_get_ram_ptr(current_addr);
3019 if (is_dup_page(p, *p)) {
3020 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3021 qemu_put_byte(f, *p);
3022 } else {
3023 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3024 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3027 found = 1;
3028 break;
3030 addr += TARGET_PAGE_SIZE;
3031 current_addr = (saved_addr + addr) % last_ram_offset;
3034 return found;
3037 static uint64_t bytes_transferred;
3039 static ram_addr_t ram_save_remaining(void)
3041 ram_addr_t addr;
3042 ram_addr_t count = 0;
3044 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3045 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3046 count++;
3049 return count;
3052 uint64_t ram_bytes_remaining(void)
3054 return ram_save_remaining() * TARGET_PAGE_SIZE;
3057 uint64_t ram_bytes_transferred(void)
3059 return bytes_transferred;
3062 uint64_t ram_bytes_total(void)
3064 return last_ram_offset;
3067 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
3069 ram_addr_t addr;
3070 uint64_t bytes_transferred_last;
3071 double bwidth = 0;
3072 uint64_t expected_time = 0;
3074 if (stage < 0) {
3075 cpu_physical_memory_set_dirty_tracking(0);
3076 return 0;
3079 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3080 qemu_file_set_error(f);
3081 return 0;
3084 if (stage == 1) {
3085 bytes_transferred = 0;
3087 /* Make sure all dirty bits are set */
3088 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3089 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3090 cpu_physical_memory_set_dirty(addr);
3093 /* Enable dirty memory tracking */
3094 cpu_physical_memory_set_dirty_tracking(1);
3096 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3099 bytes_transferred_last = bytes_transferred;
3100 bwidth = get_clock();
3102 while (!qemu_file_rate_limit(f)) {
3103 int ret;
3105 ret = ram_save_block(f);
3106 bytes_transferred += ret * TARGET_PAGE_SIZE;
3107 if (ret == 0) /* no more blocks */
3108 break;
3111 bwidth = get_clock() - bwidth;
3112 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3114 /* if we haven't transferred anything this round, force expected_time to a
3115 * a very high value, but without crashing */
3116 if (bwidth == 0)
3117 bwidth = 0.000001;
3119 /* try transferring iterative blocks of memory */
3120 if (stage == 3) {
3121 /* flush all remaining blocks regardless of rate limiting */
3122 while (ram_save_block(f) != 0) {
3123 bytes_transferred += TARGET_PAGE_SIZE;
3125 cpu_physical_memory_set_dirty_tracking(0);
3128 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3130 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3132 return (stage == 2) && (expected_time <= migrate_max_downtime());
3135 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3137 ram_addr_t addr;
3138 int flags;
3140 if (version_id != 3)
3141 return -EINVAL;
3143 do {
3144 addr = qemu_get_be64(f);
3146 flags = addr & ~TARGET_PAGE_MASK;
3147 addr &= TARGET_PAGE_MASK;
3149 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3150 if (addr != last_ram_offset)
3151 return -EINVAL;
3154 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3155 uint8_t ch = qemu_get_byte(f);
3156 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3157 #ifndef _WIN32
3158 if (ch == 0 &&
3159 (!kvm_enabled() || kvm_has_sync_mmu())) {
3160 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3162 #endif
3163 } else if (flags & RAM_SAVE_FLAG_PAGE) {
3164 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3166 if (qemu_file_has_error(f)) {
3167 return -EIO;
3169 } while (!(flags & RAM_SAVE_FLAG_EOS));
3171 return 0;
3174 void qemu_service_io(void)
3176 qemu_notify_event();
3179 /***********************************************************/
3180 /* machine registration */
3182 static QEMUMachine *first_machine = NULL;
3183 QEMUMachine *current_machine = NULL;
3185 int qemu_register_machine(QEMUMachine *m)
3187 QEMUMachine **pm;
3188 pm = &first_machine;
3189 while (*pm != NULL)
3190 pm = &(*pm)->next;
3191 m->next = NULL;
3192 *pm = m;
3193 return 0;
3196 static QEMUMachine *find_machine(const char *name)
3198 QEMUMachine *m;
3200 for(m = first_machine; m != NULL; m = m->next) {
3201 if (!strcmp(m->name, name))
3202 return m;
3203 if (m->alias && !strcmp(m->alias, name))
3204 return m;
3206 return NULL;
3209 static QEMUMachine *find_default_machine(void)
3211 QEMUMachine *m;
3213 for(m = first_machine; m != NULL; m = m->next) {
3214 if (m->is_default) {
3215 return m;
3218 return NULL;
3221 /***********************************************************/
3222 /* main execution loop */
3224 static void gui_update(void *opaque)
3226 uint64_t interval = GUI_REFRESH_INTERVAL;
3227 DisplayState *ds = opaque;
3228 DisplayChangeListener *dcl = ds->listeners;
3230 dpy_refresh(ds);
3232 while (dcl != NULL) {
3233 if (dcl->gui_timer_interval &&
3234 dcl->gui_timer_interval < interval)
3235 interval = dcl->gui_timer_interval;
3236 dcl = dcl->next;
3238 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3241 static void nographic_update(void *opaque)
3243 uint64_t interval = GUI_REFRESH_INTERVAL;
3245 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3248 struct vm_change_state_entry {
3249 VMChangeStateHandler *cb;
3250 void *opaque;
3251 QLIST_ENTRY (vm_change_state_entry) entries;
3254 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3256 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3257 void *opaque)
3259 VMChangeStateEntry *e;
3261 e = qemu_mallocz(sizeof (*e));
3263 e->cb = cb;
3264 e->opaque = opaque;
3265 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3266 return e;
3269 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3271 QLIST_REMOVE (e, entries);
3272 qemu_free (e);
3275 static void vm_state_notify(int running, int reason)
3277 VMChangeStateEntry *e;
3279 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3280 e->cb(e->opaque, running, reason);
3284 static void resume_all_vcpus(void);
3285 static void pause_all_vcpus(void);
3287 void vm_start(void)
3289 if (!vm_running) {
3290 cpu_enable_ticks();
3291 vm_running = 1;
3292 vm_state_notify(1, 0);
3293 qemu_rearm_alarm_timer(alarm_timer);
3294 resume_all_vcpus();
3298 /* reset/shutdown handler */
3300 typedef struct QEMUResetEntry {
3301 QTAILQ_ENTRY(QEMUResetEntry) entry;
3302 QEMUResetHandler *func;
3303 void *opaque;
3304 } QEMUResetEntry;
3306 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3307 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3308 static int reset_requested;
3309 static int shutdown_requested;
3310 static int powerdown_requested;
3311 static int debug_requested;
3312 static int vmstop_requested;
3314 int qemu_no_shutdown(void)
3316 int r = no_shutdown;
3317 no_shutdown = 0;
3318 return r;
3321 int qemu_shutdown_requested(void)
3323 int r = shutdown_requested;
3324 shutdown_requested = 0;
3325 return r;
3328 int qemu_reset_requested(void)
3330 int r = reset_requested;
3331 reset_requested = 0;
3332 return r;
3335 int qemu_powerdown_requested(void)
3337 int r = powerdown_requested;
3338 powerdown_requested = 0;
3339 return r;
3342 static int qemu_debug_requested(void)
3344 int r = debug_requested;
3345 debug_requested = 0;
3346 return r;
3349 static int qemu_vmstop_requested(void)
3351 int r = vmstop_requested;
3352 vmstop_requested = 0;
3353 return r;
3356 static void do_vm_stop(int reason)
3358 if (vm_running) {
3359 cpu_disable_ticks();
3360 vm_running = 0;
3361 pause_all_vcpus();
3362 vm_state_notify(0, reason);
3366 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3368 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3370 re->func = func;
3371 re->opaque = opaque;
3372 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3375 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3377 QEMUResetEntry *re;
3379 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3380 if (re->func == func && re->opaque == opaque) {
3381 QTAILQ_REMOVE(&reset_handlers, re, entry);
3382 qemu_free(re);
3383 return;
3388 void qemu_system_reset(void)
3390 QEMUResetEntry *re, *nre;
3392 /* reset all devices */
3393 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3394 re->func(re->opaque);
3398 void qemu_system_reset_request(void)
3400 if (no_reboot) {
3401 shutdown_requested = 1;
3402 } else {
3403 reset_requested = 1;
3405 if (cpu_single_env) {
3406 cpu_single_env->stopped = 1;
3408 qemu_notify_event();
3411 void qemu_system_shutdown_request(void)
3413 shutdown_requested = 1;
3414 qemu_notify_event();
3417 void qemu_system_powerdown_request(void)
3419 powerdown_requested = 1;
3420 qemu_notify_event();
3423 #ifdef CONFIG_IOTHREAD
3424 static void qemu_system_vmstop_request(int reason)
3426 vmstop_requested = reason;
3427 qemu_notify_event();
3429 #endif
3431 #ifndef _WIN32
3432 static int io_thread_fd = -1;
3434 static void qemu_event_increment(void)
3436 static const char byte = 0;
3438 if (io_thread_fd == -1)
3439 return;
3441 write(io_thread_fd, &byte, sizeof(byte));
3444 static void qemu_event_read(void *opaque)
3446 int fd = (unsigned long)opaque;
3447 ssize_t len;
3449 /* Drain the notify pipe */
3450 do {
3451 char buffer[512];
3452 len = read(fd, buffer, sizeof(buffer));
3453 } while ((len == -1 && errno == EINTR) || len > 0);
3456 static int qemu_event_init(void)
3458 int err;
3459 int fds[2];
3461 err = qemu_pipe(fds);
3462 if (err == -1)
3463 return -errno;
3465 err = fcntl_setfl(fds[0], O_NONBLOCK);
3466 if (err < 0)
3467 goto fail;
3469 err = fcntl_setfl(fds[1], O_NONBLOCK);
3470 if (err < 0)
3471 goto fail;
3473 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3474 (void *)(unsigned long)fds[0]);
3476 io_thread_fd = fds[1];
3477 return 0;
3479 fail:
3480 close(fds[0]);
3481 close(fds[1]);
3482 return err;
3484 #else
3485 HANDLE qemu_event_handle;
3487 static void dummy_event_handler(void *opaque)
3491 static int qemu_event_init(void)
3493 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3494 if (!qemu_event_handle) {
3495 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3496 return -1;
3498 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3499 return 0;
3502 static void qemu_event_increment(void)
3504 if (!SetEvent(qemu_event_handle)) {
3505 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3506 GetLastError());
3507 exit (1);
3510 #endif
3512 static int cpu_can_run(CPUState *env)
3514 if (env->stop)
3515 return 0;
3516 if (env->stopped)
3517 return 0;
3518 return 1;
3521 #ifndef CONFIG_IOTHREAD
3522 static int qemu_init_main_loop(void)
3524 return qemu_event_init();
3527 void qemu_init_vcpu(void *_env)
3529 CPUState *env = _env;
3531 if (kvm_enabled())
3532 kvm_init_vcpu(env);
3533 env->nr_cores = smp_cores;
3534 env->nr_threads = smp_threads;
3535 return;
3538 int qemu_cpu_self(void *env)
3540 return 1;
3543 static void resume_all_vcpus(void)
3547 static void pause_all_vcpus(void)
3551 void qemu_cpu_kick(void *env)
3553 return;
3556 void qemu_notify_event(void)
3558 CPUState *env = cpu_single_env;
3560 if (kvm_enabled()) {
3561 qemu_kvm_notify_work();
3562 return;
3564 if (env) {
3565 cpu_exit(env);
3569 #if defined(KVM_UPSTREAM) || !defined(CONFIG_KVM)
3570 void qemu_mutex_lock_iothread(void) {}
3571 void qemu_mutex_unlock_iothread(void) {}
3572 #endif
3574 void vm_stop(int reason)
3576 do_vm_stop(reason);
3579 #else /* CONFIG_IOTHREAD */
3581 #include "qemu-thread.h"
3583 QemuMutex qemu_global_mutex;
3584 static QemuMutex qemu_fair_mutex;
3586 static QemuThread io_thread;
3588 static QemuThread *tcg_cpu_thread;
3589 static QemuCond *tcg_halt_cond;
3591 static int qemu_system_ready;
3592 /* cpu creation */
3593 static QemuCond qemu_cpu_cond;
3594 /* system init */
3595 static QemuCond qemu_system_cond;
3596 static QemuCond qemu_pause_cond;
3598 static void block_io_signals(void);
3599 static void unblock_io_signals(void);
3600 static int tcg_has_work(void);
3602 static int qemu_init_main_loop(void)
3604 int ret;
3606 ret = qemu_event_init();
3607 if (ret)
3608 return ret;
3610 qemu_cond_init(&qemu_pause_cond);
3611 qemu_mutex_init(&qemu_fair_mutex);
3612 qemu_mutex_init(&qemu_global_mutex);
3613 qemu_mutex_lock(&qemu_global_mutex);
3615 unblock_io_signals();
3616 qemu_thread_self(&io_thread);
3618 return 0;
3621 static void qemu_wait_io_event(CPUState *env)
3623 while (!tcg_has_work())
3624 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3626 qemu_mutex_unlock(&qemu_global_mutex);
3629 * Users of qemu_global_mutex can be starved, having no chance
3630 * to acquire it since this path will get to it first.
3631 * So use another lock to provide fairness.
3633 qemu_mutex_lock(&qemu_fair_mutex);
3634 qemu_mutex_unlock(&qemu_fair_mutex);
3636 qemu_mutex_lock(&qemu_global_mutex);
3637 if (env->stop) {
3638 env->stop = 0;
3639 env->stopped = 1;
3640 qemu_cond_signal(&qemu_pause_cond);
3644 static int qemu_cpu_exec(CPUState *env);
3646 static void *kvm_cpu_thread_fn(void *arg)
3648 CPUState *env = arg;
3650 block_io_signals();
3651 qemu_thread_self(env->thread);
3652 if (kvm_enabled())
3653 kvm_init_vcpu(env);
3655 /* signal CPU creation */
3656 qemu_mutex_lock(&qemu_global_mutex);
3657 env->created = 1;
3658 qemu_cond_signal(&qemu_cpu_cond);
3660 /* and wait for machine initialization */
3661 while (!qemu_system_ready)
3662 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3664 while (1) {
3665 if (cpu_can_run(env))
3666 qemu_cpu_exec(env);
3667 qemu_wait_io_event(env);
3670 return NULL;
3673 static void tcg_cpu_exec(void);
3675 static void *tcg_cpu_thread_fn(void *arg)
3677 CPUState *env = arg;
3679 block_io_signals();
3680 qemu_thread_self(env->thread);
3682 /* signal CPU creation */
3683 qemu_mutex_lock(&qemu_global_mutex);
3684 for (env = first_cpu; env != NULL; env = env->next_cpu)
3685 env->created = 1;
3686 qemu_cond_signal(&qemu_cpu_cond);
3688 /* and wait for machine initialization */
3689 while (!qemu_system_ready)
3690 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3692 while (1) {
3693 tcg_cpu_exec();
3694 qemu_wait_io_event(cur_cpu);
3697 return NULL;
3700 void qemu_cpu_kick(void *_env)
3702 CPUState *env = _env;
3703 qemu_cond_broadcast(env->halt_cond);
3704 if (kvm_enabled())
3705 qemu_thread_signal(env->thread, SIGUSR1);
3708 int qemu_cpu_self(void *_env)
3710 CPUState *env = _env;
3711 QemuThread this;
3713 qemu_thread_self(&this);
3715 return qemu_thread_equal(&this, env->thread);
3718 static void cpu_signal(int sig)
3720 if (cpu_single_env)
3721 cpu_exit(cpu_single_env);
3724 static void block_io_signals(void)
3726 sigset_t set;
3727 struct sigaction sigact;
3729 sigemptyset(&set);
3730 sigaddset(&set, SIGUSR2);
3731 sigaddset(&set, SIGIO);
3732 sigaddset(&set, SIGALRM);
3733 pthread_sigmask(SIG_BLOCK, &set, NULL);
3735 sigemptyset(&set);
3736 sigaddset(&set, SIGUSR1);
3737 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3739 memset(&sigact, 0, sizeof(sigact));
3740 sigact.sa_handler = cpu_signal;
3741 sigaction(SIGUSR1, &sigact, NULL);
3744 static void unblock_io_signals(void)
3746 sigset_t set;
3748 sigemptyset(&set);
3749 sigaddset(&set, SIGUSR2);
3750 sigaddset(&set, SIGIO);
3751 sigaddset(&set, SIGALRM);
3752 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3754 sigemptyset(&set);
3755 sigaddset(&set, SIGUSR1);
3756 pthread_sigmask(SIG_BLOCK, &set, NULL);
3759 static void qemu_signal_lock(unsigned int msecs)
3761 qemu_mutex_lock(&qemu_fair_mutex);
3763 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3764 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3765 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3766 break;
3768 qemu_mutex_unlock(&qemu_fair_mutex);
3771 void qemu_mutex_lock_iothread(void)
3773 if (kvm_enabled()) {
3774 qemu_mutex_lock(&qemu_fair_mutex);
3775 qemu_mutex_lock(&qemu_global_mutex);
3776 qemu_mutex_unlock(&qemu_fair_mutex);
3777 } else
3778 qemu_signal_lock(100);
3781 void qemu_mutex_unlock_iothread(void)
3783 qemu_mutex_unlock(&qemu_global_mutex);
3786 static int all_vcpus_paused(void)
3788 CPUState *penv = first_cpu;
3790 while (penv) {
3791 if (!penv->stopped)
3792 return 0;
3793 penv = (CPUState *)penv->next_cpu;
3796 return 1;
3799 static void pause_all_vcpus(void)
3801 CPUState *penv = first_cpu;
3803 while (penv) {
3804 penv->stop = 1;
3805 qemu_thread_signal(penv->thread, SIGUSR1);
3806 qemu_cpu_kick(penv);
3807 penv = (CPUState *)penv->next_cpu;
3810 while (!all_vcpus_paused()) {
3811 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3812 penv = first_cpu;
3813 while (penv) {
3814 qemu_thread_signal(penv->thread, SIGUSR1);
3815 penv = (CPUState *)penv->next_cpu;
3820 static void resume_all_vcpus(void)
3822 CPUState *penv = first_cpu;
3824 while (penv) {
3825 penv->stop = 0;
3826 penv->stopped = 0;
3827 qemu_thread_signal(penv->thread, SIGUSR1);
3828 qemu_cpu_kick(penv);
3829 penv = (CPUState *)penv->next_cpu;
3833 static void tcg_init_vcpu(void *_env)
3835 CPUState *env = _env;
3836 /* share a single thread for all cpus with TCG */
3837 if (!tcg_cpu_thread) {
3838 env->thread = qemu_mallocz(sizeof(QemuThread));
3839 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3840 qemu_cond_init(env->halt_cond);
3841 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3842 while (env->created == 0)
3843 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3844 tcg_cpu_thread = env->thread;
3845 tcg_halt_cond = env->halt_cond;
3846 } else {
3847 env->thread = tcg_cpu_thread;
3848 env->halt_cond = tcg_halt_cond;
3852 static void kvm_start_vcpu(CPUState *env)
3854 env->thread = qemu_mallocz(sizeof(QemuThread));
3855 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3856 qemu_cond_init(env->halt_cond);
3857 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3858 while (env->created == 0)
3859 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3862 void qemu_init_vcpu(void *_env)
3864 CPUState *env = _env;
3866 if (kvm_enabled())
3867 kvm_start_vcpu(env);
3868 else
3869 tcg_init_vcpu(env);
3870 env->nr_cores = smp_cores;
3871 env->nr_threads = smp_threads;
3874 void qemu_notify_event(void)
3876 qemu_event_increment();
3879 void vm_stop(int reason)
3881 QemuThread me;
3882 qemu_thread_self(&me);
3884 if (!qemu_thread_equal(&me, &io_thread)) {
3885 qemu_system_vmstop_request(reason);
3887 * FIXME: should not return to device code in case
3888 * vm_stop() has been requested.
3890 if (cpu_single_env) {
3891 cpu_exit(cpu_single_env);
3892 cpu_single_env->stop = 1;
3894 return;
3896 do_vm_stop(reason);
3899 #endif
3902 #ifdef _WIN32
3903 static void host_main_loop_wait(int *timeout)
3905 int ret, ret2, i;
3906 PollingEntry *pe;
3909 /* XXX: need to suppress polling by better using win32 events */
3910 ret = 0;
3911 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3912 ret |= pe->func(pe->opaque);
3914 if (ret == 0) {
3915 int err;
3916 WaitObjects *w = &wait_objects;
3918 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3919 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3920 if (w->func[ret - WAIT_OBJECT_0])
3921 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3923 /* Check for additional signaled events */
3924 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3926 /* Check if event is signaled */
3927 ret2 = WaitForSingleObject(w->events[i], 0);
3928 if(ret2 == WAIT_OBJECT_0) {
3929 if (w->func[i])
3930 w->func[i](w->opaque[i]);
3931 } else if (ret2 == WAIT_TIMEOUT) {
3932 } else {
3933 err = GetLastError();
3934 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3937 } else if (ret == WAIT_TIMEOUT) {
3938 } else {
3939 err = GetLastError();
3940 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3944 *timeout = 0;
3946 #else
3947 static void host_main_loop_wait(int *timeout)
3950 #endif
3952 void main_loop_wait(int timeout)
3954 IOHandlerRecord *ioh;
3955 fd_set rfds, wfds, xfds;
3956 int ret, nfds;
3957 struct timeval tv;
3959 qemu_bh_update_timeout(&timeout);
3961 host_main_loop_wait(&timeout);
3963 /* poll any events */
3964 /* XXX: separate device handlers from system ones */
3965 nfds = -1;
3966 FD_ZERO(&rfds);
3967 FD_ZERO(&wfds);
3968 FD_ZERO(&xfds);
3969 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3970 if (ioh->deleted)
3971 continue;
3972 if (ioh->fd_read &&
3973 (!ioh->fd_read_poll ||
3974 ioh->fd_read_poll(ioh->opaque) != 0)) {
3975 FD_SET(ioh->fd, &rfds);
3976 if (ioh->fd > nfds)
3977 nfds = ioh->fd;
3979 if (ioh->fd_write) {
3980 FD_SET(ioh->fd, &wfds);
3981 if (ioh->fd > nfds)
3982 nfds = ioh->fd;
3986 tv.tv_sec = timeout / 1000;
3987 tv.tv_usec = (timeout % 1000) * 1000;
3989 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3991 qemu_mutex_unlock_iothread();
3992 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3993 qemu_mutex_lock_iothread();
3994 if (ret > 0) {
3995 IOHandlerRecord **pioh;
3997 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3998 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3999 ioh->fd_read(ioh->opaque);
4000 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4001 FD_CLR(ioh->fd, &rfds);
4003 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4004 ioh->fd_write(ioh->opaque);
4008 /* remove deleted IO handlers */
4009 pioh = &first_io_handler;
4010 while (*pioh) {
4011 ioh = *pioh;
4012 if (ioh->deleted) {
4013 *pioh = ioh->next;
4014 qemu_free(ioh);
4015 } else
4016 pioh = &ioh->next;
4020 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4022 /* rearm timer, if not periodic */
4023 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4024 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4025 qemu_rearm_alarm_timer(alarm_timer);
4028 /* vm time timers */
4029 if (vm_running) {
4030 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4031 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
4032 qemu_get_clock(vm_clock));
4035 /* real time timers */
4036 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
4037 qemu_get_clock(rt_clock));
4039 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
4040 qemu_get_clock(host_clock));
4042 /* Check bottom-halves last in case any of the earlier events triggered
4043 them. */
4044 qemu_bh_poll();
4048 static int qemu_cpu_exec(CPUState *env)
4050 int ret;
4051 #ifdef CONFIG_PROFILER
4052 int64_t ti;
4053 #endif
4055 #ifdef CONFIG_PROFILER
4056 ti = profile_getclock();
4057 #endif
4058 if (use_icount) {
4059 int64_t count;
4060 int decr;
4061 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4062 env->icount_decr.u16.low = 0;
4063 env->icount_extra = 0;
4064 count = qemu_next_deadline();
4065 count = (count + (1 << icount_time_shift) - 1)
4066 >> icount_time_shift;
4067 qemu_icount += count;
4068 decr = (count > 0xffff) ? 0xffff : count;
4069 count -= decr;
4070 env->icount_decr.u16.low = decr;
4071 env->icount_extra = count;
4073 ret = cpu_exec(env);
4074 #ifdef CONFIG_PROFILER
4075 qemu_time += profile_getclock() - ti;
4076 #endif
4077 if (use_icount) {
4078 /* Fold pending instructions back into the
4079 instruction counter, and clear the interrupt flag. */
4080 qemu_icount -= (env->icount_decr.u16.low
4081 + env->icount_extra);
4082 env->icount_decr.u32 = 0;
4083 env->icount_extra = 0;
4085 return ret;
4088 static void tcg_cpu_exec(void)
4090 int ret = 0;
4092 if (next_cpu == NULL)
4093 next_cpu = first_cpu;
4094 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4095 CPUState *env = cur_cpu = next_cpu;
4097 if (!vm_running)
4098 break;
4099 if (timer_alarm_pending) {
4100 timer_alarm_pending = 0;
4101 break;
4103 if (cpu_can_run(env))
4104 ret = qemu_cpu_exec(env);
4105 if (ret == EXCP_DEBUG) {
4106 gdb_set_stop_cpu(env);
4107 debug_requested = 1;
4108 break;
4113 static int cpu_has_work(CPUState *env)
4115 if (env->stop)
4116 return 1;
4117 if (env->stopped)
4118 return 0;
4119 if (!env->halted)
4120 return 1;
4121 if (qemu_cpu_has_work(env))
4122 return 1;
4123 return 0;
4126 static int tcg_has_work(void)
4128 CPUState *env;
4130 for (env = first_cpu; env != NULL; env = env->next_cpu)
4131 if (cpu_has_work(env))
4132 return 1;
4133 return 0;
4136 static int qemu_calculate_timeout(void)
4138 #ifndef CONFIG_IOTHREAD
4139 int timeout;
4141 if (!vm_running)
4142 timeout = 5000;
4143 else if (tcg_has_work())
4144 timeout = 0;
4145 else if (!use_icount)
4146 timeout = 5000;
4147 else {
4148 /* XXX: use timeout computed from timers */
4149 int64_t add;
4150 int64_t delta;
4151 /* Advance virtual time to the next event. */
4152 if (use_icount == 1) {
4153 /* When not using an adaptive execution frequency
4154 we tend to get badly out of sync with real time,
4155 so just delay for a reasonable amount of time. */
4156 delta = 0;
4157 } else {
4158 delta = cpu_get_icount() - cpu_get_clock();
4160 if (delta > 0) {
4161 /* If virtual time is ahead of real time then just
4162 wait for IO. */
4163 timeout = (delta / 1000000) + 1;
4164 } else {
4165 /* Wait for either IO to occur or the next
4166 timer event. */
4167 add = qemu_next_deadline();
4168 /* We advance the timer before checking for IO.
4169 Limit the amount we advance so that early IO
4170 activity won't get the guest too far ahead. */
4171 if (add > 10000000)
4172 add = 10000000;
4173 delta += add;
4174 add = (add + (1 << icount_time_shift) - 1)
4175 >> icount_time_shift;
4176 qemu_icount += add;
4177 timeout = delta / 1000000;
4178 if (timeout < 0)
4179 timeout = 0;
4183 return timeout;
4184 #else /* CONFIG_IOTHREAD */
4185 return 1000;
4186 #endif
4189 static int vm_can_run(void)
4191 if (powerdown_requested)
4192 return 0;
4193 if (reset_requested)
4194 return 0;
4195 if (shutdown_requested)
4196 return 0;
4197 if (debug_requested)
4198 return 0;
4199 return 1;
4202 qemu_irq qemu_system_powerdown;
4204 static void main_loop(void)
4206 int r;
4208 if (kvm_enabled()) {
4209 kvm_main_loop();
4210 cpu_disable_ticks();
4211 return;
4214 #ifdef CONFIG_IOTHREAD
4215 qemu_system_ready = 1;
4216 qemu_cond_broadcast(&qemu_system_cond);
4217 #endif
4219 for (;;) {
4220 do {
4221 #ifdef CONFIG_PROFILER
4222 int64_t ti;
4223 #endif
4224 #ifndef CONFIG_IOTHREAD
4225 tcg_cpu_exec();
4226 #endif
4227 #ifdef CONFIG_PROFILER
4228 ti = profile_getclock();
4229 #endif
4230 main_loop_wait(qemu_calculate_timeout());
4231 #ifdef CONFIG_PROFILER
4232 dev_time += profile_getclock() - ti;
4233 #endif
4234 } while (vm_can_run());
4236 if (qemu_debug_requested()) {
4237 monitor_protocol_event(QEVENT_DEBUG, NULL);
4238 vm_stop(EXCP_DEBUG);
4240 if (qemu_shutdown_requested()) {
4241 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4242 if (no_shutdown) {
4243 vm_stop(0);
4244 no_shutdown = 0;
4245 } else
4246 break;
4248 if (qemu_reset_requested()) {
4249 monitor_protocol_event(QEVENT_RESET, NULL);
4250 pause_all_vcpus();
4251 qemu_system_reset();
4252 resume_all_vcpus();
4254 if (qemu_powerdown_requested()) {
4255 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4256 qemu_irq_raise(qemu_system_powerdown);
4258 if ((r = qemu_vmstop_requested())) {
4259 monitor_protocol_event(QEVENT_STOP, NULL);
4260 vm_stop(r);
4263 pause_all_vcpus();
4266 static void version(void)
4268 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4271 static void help(int exitcode)
4273 version();
4274 printf("usage: %s [options] [disk_image]\n"
4275 "\n"
4276 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4277 "\n"
4278 #define DEF(option, opt_arg, opt_enum, opt_help) \
4279 opt_help
4280 #define DEFHEADING(text) stringify(text) "\n"
4281 #include "qemu-options.h"
4282 #undef DEF
4283 #undef DEFHEADING
4284 #undef GEN_DOCS
4285 "\n"
4286 "During emulation, the following keys are useful:\n"
4287 "ctrl-alt-f toggle full screen\n"
4288 "ctrl-alt-n switch to virtual console 'n'\n"
4289 "ctrl-alt toggle mouse and keyboard grab\n"
4290 "\n"
4291 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4293 "qemu",
4294 DEFAULT_RAM_SIZE,
4295 #ifndef _WIN32
4296 DEFAULT_NETWORK_SCRIPT,
4297 DEFAULT_NETWORK_DOWN_SCRIPT,
4298 #endif
4299 DEFAULT_GDBSTUB_PORT,
4300 "/tmp/qemu.log");
4301 exit(exitcode);
4304 #define HAS_ARG 0x0001
4306 enum {
4307 #define DEF(option, opt_arg, opt_enum, opt_help) \
4308 opt_enum,
4309 #define DEFHEADING(text)
4310 #include "qemu-options.h"
4311 #undef DEF
4312 #undef DEFHEADING
4313 #undef GEN_DOCS
4316 typedef struct QEMUOption {
4317 const char *name;
4318 int flags;
4319 int index;
4320 } QEMUOption;
4322 static const QEMUOption qemu_options[] = {
4323 { "h", 0, QEMU_OPTION_h },
4324 #define DEF(option, opt_arg, opt_enum, opt_help) \
4325 { option, opt_arg, opt_enum },
4326 #define DEFHEADING(text)
4327 #include "qemu-options.h"
4328 #undef DEF
4329 #undef DEFHEADING
4330 #undef GEN_DOCS
4331 { NULL },
4334 #ifdef HAS_AUDIO
4335 struct soundhw soundhw[] = {
4336 #ifdef HAS_AUDIO_CHOICE
4337 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4339 "pcspk",
4340 "PC speaker",
4343 { .init_isa = pcspk_audio_init }
4345 #endif
4347 #ifdef CONFIG_SB16
4349 "sb16",
4350 "Creative Sound Blaster 16",
4353 { .init_isa = SB16_init }
4355 #endif
4357 #ifdef CONFIG_CS4231A
4359 "cs4231a",
4360 "CS4231A",
4363 { .init_isa = cs4231a_init }
4365 #endif
4367 #ifdef CONFIG_ADLIB
4369 "adlib",
4370 #ifdef HAS_YMF262
4371 "Yamaha YMF262 (OPL3)",
4372 #else
4373 "Yamaha YM3812 (OPL2)",
4374 #endif
4377 { .init_isa = Adlib_init }
4379 #endif
4381 #ifdef CONFIG_GUS
4383 "gus",
4384 "Gravis Ultrasound GF1",
4387 { .init_isa = GUS_init }
4389 #endif
4391 #ifdef CONFIG_AC97
4393 "ac97",
4394 "Intel 82801AA AC97 Audio",
4397 { .init_pci = ac97_init }
4399 #endif
4401 #ifdef CONFIG_ES1370
4403 "es1370",
4404 "ENSONIQ AudioPCI ES1370",
4407 { .init_pci = es1370_init }
4409 #endif
4411 #endif /* HAS_AUDIO_CHOICE */
4413 { NULL, NULL, 0, 0, { NULL } }
4416 static void select_soundhw (const char *optarg)
4418 struct soundhw *c;
4420 if (*optarg == '?') {
4421 show_valid_cards:
4423 printf ("Valid sound card names (comma separated):\n");
4424 for (c = soundhw; c->name; ++c) {
4425 printf ("%-11s %s\n", c->name, c->descr);
4427 printf ("\n-soundhw all will enable all of the above\n");
4428 exit (*optarg != '?');
4430 else {
4431 size_t l;
4432 const char *p;
4433 char *e;
4434 int bad_card = 0;
4436 if (!strcmp (optarg, "all")) {
4437 for (c = soundhw; c->name; ++c) {
4438 c->enabled = 1;
4440 return;
4443 p = optarg;
4444 while (*p) {
4445 e = strchr (p, ',');
4446 l = !e ? strlen (p) : (size_t) (e - p);
4448 for (c = soundhw; c->name; ++c) {
4449 if (!strncmp (c->name, p, l) && !c->name[l]) {
4450 c->enabled = 1;
4451 break;
4455 if (!c->name) {
4456 if (l > 80) {
4457 fprintf (stderr,
4458 "Unknown sound card name (too big to show)\n");
4460 else {
4461 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4462 (int) l, p);
4464 bad_card = 1;
4466 p += l + (e != NULL);
4469 if (bad_card)
4470 goto show_valid_cards;
4473 #endif
4475 static void select_vgahw (const char *p)
4477 const char *opts;
4479 default_vga = 0;
4480 vga_interface_type = VGA_NONE;
4481 if (strstart(p, "std", &opts)) {
4482 vga_interface_type = VGA_STD;
4483 } else if (strstart(p, "cirrus", &opts)) {
4484 vga_interface_type = VGA_CIRRUS;
4485 } else if (strstart(p, "vmware", &opts)) {
4486 vga_interface_type = VGA_VMWARE;
4487 } else if (strstart(p, "xenfb", &opts)) {
4488 vga_interface_type = VGA_XENFB;
4489 } else if (!strstart(p, "none", &opts)) {
4490 invalid_vga:
4491 fprintf(stderr, "Unknown vga type: %s\n", p);
4492 exit(1);
4494 while (*opts) {
4495 const char *nextopt;
4497 if (strstart(opts, ",retrace=", &nextopt)) {
4498 opts = nextopt;
4499 if (strstart(opts, "dumb", &nextopt))
4500 vga_retrace_method = VGA_RETRACE_DUMB;
4501 else if (strstart(opts, "precise", &nextopt))
4502 vga_retrace_method = VGA_RETRACE_PRECISE;
4503 else goto invalid_vga;
4504 } else goto invalid_vga;
4505 opts = nextopt;
4509 #ifdef TARGET_I386
4510 static int balloon_parse(const char *arg)
4512 QemuOpts *opts;
4514 if (strcmp(arg, "none") == 0) {
4515 return 0;
4518 if (!strncmp(arg, "virtio", 6)) {
4519 if (arg[6] == ',') {
4520 /* have params -> parse them */
4521 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4522 if (!opts)
4523 return -1;
4524 } else {
4525 /* create empty opts */
4526 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4528 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4529 return 0;
4532 return -1;
4534 #endif
4536 #ifdef _WIN32
4537 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4539 exit(STATUS_CONTROL_C_EXIT);
4540 return TRUE;
4542 #endif
4544 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4546 int ret;
4548 if(strlen(str) != 36)
4549 return -1;
4551 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4552 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4553 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4555 if(ret != 16)
4556 return -1;
4558 #ifdef TARGET_I386
4559 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4560 #endif
4562 return 0;
4565 #ifndef _WIN32
4567 static void termsig_handler(int signal)
4569 qemu_system_shutdown_request();
4572 static void sigchld_handler(int signal)
4574 waitpid(-1, NULL, WNOHANG);
4577 static void sighandler_setup(void)
4579 struct sigaction act;
4581 memset(&act, 0, sizeof(act));
4582 act.sa_handler = termsig_handler;
4583 sigaction(SIGINT, &act, NULL);
4584 sigaction(SIGHUP, &act, NULL);
4585 sigaction(SIGTERM, &act, NULL);
4587 act.sa_handler = sigchld_handler;
4588 act.sa_flags = SA_NOCLDSTOP;
4589 sigaction(SIGCHLD, &act, NULL);
4592 #endif
4594 #ifdef _WIN32
4595 /* Look for support files in the same directory as the executable. */
4596 static char *find_datadir(const char *argv0)
4598 char *p;
4599 char buf[MAX_PATH];
4600 DWORD len;
4602 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4603 if (len == 0) {
4604 return NULL;
4607 buf[len] = 0;
4608 p = buf + len - 1;
4609 while (p != buf && *p != '\\')
4610 p--;
4611 *p = 0;
4612 if (access(buf, R_OK) == 0) {
4613 return qemu_strdup(buf);
4615 return NULL;
4617 #else /* !_WIN32 */
4619 /* Find a likely location for support files using the location of the binary.
4620 For installed binaries this will be "$bindir/../share/qemu". When
4621 running from the build tree this will be "$bindir/../pc-bios". */
4622 #define SHARE_SUFFIX "/share/qemu"
4623 #define BUILD_SUFFIX "/pc-bios"
4624 static char *find_datadir(const char *argv0)
4626 char *dir;
4627 char *p = NULL;
4628 char *res;
4629 char buf[PATH_MAX];
4630 size_t max_len;
4632 #if defined(__linux__)
4634 int len;
4635 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4636 if (len > 0) {
4637 buf[len] = 0;
4638 p = buf;
4641 #elif defined(__FreeBSD__)
4643 int len;
4644 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4645 if (len > 0) {
4646 buf[len] = 0;
4647 p = buf;
4650 #endif
4651 /* If we don't have any way of figuring out the actual executable
4652 location then try argv[0]. */
4653 if (!p) {
4654 p = realpath(argv0, buf);
4655 if (!p) {
4656 return NULL;
4659 dir = dirname(p);
4660 dir = dirname(dir);
4662 max_len = strlen(dir) +
4663 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4664 res = qemu_mallocz(max_len);
4665 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4666 if (access(res, R_OK)) {
4667 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4668 if (access(res, R_OK)) {
4669 qemu_free(res);
4670 res = NULL;
4674 return res;
4676 #undef SHARE_SUFFIX
4677 #undef BUILD_SUFFIX
4678 #endif
4680 char *qemu_find_file(int type, const char *name)
4682 int len;
4683 const char *subdir;
4684 char *buf;
4686 /* If name contains path separators then try it as a straight path. */
4687 if ((strchr(name, '/') || strchr(name, '\\'))
4688 && access(name, R_OK) == 0) {
4689 return qemu_strdup(name);
4691 switch (type) {
4692 case QEMU_FILE_TYPE_BIOS:
4693 subdir = "";
4694 break;
4695 case QEMU_FILE_TYPE_KEYMAP:
4696 subdir = "keymaps/";
4697 break;
4698 default:
4699 abort();
4701 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4702 buf = qemu_mallocz(len);
4703 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4704 if (access(buf, R_OK)) {
4705 qemu_free(buf);
4706 return NULL;
4708 return buf;
4711 static int device_init_func(QemuOpts *opts, void *opaque)
4713 DeviceState *dev;
4715 dev = qdev_device_add(opts);
4716 if (!dev)
4717 return -1;
4718 return 0;
4721 static int chardev_init_func(QemuOpts *opts, void *opaque)
4723 CharDriverState *chr;
4725 chr = qemu_chr_open_opts(opts, NULL);
4726 if (!chr)
4727 return -1;
4728 return 0;
4731 static int mon_init_func(QemuOpts *opts, void *opaque)
4733 CharDriverState *chr;
4734 const char *chardev;
4735 const char *mode;
4736 int flags;
4738 mode = qemu_opt_get(opts, "mode");
4739 if (mode == NULL) {
4740 mode = "readline";
4742 if (strcmp(mode, "readline") == 0) {
4743 flags = MONITOR_USE_READLINE;
4744 } else if (strcmp(mode, "control") == 0) {
4745 flags = MONITOR_USE_CONTROL;
4746 } else {
4747 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4748 exit(1);
4751 if (qemu_opt_get_bool(opts, "default", 0))
4752 flags |= MONITOR_IS_DEFAULT;
4754 chardev = qemu_opt_get(opts, "chardev");
4755 chr = qemu_chr_find(chardev);
4756 if (chr == NULL) {
4757 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4758 exit(1);
4761 monitor_init(chr, flags);
4762 return 0;
4765 static void monitor_parse(const char *optarg, const char *mode)
4767 static int monitor_device_index = 0;
4768 QemuOpts *opts;
4769 const char *p;
4770 char label[32];
4771 int def = 0;
4773 if (strstart(optarg, "chardev:", &p)) {
4774 snprintf(label, sizeof(label), "%s", p);
4775 } else {
4776 if (monitor_device_index) {
4777 snprintf(label, sizeof(label), "monitor%d",
4778 monitor_device_index);
4779 } else {
4780 snprintf(label, sizeof(label), "monitor");
4781 def = 1;
4783 opts = qemu_chr_parse_compat(label, optarg);
4784 if (!opts) {
4785 fprintf(stderr, "parse error: %s\n", optarg);
4786 exit(1);
4790 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4791 if (!opts) {
4792 fprintf(stderr, "duplicate chardev: %s\n", label);
4793 exit(1);
4795 qemu_opt_set(opts, "mode", mode);
4796 qemu_opt_set(opts, "chardev", label);
4797 if (def)
4798 qemu_opt_set(opts, "default", "on");
4799 monitor_device_index++;
4802 struct device_config {
4803 enum {
4804 DEV_USB, /* -usbdevice */
4805 DEV_BT, /* -bt */
4806 DEV_SERIAL, /* -serial */
4807 DEV_PARALLEL, /* -parallel */
4808 DEV_VIRTCON, /* -virtioconsole */
4809 DEV_DEBUGCON, /* -debugcon */
4810 } type;
4811 const char *cmdline;
4812 QTAILQ_ENTRY(device_config) next;
4814 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4816 static void add_device_config(int type, const char *cmdline)
4818 struct device_config *conf;
4820 conf = qemu_mallocz(sizeof(*conf));
4821 conf->type = type;
4822 conf->cmdline = cmdline;
4823 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4826 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4828 struct device_config *conf;
4829 int rc;
4831 QTAILQ_FOREACH(conf, &device_configs, next) {
4832 if (conf->type != type)
4833 continue;
4834 rc = func(conf->cmdline);
4835 if (0 != rc)
4836 return rc;
4838 return 0;
4841 static int serial_parse(const char *devname)
4843 static int index = 0;
4844 char label[32];
4846 if (strcmp(devname, "none") == 0)
4847 return 0;
4848 if (index == MAX_SERIAL_PORTS) {
4849 fprintf(stderr, "qemu: too many serial ports\n");
4850 exit(1);
4852 snprintf(label, sizeof(label), "serial%d", index);
4853 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4854 if (!serial_hds[index]) {
4855 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4856 devname, strerror(errno));
4857 return -1;
4859 index++;
4860 return 0;
4863 static int parallel_parse(const char *devname)
4865 static int index = 0;
4866 char label[32];
4868 if (strcmp(devname, "none") == 0)
4869 return 0;
4870 if (index == MAX_PARALLEL_PORTS) {
4871 fprintf(stderr, "qemu: too many parallel ports\n");
4872 exit(1);
4874 snprintf(label, sizeof(label), "parallel%d", index);
4875 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4876 if (!parallel_hds[index]) {
4877 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4878 devname, strerror(errno));
4879 return -1;
4881 index++;
4882 return 0;
4885 static int virtcon_parse(const char *devname)
4887 static int index = 0;
4888 char label[32];
4890 if (strcmp(devname, "none") == 0)
4891 return 0;
4892 if (index == MAX_VIRTIO_CONSOLES) {
4893 fprintf(stderr, "qemu: too many virtio consoles\n");
4894 exit(1);
4896 snprintf(label, sizeof(label), "virtcon%d", index);
4897 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4898 if (!virtcon_hds[index]) {
4899 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4900 devname, strerror(errno));
4901 return -1;
4903 index++;
4904 return 0;
4907 static int debugcon_parse(const char *devname)
4909 QemuOpts *opts;
4911 if (!qemu_chr_open("debugcon", devname, NULL)) {
4912 exit(1);
4914 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4915 if (!opts) {
4916 fprintf(stderr, "qemu: already have a debugcon device\n");
4917 exit(1);
4919 qemu_opt_set(opts, "driver", "isa-debugcon");
4920 qemu_opt_set(opts, "chardev", "debugcon");
4921 return 0;
4924 int main(int argc, char **argv, char **envp)
4926 const char *gdbstub_dev = NULL;
4927 uint32_t boot_devices_bitmap = 0;
4928 int i;
4929 int snapshot, linux_boot, net_boot;
4930 const char *initrd_filename;
4931 const char *kernel_filename, *kernel_cmdline;
4932 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4933 DisplayState *ds;
4934 DisplayChangeListener *dcl;
4935 int cyls, heads, secs, translation;
4936 QemuOpts *hda_opts = NULL, *opts;
4937 int optind;
4938 const char *r, *optarg;
4939 const char *loadvm = NULL;
4940 QEMUMachine *machine;
4941 const char *cpu_model;
4942 #ifndef _WIN32
4943 int fds[2];
4944 #endif
4945 int tb_size;
4946 const char *pid_file = NULL;
4947 const char *incoming = NULL;
4948 #ifndef _WIN32
4949 int fd = 0;
4950 struct passwd *pwd = NULL;
4951 const char *chroot_dir = NULL;
4952 const char *run_as = NULL;
4953 #endif
4954 CPUState *env;
4955 int show_vnc_port = 0;
4957 init_clocks();
4959 qemu_errors_to_file(stderr);
4960 qemu_cache_utils_init(envp);
4962 QLIST_INIT (&vm_change_state_head);
4963 #ifndef _WIN32
4965 struct sigaction act;
4966 sigfillset(&act.sa_mask);
4967 act.sa_flags = 0;
4968 act.sa_handler = SIG_IGN;
4969 sigaction(SIGPIPE, &act, NULL);
4971 #else
4972 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4973 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4974 QEMU to run on a single CPU */
4976 HANDLE h;
4977 DWORD mask, smask;
4978 int i;
4979 h = GetCurrentProcess();
4980 if (GetProcessAffinityMask(h, &mask, &smask)) {
4981 for(i = 0; i < 32; i++) {
4982 if (mask & (1 << i))
4983 break;
4985 if (i != 32) {
4986 mask = 1 << i;
4987 SetProcessAffinityMask(h, mask);
4991 #endif
4993 module_call_init(MODULE_INIT_MACHINE);
4994 machine = find_default_machine();
4995 cpu_model = NULL;
4996 initrd_filename = NULL;
4997 ram_size = 0;
4998 snapshot = 0;
4999 kernel_filename = NULL;
5000 kernel_cmdline = "";
5001 cyls = heads = secs = 0;
5002 translation = BIOS_ATA_TRANSLATION_AUTO;
5004 for (i = 0; i < MAX_NODES; i++) {
5005 node_mem[i] = 0;
5006 node_cpumask[i] = 0;
5009 assigned_devices_index = 0;
5011 nb_numa_nodes = 0;
5012 nb_nics = 0;
5014 tb_size = 0;
5015 autostart= 1;
5017 optind = 1;
5018 for(;;) {
5019 if (optind >= argc)
5020 break;
5021 r = argv[optind];
5022 if (r[0] != '-') {
5023 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
5024 } else {
5025 const QEMUOption *popt;
5027 optind++;
5028 /* Treat --foo the same as -foo. */
5029 if (r[1] == '-')
5030 r++;
5031 popt = qemu_options;
5032 for(;;) {
5033 if (!popt->name) {
5034 fprintf(stderr, "%s: invalid option -- '%s'\n",
5035 argv[0], r);
5036 exit(1);
5038 if (!strcmp(popt->name, r + 1))
5039 break;
5040 popt++;
5042 if (popt->flags & HAS_ARG) {
5043 if (optind >= argc) {
5044 fprintf(stderr, "%s: option '%s' requires an argument\n",
5045 argv[0], r);
5046 exit(1);
5048 optarg = argv[optind++];
5049 } else {
5050 optarg = NULL;
5053 switch(popt->index) {
5054 case QEMU_OPTION_M:
5055 machine = find_machine(optarg);
5056 if (!machine) {
5057 QEMUMachine *m;
5058 printf("Supported machines are:\n");
5059 for(m = first_machine; m != NULL; m = m->next) {
5060 if (m->alias)
5061 printf("%-10s %s (alias of %s)\n",
5062 m->alias, m->desc, m->name);
5063 printf("%-10s %s%s\n",
5064 m->name, m->desc,
5065 m->is_default ? " (default)" : "");
5067 exit(*optarg != '?');
5069 break;
5070 case QEMU_OPTION_cpu:
5071 /* hw initialization will check this */
5072 if (*optarg == '?') {
5073 /* XXX: implement xxx_cpu_list for targets that still miss it */
5074 #if defined(cpu_list)
5075 cpu_list(stdout, &fprintf);
5076 #endif
5077 exit(0);
5078 } else {
5079 cpu_model = optarg;
5081 break;
5082 case QEMU_OPTION_initrd:
5083 initrd_filename = optarg;
5084 break;
5085 case QEMU_OPTION_hda:
5086 if (cyls == 0)
5087 hda_opts = drive_add(optarg, HD_ALIAS, 0);
5088 else
5089 hda_opts = drive_add(optarg, HD_ALIAS
5090 ",cyls=%d,heads=%d,secs=%d%s",
5091 0, cyls, heads, secs,
5092 translation == BIOS_ATA_TRANSLATION_LBA ?
5093 ",trans=lba" :
5094 translation == BIOS_ATA_TRANSLATION_NONE ?
5095 ",trans=none" : "");
5096 break;
5097 case QEMU_OPTION_hdb:
5098 case QEMU_OPTION_hdc:
5099 case QEMU_OPTION_hdd:
5100 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5101 break;
5102 case QEMU_OPTION_drive:
5103 drive_add(NULL, "%s", optarg);
5104 break;
5105 case QEMU_OPTION_set:
5106 if (qemu_set_option(optarg) != 0)
5107 exit(1);
5108 break;
5109 case QEMU_OPTION_global:
5110 if (qemu_global_option(optarg) != 0)
5111 exit(1);
5112 break;
5113 case QEMU_OPTION_mtdblock:
5114 drive_add(optarg, MTD_ALIAS);
5115 break;
5116 case QEMU_OPTION_sd:
5117 drive_add(optarg, SD_ALIAS);
5118 break;
5119 case QEMU_OPTION_pflash:
5120 drive_add(optarg, PFLASH_ALIAS);
5121 break;
5122 case QEMU_OPTION_snapshot:
5123 snapshot = 1;
5124 break;
5125 case QEMU_OPTION_hdachs:
5127 const char *p;
5128 p = optarg;
5129 cyls = strtol(p, (char **)&p, 0);
5130 if (cyls < 1 || cyls > 16383)
5131 goto chs_fail;
5132 if (*p != ',')
5133 goto chs_fail;
5134 p++;
5135 heads = strtol(p, (char **)&p, 0);
5136 if (heads < 1 || heads > 16)
5137 goto chs_fail;
5138 if (*p != ',')
5139 goto chs_fail;
5140 p++;
5141 secs = strtol(p, (char **)&p, 0);
5142 if (secs < 1 || secs > 63)
5143 goto chs_fail;
5144 if (*p == ',') {
5145 p++;
5146 if (!strcmp(p, "none"))
5147 translation = BIOS_ATA_TRANSLATION_NONE;
5148 else if (!strcmp(p, "lba"))
5149 translation = BIOS_ATA_TRANSLATION_LBA;
5150 else if (!strcmp(p, "auto"))
5151 translation = BIOS_ATA_TRANSLATION_AUTO;
5152 else
5153 goto chs_fail;
5154 } else if (*p != '\0') {
5155 chs_fail:
5156 fprintf(stderr, "qemu: invalid physical CHS format\n");
5157 exit(1);
5159 if (hda_opts != NULL) {
5160 char num[16];
5161 snprintf(num, sizeof(num), "%d", cyls);
5162 qemu_opt_set(hda_opts, "cyls", num);
5163 snprintf(num, sizeof(num), "%d", heads);
5164 qemu_opt_set(hda_opts, "heads", num);
5165 snprintf(num, sizeof(num), "%d", secs);
5166 qemu_opt_set(hda_opts, "secs", num);
5167 if (translation == BIOS_ATA_TRANSLATION_LBA)
5168 qemu_opt_set(hda_opts, "trans", "lba");
5169 if (translation == BIOS_ATA_TRANSLATION_NONE)
5170 qemu_opt_set(hda_opts, "trans", "none");
5173 break;
5174 case QEMU_OPTION_numa:
5175 if (nb_numa_nodes >= MAX_NODES) {
5176 fprintf(stderr, "qemu: too many NUMA nodes\n");
5177 exit(1);
5179 numa_add(optarg);
5180 break;
5181 case QEMU_OPTION_nographic:
5182 display_type = DT_NOGRAPHIC;
5183 break;
5184 #ifdef CONFIG_CURSES
5185 case QEMU_OPTION_curses:
5186 display_type = DT_CURSES;
5187 break;
5188 #endif
5189 case QEMU_OPTION_portrait:
5190 graphic_rotate = 1;
5191 break;
5192 case QEMU_OPTION_kernel:
5193 kernel_filename = optarg;
5194 break;
5195 case QEMU_OPTION_append:
5196 kernel_cmdline = optarg;
5197 break;
5198 case QEMU_OPTION_cdrom:
5199 drive_add(optarg, CDROM_ALIAS);
5200 break;
5201 case QEMU_OPTION_boot:
5203 static const char * const params[] = {
5204 "order", "once", "menu", NULL
5206 char buf[sizeof(boot_devices)];
5207 char *standard_boot_devices;
5208 int legacy = 0;
5210 if (!strchr(optarg, '=')) {
5211 legacy = 1;
5212 pstrcpy(buf, sizeof(buf), optarg);
5213 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5214 fprintf(stderr,
5215 "qemu: unknown boot parameter '%s' in '%s'\n",
5216 buf, optarg);
5217 exit(1);
5220 if (legacy ||
5221 get_param_value(buf, sizeof(buf), "order", optarg)) {
5222 boot_devices_bitmap = parse_bootdevices(buf);
5223 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5225 if (!legacy) {
5226 if (get_param_value(buf, sizeof(buf),
5227 "once", optarg)) {
5228 boot_devices_bitmap |= parse_bootdevices(buf);
5229 standard_boot_devices = qemu_strdup(boot_devices);
5230 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5231 qemu_register_reset(restore_boot_devices,
5232 standard_boot_devices);
5234 if (get_param_value(buf, sizeof(buf),
5235 "menu", optarg)) {
5236 if (!strcmp(buf, "on")) {
5237 boot_menu = 1;
5238 } else if (!strcmp(buf, "off")) {
5239 boot_menu = 0;
5240 } else {
5241 fprintf(stderr,
5242 "qemu: invalid option value '%s'\n",
5243 buf);
5244 exit(1);
5249 break;
5250 case QEMU_OPTION_fda:
5251 case QEMU_OPTION_fdb:
5252 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5253 break;
5254 #ifdef TARGET_I386
5255 case QEMU_OPTION_no_fd_bootchk:
5256 fd_bootchk = 0;
5257 break;
5258 #endif
5259 case QEMU_OPTION_netdev:
5260 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5261 exit(1);
5263 break;
5264 case QEMU_OPTION_net:
5265 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5266 exit(1);
5268 break;
5269 #ifdef CONFIG_SLIRP
5270 case QEMU_OPTION_tftp:
5271 legacy_tftp_prefix = optarg;
5272 break;
5273 case QEMU_OPTION_bootp:
5274 legacy_bootp_filename = optarg;
5275 break;
5276 #ifndef _WIN32
5277 case QEMU_OPTION_smb:
5278 if (net_slirp_smb(optarg) < 0)
5279 exit(1);
5280 break;
5281 #endif
5282 case QEMU_OPTION_redir:
5283 if (net_slirp_redir(optarg) < 0)
5284 exit(1);
5285 break;
5286 #endif
5287 case QEMU_OPTION_bt:
5288 add_device_config(DEV_BT, optarg);
5289 break;
5290 #ifdef HAS_AUDIO
5291 case QEMU_OPTION_audio_help:
5292 AUD_help ();
5293 exit (0);
5294 break;
5295 case QEMU_OPTION_soundhw:
5296 select_soundhw (optarg);
5297 break;
5298 #endif
5299 case QEMU_OPTION_h:
5300 help(0);
5301 break;
5302 case QEMU_OPTION_version:
5303 version();
5304 exit(0);
5305 break;
5306 case QEMU_OPTION_m: {
5307 uint64_t value;
5308 char *ptr;
5310 value = strtoul(optarg, &ptr, 10);
5311 switch (*ptr) {
5312 case 0: case 'M': case 'm':
5313 value <<= 20;
5314 break;
5315 case 'G': case 'g':
5316 value <<= 30;
5317 break;
5318 default:
5319 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5320 exit(1);
5323 /* On 32-bit hosts, QEMU is limited by virtual address space */
5324 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5325 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5326 exit(1);
5328 if (value != (uint64_t)(ram_addr_t)value) {
5329 fprintf(stderr, "qemu: ram size too large\n");
5330 exit(1);
5332 ram_size = value;
5333 break;
5335 case QEMU_OPTION_d:
5337 int mask;
5338 const CPULogItem *item;
5340 mask = cpu_str_to_log_mask(optarg);
5341 if (!mask) {
5342 printf("Log items (comma separated):\n");
5343 for(item = cpu_log_items; item->mask != 0; item++) {
5344 printf("%-10s %s\n", item->name, item->help);
5346 exit(1);
5348 cpu_set_log(mask);
5350 break;
5351 case QEMU_OPTION_s:
5352 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5353 break;
5354 case QEMU_OPTION_gdb:
5355 gdbstub_dev = optarg;
5356 break;
5357 case QEMU_OPTION_L:
5358 data_dir = optarg;
5359 break;
5360 case QEMU_OPTION_bios:
5361 bios_name = optarg;
5362 break;
5363 case QEMU_OPTION_singlestep:
5364 singlestep = 1;
5365 break;
5366 case QEMU_OPTION_S:
5367 autostart = 0;
5368 break;
5369 case QEMU_OPTION_k:
5370 keyboard_layout = optarg;
5371 break;
5372 case QEMU_OPTION_localtime:
5373 rtc_utc = 0;
5374 break;
5375 case QEMU_OPTION_vga:
5376 select_vgahw (optarg);
5377 break;
5378 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5379 case QEMU_OPTION_g:
5381 const char *p;
5382 int w, h, depth;
5383 p = optarg;
5384 w = strtol(p, (char **)&p, 10);
5385 if (w <= 0) {
5386 graphic_error:
5387 fprintf(stderr, "qemu: invalid resolution or depth\n");
5388 exit(1);
5390 if (*p != 'x')
5391 goto graphic_error;
5392 p++;
5393 h = strtol(p, (char **)&p, 10);
5394 if (h <= 0)
5395 goto graphic_error;
5396 if (*p == 'x') {
5397 p++;
5398 depth = strtol(p, (char **)&p, 10);
5399 if (depth != 8 && depth != 15 && depth != 16 &&
5400 depth != 24 && depth != 32)
5401 goto graphic_error;
5402 } else if (*p == '\0') {
5403 depth = graphic_depth;
5404 } else {
5405 goto graphic_error;
5408 graphic_width = w;
5409 graphic_height = h;
5410 graphic_depth = depth;
5412 break;
5413 #endif
5414 case QEMU_OPTION_echr:
5416 char *r;
5417 term_escape_char = strtol(optarg, &r, 0);
5418 if (r == optarg)
5419 printf("Bad argument to echr\n");
5420 break;
5422 case QEMU_OPTION_monitor:
5423 monitor_parse(optarg, "readline");
5424 default_monitor = 0;
5425 break;
5426 case QEMU_OPTION_qmp:
5427 monitor_parse(optarg, "control");
5428 default_monitor = 0;
5429 break;
5430 case QEMU_OPTION_mon:
5431 opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5432 if (!opts) {
5433 fprintf(stderr, "parse error: %s\n", optarg);
5434 exit(1);
5436 default_monitor = 0;
5437 break;
5438 case QEMU_OPTION_chardev:
5439 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5440 if (!opts) {
5441 fprintf(stderr, "parse error: %s\n", optarg);
5442 exit(1);
5444 break;
5445 case QEMU_OPTION_serial:
5446 add_device_config(DEV_SERIAL, optarg);
5447 default_serial = 0;
5448 break;
5449 case QEMU_OPTION_watchdog:
5450 if (watchdog) {
5451 fprintf(stderr,
5452 "qemu: only one watchdog option may be given\n");
5453 return 1;
5455 watchdog = optarg;
5456 break;
5457 case QEMU_OPTION_watchdog_action:
5458 if (select_watchdog_action(optarg) == -1) {
5459 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5460 exit(1);
5462 break;
5463 case QEMU_OPTION_virtiocon:
5464 add_device_config(DEV_VIRTCON, optarg);
5465 default_virtcon = 0;
5466 break;
5467 case QEMU_OPTION_parallel:
5468 add_device_config(DEV_PARALLEL, optarg);
5469 default_parallel = 0;
5470 break;
5471 case QEMU_OPTION_debugcon:
5472 add_device_config(DEV_DEBUGCON, optarg);
5473 break;
5474 case QEMU_OPTION_loadvm:
5475 loadvm = optarg;
5476 break;
5477 case QEMU_OPTION_full_screen:
5478 full_screen = 1;
5479 break;
5480 #ifdef CONFIG_SDL
5481 case QEMU_OPTION_no_frame:
5482 no_frame = 1;
5483 break;
5484 case QEMU_OPTION_alt_grab:
5485 alt_grab = 1;
5486 break;
5487 case QEMU_OPTION_ctrl_grab:
5488 ctrl_grab = 1;
5489 break;
5490 case QEMU_OPTION_no_quit:
5491 no_quit = 1;
5492 break;
5493 case QEMU_OPTION_sdl:
5494 display_type = DT_SDL;
5495 break;
5496 #endif
5497 case QEMU_OPTION_pidfile:
5498 pid_file = optarg;
5499 break;
5500 #ifdef TARGET_I386
5501 case QEMU_OPTION_win2k_hack:
5502 win2k_install_hack = 1;
5503 break;
5504 case QEMU_OPTION_rtc_td_hack:
5505 rtc_td_hack = 1;
5506 break;
5507 case QEMU_OPTION_acpitable:
5508 if(acpi_table_add(optarg) < 0) {
5509 fprintf(stderr, "Wrong acpi table provided\n");
5510 exit(1);
5512 break;
5513 case QEMU_OPTION_smbios:
5514 if(smbios_entry_add(optarg) < 0) {
5515 fprintf(stderr, "Wrong smbios provided\n");
5516 exit(1);
5518 break;
5519 #endif
5520 #ifdef CONFIG_KVM
5521 #ifdef KVM_UPSTREAM
5522 case QEMU_OPTION_enable_kvm:
5523 kvm_allowed = 1;
5524 #endif
5525 break;
5526 case QEMU_OPTION_no_kvm:
5527 kvm_allowed = 0;
5528 break;
5529 case QEMU_OPTION_no_kvm_irqchip: {
5530 kvm_irqchip = 0;
5531 kvm_pit = 0;
5532 break;
5534 case QEMU_OPTION_no_kvm_pit: {
5535 kvm_pit = 0;
5536 break;
5538 case QEMU_OPTION_no_kvm_pit_reinjection: {
5539 kvm_pit_reinject = 0;
5540 break;
5542 case QEMU_OPTION_enable_nesting: {
5543 kvm_nested = 1;
5544 break;
5546 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5547 case QEMU_OPTION_pcidevice:
5548 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5549 fprintf(stderr, "Too many assigned devices\n");
5550 exit(1);
5552 assigned_devices[assigned_devices_index] = optarg;
5553 assigned_devices_index++;
5554 break;
5555 #endif
5556 #endif
5557 case QEMU_OPTION_usb:
5558 usb_enabled = 1;
5559 break;
5560 case QEMU_OPTION_usbdevice:
5561 usb_enabled = 1;
5562 add_device_config(DEV_USB, optarg);
5563 break;
5564 case QEMU_OPTION_device:
5565 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5566 exit(1);
5568 break;
5569 case QEMU_OPTION_smp:
5570 smp_parse(optarg);
5571 if (smp_cpus < 1) {
5572 fprintf(stderr, "Invalid number of CPUs\n");
5573 exit(1);
5575 if (max_cpus < smp_cpus) {
5576 fprintf(stderr, "maxcpus must be equal to or greater than "
5577 "smp\n");
5578 exit(1);
5580 if (max_cpus > 255) {
5581 fprintf(stderr, "Unsupported number of maxcpus\n");
5582 exit(1);
5584 break;
5585 case QEMU_OPTION_vnc:
5586 display_type = DT_VNC;
5587 vnc_display = optarg;
5588 break;
5589 #ifdef TARGET_I386
5590 case QEMU_OPTION_no_acpi:
5591 acpi_enabled = 0;
5592 break;
5593 case QEMU_OPTION_no_hpet:
5594 no_hpet = 1;
5595 break;
5596 case QEMU_OPTION_balloon:
5597 if (balloon_parse(optarg) < 0) {
5598 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5599 exit(1);
5601 break;
5602 #endif
5603 case QEMU_OPTION_no_reboot:
5604 no_reboot = 1;
5605 break;
5606 case QEMU_OPTION_no_shutdown:
5607 no_shutdown = 1;
5608 break;
5609 case QEMU_OPTION_show_cursor:
5610 cursor_hide = 0;
5611 break;
5612 case QEMU_OPTION_uuid:
5613 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5614 fprintf(stderr, "Fail to parse UUID string."
5615 " Wrong format.\n");
5616 exit(1);
5618 break;
5619 #ifndef _WIN32
5620 case QEMU_OPTION_daemonize:
5621 daemonize = 1;
5622 break;
5623 #endif
5624 case QEMU_OPTION_option_rom:
5625 if (nb_option_roms >= MAX_OPTION_ROMS) {
5626 fprintf(stderr, "Too many option ROMs\n");
5627 exit(1);
5629 option_rom[nb_option_roms] = optarg;
5630 nb_option_roms++;
5631 break;
5632 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5633 case QEMU_OPTION_semihosting:
5634 semihosting_enabled = 1;
5635 break;
5636 #endif
5637 case QEMU_OPTION_tdf:
5638 time_drift_fix = 1;
5639 break;
5640 case QEMU_OPTION_kvm_shadow_memory:
5641 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5642 break;
5643 case QEMU_OPTION_mempath:
5644 mem_path = optarg;
5645 break;
5646 #ifdef MAP_POPULATE
5647 case QEMU_OPTION_mem_prealloc:
5648 mem_prealloc = !mem_prealloc;
5649 break;
5650 #endif
5651 case QEMU_OPTION_name:
5652 qemu_name = qemu_strdup(optarg);
5654 char *p = strchr(qemu_name, ',');
5655 if (p != NULL) {
5656 *p++ = 0;
5657 if (strncmp(p, "process=", 8)) {
5658 fprintf(stderr, "Unknown subargument %s to -name", p);
5659 exit(1);
5661 p += 8;
5662 set_proc_name(p);
5665 break;
5666 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5667 case QEMU_OPTION_prom_env:
5668 if (nb_prom_envs >= MAX_PROM_ENVS) {
5669 fprintf(stderr, "Too many prom variables\n");
5670 exit(1);
5672 prom_envs[nb_prom_envs] = optarg;
5673 nb_prom_envs++;
5674 break;
5675 #endif
5676 #ifdef TARGET_ARM
5677 case QEMU_OPTION_old_param:
5678 old_param = 1;
5679 break;
5680 #endif
5681 case QEMU_OPTION_clock:
5682 configure_alarms(optarg);
5683 break;
5684 case QEMU_OPTION_startdate:
5685 configure_rtc_date_offset(optarg, 1);
5686 break;
5687 case QEMU_OPTION_rtc:
5688 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5689 if (!opts) {
5690 fprintf(stderr, "parse error: %s\n", optarg);
5691 exit(1);
5693 configure_rtc(opts);
5694 break;
5695 case QEMU_OPTION_tb_size:
5696 tb_size = strtol(optarg, NULL, 0);
5697 if (tb_size < 0)
5698 tb_size = 0;
5699 break;
5700 case QEMU_OPTION_icount:
5701 use_icount = 1;
5702 if (strcmp(optarg, "auto") == 0) {
5703 icount_time_shift = -1;
5704 } else {
5705 icount_time_shift = strtol(optarg, NULL, 0);
5707 break;
5708 case QEMU_OPTION_incoming:
5709 incoming = optarg;
5710 break;
5711 case QEMU_OPTION_nodefaults:
5712 default_serial = 0;
5713 default_parallel = 0;
5714 default_virtcon = 0;
5715 default_monitor = 0;
5716 default_vga = 0;
5717 default_net = 0;
5718 default_floppy = 0;
5719 default_cdrom = 0;
5720 default_sdcard = 0;
5721 break;
5722 #ifndef _WIN32
5723 case QEMU_OPTION_chroot:
5724 chroot_dir = optarg;
5725 break;
5726 case QEMU_OPTION_runas:
5727 run_as = optarg;
5728 break;
5729 case QEMU_OPTION_nvram:
5730 nvram = optarg;
5731 break;
5732 #endif
5733 #ifdef CONFIG_XEN
5734 case QEMU_OPTION_xen_domid:
5735 xen_domid = atoi(optarg);
5736 break;
5737 case QEMU_OPTION_xen_create:
5738 xen_mode = XEN_CREATE;
5739 break;
5740 case QEMU_OPTION_xen_attach:
5741 xen_mode = XEN_ATTACH;
5742 break;
5743 #endif
5744 case QEMU_OPTION_readconfig:
5746 FILE *fp;
5747 fp = fopen(optarg, "r");
5748 if (fp == NULL) {
5749 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5750 exit(1);
5752 if (qemu_config_parse(fp) != 0) {
5753 exit(1);
5755 fclose(fp);
5756 break;
5758 case QEMU_OPTION_writeconfig:
5760 FILE *fp;
5761 if (strcmp(optarg, "-") == 0) {
5762 fp = stdout;
5763 } else {
5764 fp = fopen(optarg, "w");
5765 if (fp == NULL) {
5766 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5767 exit(1);
5770 qemu_config_write(fp);
5771 fclose(fp);
5772 break;
5778 /* If no data_dir is specified then try to find it relative to the
5779 executable path. */
5780 if (!data_dir) {
5781 data_dir = find_datadir(argv[0]);
5783 /* If all else fails use the install patch specified when building. */
5784 if (!data_dir) {
5785 data_dir = CONFIG_QEMU_SHAREDIR;
5789 * Default to max_cpus = smp_cpus, in case the user doesn't
5790 * specify a max_cpus value.
5792 if (!max_cpus)
5793 max_cpus = smp_cpus;
5795 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5796 if (smp_cpus > machine->max_cpus) {
5797 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5798 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5799 machine->max_cpus);
5800 exit(1);
5803 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5804 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5806 if (machine->no_serial) {
5807 default_serial = 0;
5809 if (machine->no_parallel) {
5810 default_parallel = 0;
5812 if (!machine->use_virtcon) {
5813 default_virtcon = 0;
5815 if (machine->no_vga) {
5816 default_vga = 0;
5818 if (machine->no_floppy) {
5819 default_floppy = 0;
5821 if (machine->no_cdrom) {
5822 default_cdrom = 0;
5824 if (machine->no_sdcard) {
5825 default_sdcard = 0;
5828 if (display_type == DT_NOGRAPHIC) {
5829 if (default_parallel)
5830 add_device_config(DEV_PARALLEL, "null");
5831 if (default_serial && default_monitor) {
5832 add_device_config(DEV_SERIAL, "mon:stdio");
5833 } else if (default_virtcon && default_monitor) {
5834 add_device_config(DEV_VIRTCON, "mon:stdio");
5835 } else {
5836 if (default_serial)
5837 add_device_config(DEV_SERIAL, "stdio");
5838 if (default_virtcon)
5839 add_device_config(DEV_VIRTCON, "stdio");
5840 if (default_monitor)
5841 monitor_parse("stdio", "readline");
5843 } else {
5844 if (default_serial)
5845 add_device_config(DEV_SERIAL, "vc:80Cx24C");
5846 if (default_parallel)
5847 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5848 if (default_monitor)
5849 monitor_parse("vc:80Cx24C", "readline");
5850 if (default_virtcon)
5851 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5853 if (default_vga)
5854 vga_interface_type = VGA_CIRRUS;
5856 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5857 exit(1);
5859 #ifndef _WIN32
5860 if (daemonize) {
5861 pid_t pid;
5863 if (pipe(fds) == -1)
5864 exit(1);
5866 pid = fork();
5867 if (pid > 0) {
5868 uint8_t status;
5869 ssize_t len;
5871 close(fds[1]);
5873 again:
5874 len = read(fds[0], &status, 1);
5875 if (len == -1 && (errno == EINTR))
5876 goto again;
5878 if (len != 1)
5879 exit(1);
5880 else if (status == 1) {
5881 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5882 exit(1);
5883 } else
5884 exit(0);
5885 } else if (pid < 0)
5886 exit(1);
5888 close(fds[0]);
5889 qemu_set_cloexec(fds[1]);
5891 setsid();
5893 pid = fork();
5894 if (pid > 0)
5895 exit(0);
5896 else if (pid < 0)
5897 exit(1);
5899 umask(027);
5901 signal(SIGTSTP, SIG_IGN);
5902 signal(SIGTTOU, SIG_IGN);
5903 signal(SIGTTIN, SIG_IGN);
5905 #endif
5907 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5908 #ifndef _WIN32
5909 if (daemonize) {
5910 uint8_t status = 1;
5911 write(fds[1], &status, 1);
5912 } else
5913 #endif
5914 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5915 exit(1);
5918 if (kvm_enabled()) {
5919 int ret;
5921 ret = kvm_init(smp_cpus);
5922 if (ret < 0) {
5923 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5924 fprintf(stderr, "failed to initialize KVM\n");
5925 exit(1);
5926 #endif
5927 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5928 kvm_allowed = 0;
5932 if (qemu_init_main_loop()) {
5933 fprintf(stderr, "qemu_init_main_loop failed\n");
5934 exit(1);
5936 linux_boot = (kernel_filename != NULL);
5938 if (!linux_boot && *kernel_cmdline != '\0') {
5939 fprintf(stderr, "-append only allowed with -kernel option\n");
5940 exit(1);
5943 if (!linux_boot && initrd_filename != NULL) {
5944 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5945 exit(1);
5948 #ifndef _WIN32
5949 /* Win32 doesn't support line-buffering and requires size >= 2 */
5950 setvbuf(stdout, NULL, _IOLBF, 0);
5951 #endif
5953 if (init_timer_alarm() < 0) {
5954 fprintf(stderr, "could not initialize alarm timer\n");
5955 exit(1);
5957 if (use_icount && icount_time_shift < 0) {
5958 use_icount = 2;
5959 /* 125MIPS seems a reasonable initial guess at the guest speed.
5960 It will be corrected fairly quickly anyway. */
5961 icount_time_shift = 3;
5962 init_icount_adjust();
5965 #ifdef _WIN32
5966 socket_init();
5967 #endif
5969 if (net_init_clients() < 0) {
5970 exit(1);
5973 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5974 net_set_boot_mask(net_boot);
5976 /* init the bluetooth world */
5977 if (foreach_device_config(DEV_BT, bt_parse))
5978 exit(1);
5980 /* init the memory */
5981 if (ram_size == 0)
5982 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5984 /* init the dynamic translator */
5985 cpu_exec_init_all(tb_size * 1024 * 1024);
5987 bdrv_init_with_whitelist();
5989 blk_mig_init();
5991 if (default_cdrom) {
5992 /* we always create the cdrom drive, even if no disk is there */
5993 drive_add(NULL, CDROM_ALIAS);
5996 if (default_floppy) {
5997 /* we always create at least one floppy */
5998 drive_add(NULL, FD_ALIAS, 0);
6001 if (default_sdcard) {
6002 /* we always create one sd slot, even if no card is in it */
6003 drive_add(NULL, SD_ALIAS);
6006 /* open the virtual block devices */
6007 if (snapshot)
6008 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
6009 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
6010 exit(1);
6012 vmstate_register(0, &vmstate_timers ,&timers_state);
6013 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
6014 ram_load, NULL);
6016 if (nb_numa_nodes > 0) {
6017 int i;
6019 if (nb_numa_nodes > smp_cpus) {
6020 nb_numa_nodes = smp_cpus;
6023 /* If no memory size if given for any node, assume the default case
6024 * and distribute the available memory equally across all nodes
6026 for (i = 0; i < nb_numa_nodes; i++) {
6027 if (node_mem[i] != 0)
6028 break;
6030 if (i == nb_numa_nodes) {
6031 uint64_t usedmem = 0;
6033 /* On Linux, the each node's border has to be 8MB aligned,
6034 * the final node gets the rest.
6036 for (i = 0; i < nb_numa_nodes - 1; i++) {
6037 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
6038 usedmem += node_mem[i];
6040 node_mem[i] = ram_size - usedmem;
6043 for (i = 0; i < nb_numa_nodes; i++) {
6044 if (node_cpumask[i] != 0)
6045 break;
6047 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6048 * must cope with this anyway, because there are BIOSes out there in
6049 * real machines which also use this scheme.
6051 if (i == nb_numa_nodes) {
6052 for (i = 0; i < smp_cpus; i++) {
6053 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6058 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
6059 exit(1);
6060 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
6061 exit(1);
6062 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
6063 exit(1);
6064 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
6065 exit(1);
6067 module_call_init(MODULE_INIT_DEVICE);
6069 if (watchdog) {
6070 i = select_watchdog(watchdog);
6071 if (i > 0)
6072 exit (i == 1 ? 1 : 0);
6075 if (machine->compat_props) {
6076 qdev_prop_register_global_list(machine->compat_props);
6078 qemu_add_globals();
6080 machine->init(ram_size, boot_devices,
6081 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6084 #ifndef _WIN32
6085 /* must be after terminal init, SDL library changes signal handlers */
6086 sighandler_setup();
6087 #endif
6089 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6090 for (i = 0; i < nb_numa_nodes; i++) {
6091 if (node_cpumask[i] & (1 << env->cpu_index)) {
6092 env->numa_node = i;
6097 current_machine = machine;
6099 /* init USB devices */
6100 if (usb_enabled) {
6101 if (foreach_device_config(DEV_USB, usb_parse) < 0)
6102 exit(1);
6105 /* init generic devices */
6106 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
6107 exit(1);
6109 if (!display_state)
6110 dumb_display_init();
6111 /* just use the first displaystate for the moment */
6112 ds = display_state;
6114 if (display_type == DT_DEFAULT) {
6115 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6116 display_type = DT_SDL;
6117 #else
6118 display_type = DT_VNC;
6119 vnc_display = "localhost:0,to=99";
6120 show_vnc_port = 1;
6121 #endif
6125 switch (display_type) {
6126 case DT_NOGRAPHIC:
6127 break;
6128 #if defined(CONFIG_CURSES)
6129 case DT_CURSES:
6130 curses_display_init(ds, full_screen);
6131 break;
6132 #endif
6133 #if defined(CONFIG_SDL)
6134 case DT_SDL:
6135 sdl_display_init(ds, full_screen, no_frame);
6136 break;
6137 #elif defined(CONFIG_COCOA)
6138 case DT_SDL:
6139 cocoa_display_init(ds, full_screen);
6140 break;
6141 #endif
6142 case DT_VNC:
6143 vnc_display_init(ds);
6144 if (vnc_display_open(ds, vnc_display) < 0)
6145 exit(1);
6147 if (show_vnc_port) {
6148 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6150 break;
6151 default:
6152 break;
6154 dpy_resize(ds);
6156 dcl = ds->listeners;
6157 while (dcl != NULL) {
6158 if (dcl->dpy_refresh != NULL) {
6159 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6160 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6162 dcl = dcl->next;
6165 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6166 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6167 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6170 text_consoles_set_display(display_state);
6172 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6173 exit(1);
6175 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6176 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6177 gdbstub_dev);
6178 exit(1);
6181 qdev_machine_creation_done();
6183 if (rom_load_all() != 0) {
6184 fprintf(stderr, "rom loading failed\n");
6185 exit(1);
6188 qemu_system_reset();
6189 if (loadvm) {
6190 if (load_vmstate(cur_mon, loadvm) < 0) {
6191 autostart = 0;
6195 if (incoming) {
6196 qemu_start_incoming_migration(incoming);
6197 } else if (autostart) {
6198 vm_start();
6201 #ifndef _WIN32
6202 if (daemonize) {
6203 uint8_t status = 0;
6204 ssize_t len;
6206 again1:
6207 len = write(fds[1], &status, 1);
6208 if (len == -1 && (errno == EINTR))
6209 goto again1;
6211 if (len != 1)
6212 exit(1);
6214 chdir("/");
6215 TFR(fd = qemu_open("/dev/null", O_RDWR));
6216 if (fd == -1)
6217 exit(1);
6220 if (run_as) {
6221 pwd = getpwnam(run_as);
6222 if (!pwd) {
6223 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6224 exit(1);
6228 if (chroot_dir) {
6229 if (chroot(chroot_dir) < 0) {
6230 fprintf(stderr, "chroot failed\n");
6231 exit(1);
6233 chdir("/");
6236 if (run_as) {
6237 if (setgid(pwd->pw_gid) < 0) {
6238 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6239 exit(1);
6241 if (setuid(pwd->pw_uid) < 0) {
6242 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6243 exit(1);
6245 if (setuid(0) != -1) {
6246 fprintf(stderr, "Dropping privileges failed\n");
6247 exit(1);
6251 if (daemonize) {
6252 dup2(fd, 0);
6253 dup2(fd, 1);
6254 dup2(fd, 2);
6256 close(fd);
6258 #endif
6260 main_loop();
6261 quit_timers();
6262 net_cleanup();
6264 return 0;