Merge commit 'f0138a63a41fe26bcef61d031ae53d872d12a992' into upstream-merge
[qemu/qemu-dev-zwu.git] / vl.c
blob31c696e7bdf38150df00b8f81d4d7858d66a0a7b
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 return usb_device_add(cmdline, 0);
2719 void do_usb_add(Monitor *mon, const QDict *qdict)
2721 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2724 void do_usb_del(Monitor *mon, const QDict *qdict)
2726 usb_device_del(qdict_get_str(qdict, "devname"));
2729 /***********************************************************/
2730 /* PCMCIA/Cardbus */
2732 static struct pcmcia_socket_entry_s {
2733 PCMCIASocket *socket;
2734 struct pcmcia_socket_entry_s *next;
2735 } *pcmcia_sockets = 0;
2737 void pcmcia_socket_register(PCMCIASocket *socket)
2739 struct pcmcia_socket_entry_s *entry;
2741 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2742 entry->socket = socket;
2743 entry->next = pcmcia_sockets;
2744 pcmcia_sockets = entry;
2747 void pcmcia_socket_unregister(PCMCIASocket *socket)
2749 struct pcmcia_socket_entry_s *entry, **ptr;
2751 ptr = &pcmcia_sockets;
2752 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2753 if (entry->socket == socket) {
2754 *ptr = entry->next;
2755 qemu_free(entry);
2759 void pcmcia_info(Monitor *mon)
2761 struct pcmcia_socket_entry_s *iter;
2763 if (!pcmcia_sockets)
2764 monitor_printf(mon, "No PCMCIA sockets\n");
2766 for (iter = pcmcia_sockets; iter; iter = iter->next)
2767 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2768 iter->socket->attached ? iter->socket->card_string :
2769 "Empty");
2772 /***********************************************************/
2773 /* register display */
2775 struct DisplayAllocator default_allocator = {
2776 defaultallocator_create_displaysurface,
2777 defaultallocator_resize_displaysurface,
2778 defaultallocator_free_displaysurface
2781 void register_displaystate(DisplayState *ds)
2783 DisplayState **s;
2784 s = &display_state;
2785 while (*s != NULL)
2786 s = &(*s)->next;
2787 ds->next = NULL;
2788 *s = ds;
2791 DisplayState *get_displaystate(void)
2793 return display_state;
2796 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2798 if(ds->allocator == &default_allocator) ds->allocator = da;
2799 return ds->allocator;
2802 /* dumb display */
2804 static void dumb_display_init(void)
2806 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2807 ds->allocator = &default_allocator;
2808 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2809 register_displaystate(ds);
2812 /***********************************************************/
2813 /* I/O handling */
2815 typedef struct IOHandlerRecord {
2816 int fd;
2817 IOCanRWHandler *fd_read_poll;
2818 IOHandler *fd_read;
2819 IOHandler *fd_write;
2820 int deleted;
2821 void *opaque;
2822 /* temporary data */
2823 struct pollfd *ufd;
2824 struct IOHandlerRecord *next;
2825 } IOHandlerRecord;
2827 static IOHandlerRecord *first_io_handler;
2829 /* XXX: fd_read_poll should be suppressed, but an API change is
2830 necessary in the character devices to suppress fd_can_read(). */
2831 int qemu_set_fd_handler2(int fd,
2832 IOCanRWHandler *fd_read_poll,
2833 IOHandler *fd_read,
2834 IOHandler *fd_write,
2835 void *opaque)
2837 IOHandlerRecord **pioh, *ioh;
2839 if (!fd_read && !fd_write) {
2840 pioh = &first_io_handler;
2841 for(;;) {
2842 ioh = *pioh;
2843 if (ioh == NULL)
2844 break;
2845 if (ioh->fd == fd) {
2846 ioh->deleted = 1;
2847 break;
2849 pioh = &ioh->next;
2851 } else {
2852 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2853 if (ioh->fd == fd)
2854 goto found;
2856 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2857 ioh->next = first_io_handler;
2858 first_io_handler = ioh;
2859 found:
2860 ioh->fd = fd;
2861 ioh->fd_read_poll = fd_read_poll;
2862 ioh->fd_read = fd_read;
2863 ioh->fd_write = fd_write;
2864 ioh->opaque = opaque;
2865 ioh->deleted = 0;
2867 qemu_notify_event();
2868 return 0;
2871 int qemu_set_fd_handler(int fd,
2872 IOHandler *fd_read,
2873 IOHandler *fd_write,
2874 void *opaque)
2876 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2879 #ifdef _WIN32
2880 /***********************************************************/
2881 /* Polling handling */
2883 typedef struct PollingEntry {
2884 PollingFunc *func;
2885 void *opaque;
2886 struct PollingEntry *next;
2887 } PollingEntry;
2889 static PollingEntry *first_polling_entry;
2891 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2893 PollingEntry **ppe, *pe;
2894 pe = qemu_mallocz(sizeof(PollingEntry));
2895 pe->func = func;
2896 pe->opaque = opaque;
2897 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2898 *ppe = pe;
2899 return 0;
2902 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2904 PollingEntry **ppe, *pe;
2905 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2906 pe = *ppe;
2907 if (pe->func == func && pe->opaque == opaque) {
2908 *ppe = pe->next;
2909 qemu_free(pe);
2910 break;
2915 /***********************************************************/
2916 /* Wait objects support */
2917 typedef struct WaitObjects {
2918 int num;
2919 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2920 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2921 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2922 } WaitObjects;
2924 static WaitObjects wait_objects = {0};
2926 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2928 WaitObjects *w = &wait_objects;
2930 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2931 return -1;
2932 w->events[w->num] = handle;
2933 w->func[w->num] = func;
2934 w->opaque[w->num] = opaque;
2935 w->num++;
2936 return 0;
2939 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2941 int i, found;
2942 WaitObjects *w = &wait_objects;
2944 found = 0;
2945 for (i = 0; i < w->num; i++) {
2946 if (w->events[i] == handle)
2947 found = 1;
2948 if (found) {
2949 w->events[i] = w->events[i + 1];
2950 w->func[i] = w->func[i + 1];
2951 w->opaque[i] = w->opaque[i + 1];
2954 if (found)
2955 w->num--;
2957 #endif
2959 /***********************************************************/
2960 /* ram save/restore */
2962 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2963 #define RAM_SAVE_FLAG_COMPRESS 0x02
2964 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2965 #define RAM_SAVE_FLAG_PAGE 0x08
2966 #define RAM_SAVE_FLAG_EOS 0x10
2968 static int is_dup_page(uint8_t *page, uint8_t ch)
2970 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2971 uint32_t *array = (uint32_t *)page;
2972 int i;
2974 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2975 if (array[i] != val)
2976 return 0;
2979 return 1;
2982 static int ram_save_block(QEMUFile *f)
2984 static ram_addr_t current_addr = 0;
2985 ram_addr_t saved_addr = current_addr;
2986 ram_addr_t addr = 0;
2987 int found = 0;
2989 while (addr < last_ram_offset) {
2990 if (kvm_enabled() && current_addr == 0) {
2991 int r;
2992 r = kvm_update_dirty_pages_log();
2993 if (r) {
2994 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
2995 qemu_file_set_error(f);
2996 return 0;
2999 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3000 uint8_t *p;
3002 cpu_physical_memory_reset_dirty(current_addr,
3003 current_addr + TARGET_PAGE_SIZE,
3004 MIGRATION_DIRTY_FLAG);
3006 p = qemu_get_ram_ptr(current_addr);
3008 if (is_dup_page(p, *p)) {
3009 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3010 qemu_put_byte(f, *p);
3011 } else {
3012 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3013 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3016 found = 1;
3017 break;
3019 addr += TARGET_PAGE_SIZE;
3020 current_addr = (saved_addr + addr) % last_ram_offset;
3023 return found;
3026 static uint64_t bytes_transferred;
3028 static ram_addr_t ram_save_remaining(void)
3030 ram_addr_t addr;
3031 ram_addr_t count = 0;
3033 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3034 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3035 count++;
3038 return count;
3041 uint64_t ram_bytes_remaining(void)
3043 return ram_save_remaining() * TARGET_PAGE_SIZE;
3046 uint64_t ram_bytes_transferred(void)
3048 return bytes_transferred;
3051 uint64_t ram_bytes_total(void)
3053 return last_ram_offset;
3056 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
3058 ram_addr_t addr;
3059 uint64_t bytes_transferred_last;
3060 double bwidth = 0;
3061 uint64_t expected_time = 0;
3063 if (stage < 0) {
3064 cpu_physical_memory_set_dirty_tracking(0);
3065 return 0;
3068 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3069 qemu_file_set_error(f);
3070 return 0;
3073 if (stage == 1) {
3074 bytes_transferred = 0;
3076 /* Make sure all dirty bits are set */
3077 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3078 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3079 cpu_physical_memory_set_dirty(addr);
3082 /* Enable dirty memory tracking */
3083 cpu_physical_memory_set_dirty_tracking(1);
3085 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3088 bytes_transferred_last = bytes_transferred;
3089 bwidth = get_clock();
3091 while (!qemu_file_rate_limit(f)) {
3092 int ret;
3094 ret = ram_save_block(f);
3095 bytes_transferred += ret * TARGET_PAGE_SIZE;
3096 if (ret == 0) /* no more blocks */
3097 break;
3100 bwidth = get_clock() - bwidth;
3101 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3103 /* if we haven't transferred anything this round, force expected_time to a
3104 * a very high value, but without crashing */
3105 if (bwidth == 0)
3106 bwidth = 0.000001;
3108 /* try transferring iterative blocks of memory */
3109 if (stage == 3) {
3110 /* flush all remaining blocks regardless of rate limiting */
3111 while (ram_save_block(f) != 0) {
3112 bytes_transferred += TARGET_PAGE_SIZE;
3114 cpu_physical_memory_set_dirty_tracking(0);
3117 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3119 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3121 return (stage == 2) && (expected_time <= migrate_max_downtime());
3124 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3126 ram_addr_t addr;
3127 int flags;
3129 if (version_id != 3)
3130 return -EINVAL;
3132 do {
3133 addr = qemu_get_be64(f);
3135 flags = addr & ~TARGET_PAGE_MASK;
3136 addr &= TARGET_PAGE_MASK;
3138 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3139 if (addr != last_ram_offset)
3140 return -EINVAL;
3143 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3144 uint8_t ch = qemu_get_byte(f);
3145 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3146 #ifndef _WIN32
3147 if (ch == 0 &&
3148 (!kvm_enabled() || kvm_has_sync_mmu())) {
3149 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3151 #endif
3152 } else if (flags & RAM_SAVE_FLAG_PAGE) {
3153 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3155 if (qemu_file_has_error(f)) {
3156 return -EIO;
3158 } while (!(flags & RAM_SAVE_FLAG_EOS));
3160 return 0;
3163 void qemu_service_io(void)
3165 qemu_notify_event();
3168 /***********************************************************/
3169 /* machine registration */
3171 static QEMUMachine *first_machine = NULL;
3172 QEMUMachine *current_machine = NULL;
3174 int qemu_register_machine(QEMUMachine *m)
3176 QEMUMachine **pm;
3177 pm = &first_machine;
3178 while (*pm != NULL)
3179 pm = &(*pm)->next;
3180 m->next = NULL;
3181 *pm = m;
3182 return 0;
3185 static QEMUMachine *find_machine(const char *name)
3187 QEMUMachine *m;
3189 for(m = first_machine; m != NULL; m = m->next) {
3190 if (!strcmp(m->name, name))
3191 return m;
3192 if (m->alias && !strcmp(m->alias, name))
3193 return m;
3195 return NULL;
3198 static QEMUMachine *find_default_machine(void)
3200 QEMUMachine *m;
3202 for(m = first_machine; m != NULL; m = m->next) {
3203 if (m->is_default) {
3204 return m;
3207 return NULL;
3210 /***********************************************************/
3211 /* main execution loop */
3213 static void gui_update(void *opaque)
3215 uint64_t interval = GUI_REFRESH_INTERVAL;
3216 DisplayState *ds = opaque;
3217 DisplayChangeListener *dcl = ds->listeners;
3219 dpy_refresh(ds);
3221 while (dcl != NULL) {
3222 if (dcl->gui_timer_interval &&
3223 dcl->gui_timer_interval < interval)
3224 interval = dcl->gui_timer_interval;
3225 dcl = dcl->next;
3227 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3230 static void nographic_update(void *opaque)
3232 uint64_t interval = GUI_REFRESH_INTERVAL;
3234 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3237 struct vm_change_state_entry {
3238 VMChangeStateHandler *cb;
3239 void *opaque;
3240 QLIST_ENTRY (vm_change_state_entry) entries;
3243 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3245 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3246 void *opaque)
3248 VMChangeStateEntry *e;
3250 e = qemu_mallocz(sizeof (*e));
3252 e->cb = cb;
3253 e->opaque = opaque;
3254 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3255 return e;
3258 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3260 QLIST_REMOVE (e, entries);
3261 qemu_free (e);
3264 static void vm_state_notify(int running, int reason)
3266 VMChangeStateEntry *e;
3268 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3269 e->cb(e->opaque, running, reason);
3273 static void resume_all_vcpus(void);
3274 static void pause_all_vcpus(void);
3276 void vm_start(void)
3278 if (!vm_running) {
3279 cpu_enable_ticks();
3280 vm_running = 1;
3281 vm_state_notify(1, 0);
3282 qemu_rearm_alarm_timer(alarm_timer);
3283 resume_all_vcpus();
3287 /* reset/shutdown handler */
3289 typedef struct QEMUResetEntry {
3290 QTAILQ_ENTRY(QEMUResetEntry) entry;
3291 QEMUResetHandler *func;
3292 void *opaque;
3293 } QEMUResetEntry;
3295 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3296 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3297 static int reset_requested;
3298 static int shutdown_requested;
3299 static int powerdown_requested;
3300 static int debug_requested;
3301 static int vmstop_requested;
3303 int qemu_no_shutdown(void)
3305 int r = no_shutdown;
3306 no_shutdown = 0;
3307 return r;
3310 int qemu_shutdown_requested(void)
3312 int r = shutdown_requested;
3313 shutdown_requested = 0;
3314 return r;
3317 int qemu_reset_requested(void)
3319 int r = reset_requested;
3320 reset_requested = 0;
3321 return r;
3324 int qemu_powerdown_requested(void)
3326 int r = powerdown_requested;
3327 powerdown_requested = 0;
3328 return r;
3331 static int qemu_debug_requested(void)
3333 int r = debug_requested;
3334 debug_requested = 0;
3335 return r;
3338 static int qemu_vmstop_requested(void)
3340 int r = vmstop_requested;
3341 vmstop_requested = 0;
3342 return r;
3345 static void do_vm_stop(int reason)
3347 if (vm_running) {
3348 cpu_disable_ticks();
3349 vm_running = 0;
3350 pause_all_vcpus();
3351 vm_state_notify(0, reason);
3355 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3357 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3359 re->func = func;
3360 re->opaque = opaque;
3361 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3364 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3366 QEMUResetEntry *re;
3368 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3369 if (re->func == func && re->opaque == opaque) {
3370 QTAILQ_REMOVE(&reset_handlers, re, entry);
3371 qemu_free(re);
3372 return;
3377 void qemu_system_reset(void)
3379 QEMUResetEntry *re, *nre;
3381 /* reset all devices */
3382 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3383 re->func(re->opaque);
3387 void qemu_system_reset_request(void)
3389 if (no_reboot) {
3390 shutdown_requested = 1;
3391 } else {
3392 reset_requested = 1;
3394 if (cpu_single_env) {
3395 cpu_single_env->stopped = 1;
3397 qemu_notify_event();
3400 void qemu_system_shutdown_request(void)
3402 shutdown_requested = 1;
3403 qemu_notify_event();
3406 void qemu_system_powerdown_request(void)
3408 powerdown_requested = 1;
3409 qemu_notify_event();
3412 #ifdef CONFIG_IOTHREAD
3413 static void qemu_system_vmstop_request(int reason)
3415 vmstop_requested = reason;
3416 qemu_notify_event();
3418 #endif
3420 #ifndef _WIN32
3421 static int io_thread_fd = -1;
3423 static void qemu_event_increment(void)
3425 static const char byte = 0;
3427 if (io_thread_fd == -1)
3428 return;
3430 write(io_thread_fd, &byte, sizeof(byte));
3433 static void qemu_event_read(void *opaque)
3435 int fd = (unsigned long)opaque;
3436 ssize_t len;
3438 /* Drain the notify pipe */
3439 do {
3440 char buffer[512];
3441 len = read(fd, buffer, sizeof(buffer));
3442 } while ((len == -1 && errno == EINTR) || len > 0);
3445 static int qemu_event_init(void)
3447 int err;
3448 int fds[2];
3450 err = qemu_pipe(fds);
3451 if (err == -1)
3452 return -errno;
3454 err = fcntl_setfl(fds[0], O_NONBLOCK);
3455 if (err < 0)
3456 goto fail;
3458 err = fcntl_setfl(fds[1], O_NONBLOCK);
3459 if (err < 0)
3460 goto fail;
3462 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3463 (void *)(unsigned long)fds[0]);
3465 io_thread_fd = fds[1];
3466 return 0;
3468 fail:
3469 close(fds[0]);
3470 close(fds[1]);
3471 return err;
3473 #else
3474 HANDLE qemu_event_handle;
3476 static void dummy_event_handler(void *opaque)
3480 static int qemu_event_init(void)
3482 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3483 if (!qemu_event_handle) {
3484 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3485 return -1;
3487 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3488 return 0;
3491 static void qemu_event_increment(void)
3493 if (!SetEvent(qemu_event_handle)) {
3494 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3495 GetLastError());
3496 exit (1);
3499 #endif
3501 static int cpu_can_run(CPUState *env)
3503 if (env->stop)
3504 return 0;
3505 if (env->stopped)
3506 return 0;
3507 return 1;
3510 #ifndef CONFIG_IOTHREAD
3511 static int qemu_init_main_loop(void)
3513 return qemu_event_init();
3516 void qemu_init_vcpu(void *_env)
3518 CPUState *env = _env;
3520 if (kvm_enabled())
3521 kvm_init_vcpu(env);
3522 env->nr_cores = smp_cores;
3523 env->nr_threads = smp_threads;
3524 return;
3527 int qemu_cpu_self(void *env)
3529 return 1;
3532 static void resume_all_vcpus(void)
3536 static void pause_all_vcpus(void)
3540 void qemu_cpu_kick(void *env)
3542 return;
3545 void qemu_notify_event(void)
3547 CPUState *env = cpu_single_env;
3549 if (kvm_enabled()) {
3550 qemu_kvm_notify_work();
3551 return;
3553 if (env) {
3554 cpu_exit(env);
3558 #if defined(KVM_UPSTREAM) || !defined(CONFIG_KVM)
3559 void qemu_mutex_lock_iothread(void) {}
3560 void qemu_mutex_unlock_iothread(void) {}
3561 #endif
3563 void vm_stop(int reason)
3565 do_vm_stop(reason);
3568 #else /* CONFIG_IOTHREAD */
3570 #include "qemu-thread.h"
3572 QemuMutex qemu_global_mutex;
3573 static QemuMutex qemu_fair_mutex;
3575 static QemuThread io_thread;
3577 static QemuThread *tcg_cpu_thread;
3578 static QemuCond *tcg_halt_cond;
3580 static int qemu_system_ready;
3581 /* cpu creation */
3582 static QemuCond qemu_cpu_cond;
3583 /* system init */
3584 static QemuCond qemu_system_cond;
3585 static QemuCond qemu_pause_cond;
3587 static void block_io_signals(void);
3588 static void unblock_io_signals(void);
3589 static int tcg_has_work(void);
3591 static int qemu_init_main_loop(void)
3593 int ret;
3595 ret = qemu_event_init();
3596 if (ret)
3597 return ret;
3599 qemu_cond_init(&qemu_pause_cond);
3600 qemu_mutex_init(&qemu_fair_mutex);
3601 qemu_mutex_init(&qemu_global_mutex);
3602 qemu_mutex_lock(&qemu_global_mutex);
3604 unblock_io_signals();
3605 qemu_thread_self(&io_thread);
3607 return 0;
3610 static void qemu_wait_io_event(CPUState *env)
3612 while (!tcg_has_work())
3613 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3615 qemu_mutex_unlock(&qemu_global_mutex);
3618 * Users of qemu_global_mutex can be starved, having no chance
3619 * to acquire it since this path will get to it first.
3620 * So use another lock to provide fairness.
3622 qemu_mutex_lock(&qemu_fair_mutex);
3623 qemu_mutex_unlock(&qemu_fair_mutex);
3625 qemu_mutex_lock(&qemu_global_mutex);
3626 if (env->stop) {
3627 env->stop = 0;
3628 env->stopped = 1;
3629 qemu_cond_signal(&qemu_pause_cond);
3633 static int qemu_cpu_exec(CPUState *env);
3635 static void *kvm_cpu_thread_fn(void *arg)
3637 CPUState *env = arg;
3639 block_io_signals();
3640 qemu_thread_self(env->thread);
3641 if (kvm_enabled())
3642 kvm_init_vcpu(env);
3644 /* signal CPU creation */
3645 qemu_mutex_lock(&qemu_global_mutex);
3646 env->created = 1;
3647 qemu_cond_signal(&qemu_cpu_cond);
3649 /* and wait for machine initialization */
3650 while (!qemu_system_ready)
3651 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3653 while (1) {
3654 if (cpu_can_run(env))
3655 qemu_cpu_exec(env);
3656 qemu_wait_io_event(env);
3659 return NULL;
3662 static void tcg_cpu_exec(void);
3664 static void *tcg_cpu_thread_fn(void *arg)
3666 CPUState *env = arg;
3668 block_io_signals();
3669 qemu_thread_self(env->thread);
3671 /* signal CPU creation */
3672 qemu_mutex_lock(&qemu_global_mutex);
3673 for (env = first_cpu; env != NULL; env = env->next_cpu)
3674 env->created = 1;
3675 qemu_cond_signal(&qemu_cpu_cond);
3677 /* and wait for machine initialization */
3678 while (!qemu_system_ready)
3679 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3681 while (1) {
3682 tcg_cpu_exec();
3683 qemu_wait_io_event(cur_cpu);
3686 return NULL;
3689 void qemu_cpu_kick(void *_env)
3691 CPUState *env = _env;
3692 qemu_cond_broadcast(env->halt_cond);
3693 if (kvm_enabled())
3694 qemu_thread_signal(env->thread, SIGUSR1);
3697 int qemu_cpu_self(void *_env)
3699 CPUState *env = _env;
3700 QemuThread this;
3702 qemu_thread_self(&this);
3704 return qemu_thread_equal(&this, env->thread);
3707 static void cpu_signal(int sig)
3709 if (cpu_single_env)
3710 cpu_exit(cpu_single_env);
3713 static void block_io_signals(void)
3715 sigset_t set;
3716 struct sigaction sigact;
3718 sigemptyset(&set);
3719 sigaddset(&set, SIGUSR2);
3720 sigaddset(&set, SIGIO);
3721 sigaddset(&set, SIGALRM);
3722 pthread_sigmask(SIG_BLOCK, &set, NULL);
3724 sigemptyset(&set);
3725 sigaddset(&set, SIGUSR1);
3726 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3728 memset(&sigact, 0, sizeof(sigact));
3729 sigact.sa_handler = cpu_signal;
3730 sigaction(SIGUSR1, &sigact, NULL);
3733 static void unblock_io_signals(void)
3735 sigset_t set;
3737 sigemptyset(&set);
3738 sigaddset(&set, SIGUSR2);
3739 sigaddset(&set, SIGIO);
3740 sigaddset(&set, SIGALRM);
3741 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3743 sigemptyset(&set);
3744 sigaddset(&set, SIGUSR1);
3745 pthread_sigmask(SIG_BLOCK, &set, NULL);
3748 static void qemu_signal_lock(unsigned int msecs)
3750 qemu_mutex_lock(&qemu_fair_mutex);
3752 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3753 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3754 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3755 break;
3757 qemu_mutex_unlock(&qemu_fair_mutex);
3760 void qemu_mutex_lock_iothread(void)
3762 if (kvm_enabled()) {
3763 qemu_mutex_lock(&qemu_fair_mutex);
3764 qemu_mutex_lock(&qemu_global_mutex);
3765 qemu_mutex_unlock(&qemu_fair_mutex);
3766 } else
3767 qemu_signal_lock(100);
3770 void qemu_mutex_unlock_iothread(void)
3772 qemu_mutex_unlock(&qemu_global_mutex);
3775 static int all_vcpus_paused(void)
3777 CPUState *penv = first_cpu;
3779 while (penv) {
3780 if (!penv->stopped)
3781 return 0;
3782 penv = (CPUState *)penv->next_cpu;
3785 return 1;
3788 static void pause_all_vcpus(void)
3790 CPUState *penv = first_cpu;
3792 while (penv) {
3793 penv->stop = 1;
3794 qemu_thread_signal(penv->thread, SIGUSR1);
3795 qemu_cpu_kick(penv);
3796 penv = (CPUState *)penv->next_cpu;
3799 while (!all_vcpus_paused()) {
3800 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3801 penv = first_cpu;
3802 while (penv) {
3803 qemu_thread_signal(penv->thread, SIGUSR1);
3804 penv = (CPUState *)penv->next_cpu;
3809 static void resume_all_vcpus(void)
3811 CPUState *penv = first_cpu;
3813 while (penv) {
3814 penv->stop = 0;
3815 penv->stopped = 0;
3816 qemu_thread_signal(penv->thread, SIGUSR1);
3817 qemu_cpu_kick(penv);
3818 penv = (CPUState *)penv->next_cpu;
3822 static void tcg_init_vcpu(void *_env)
3824 CPUState *env = _env;
3825 /* share a single thread for all cpus with TCG */
3826 if (!tcg_cpu_thread) {
3827 env->thread = qemu_mallocz(sizeof(QemuThread));
3828 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3829 qemu_cond_init(env->halt_cond);
3830 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3831 while (env->created == 0)
3832 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3833 tcg_cpu_thread = env->thread;
3834 tcg_halt_cond = env->halt_cond;
3835 } else {
3836 env->thread = tcg_cpu_thread;
3837 env->halt_cond = tcg_halt_cond;
3841 static void kvm_start_vcpu(CPUState *env)
3843 env->thread = qemu_mallocz(sizeof(QemuThread));
3844 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3845 qemu_cond_init(env->halt_cond);
3846 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3847 while (env->created == 0)
3848 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3851 void qemu_init_vcpu(void *_env)
3853 CPUState *env = _env;
3855 if (kvm_enabled())
3856 kvm_start_vcpu(env);
3857 else
3858 tcg_init_vcpu(env);
3859 env->nr_cores = smp_cores;
3860 env->nr_threads = smp_threads;
3863 void qemu_notify_event(void)
3865 qemu_event_increment();
3868 void vm_stop(int reason)
3870 QemuThread me;
3871 qemu_thread_self(&me);
3873 if (!qemu_thread_equal(&me, &io_thread)) {
3874 qemu_system_vmstop_request(reason);
3876 * FIXME: should not return to device code in case
3877 * vm_stop() has been requested.
3879 if (cpu_single_env) {
3880 cpu_exit(cpu_single_env);
3881 cpu_single_env->stop = 1;
3883 return;
3885 do_vm_stop(reason);
3888 #endif
3891 #ifdef _WIN32
3892 static void host_main_loop_wait(int *timeout)
3894 int ret, ret2, i;
3895 PollingEntry *pe;
3898 /* XXX: need to suppress polling by better using win32 events */
3899 ret = 0;
3900 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3901 ret |= pe->func(pe->opaque);
3903 if (ret == 0) {
3904 int err;
3905 WaitObjects *w = &wait_objects;
3907 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3908 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3909 if (w->func[ret - WAIT_OBJECT_0])
3910 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3912 /* Check for additional signaled events */
3913 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3915 /* Check if event is signaled */
3916 ret2 = WaitForSingleObject(w->events[i], 0);
3917 if(ret2 == WAIT_OBJECT_0) {
3918 if (w->func[i])
3919 w->func[i](w->opaque[i]);
3920 } else if (ret2 == WAIT_TIMEOUT) {
3921 } else {
3922 err = GetLastError();
3923 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3926 } else if (ret == WAIT_TIMEOUT) {
3927 } else {
3928 err = GetLastError();
3929 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3933 *timeout = 0;
3935 #else
3936 static void host_main_loop_wait(int *timeout)
3939 #endif
3941 void main_loop_wait(int timeout)
3943 IOHandlerRecord *ioh;
3944 fd_set rfds, wfds, xfds;
3945 int ret, nfds;
3946 struct timeval tv;
3948 qemu_bh_update_timeout(&timeout);
3950 host_main_loop_wait(&timeout);
3952 /* poll any events */
3953 /* XXX: separate device handlers from system ones */
3954 nfds = -1;
3955 FD_ZERO(&rfds);
3956 FD_ZERO(&wfds);
3957 FD_ZERO(&xfds);
3958 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3959 if (ioh->deleted)
3960 continue;
3961 if (ioh->fd_read &&
3962 (!ioh->fd_read_poll ||
3963 ioh->fd_read_poll(ioh->opaque) != 0)) {
3964 FD_SET(ioh->fd, &rfds);
3965 if (ioh->fd > nfds)
3966 nfds = ioh->fd;
3968 if (ioh->fd_write) {
3969 FD_SET(ioh->fd, &wfds);
3970 if (ioh->fd > nfds)
3971 nfds = ioh->fd;
3975 tv.tv_sec = timeout / 1000;
3976 tv.tv_usec = (timeout % 1000) * 1000;
3978 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3980 qemu_mutex_unlock_iothread();
3981 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3982 qemu_mutex_lock_iothread();
3983 if (ret > 0) {
3984 IOHandlerRecord **pioh;
3986 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3987 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3988 ioh->fd_read(ioh->opaque);
3989 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3990 FD_CLR(ioh->fd, &rfds);
3992 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3993 ioh->fd_write(ioh->opaque);
3997 /* remove deleted IO handlers */
3998 pioh = &first_io_handler;
3999 while (*pioh) {
4000 ioh = *pioh;
4001 if (ioh->deleted) {
4002 *pioh = ioh->next;
4003 qemu_free(ioh);
4004 } else
4005 pioh = &ioh->next;
4009 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4011 /* rearm timer, if not periodic */
4012 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4013 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4014 qemu_rearm_alarm_timer(alarm_timer);
4017 /* vm time timers */
4018 if (vm_running) {
4019 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4020 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
4021 qemu_get_clock(vm_clock));
4024 /* real time timers */
4025 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
4026 qemu_get_clock(rt_clock));
4028 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
4029 qemu_get_clock(host_clock));
4031 /* Check bottom-halves last in case any of the earlier events triggered
4032 them. */
4033 qemu_bh_poll();
4037 static int qemu_cpu_exec(CPUState *env)
4039 int ret;
4040 #ifdef CONFIG_PROFILER
4041 int64_t ti;
4042 #endif
4044 #ifdef CONFIG_PROFILER
4045 ti = profile_getclock();
4046 #endif
4047 if (use_icount) {
4048 int64_t count;
4049 int decr;
4050 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4051 env->icount_decr.u16.low = 0;
4052 env->icount_extra = 0;
4053 count = qemu_next_deadline();
4054 count = (count + (1 << icount_time_shift) - 1)
4055 >> icount_time_shift;
4056 qemu_icount += count;
4057 decr = (count > 0xffff) ? 0xffff : count;
4058 count -= decr;
4059 env->icount_decr.u16.low = decr;
4060 env->icount_extra = count;
4062 ret = cpu_exec(env);
4063 #ifdef CONFIG_PROFILER
4064 qemu_time += profile_getclock() - ti;
4065 #endif
4066 if (use_icount) {
4067 /* Fold pending instructions back into the
4068 instruction counter, and clear the interrupt flag. */
4069 qemu_icount -= (env->icount_decr.u16.low
4070 + env->icount_extra);
4071 env->icount_decr.u32 = 0;
4072 env->icount_extra = 0;
4074 return ret;
4077 static void tcg_cpu_exec(void)
4079 int ret = 0;
4081 if (next_cpu == NULL)
4082 next_cpu = first_cpu;
4083 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4084 CPUState *env = cur_cpu = next_cpu;
4086 if (!vm_running)
4087 break;
4088 if (timer_alarm_pending) {
4089 timer_alarm_pending = 0;
4090 break;
4092 if (cpu_can_run(env))
4093 ret = qemu_cpu_exec(env);
4094 if (ret == EXCP_DEBUG) {
4095 gdb_set_stop_cpu(env);
4096 debug_requested = 1;
4097 break;
4102 static int cpu_has_work(CPUState *env)
4104 if (env->stop)
4105 return 1;
4106 if (env->stopped)
4107 return 0;
4108 if (!env->halted)
4109 return 1;
4110 if (qemu_cpu_has_work(env))
4111 return 1;
4112 return 0;
4115 static int tcg_has_work(void)
4117 CPUState *env;
4119 for (env = first_cpu; env != NULL; env = env->next_cpu)
4120 if (cpu_has_work(env))
4121 return 1;
4122 return 0;
4125 static int qemu_calculate_timeout(void)
4127 #ifndef CONFIG_IOTHREAD
4128 int timeout;
4130 if (!vm_running)
4131 timeout = 5000;
4132 else if (tcg_has_work())
4133 timeout = 0;
4134 else if (!use_icount)
4135 timeout = 5000;
4136 else {
4137 /* XXX: use timeout computed from timers */
4138 int64_t add;
4139 int64_t delta;
4140 /* Advance virtual time to the next event. */
4141 if (use_icount == 1) {
4142 /* When not using an adaptive execution frequency
4143 we tend to get badly out of sync with real time,
4144 so just delay for a reasonable amount of time. */
4145 delta = 0;
4146 } else {
4147 delta = cpu_get_icount() - cpu_get_clock();
4149 if (delta > 0) {
4150 /* If virtual time is ahead of real time then just
4151 wait for IO. */
4152 timeout = (delta / 1000000) + 1;
4153 } else {
4154 /* Wait for either IO to occur or the next
4155 timer event. */
4156 add = qemu_next_deadline();
4157 /* We advance the timer before checking for IO.
4158 Limit the amount we advance so that early IO
4159 activity won't get the guest too far ahead. */
4160 if (add > 10000000)
4161 add = 10000000;
4162 delta += add;
4163 add = (add + (1 << icount_time_shift) - 1)
4164 >> icount_time_shift;
4165 qemu_icount += add;
4166 timeout = delta / 1000000;
4167 if (timeout < 0)
4168 timeout = 0;
4172 return timeout;
4173 #else /* CONFIG_IOTHREAD */
4174 return 1000;
4175 #endif
4178 static int vm_can_run(void)
4180 if (powerdown_requested)
4181 return 0;
4182 if (reset_requested)
4183 return 0;
4184 if (shutdown_requested)
4185 return 0;
4186 if (debug_requested)
4187 return 0;
4188 return 1;
4191 qemu_irq qemu_system_powerdown;
4193 static void main_loop(void)
4195 int r;
4197 if (kvm_enabled()) {
4198 kvm_main_loop();
4199 cpu_disable_ticks();
4200 return;
4203 #ifdef CONFIG_IOTHREAD
4204 qemu_system_ready = 1;
4205 qemu_cond_broadcast(&qemu_system_cond);
4206 #endif
4208 for (;;) {
4209 do {
4210 #ifdef CONFIG_PROFILER
4211 int64_t ti;
4212 #endif
4213 #ifndef CONFIG_IOTHREAD
4214 tcg_cpu_exec();
4215 #endif
4216 #ifdef CONFIG_PROFILER
4217 ti = profile_getclock();
4218 #endif
4219 main_loop_wait(qemu_calculate_timeout());
4220 #ifdef CONFIG_PROFILER
4221 dev_time += profile_getclock() - ti;
4222 #endif
4223 } while (vm_can_run());
4225 if (qemu_debug_requested()) {
4226 monitor_protocol_event(QEVENT_DEBUG, NULL);
4227 vm_stop(EXCP_DEBUG);
4229 if (qemu_shutdown_requested()) {
4230 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4231 if (no_shutdown) {
4232 vm_stop(0);
4233 no_shutdown = 0;
4234 } else
4235 break;
4237 if (qemu_reset_requested()) {
4238 monitor_protocol_event(QEVENT_RESET, NULL);
4239 pause_all_vcpus();
4240 qemu_system_reset();
4241 resume_all_vcpus();
4243 if (qemu_powerdown_requested()) {
4244 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4245 qemu_irq_raise(qemu_system_powerdown);
4247 if ((r = qemu_vmstop_requested())) {
4248 monitor_protocol_event(QEVENT_STOP, NULL);
4249 vm_stop(r);
4252 pause_all_vcpus();
4255 static void version(void)
4257 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4260 static void help(int exitcode)
4262 version();
4263 printf("usage: %s [options] [disk_image]\n"
4264 "\n"
4265 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4266 "\n"
4267 #define DEF(option, opt_arg, opt_enum, opt_help) \
4268 opt_help
4269 #define DEFHEADING(text) stringify(text) "\n"
4270 #include "qemu-options.h"
4271 #undef DEF
4272 #undef DEFHEADING
4273 #undef GEN_DOCS
4274 "\n"
4275 "During emulation, the following keys are useful:\n"
4276 "ctrl-alt-f toggle full screen\n"
4277 "ctrl-alt-n switch to virtual console 'n'\n"
4278 "ctrl-alt toggle mouse and keyboard grab\n"
4279 "\n"
4280 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4282 "qemu",
4283 DEFAULT_RAM_SIZE,
4284 #ifndef _WIN32
4285 DEFAULT_NETWORK_SCRIPT,
4286 DEFAULT_NETWORK_DOWN_SCRIPT,
4287 #endif
4288 DEFAULT_GDBSTUB_PORT,
4289 "/tmp/qemu.log");
4290 exit(exitcode);
4293 #define HAS_ARG 0x0001
4295 enum {
4296 #define DEF(option, opt_arg, opt_enum, opt_help) \
4297 opt_enum,
4298 #define DEFHEADING(text)
4299 #include "qemu-options.h"
4300 #undef DEF
4301 #undef DEFHEADING
4302 #undef GEN_DOCS
4305 typedef struct QEMUOption {
4306 const char *name;
4307 int flags;
4308 int index;
4309 } QEMUOption;
4311 static const QEMUOption qemu_options[] = {
4312 { "h", 0, QEMU_OPTION_h },
4313 #define DEF(option, opt_arg, opt_enum, opt_help) \
4314 { option, opt_arg, opt_enum },
4315 #define DEFHEADING(text)
4316 #include "qemu-options.h"
4317 #undef DEF
4318 #undef DEFHEADING
4319 #undef GEN_DOCS
4320 { NULL },
4323 #ifdef HAS_AUDIO
4324 struct soundhw soundhw[] = {
4325 #ifdef HAS_AUDIO_CHOICE
4326 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4328 "pcspk",
4329 "PC speaker",
4332 { .init_isa = pcspk_audio_init }
4334 #endif
4336 #ifdef CONFIG_SB16
4338 "sb16",
4339 "Creative Sound Blaster 16",
4342 { .init_isa = SB16_init }
4344 #endif
4346 #ifdef CONFIG_CS4231A
4348 "cs4231a",
4349 "CS4231A",
4352 { .init_isa = cs4231a_init }
4354 #endif
4356 #ifdef CONFIG_ADLIB
4358 "adlib",
4359 #ifdef HAS_YMF262
4360 "Yamaha YMF262 (OPL3)",
4361 #else
4362 "Yamaha YM3812 (OPL2)",
4363 #endif
4366 { .init_isa = Adlib_init }
4368 #endif
4370 #ifdef CONFIG_GUS
4372 "gus",
4373 "Gravis Ultrasound GF1",
4376 { .init_isa = GUS_init }
4378 #endif
4380 #ifdef CONFIG_AC97
4382 "ac97",
4383 "Intel 82801AA AC97 Audio",
4386 { .init_pci = ac97_init }
4388 #endif
4390 #ifdef CONFIG_ES1370
4392 "es1370",
4393 "ENSONIQ AudioPCI ES1370",
4396 { .init_pci = es1370_init }
4398 #endif
4400 #endif /* HAS_AUDIO_CHOICE */
4402 { NULL, NULL, 0, 0, { NULL } }
4405 static void select_soundhw (const char *optarg)
4407 struct soundhw *c;
4409 if (*optarg == '?') {
4410 show_valid_cards:
4412 printf ("Valid sound card names (comma separated):\n");
4413 for (c = soundhw; c->name; ++c) {
4414 printf ("%-11s %s\n", c->name, c->descr);
4416 printf ("\n-soundhw all will enable all of the above\n");
4417 exit (*optarg != '?');
4419 else {
4420 size_t l;
4421 const char *p;
4422 char *e;
4423 int bad_card = 0;
4425 if (!strcmp (optarg, "all")) {
4426 for (c = soundhw; c->name; ++c) {
4427 c->enabled = 1;
4429 return;
4432 p = optarg;
4433 while (*p) {
4434 e = strchr (p, ',');
4435 l = !e ? strlen (p) : (size_t) (e - p);
4437 for (c = soundhw; c->name; ++c) {
4438 if (!strncmp (c->name, p, l) && !c->name[l]) {
4439 c->enabled = 1;
4440 break;
4444 if (!c->name) {
4445 if (l > 80) {
4446 fprintf (stderr,
4447 "Unknown sound card name (too big to show)\n");
4449 else {
4450 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4451 (int) l, p);
4453 bad_card = 1;
4455 p += l + (e != NULL);
4458 if (bad_card)
4459 goto show_valid_cards;
4462 #endif
4464 static void select_vgahw (const char *p)
4466 const char *opts;
4468 default_vga = 0;
4469 vga_interface_type = VGA_NONE;
4470 if (strstart(p, "std", &opts)) {
4471 vga_interface_type = VGA_STD;
4472 } else if (strstart(p, "cirrus", &opts)) {
4473 vga_interface_type = VGA_CIRRUS;
4474 } else if (strstart(p, "vmware", &opts)) {
4475 vga_interface_type = VGA_VMWARE;
4476 } else if (strstart(p, "xenfb", &opts)) {
4477 vga_interface_type = VGA_XENFB;
4478 } else if (!strstart(p, "none", &opts)) {
4479 invalid_vga:
4480 fprintf(stderr, "Unknown vga type: %s\n", p);
4481 exit(1);
4483 while (*opts) {
4484 const char *nextopt;
4486 if (strstart(opts, ",retrace=", &nextopt)) {
4487 opts = nextopt;
4488 if (strstart(opts, "dumb", &nextopt))
4489 vga_retrace_method = VGA_RETRACE_DUMB;
4490 else if (strstart(opts, "precise", &nextopt))
4491 vga_retrace_method = VGA_RETRACE_PRECISE;
4492 else goto invalid_vga;
4493 } else goto invalid_vga;
4494 opts = nextopt;
4498 #ifdef TARGET_I386
4499 static int balloon_parse(const char *arg)
4501 QemuOpts *opts;
4503 if (strcmp(arg, "none") == 0) {
4504 return 0;
4507 if (!strncmp(arg, "virtio", 6)) {
4508 if (arg[6] == ',') {
4509 /* have params -> parse them */
4510 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4511 if (!opts)
4512 return -1;
4513 } else {
4514 /* create empty opts */
4515 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4517 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4518 return 0;
4521 return -1;
4523 #endif
4525 #ifdef _WIN32
4526 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4528 exit(STATUS_CONTROL_C_EXIT);
4529 return TRUE;
4531 #endif
4533 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4535 int ret;
4537 if(strlen(str) != 36)
4538 return -1;
4540 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4541 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4542 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4544 if(ret != 16)
4545 return -1;
4547 #ifdef TARGET_I386
4548 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4549 #endif
4551 return 0;
4554 #ifndef _WIN32
4556 static void termsig_handler(int signal)
4558 qemu_system_shutdown_request();
4561 static void sigchld_handler(int signal)
4563 waitpid(-1, NULL, WNOHANG);
4566 static void sighandler_setup(void)
4568 struct sigaction act;
4570 memset(&act, 0, sizeof(act));
4571 act.sa_handler = termsig_handler;
4572 sigaction(SIGINT, &act, NULL);
4573 sigaction(SIGHUP, &act, NULL);
4574 sigaction(SIGTERM, &act, NULL);
4576 act.sa_handler = sigchld_handler;
4577 act.sa_flags = SA_NOCLDSTOP;
4578 sigaction(SIGCHLD, &act, NULL);
4581 #endif
4583 #ifdef _WIN32
4584 /* Look for support files in the same directory as the executable. */
4585 static char *find_datadir(const char *argv0)
4587 char *p;
4588 char buf[MAX_PATH];
4589 DWORD len;
4591 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4592 if (len == 0) {
4593 return NULL;
4596 buf[len] = 0;
4597 p = buf + len - 1;
4598 while (p != buf && *p != '\\')
4599 p--;
4600 *p = 0;
4601 if (access(buf, R_OK) == 0) {
4602 return qemu_strdup(buf);
4604 return NULL;
4606 #else /* !_WIN32 */
4608 /* Find a likely location for support files using the location of the binary.
4609 For installed binaries this will be "$bindir/../share/qemu". When
4610 running from the build tree this will be "$bindir/../pc-bios". */
4611 #define SHARE_SUFFIX "/share/qemu"
4612 #define BUILD_SUFFIX "/pc-bios"
4613 static char *find_datadir(const char *argv0)
4615 char *dir;
4616 char *p = NULL;
4617 char *res;
4618 char buf[PATH_MAX];
4619 size_t max_len;
4621 #if defined(__linux__)
4623 int len;
4624 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4625 if (len > 0) {
4626 buf[len] = 0;
4627 p = buf;
4630 #elif defined(__FreeBSD__)
4632 int len;
4633 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4634 if (len > 0) {
4635 buf[len] = 0;
4636 p = buf;
4639 #endif
4640 /* If we don't have any way of figuring out the actual executable
4641 location then try argv[0]. */
4642 if (!p) {
4643 p = realpath(argv0, buf);
4644 if (!p) {
4645 return NULL;
4648 dir = dirname(p);
4649 dir = dirname(dir);
4651 max_len = strlen(dir) +
4652 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4653 res = qemu_mallocz(max_len);
4654 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4655 if (access(res, R_OK)) {
4656 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4657 if (access(res, R_OK)) {
4658 qemu_free(res);
4659 res = NULL;
4663 return res;
4665 #undef SHARE_SUFFIX
4666 #undef BUILD_SUFFIX
4667 #endif
4669 char *qemu_find_file(int type, const char *name)
4671 int len;
4672 const char *subdir;
4673 char *buf;
4675 /* If name contains path separators then try it as a straight path. */
4676 if ((strchr(name, '/') || strchr(name, '\\'))
4677 && access(name, R_OK) == 0) {
4678 return qemu_strdup(name);
4680 switch (type) {
4681 case QEMU_FILE_TYPE_BIOS:
4682 subdir = "";
4683 break;
4684 case QEMU_FILE_TYPE_KEYMAP:
4685 subdir = "keymaps/";
4686 break;
4687 default:
4688 abort();
4690 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4691 buf = qemu_mallocz(len);
4692 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4693 if (access(buf, R_OK)) {
4694 qemu_free(buf);
4695 return NULL;
4697 return buf;
4700 static int device_init_func(QemuOpts *opts, void *opaque)
4702 DeviceState *dev;
4704 dev = qdev_device_add(opts);
4705 if (!dev)
4706 return -1;
4707 return 0;
4710 static int chardev_init_func(QemuOpts *opts, void *opaque)
4712 CharDriverState *chr;
4714 chr = qemu_chr_open_opts(opts, NULL);
4715 if (!chr)
4716 return -1;
4717 return 0;
4720 static int mon_init_func(QemuOpts *opts, void *opaque)
4722 CharDriverState *chr;
4723 const char *chardev;
4724 const char *mode;
4725 int flags;
4727 mode = qemu_opt_get(opts, "mode");
4728 if (mode == NULL) {
4729 mode = "readline";
4731 if (strcmp(mode, "readline") == 0) {
4732 flags = MONITOR_USE_READLINE;
4733 } else if (strcmp(mode, "control") == 0) {
4734 flags = MONITOR_USE_CONTROL;
4735 } else {
4736 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4737 exit(1);
4740 if (qemu_opt_get_bool(opts, "default", 0))
4741 flags |= MONITOR_IS_DEFAULT;
4743 chardev = qemu_opt_get(opts, "chardev");
4744 chr = qemu_chr_find(chardev);
4745 if (chr == NULL) {
4746 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4747 exit(1);
4750 monitor_init(chr, flags);
4751 return 0;
4754 static void monitor_parse(const char *optarg, const char *mode)
4756 static int monitor_device_index = 0;
4757 QemuOpts *opts;
4758 const char *p;
4759 char label[32];
4760 int def = 0;
4762 if (strstart(optarg, "chardev:", &p)) {
4763 snprintf(label, sizeof(label), "%s", p);
4764 } else {
4765 if (monitor_device_index) {
4766 snprintf(label, sizeof(label), "monitor%d",
4767 monitor_device_index);
4768 } else {
4769 snprintf(label, sizeof(label), "monitor");
4770 def = 1;
4772 opts = qemu_chr_parse_compat(label, optarg);
4773 if (!opts) {
4774 fprintf(stderr, "parse error: %s\n", optarg);
4775 exit(1);
4779 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4780 if (!opts) {
4781 fprintf(stderr, "duplicate chardev: %s\n", label);
4782 exit(1);
4784 qemu_opt_set(opts, "mode", mode);
4785 qemu_opt_set(opts, "chardev", label);
4786 if (def)
4787 qemu_opt_set(opts, "default", "on");
4788 monitor_device_index++;
4791 struct device_config {
4792 enum {
4793 DEV_USB, /* -usbdevice */
4794 DEV_BT, /* -bt */
4795 DEV_SERIAL, /* -serial */
4796 DEV_PARALLEL, /* -parallel */
4797 DEV_VIRTCON, /* -virtioconsole */
4798 } type;
4799 const char *cmdline;
4800 QTAILQ_ENTRY(device_config) next;
4802 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4804 static void add_device_config(int type, const char *cmdline)
4806 struct device_config *conf;
4808 conf = qemu_mallocz(sizeof(*conf));
4809 conf->type = type;
4810 conf->cmdline = cmdline;
4811 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4814 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4816 struct device_config *conf;
4817 int rc;
4819 QTAILQ_FOREACH(conf, &device_configs, next) {
4820 if (conf->type != type)
4821 continue;
4822 rc = func(conf->cmdline);
4823 if (0 != rc)
4824 return rc;
4826 return 0;
4829 static int serial_parse(const char *devname)
4831 static int index = 0;
4832 char label[32];
4834 if (strcmp(devname, "none") == 0)
4835 return 0;
4836 if (index == MAX_SERIAL_PORTS) {
4837 fprintf(stderr, "qemu: too many serial ports\n");
4838 exit(1);
4840 snprintf(label, sizeof(label), "serial%d", index);
4841 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4842 if (!serial_hds[index]) {
4843 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4844 devname, strerror(errno));
4845 return -1;
4847 index++;
4848 return 0;
4851 static int parallel_parse(const char *devname)
4853 static int index = 0;
4854 char label[32];
4856 if (strcmp(devname, "none") == 0)
4857 return 0;
4858 if (index == MAX_PARALLEL_PORTS) {
4859 fprintf(stderr, "qemu: too many parallel ports\n");
4860 exit(1);
4862 snprintf(label, sizeof(label), "parallel%d", index);
4863 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4864 if (!parallel_hds[index]) {
4865 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4866 devname, strerror(errno));
4867 return -1;
4869 index++;
4870 return 0;
4873 static int virtcon_parse(const char *devname)
4875 static int index = 0;
4876 char label[32];
4878 if (strcmp(devname, "none") == 0)
4879 return 0;
4880 if (index == MAX_VIRTIO_CONSOLES) {
4881 fprintf(stderr, "qemu: too many virtio consoles\n");
4882 exit(1);
4884 snprintf(label, sizeof(label), "virtcon%d", index);
4885 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4886 if (!virtcon_hds[index]) {
4887 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4888 devname, strerror(errno));
4889 return -1;
4891 index++;
4892 return 0;
4895 int main(int argc, char **argv, char **envp)
4897 const char *gdbstub_dev = NULL;
4898 uint32_t boot_devices_bitmap = 0;
4899 int i;
4900 int snapshot, linux_boot, net_boot;
4901 const char *initrd_filename;
4902 const char *kernel_filename, *kernel_cmdline;
4903 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4904 DisplayState *ds;
4905 DisplayChangeListener *dcl;
4906 int cyls, heads, secs, translation;
4907 QemuOpts *hda_opts = NULL, *opts;
4908 int optind;
4909 const char *r, *optarg;
4910 const char *loadvm = NULL;
4911 QEMUMachine *machine;
4912 const char *cpu_model;
4913 #ifndef _WIN32
4914 int fds[2];
4915 #endif
4916 int tb_size;
4917 const char *pid_file = NULL;
4918 const char *incoming = NULL;
4919 #ifndef _WIN32
4920 int fd = 0;
4921 struct passwd *pwd = NULL;
4922 const char *chroot_dir = NULL;
4923 const char *run_as = NULL;
4924 #endif
4925 CPUState *env;
4926 int show_vnc_port = 0;
4928 init_clocks();
4930 qemu_errors_to_file(stderr);
4931 qemu_cache_utils_init(envp);
4933 QLIST_INIT (&vm_change_state_head);
4934 #ifndef _WIN32
4936 struct sigaction act;
4937 sigfillset(&act.sa_mask);
4938 act.sa_flags = 0;
4939 act.sa_handler = SIG_IGN;
4940 sigaction(SIGPIPE, &act, NULL);
4942 #else
4943 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4944 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4945 QEMU to run on a single CPU */
4947 HANDLE h;
4948 DWORD mask, smask;
4949 int i;
4950 h = GetCurrentProcess();
4951 if (GetProcessAffinityMask(h, &mask, &smask)) {
4952 for(i = 0; i < 32; i++) {
4953 if (mask & (1 << i))
4954 break;
4956 if (i != 32) {
4957 mask = 1 << i;
4958 SetProcessAffinityMask(h, mask);
4962 #endif
4964 module_call_init(MODULE_INIT_MACHINE);
4965 machine = find_default_machine();
4966 cpu_model = NULL;
4967 initrd_filename = NULL;
4968 ram_size = 0;
4969 snapshot = 0;
4970 kernel_filename = NULL;
4971 kernel_cmdline = "";
4972 cyls = heads = secs = 0;
4973 translation = BIOS_ATA_TRANSLATION_AUTO;
4975 for (i = 0; i < MAX_NODES; i++) {
4976 node_mem[i] = 0;
4977 node_cpumask[i] = 0;
4980 assigned_devices_index = 0;
4982 nb_numa_nodes = 0;
4983 nb_nics = 0;
4985 tb_size = 0;
4986 autostart= 1;
4988 optind = 1;
4989 for(;;) {
4990 if (optind >= argc)
4991 break;
4992 r = argv[optind];
4993 if (r[0] != '-') {
4994 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4995 } else {
4996 const QEMUOption *popt;
4998 optind++;
4999 /* Treat --foo the same as -foo. */
5000 if (r[1] == '-')
5001 r++;
5002 popt = qemu_options;
5003 for(;;) {
5004 if (!popt->name) {
5005 fprintf(stderr, "%s: invalid option -- '%s'\n",
5006 argv[0], r);
5007 exit(1);
5009 if (!strcmp(popt->name, r + 1))
5010 break;
5011 popt++;
5013 if (popt->flags & HAS_ARG) {
5014 if (optind >= argc) {
5015 fprintf(stderr, "%s: option '%s' requires an argument\n",
5016 argv[0], r);
5017 exit(1);
5019 optarg = argv[optind++];
5020 } else {
5021 optarg = NULL;
5024 switch(popt->index) {
5025 case QEMU_OPTION_M:
5026 machine = find_machine(optarg);
5027 if (!machine) {
5028 QEMUMachine *m;
5029 printf("Supported machines are:\n");
5030 for(m = first_machine; m != NULL; m = m->next) {
5031 if (m->alias)
5032 printf("%-10s %s (alias of %s)\n",
5033 m->alias, m->desc, m->name);
5034 printf("%-10s %s%s\n",
5035 m->name, m->desc,
5036 m->is_default ? " (default)" : "");
5038 exit(*optarg != '?');
5040 break;
5041 case QEMU_OPTION_cpu:
5042 /* hw initialization will check this */
5043 if (*optarg == '?') {
5044 /* XXX: implement xxx_cpu_list for targets that still miss it */
5045 #if defined(cpu_list)
5046 cpu_list(stdout, &fprintf);
5047 #endif
5048 exit(0);
5049 } else {
5050 cpu_model = optarg;
5052 break;
5053 case QEMU_OPTION_initrd:
5054 initrd_filename = optarg;
5055 break;
5056 case QEMU_OPTION_hda:
5057 if (cyls == 0)
5058 hda_opts = drive_add(optarg, HD_ALIAS, 0);
5059 else
5060 hda_opts = drive_add(optarg, HD_ALIAS
5061 ",cyls=%d,heads=%d,secs=%d%s",
5062 0, cyls, heads, secs,
5063 translation == BIOS_ATA_TRANSLATION_LBA ?
5064 ",trans=lba" :
5065 translation == BIOS_ATA_TRANSLATION_NONE ?
5066 ",trans=none" : "");
5067 break;
5068 case QEMU_OPTION_hdb:
5069 case QEMU_OPTION_hdc:
5070 case QEMU_OPTION_hdd:
5071 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5072 break;
5073 case QEMU_OPTION_drive:
5074 drive_add(NULL, "%s", optarg);
5075 break;
5076 case QEMU_OPTION_set:
5077 if (qemu_set_option(optarg) != 0)
5078 exit(1);
5079 break;
5080 case QEMU_OPTION_global:
5081 if (qemu_global_option(optarg) != 0)
5082 exit(1);
5083 break;
5084 case QEMU_OPTION_mtdblock:
5085 drive_add(optarg, MTD_ALIAS);
5086 break;
5087 case QEMU_OPTION_sd:
5088 drive_add(optarg, SD_ALIAS);
5089 break;
5090 case QEMU_OPTION_pflash:
5091 drive_add(optarg, PFLASH_ALIAS);
5092 break;
5093 case QEMU_OPTION_snapshot:
5094 snapshot = 1;
5095 break;
5096 case QEMU_OPTION_hdachs:
5098 const char *p;
5099 p = optarg;
5100 cyls = strtol(p, (char **)&p, 0);
5101 if (cyls < 1 || cyls > 16383)
5102 goto chs_fail;
5103 if (*p != ',')
5104 goto chs_fail;
5105 p++;
5106 heads = strtol(p, (char **)&p, 0);
5107 if (heads < 1 || heads > 16)
5108 goto chs_fail;
5109 if (*p != ',')
5110 goto chs_fail;
5111 p++;
5112 secs = strtol(p, (char **)&p, 0);
5113 if (secs < 1 || secs > 63)
5114 goto chs_fail;
5115 if (*p == ',') {
5116 p++;
5117 if (!strcmp(p, "none"))
5118 translation = BIOS_ATA_TRANSLATION_NONE;
5119 else if (!strcmp(p, "lba"))
5120 translation = BIOS_ATA_TRANSLATION_LBA;
5121 else if (!strcmp(p, "auto"))
5122 translation = BIOS_ATA_TRANSLATION_AUTO;
5123 else
5124 goto chs_fail;
5125 } else if (*p != '\0') {
5126 chs_fail:
5127 fprintf(stderr, "qemu: invalid physical CHS format\n");
5128 exit(1);
5130 if (hda_opts != NULL) {
5131 char num[16];
5132 snprintf(num, sizeof(num), "%d", cyls);
5133 qemu_opt_set(hda_opts, "cyls", num);
5134 snprintf(num, sizeof(num), "%d", heads);
5135 qemu_opt_set(hda_opts, "heads", num);
5136 snprintf(num, sizeof(num), "%d", secs);
5137 qemu_opt_set(hda_opts, "secs", num);
5138 if (translation == BIOS_ATA_TRANSLATION_LBA)
5139 qemu_opt_set(hda_opts, "trans", "lba");
5140 if (translation == BIOS_ATA_TRANSLATION_NONE)
5141 qemu_opt_set(hda_opts, "trans", "none");
5144 break;
5145 case QEMU_OPTION_numa:
5146 if (nb_numa_nodes >= MAX_NODES) {
5147 fprintf(stderr, "qemu: too many NUMA nodes\n");
5148 exit(1);
5150 numa_add(optarg);
5151 break;
5152 case QEMU_OPTION_nographic:
5153 display_type = DT_NOGRAPHIC;
5154 break;
5155 #ifdef CONFIG_CURSES
5156 case QEMU_OPTION_curses:
5157 display_type = DT_CURSES;
5158 break;
5159 #endif
5160 case QEMU_OPTION_portrait:
5161 graphic_rotate = 1;
5162 break;
5163 case QEMU_OPTION_kernel:
5164 kernel_filename = optarg;
5165 break;
5166 case QEMU_OPTION_append:
5167 kernel_cmdline = optarg;
5168 break;
5169 case QEMU_OPTION_cdrom:
5170 drive_add(optarg, CDROM_ALIAS);
5171 break;
5172 case QEMU_OPTION_boot:
5174 static const char * const params[] = {
5175 "order", "once", "menu", NULL
5177 char buf[sizeof(boot_devices)];
5178 char *standard_boot_devices;
5179 int legacy = 0;
5181 if (!strchr(optarg, '=')) {
5182 legacy = 1;
5183 pstrcpy(buf, sizeof(buf), optarg);
5184 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5185 fprintf(stderr,
5186 "qemu: unknown boot parameter '%s' in '%s'\n",
5187 buf, optarg);
5188 exit(1);
5191 if (legacy ||
5192 get_param_value(buf, sizeof(buf), "order", optarg)) {
5193 boot_devices_bitmap = parse_bootdevices(buf);
5194 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5196 if (!legacy) {
5197 if (get_param_value(buf, sizeof(buf),
5198 "once", optarg)) {
5199 boot_devices_bitmap |= parse_bootdevices(buf);
5200 standard_boot_devices = qemu_strdup(boot_devices);
5201 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5202 qemu_register_reset(restore_boot_devices,
5203 standard_boot_devices);
5205 if (get_param_value(buf, sizeof(buf),
5206 "menu", optarg)) {
5207 if (!strcmp(buf, "on")) {
5208 boot_menu = 1;
5209 } else if (!strcmp(buf, "off")) {
5210 boot_menu = 0;
5211 } else {
5212 fprintf(stderr,
5213 "qemu: invalid option value '%s'\n",
5214 buf);
5215 exit(1);
5220 break;
5221 case QEMU_OPTION_fda:
5222 case QEMU_OPTION_fdb:
5223 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5224 break;
5225 #ifdef TARGET_I386
5226 case QEMU_OPTION_no_fd_bootchk:
5227 fd_bootchk = 0;
5228 break;
5229 #endif
5230 case QEMU_OPTION_netdev:
5231 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5232 exit(1);
5234 break;
5235 case QEMU_OPTION_net:
5236 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5237 exit(1);
5239 break;
5240 #ifdef CONFIG_SLIRP
5241 case QEMU_OPTION_tftp:
5242 legacy_tftp_prefix = optarg;
5243 break;
5244 case QEMU_OPTION_bootp:
5245 legacy_bootp_filename = optarg;
5246 break;
5247 #ifndef _WIN32
5248 case QEMU_OPTION_smb:
5249 if (net_slirp_smb(optarg) < 0)
5250 exit(1);
5251 break;
5252 #endif
5253 case QEMU_OPTION_redir:
5254 if (net_slirp_redir(optarg) < 0)
5255 exit(1);
5256 break;
5257 #endif
5258 case QEMU_OPTION_bt:
5259 add_device_config(DEV_BT, optarg);
5260 break;
5261 #ifdef HAS_AUDIO
5262 case QEMU_OPTION_audio_help:
5263 AUD_help ();
5264 exit (0);
5265 break;
5266 case QEMU_OPTION_soundhw:
5267 select_soundhw (optarg);
5268 break;
5269 #endif
5270 case QEMU_OPTION_h:
5271 help(0);
5272 break;
5273 case QEMU_OPTION_version:
5274 version();
5275 exit(0);
5276 break;
5277 case QEMU_OPTION_m: {
5278 uint64_t value;
5279 char *ptr;
5281 value = strtoul(optarg, &ptr, 10);
5282 switch (*ptr) {
5283 case 0: case 'M': case 'm':
5284 value <<= 20;
5285 break;
5286 case 'G': case 'g':
5287 value <<= 30;
5288 break;
5289 default:
5290 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5291 exit(1);
5294 /* On 32-bit hosts, QEMU is limited by virtual address space */
5295 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5296 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5297 exit(1);
5299 if (value != (uint64_t)(ram_addr_t)value) {
5300 fprintf(stderr, "qemu: ram size too large\n");
5301 exit(1);
5303 ram_size = value;
5304 break;
5306 case QEMU_OPTION_d:
5308 int mask;
5309 const CPULogItem *item;
5311 mask = cpu_str_to_log_mask(optarg);
5312 if (!mask) {
5313 printf("Log items (comma separated):\n");
5314 for(item = cpu_log_items; item->mask != 0; item++) {
5315 printf("%-10s %s\n", item->name, item->help);
5317 exit(1);
5319 cpu_set_log(mask);
5321 break;
5322 case QEMU_OPTION_s:
5323 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5324 break;
5325 case QEMU_OPTION_gdb:
5326 gdbstub_dev = optarg;
5327 break;
5328 case QEMU_OPTION_L:
5329 data_dir = optarg;
5330 break;
5331 case QEMU_OPTION_bios:
5332 bios_name = optarg;
5333 break;
5334 case QEMU_OPTION_singlestep:
5335 singlestep = 1;
5336 break;
5337 case QEMU_OPTION_S:
5338 autostart = 0;
5339 break;
5340 case QEMU_OPTION_k:
5341 keyboard_layout = optarg;
5342 break;
5343 case QEMU_OPTION_localtime:
5344 rtc_utc = 0;
5345 break;
5346 case QEMU_OPTION_vga:
5347 select_vgahw (optarg);
5348 break;
5349 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5350 case QEMU_OPTION_g:
5352 const char *p;
5353 int w, h, depth;
5354 p = optarg;
5355 w = strtol(p, (char **)&p, 10);
5356 if (w <= 0) {
5357 graphic_error:
5358 fprintf(stderr, "qemu: invalid resolution or depth\n");
5359 exit(1);
5361 if (*p != 'x')
5362 goto graphic_error;
5363 p++;
5364 h = strtol(p, (char **)&p, 10);
5365 if (h <= 0)
5366 goto graphic_error;
5367 if (*p == 'x') {
5368 p++;
5369 depth = strtol(p, (char **)&p, 10);
5370 if (depth != 8 && depth != 15 && depth != 16 &&
5371 depth != 24 && depth != 32)
5372 goto graphic_error;
5373 } else if (*p == '\0') {
5374 depth = graphic_depth;
5375 } else {
5376 goto graphic_error;
5379 graphic_width = w;
5380 graphic_height = h;
5381 graphic_depth = depth;
5383 break;
5384 #endif
5385 case QEMU_OPTION_echr:
5387 char *r;
5388 term_escape_char = strtol(optarg, &r, 0);
5389 if (r == optarg)
5390 printf("Bad argument to echr\n");
5391 break;
5393 case QEMU_OPTION_monitor:
5394 monitor_parse(optarg, "readline");
5395 default_monitor = 0;
5396 break;
5397 case QEMU_OPTION_qmp:
5398 monitor_parse(optarg, "control");
5399 default_monitor = 0;
5400 break;
5401 case QEMU_OPTION_mon:
5402 opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5403 if (!opts) {
5404 fprintf(stderr, "parse error: %s\n", optarg);
5405 exit(1);
5407 default_monitor = 0;
5408 break;
5409 case QEMU_OPTION_chardev:
5410 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5411 if (!opts) {
5412 fprintf(stderr, "parse error: %s\n", optarg);
5413 exit(1);
5415 break;
5416 case QEMU_OPTION_serial:
5417 add_device_config(DEV_SERIAL, optarg);
5418 default_serial = 0;
5419 break;
5420 case QEMU_OPTION_watchdog:
5421 if (watchdog) {
5422 fprintf(stderr,
5423 "qemu: only one watchdog option may be given\n");
5424 return 1;
5426 watchdog = optarg;
5427 break;
5428 case QEMU_OPTION_watchdog_action:
5429 if (select_watchdog_action(optarg) == -1) {
5430 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5431 exit(1);
5433 break;
5434 case QEMU_OPTION_virtiocon:
5435 add_device_config(DEV_VIRTCON, optarg);
5436 default_virtcon = 0;
5437 break;
5438 case QEMU_OPTION_parallel:
5439 add_device_config(DEV_PARALLEL, optarg);
5440 default_parallel = 0;
5441 break;
5442 case QEMU_OPTION_loadvm:
5443 loadvm = optarg;
5444 break;
5445 case QEMU_OPTION_full_screen:
5446 full_screen = 1;
5447 break;
5448 #ifdef CONFIG_SDL
5449 case QEMU_OPTION_no_frame:
5450 no_frame = 1;
5451 break;
5452 case QEMU_OPTION_alt_grab:
5453 alt_grab = 1;
5454 break;
5455 case QEMU_OPTION_ctrl_grab:
5456 ctrl_grab = 1;
5457 break;
5458 case QEMU_OPTION_no_quit:
5459 no_quit = 1;
5460 break;
5461 case QEMU_OPTION_sdl:
5462 display_type = DT_SDL;
5463 break;
5464 #endif
5465 case QEMU_OPTION_pidfile:
5466 pid_file = optarg;
5467 break;
5468 #ifdef TARGET_I386
5469 case QEMU_OPTION_win2k_hack:
5470 win2k_install_hack = 1;
5471 break;
5472 case QEMU_OPTION_rtc_td_hack:
5473 rtc_td_hack = 1;
5474 break;
5475 case QEMU_OPTION_acpitable:
5476 if(acpi_table_add(optarg) < 0) {
5477 fprintf(stderr, "Wrong acpi table provided\n");
5478 exit(1);
5480 break;
5481 case QEMU_OPTION_smbios:
5482 if(smbios_entry_add(optarg) < 0) {
5483 fprintf(stderr, "Wrong smbios provided\n");
5484 exit(1);
5486 break;
5487 #endif
5488 #ifdef CONFIG_KVM
5489 #ifdef KVM_UPSTREAM
5490 case QEMU_OPTION_enable_kvm:
5491 kvm_allowed = 1;
5492 #endif
5493 break;
5494 case QEMU_OPTION_no_kvm:
5495 kvm_allowed = 0;
5496 break;
5497 case QEMU_OPTION_no_kvm_irqchip: {
5498 kvm_irqchip = 0;
5499 kvm_pit = 0;
5500 break;
5502 case QEMU_OPTION_no_kvm_pit: {
5503 kvm_pit = 0;
5504 break;
5506 case QEMU_OPTION_no_kvm_pit_reinjection: {
5507 kvm_pit_reinject = 0;
5508 break;
5510 case QEMU_OPTION_enable_nesting: {
5511 kvm_nested = 1;
5512 break;
5514 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5515 case QEMU_OPTION_pcidevice:
5516 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5517 fprintf(stderr, "Too many assigned devices\n");
5518 exit(1);
5520 assigned_devices[assigned_devices_index] = optarg;
5521 assigned_devices_index++;
5522 break;
5523 #endif
5524 #endif
5525 case QEMU_OPTION_usb:
5526 usb_enabled = 1;
5527 break;
5528 case QEMU_OPTION_usbdevice:
5529 usb_enabled = 1;
5530 add_device_config(DEV_USB, optarg);
5531 break;
5532 case QEMU_OPTION_device:
5533 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5534 exit(1);
5536 break;
5537 case QEMU_OPTION_smp:
5538 smp_parse(optarg);
5539 if (smp_cpus < 1) {
5540 fprintf(stderr, "Invalid number of CPUs\n");
5541 exit(1);
5543 if (max_cpus < smp_cpus) {
5544 fprintf(stderr, "maxcpus must be equal to or greater than "
5545 "smp\n");
5546 exit(1);
5548 if (max_cpus > 255) {
5549 fprintf(stderr, "Unsupported number of maxcpus\n");
5550 exit(1);
5552 break;
5553 case QEMU_OPTION_vnc:
5554 display_type = DT_VNC;
5555 vnc_display = optarg;
5556 break;
5557 #ifdef TARGET_I386
5558 case QEMU_OPTION_no_acpi:
5559 acpi_enabled = 0;
5560 break;
5561 case QEMU_OPTION_no_hpet:
5562 no_hpet = 1;
5563 break;
5564 case QEMU_OPTION_balloon:
5565 if (balloon_parse(optarg) < 0) {
5566 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5567 exit(1);
5569 break;
5570 #endif
5571 case QEMU_OPTION_no_reboot:
5572 no_reboot = 1;
5573 break;
5574 case QEMU_OPTION_no_shutdown:
5575 no_shutdown = 1;
5576 break;
5577 case QEMU_OPTION_show_cursor:
5578 cursor_hide = 0;
5579 break;
5580 case QEMU_OPTION_uuid:
5581 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5582 fprintf(stderr, "Fail to parse UUID string."
5583 " Wrong format.\n");
5584 exit(1);
5586 break;
5587 #ifndef _WIN32
5588 case QEMU_OPTION_daemonize:
5589 daemonize = 1;
5590 break;
5591 #endif
5592 case QEMU_OPTION_option_rom:
5593 if (nb_option_roms >= MAX_OPTION_ROMS) {
5594 fprintf(stderr, "Too many option ROMs\n");
5595 exit(1);
5597 option_rom[nb_option_roms] = optarg;
5598 nb_option_roms++;
5599 break;
5600 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5601 case QEMU_OPTION_semihosting:
5602 semihosting_enabled = 1;
5603 break;
5604 #endif
5605 case QEMU_OPTION_tdf:
5606 time_drift_fix = 1;
5607 break;
5608 case QEMU_OPTION_kvm_shadow_memory:
5609 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5610 break;
5611 case QEMU_OPTION_mempath:
5612 mem_path = optarg;
5613 break;
5614 #ifdef MAP_POPULATE
5615 case QEMU_OPTION_mem_prealloc:
5616 mem_prealloc = !mem_prealloc;
5617 break;
5618 #endif
5619 case QEMU_OPTION_name:
5620 qemu_name = qemu_strdup(optarg);
5622 char *p = strchr(qemu_name, ',');
5623 if (p != NULL) {
5624 *p++ = 0;
5625 if (strncmp(p, "process=", 8)) {
5626 fprintf(stderr, "Unknown subargument %s to -name", p);
5627 exit(1);
5629 p += 8;
5630 set_proc_name(p);
5633 break;
5634 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5635 case QEMU_OPTION_prom_env:
5636 if (nb_prom_envs >= MAX_PROM_ENVS) {
5637 fprintf(stderr, "Too many prom variables\n");
5638 exit(1);
5640 prom_envs[nb_prom_envs] = optarg;
5641 nb_prom_envs++;
5642 break;
5643 #endif
5644 #ifdef TARGET_ARM
5645 case QEMU_OPTION_old_param:
5646 old_param = 1;
5647 break;
5648 #endif
5649 case QEMU_OPTION_clock:
5650 configure_alarms(optarg);
5651 break;
5652 case QEMU_OPTION_startdate:
5653 configure_rtc_date_offset(optarg, 1);
5654 break;
5655 case QEMU_OPTION_rtc:
5656 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5657 if (!opts) {
5658 fprintf(stderr, "parse error: %s\n", optarg);
5659 exit(1);
5661 configure_rtc(opts);
5662 break;
5663 case QEMU_OPTION_tb_size:
5664 tb_size = strtol(optarg, NULL, 0);
5665 if (tb_size < 0)
5666 tb_size = 0;
5667 break;
5668 case QEMU_OPTION_icount:
5669 use_icount = 1;
5670 if (strcmp(optarg, "auto") == 0) {
5671 icount_time_shift = -1;
5672 } else {
5673 icount_time_shift = strtol(optarg, NULL, 0);
5675 break;
5676 case QEMU_OPTION_incoming:
5677 incoming = optarg;
5678 break;
5679 case QEMU_OPTION_nodefaults:
5680 default_serial = 0;
5681 default_parallel = 0;
5682 default_virtcon = 0;
5683 default_monitor = 0;
5684 default_vga = 0;
5685 default_net = 0;
5686 default_floppy = 0;
5687 default_cdrom = 0;
5688 default_sdcard = 0;
5689 break;
5690 #ifndef _WIN32
5691 case QEMU_OPTION_chroot:
5692 chroot_dir = optarg;
5693 break;
5694 case QEMU_OPTION_runas:
5695 run_as = optarg;
5696 break;
5697 case QEMU_OPTION_nvram:
5698 nvram = optarg;
5699 break;
5700 #endif
5701 #ifdef CONFIG_XEN
5702 case QEMU_OPTION_xen_domid:
5703 xen_domid = atoi(optarg);
5704 break;
5705 case QEMU_OPTION_xen_create:
5706 xen_mode = XEN_CREATE;
5707 break;
5708 case QEMU_OPTION_xen_attach:
5709 xen_mode = XEN_ATTACH;
5710 break;
5711 #endif
5712 case QEMU_OPTION_readconfig:
5714 FILE *fp;
5715 fp = fopen(optarg, "r");
5716 if (fp == NULL) {
5717 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5718 exit(1);
5720 if (qemu_config_parse(fp) != 0) {
5721 exit(1);
5723 fclose(fp);
5724 break;
5726 case QEMU_OPTION_writeconfig:
5728 FILE *fp;
5729 if (strcmp(optarg, "-") == 0) {
5730 fp = stdout;
5731 } else {
5732 fp = fopen(optarg, "w");
5733 if (fp == NULL) {
5734 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5735 exit(1);
5738 qemu_config_write(fp);
5739 fclose(fp);
5740 break;
5746 /* If no data_dir is specified then try to find it relative to the
5747 executable path. */
5748 if (!data_dir) {
5749 data_dir = find_datadir(argv[0]);
5751 /* If all else fails use the install patch specified when building. */
5752 if (!data_dir) {
5753 data_dir = CONFIG_QEMU_SHAREDIR;
5757 * Default to max_cpus = smp_cpus, in case the user doesn't
5758 * specify a max_cpus value.
5760 if (!max_cpus)
5761 max_cpus = smp_cpus;
5763 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5764 if (smp_cpus > machine->max_cpus) {
5765 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5766 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5767 machine->max_cpus);
5768 exit(1);
5771 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5772 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5774 if (machine->no_serial) {
5775 default_serial = 0;
5777 if (machine->no_parallel) {
5778 default_parallel = 0;
5780 if (!machine->use_virtcon) {
5781 default_virtcon = 0;
5783 if (machine->no_vga) {
5784 default_vga = 0;
5786 if (machine->no_floppy) {
5787 default_floppy = 0;
5789 if (machine->no_cdrom) {
5790 default_cdrom = 0;
5792 if (machine->no_sdcard) {
5793 default_sdcard = 0;
5796 if (display_type == DT_NOGRAPHIC) {
5797 if (default_parallel)
5798 add_device_config(DEV_PARALLEL, "null");
5799 if (default_serial && default_monitor) {
5800 add_device_config(DEV_SERIAL, "mon:stdio");
5801 } else if (default_virtcon && default_monitor) {
5802 add_device_config(DEV_VIRTCON, "mon:stdio");
5803 } else {
5804 if (default_serial)
5805 add_device_config(DEV_SERIAL, "stdio");
5806 if (default_virtcon)
5807 add_device_config(DEV_VIRTCON, "stdio");
5808 if (default_monitor)
5809 monitor_parse("stdio", "readline");
5811 } else {
5812 if (default_serial)
5813 add_device_config(DEV_SERIAL, "vc:80Cx24C");
5814 if (default_parallel)
5815 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5816 if (default_monitor)
5817 monitor_parse("vc:80Cx24C", "readline");
5818 if (default_virtcon)
5819 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5821 if (default_vga)
5822 vga_interface_type = VGA_CIRRUS;
5824 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5825 exit(1);
5827 #ifndef _WIN32
5828 if (daemonize) {
5829 pid_t pid;
5831 if (pipe(fds) == -1)
5832 exit(1);
5834 pid = fork();
5835 if (pid > 0) {
5836 uint8_t status;
5837 ssize_t len;
5839 close(fds[1]);
5841 again:
5842 len = read(fds[0], &status, 1);
5843 if (len == -1 && (errno == EINTR))
5844 goto again;
5846 if (len != 1)
5847 exit(1);
5848 else if (status == 1) {
5849 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5850 exit(1);
5851 } else
5852 exit(0);
5853 } else if (pid < 0)
5854 exit(1);
5856 close(fds[0]);
5857 qemu_set_cloexec(fds[1]);
5859 setsid();
5861 pid = fork();
5862 if (pid > 0)
5863 exit(0);
5864 else if (pid < 0)
5865 exit(1);
5867 umask(027);
5869 signal(SIGTSTP, SIG_IGN);
5870 signal(SIGTTOU, SIG_IGN);
5871 signal(SIGTTIN, SIG_IGN);
5874 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5875 if (daemonize) {
5876 uint8_t status = 1;
5877 write(fds[1], &status, 1);
5878 } else
5879 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5880 exit(1);
5882 #endif
5884 if (kvm_enabled()) {
5885 int ret;
5887 ret = kvm_init(smp_cpus);
5888 if (ret < 0) {
5889 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5890 fprintf(stderr, "failed to initialize KVM\n");
5891 exit(1);
5892 #endif
5893 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5894 kvm_allowed = 0;
5898 if (qemu_init_main_loop()) {
5899 fprintf(stderr, "qemu_init_main_loop failed\n");
5900 exit(1);
5902 linux_boot = (kernel_filename != NULL);
5904 if (!linux_boot && *kernel_cmdline != '\0') {
5905 fprintf(stderr, "-append only allowed with -kernel option\n");
5906 exit(1);
5909 if (!linux_boot && initrd_filename != NULL) {
5910 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5911 exit(1);
5914 #ifndef _WIN32
5915 /* Win32 doesn't support line-buffering and requires size >= 2 */
5916 setvbuf(stdout, NULL, _IOLBF, 0);
5917 #endif
5919 if (init_timer_alarm() < 0) {
5920 fprintf(stderr, "could not initialize alarm timer\n");
5921 exit(1);
5923 if (use_icount && icount_time_shift < 0) {
5924 use_icount = 2;
5925 /* 125MIPS seems a reasonable initial guess at the guest speed.
5926 It will be corrected fairly quickly anyway. */
5927 icount_time_shift = 3;
5928 init_icount_adjust();
5931 #ifdef _WIN32
5932 socket_init();
5933 #endif
5935 if (net_init_clients() < 0) {
5936 exit(1);
5939 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5940 net_set_boot_mask(net_boot);
5942 /* init the bluetooth world */
5943 if (foreach_device_config(DEV_BT, bt_parse))
5944 exit(1);
5946 /* init the memory */
5947 if (ram_size == 0)
5948 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5950 /* init the dynamic translator */
5951 cpu_exec_init_all(tb_size * 1024 * 1024);
5953 bdrv_init_with_whitelist();
5955 blk_mig_init();
5957 if (default_cdrom) {
5958 /* we always create the cdrom drive, even if no disk is there */
5959 drive_add(NULL, CDROM_ALIAS);
5962 if (default_floppy) {
5963 /* we always create at least one floppy */
5964 drive_add(NULL, FD_ALIAS, 0);
5967 if (default_sdcard) {
5968 /* we always create one sd slot, even if no card is in it */
5969 drive_add(NULL, SD_ALIAS);
5972 /* open the virtual block devices */
5973 if (snapshot)
5974 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5975 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5976 exit(1);
5978 vmstate_register(0, &vmstate_timers ,&timers_state);
5979 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5980 ram_load, NULL);
5982 if (nb_numa_nodes > 0) {
5983 int i;
5985 if (nb_numa_nodes > smp_cpus) {
5986 nb_numa_nodes = smp_cpus;
5989 /* If no memory size if given for any node, assume the default case
5990 * and distribute the available memory equally across all nodes
5992 for (i = 0; i < nb_numa_nodes; i++) {
5993 if (node_mem[i] != 0)
5994 break;
5996 if (i == nb_numa_nodes) {
5997 uint64_t usedmem = 0;
5999 /* On Linux, the each node's border has to be 8MB aligned,
6000 * the final node gets the rest.
6002 for (i = 0; i < nb_numa_nodes - 1; i++) {
6003 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
6004 usedmem += node_mem[i];
6006 node_mem[i] = ram_size - usedmem;
6009 for (i = 0; i < nb_numa_nodes; i++) {
6010 if (node_cpumask[i] != 0)
6011 break;
6013 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6014 * must cope with this anyway, because there are BIOSes out there in
6015 * real machines which also use this scheme.
6017 if (i == nb_numa_nodes) {
6018 for (i = 0; i < smp_cpus; i++) {
6019 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6024 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
6025 exit(1);
6026 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
6027 exit(1);
6028 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
6029 exit(1);
6031 module_call_init(MODULE_INIT_DEVICE);
6033 if (watchdog) {
6034 i = select_watchdog(watchdog);
6035 if (i > 0)
6036 exit (i == 1 ? 1 : 0);
6039 if (machine->compat_props) {
6040 qdev_prop_register_global_list(machine->compat_props);
6042 qemu_add_globals();
6044 machine->init(ram_size, boot_devices,
6045 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6048 #ifndef _WIN32
6049 /* must be after terminal init, SDL library changes signal handlers */
6050 sighandler_setup();
6051 #endif
6053 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6054 for (i = 0; i < nb_numa_nodes; i++) {
6055 if (node_cpumask[i] & (1 << env->cpu_index)) {
6056 env->numa_node = i;
6061 current_machine = machine;
6063 /* init USB devices */
6064 if (usb_enabled) {
6065 if (foreach_device_config(DEV_USB, usb_parse) < 0)
6066 exit(1);
6069 /* init generic devices */
6070 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
6071 exit(1);
6073 if (!display_state)
6074 dumb_display_init();
6075 /* just use the first displaystate for the moment */
6076 ds = display_state;
6078 if (display_type == DT_DEFAULT) {
6079 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6080 display_type = DT_SDL;
6081 #else
6082 display_type = DT_VNC;
6083 vnc_display = "localhost:0,to=99";
6084 show_vnc_port = 1;
6085 #endif
6089 switch (display_type) {
6090 case DT_NOGRAPHIC:
6091 break;
6092 #if defined(CONFIG_CURSES)
6093 case DT_CURSES:
6094 curses_display_init(ds, full_screen);
6095 break;
6096 #endif
6097 #if defined(CONFIG_SDL)
6098 case DT_SDL:
6099 sdl_display_init(ds, full_screen, no_frame);
6100 break;
6101 #elif defined(CONFIG_COCOA)
6102 case DT_SDL:
6103 cocoa_display_init(ds, full_screen);
6104 break;
6105 #endif
6106 case DT_VNC:
6107 vnc_display_init(ds);
6108 if (vnc_display_open(ds, vnc_display) < 0)
6109 exit(1);
6111 if (show_vnc_port) {
6112 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6114 break;
6115 default:
6116 break;
6118 dpy_resize(ds);
6120 dcl = ds->listeners;
6121 while (dcl != NULL) {
6122 if (dcl->dpy_refresh != NULL) {
6123 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6124 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6126 dcl = dcl->next;
6129 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6130 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6131 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6134 text_consoles_set_display(display_state);
6136 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6137 exit(1);
6139 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6140 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6141 gdbstub_dev);
6142 exit(1);
6145 qdev_machine_creation_done();
6147 if (rom_load_all() != 0) {
6148 fprintf(stderr, "rom loading failed\n");
6149 exit(1);
6152 qemu_system_reset();
6153 if (loadvm) {
6154 if (load_vmstate(cur_mon, loadvm) < 0) {
6155 autostart = 0;
6159 if (incoming) {
6160 qemu_start_incoming_migration(incoming);
6161 } else if (autostart) {
6162 vm_start();
6165 #ifndef _WIN32
6166 if (daemonize) {
6167 uint8_t status = 0;
6168 ssize_t len;
6170 again1:
6171 len = write(fds[1], &status, 1);
6172 if (len == -1 && (errno == EINTR))
6173 goto again1;
6175 if (len != 1)
6176 exit(1);
6178 chdir("/");
6179 TFR(fd = qemu_open("/dev/null", O_RDWR));
6180 if (fd == -1)
6181 exit(1);
6184 if (run_as) {
6185 pwd = getpwnam(run_as);
6186 if (!pwd) {
6187 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6188 exit(1);
6192 if (chroot_dir) {
6193 if (chroot(chroot_dir) < 0) {
6194 fprintf(stderr, "chroot failed\n");
6195 exit(1);
6197 chdir("/");
6200 if (run_as) {
6201 if (setgid(pwd->pw_gid) < 0) {
6202 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6203 exit(1);
6205 if (setuid(pwd->pw_uid) < 0) {
6206 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6207 exit(1);
6209 if (setuid(0) != -1) {
6210 fprintf(stderr, "Dropping privileges failed\n");
6211 exit(1);
6215 if (daemonize) {
6216 dup2(fd, 0);
6217 dup2(fd, 1);
6218 dup2(fd, 2);
6220 close(fd);
6222 #endif
6224 main_loop();
6225 quit_timers();
6226 net_cleanup();
6228 return 0;