Update to SeaBIOS 0.5.0
[qemu/aliguori-queue.git] / vl.c
blobe6069034658432dba047be8d9ac5d0609e17f1b2
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"
161 #include "disas.h"
163 #include "exec-all.h"
165 #include "qemu_socket.h"
167 #include "slirp/libslirp.h"
169 #include "qemu-queue.h"
171 //#define DEBUG_NET
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 static const char *data_dir;
177 const char *bios_name = NULL;
178 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
179 to store the VM snapshots */
180 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
181 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
182 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
183 static DisplayState *display_state;
184 DisplayType display_type = DT_DEFAULT;
185 const char* keyboard_layout = NULL;
186 ram_addr_t ram_size;
187 int nb_nics;
188 NICInfo nd_table[MAX_NICS];
189 int vm_running;
190 int autostart;
191 static int rtc_utc = 1;
192 static int rtc_date_offset = -1; /* -1 means no change */
193 QEMUClock *rtc_clock;
194 int vga_interface_type = VGA_NONE;
195 #ifdef TARGET_SPARC
196 int graphic_width = 1024;
197 int graphic_height = 768;
198 int graphic_depth = 8;
199 #else
200 int graphic_width = 800;
201 int graphic_height = 600;
202 int graphic_depth = 15;
203 #endif
204 static int full_screen = 0;
205 #ifdef CONFIG_SDL
206 static int no_frame = 0;
207 #endif
208 int no_quit = 0;
209 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
210 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
211 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
212 #ifdef TARGET_I386
213 int win2k_install_hack = 0;
214 int rtc_td_hack = 0;
215 #endif
216 int usb_enabled = 0;
217 int singlestep = 0;
218 int smp_cpus = 1;
219 int max_cpus = 0;
220 int smp_cores = 1;
221 int smp_threads = 1;
222 const char *vnc_display;
223 int acpi_enabled = 1;
224 int no_hpet = 0;
225 int fd_bootchk = 1;
226 int no_reboot = 0;
227 int no_shutdown = 0;
228 int cursor_hide = 1;
229 int graphic_rotate = 0;
230 uint8_t irq0override = 1;
231 #ifndef _WIN32
232 int daemonize = 0;
233 #endif
234 const char *watchdog;
235 const char *option_rom[MAX_OPTION_ROMS];
236 int nb_option_roms;
237 int semihosting_enabled = 0;
238 #ifdef TARGET_ARM
239 int old_param = 0;
240 #endif
241 const char *qemu_name;
242 int alt_grab = 0;
243 int ctrl_grab = 0;
244 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
245 unsigned int nb_prom_envs = 0;
246 const char *prom_envs[MAX_PROM_ENVS];
247 #endif
248 int boot_menu;
250 int nb_numa_nodes;
251 uint64_t node_mem[MAX_NODES];
252 uint64_t node_cpumask[MAX_NODES];
254 static CPUState *cur_cpu;
255 static CPUState *next_cpu;
256 static int timer_alarm_pending = 1;
257 /* Conversion factor from emulated instructions to virtual clock ticks. */
258 static int icount_time_shift;
259 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
260 #define MAX_ICOUNT_SHIFT 10
261 /* Compensate for varying guest execution speed. */
262 static int64_t qemu_icount_bias;
263 static QEMUTimer *icount_rt_timer;
264 static QEMUTimer *icount_vm_timer;
265 static QEMUTimer *nographic_timer;
267 uint8_t qemu_uuid[16];
269 static QEMUBootSetHandler *boot_set_handler;
270 static void *boot_set_opaque;
272 static int default_serial = 1;
273 static int default_parallel = 1;
274 static int default_virtcon = 1;
275 static int default_monitor = 1;
276 static int default_vga = 1;
277 static int default_floppy = 1;
278 static int default_cdrom = 1;
279 static int default_sdcard = 1;
281 static struct {
282 const char *driver;
283 int *flag;
284 } default_list[] = {
285 { .driver = "isa-serial", .flag = &default_serial },
286 { .driver = "isa-parallel", .flag = &default_parallel },
287 { .driver = "isa-fdc", .flag = &default_floppy },
288 { .driver = "ide-drive", .flag = &default_cdrom },
289 { .driver = "virtio-console-pci", .flag = &default_virtcon },
290 { .driver = "virtio-console-s390", .flag = &default_virtcon },
291 { .driver = "VGA", .flag = &default_vga },
292 { .driver = "cirrus-vga", .flag = &default_vga },
293 { .driver = "vmware-svga", .flag = &default_vga },
296 static int default_driver_check(QemuOpts *opts, void *opaque)
298 const char *driver = qemu_opt_get(opts, "driver");
299 int i;
301 if (!driver)
302 return 0;
303 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
304 if (strcmp(default_list[i].driver, driver) != 0)
305 continue;
306 *(default_list[i].flag) = 0;
308 return 0;
311 /***********************************************************/
312 /* x86 ISA bus support */
314 target_phys_addr_t isa_mem_base = 0;
315 PicState2 *isa_pic;
317 /***********************************************************/
318 void hw_error(const char *fmt, ...)
320 va_list ap;
321 CPUState *env;
323 va_start(ap, fmt);
324 fprintf(stderr, "qemu: hardware error: ");
325 vfprintf(stderr, fmt, ap);
326 fprintf(stderr, "\n");
327 for(env = first_cpu; env != NULL; env = env->next_cpu) {
328 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
329 #ifdef TARGET_I386
330 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
331 #else
332 cpu_dump_state(env, stderr, fprintf, 0);
333 #endif
335 va_end(ap);
336 abort();
339 static void set_proc_name(const char *s)
341 #if defined(__linux__) && defined(PR_SET_NAME)
342 char name[16];
343 if (!s)
344 return;
345 name[sizeof(name) - 1] = 0;
346 strncpy(name, s, sizeof(name));
347 /* Could rewrite argv[0] too, but that's a bit more complicated.
348 This simple way is enough for `top'. */
349 prctl(PR_SET_NAME, name);
350 #endif
353 /***************/
354 /* ballooning */
356 static QEMUBalloonEvent *qemu_balloon_event;
357 void *qemu_balloon_event_opaque;
359 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
361 qemu_balloon_event = func;
362 qemu_balloon_event_opaque = opaque;
365 void qemu_balloon(ram_addr_t target)
367 if (qemu_balloon_event)
368 qemu_balloon_event(qemu_balloon_event_opaque, target);
371 ram_addr_t qemu_balloon_status(void)
373 if (qemu_balloon_event)
374 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
375 return 0;
378 /***********************************************************/
379 /* keyboard/mouse */
381 static QEMUPutKBDEvent *qemu_put_kbd_event;
382 static void *qemu_put_kbd_event_opaque;
383 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
384 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
386 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
388 qemu_put_kbd_event_opaque = opaque;
389 qemu_put_kbd_event = func;
392 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
393 void *opaque, int absolute,
394 const char *name)
396 QEMUPutMouseEntry *s, *cursor;
398 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
400 s->qemu_put_mouse_event = func;
401 s->qemu_put_mouse_event_opaque = opaque;
402 s->qemu_put_mouse_event_absolute = absolute;
403 s->qemu_put_mouse_event_name = qemu_strdup(name);
404 s->next = NULL;
406 if (!qemu_put_mouse_event_head) {
407 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
408 return s;
411 cursor = qemu_put_mouse_event_head;
412 while (cursor->next != NULL)
413 cursor = cursor->next;
415 cursor->next = s;
416 qemu_put_mouse_event_current = s;
418 return s;
421 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
423 QEMUPutMouseEntry *prev = NULL, *cursor;
425 if (!qemu_put_mouse_event_head || entry == NULL)
426 return;
428 cursor = qemu_put_mouse_event_head;
429 while (cursor != NULL && cursor != entry) {
430 prev = cursor;
431 cursor = cursor->next;
434 if (cursor == NULL) // does not exist or list empty
435 return;
436 else if (prev == NULL) { // entry is head
437 qemu_put_mouse_event_head = cursor->next;
438 if (qemu_put_mouse_event_current == entry)
439 qemu_put_mouse_event_current = cursor->next;
440 qemu_free(entry->qemu_put_mouse_event_name);
441 qemu_free(entry);
442 return;
445 prev->next = entry->next;
447 if (qemu_put_mouse_event_current == entry)
448 qemu_put_mouse_event_current = prev;
450 qemu_free(entry->qemu_put_mouse_event_name);
451 qemu_free(entry);
454 void kbd_put_keycode(int keycode)
456 if (qemu_put_kbd_event) {
457 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
461 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
463 QEMUPutMouseEvent *mouse_event;
464 void *mouse_event_opaque;
465 int width;
467 if (!qemu_put_mouse_event_current) {
468 return;
471 mouse_event =
472 qemu_put_mouse_event_current->qemu_put_mouse_event;
473 mouse_event_opaque =
474 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
476 if (mouse_event) {
477 if (graphic_rotate) {
478 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
479 width = 0x7fff;
480 else
481 width = graphic_width - 1;
482 mouse_event(mouse_event_opaque,
483 width - dy, dx, dz, buttons_state);
484 } else
485 mouse_event(mouse_event_opaque,
486 dx, dy, dz, buttons_state);
490 int kbd_mouse_is_absolute(void)
492 if (!qemu_put_mouse_event_current)
493 return 0;
495 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
498 static void info_mice_iter(QObject *data, void *opaque)
500 QDict *mouse;
501 Monitor *mon = opaque;
503 mouse = qobject_to_qdict(data);
504 monitor_printf(mon, "%c Mouse #%" PRId64 ": %s\n",
505 (qdict_get_bool(mouse, "current") ? '*' : ' '),
506 qdict_get_int(mouse, "index"), qdict_get_str(mouse, "name"));
509 void do_info_mice_print(Monitor *mon, const QObject *data)
511 QList *mice_list;
513 mice_list = qobject_to_qlist(data);
514 if (qlist_empty(mice_list)) {
515 monitor_printf(mon, "No mouse devices connected\n");
516 return;
519 qlist_iter(mice_list, info_mice_iter, mon);
523 * do_info_mice(): Show VM mice information
525 * Each mouse is represented by a QDict, the returned QObject is a QList of
526 * all mice.
528 * The mouse QDict contains the following:
530 * - "name": mouse's name
531 * - "index": mouse's index
532 * - "current": true if this mouse is receiving events, false otherwise
534 * Example:
536 * [ { "name": "QEMU Microsoft Mouse", "index": 0, "current": false },
537 * { "name": "QEMU PS/2 Mouse", "index": 1, "current": true } ]
539 void do_info_mice(Monitor *mon, QObject **ret_data)
541 QEMUPutMouseEntry *cursor;
542 QList *mice_list;
543 int index = 0;
545 mice_list = qlist_new();
547 if (!qemu_put_mouse_event_head) {
548 goto out;
551 cursor = qemu_put_mouse_event_head;
552 while (cursor != NULL) {
553 QObject *obj;
554 obj = qobject_from_jsonf("{ 'name': %s, 'index': %d, 'current': %i }",
555 cursor->qemu_put_mouse_event_name,
556 index, cursor == qemu_put_mouse_event_current);
557 qlist_append_obj(mice_list, obj);
558 index++;
559 cursor = cursor->next;
562 out:
563 *ret_data = QOBJECT(mice_list);
566 void do_mouse_set(Monitor *mon, const QDict *qdict)
568 QEMUPutMouseEntry *cursor;
569 int i = 0;
570 int index = qdict_get_int(qdict, "index");
572 if (!qemu_put_mouse_event_head) {
573 monitor_printf(mon, "No mouse devices connected\n");
574 return;
577 cursor = qemu_put_mouse_event_head;
578 while (cursor != NULL && index != i) {
579 i++;
580 cursor = cursor->next;
583 if (cursor != NULL)
584 qemu_put_mouse_event_current = cursor;
585 else
586 monitor_printf(mon, "Mouse at given index not found\n");
589 /* compute with 96 bit intermediate result: (a*b)/c */
590 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
592 union {
593 uint64_t ll;
594 struct {
595 #ifdef HOST_WORDS_BIGENDIAN
596 uint32_t high, low;
597 #else
598 uint32_t low, high;
599 #endif
600 } l;
601 } u, res;
602 uint64_t rl, rh;
604 u.ll = a;
605 rl = (uint64_t)u.l.low * (uint64_t)b;
606 rh = (uint64_t)u.l.high * (uint64_t)b;
607 rh += (rl >> 32);
608 res.l.high = rh / c;
609 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
610 return res.ll;
613 /***********************************************************/
614 /* real time host monotonic timer */
616 static int64_t get_clock_realtime(void)
618 struct timeval tv;
620 gettimeofday(&tv, NULL);
621 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
624 #ifdef WIN32
626 static int64_t clock_freq;
628 static void init_get_clock(void)
630 LARGE_INTEGER freq;
631 int ret;
632 ret = QueryPerformanceFrequency(&freq);
633 if (ret == 0) {
634 fprintf(stderr, "Could not calibrate ticks\n");
635 exit(1);
637 clock_freq = freq.QuadPart;
640 static int64_t get_clock(void)
642 LARGE_INTEGER ti;
643 QueryPerformanceCounter(&ti);
644 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
647 #else
649 static int use_rt_clock;
651 static void init_get_clock(void)
653 use_rt_clock = 0;
654 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
655 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
657 struct timespec ts;
658 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
659 use_rt_clock = 1;
662 #endif
665 static int64_t get_clock(void)
667 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
668 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
669 if (use_rt_clock) {
670 struct timespec ts;
671 clock_gettime(CLOCK_MONOTONIC, &ts);
672 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
673 } else
674 #endif
676 /* XXX: using gettimeofday leads to problems if the date
677 changes, so it should be avoided. */
678 return get_clock_realtime();
681 #endif
683 /* Return the virtual CPU time, based on the instruction counter. */
684 static int64_t cpu_get_icount(void)
686 int64_t icount;
687 CPUState *env = cpu_single_env;;
688 icount = qemu_icount;
689 if (env) {
690 if (!can_do_io(env))
691 fprintf(stderr, "Bad clock read\n");
692 icount -= (env->icount_decr.u16.low + env->icount_extra);
694 return qemu_icount_bias + (icount << icount_time_shift);
697 /***********************************************************/
698 /* guest cycle counter */
700 typedef struct TimersState {
701 int64_t cpu_ticks_prev;
702 int64_t cpu_ticks_offset;
703 int64_t cpu_clock_offset;
704 int32_t cpu_ticks_enabled;
705 int64_t dummy;
706 } TimersState;
708 TimersState timers_state;
710 /* return the host CPU cycle counter and handle stop/restart */
711 int64_t cpu_get_ticks(void)
713 if (use_icount) {
714 return cpu_get_icount();
716 if (!timers_state.cpu_ticks_enabled) {
717 return timers_state.cpu_ticks_offset;
718 } else {
719 int64_t ticks;
720 ticks = cpu_get_real_ticks();
721 if (timers_state.cpu_ticks_prev > ticks) {
722 /* Note: non increasing ticks may happen if the host uses
723 software suspend */
724 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
726 timers_state.cpu_ticks_prev = ticks;
727 return ticks + timers_state.cpu_ticks_offset;
731 /* return the host CPU monotonic timer and handle stop/restart */
732 static int64_t cpu_get_clock(void)
734 int64_t ti;
735 if (!timers_state.cpu_ticks_enabled) {
736 return timers_state.cpu_clock_offset;
737 } else {
738 ti = get_clock();
739 return ti + timers_state.cpu_clock_offset;
743 /* enable cpu_get_ticks() */
744 void cpu_enable_ticks(void)
746 if (!timers_state.cpu_ticks_enabled) {
747 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
748 timers_state.cpu_clock_offset -= get_clock();
749 timers_state.cpu_ticks_enabled = 1;
753 /* disable cpu_get_ticks() : the clock is stopped. You must not call
754 cpu_get_ticks() after that. */
755 void cpu_disable_ticks(void)
757 if (timers_state.cpu_ticks_enabled) {
758 timers_state.cpu_ticks_offset = cpu_get_ticks();
759 timers_state.cpu_clock_offset = cpu_get_clock();
760 timers_state.cpu_ticks_enabled = 0;
764 /***********************************************************/
765 /* timers */
767 #define QEMU_CLOCK_REALTIME 0
768 #define QEMU_CLOCK_VIRTUAL 1
769 #define QEMU_CLOCK_HOST 2
771 struct QEMUClock {
772 int type;
773 /* XXX: add frequency */
776 struct QEMUTimer {
777 QEMUClock *clock;
778 int64_t expire_time;
779 QEMUTimerCB *cb;
780 void *opaque;
781 struct QEMUTimer *next;
784 struct qemu_alarm_timer {
785 char const *name;
786 unsigned int flags;
788 int (*start)(struct qemu_alarm_timer *t);
789 void (*stop)(struct qemu_alarm_timer *t);
790 void (*rearm)(struct qemu_alarm_timer *t);
791 void *priv;
794 #define ALARM_FLAG_DYNTICKS 0x1
795 #define ALARM_FLAG_EXPIRED 0x2
797 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
799 return t && (t->flags & ALARM_FLAG_DYNTICKS);
802 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
804 if (!alarm_has_dynticks(t))
805 return;
807 t->rearm(t);
810 /* TODO: MIN_TIMER_REARM_US should be optimized */
811 #define MIN_TIMER_REARM_US 250
813 static struct qemu_alarm_timer *alarm_timer;
815 #ifdef _WIN32
817 struct qemu_alarm_win32 {
818 MMRESULT timerId;
819 unsigned int period;
820 } alarm_win32_data = {0, -1};
822 static int win32_start_timer(struct qemu_alarm_timer *t);
823 static void win32_stop_timer(struct qemu_alarm_timer *t);
824 static void win32_rearm_timer(struct qemu_alarm_timer *t);
826 #else
828 static int unix_start_timer(struct qemu_alarm_timer *t);
829 static void unix_stop_timer(struct qemu_alarm_timer *t);
831 #ifdef __linux__
833 static int dynticks_start_timer(struct qemu_alarm_timer *t);
834 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
835 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
837 static int hpet_start_timer(struct qemu_alarm_timer *t);
838 static void hpet_stop_timer(struct qemu_alarm_timer *t);
840 static int rtc_start_timer(struct qemu_alarm_timer *t);
841 static void rtc_stop_timer(struct qemu_alarm_timer *t);
843 #endif /* __linux__ */
845 #endif /* _WIN32 */
847 /* Correlation between real and virtual time is always going to be
848 fairly approximate, so ignore small variation.
849 When the guest is idle real and virtual time will be aligned in
850 the IO wait loop. */
851 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
853 static void icount_adjust(void)
855 int64_t cur_time;
856 int64_t cur_icount;
857 int64_t delta;
858 static int64_t last_delta;
859 /* If the VM is not running, then do nothing. */
860 if (!vm_running)
861 return;
863 cur_time = cpu_get_clock();
864 cur_icount = qemu_get_clock(vm_clock);
865 delta = cur_icount - cur_time;
866 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
867 if (delta > 0
868 && last_delta + ICOUNT_WOBBLE < delta * 2
869 && icount_time_shift > 0) {
870 /* The guest is getting too far ahead. Slow time down. */
871 icount_time_shift--;
873 if (delta < 0
874 && last_delta - ICOUNT_WOBBLE > delta * 2
875 && icount_time_shift < MAX_ICOUNT_SHIFT) {
876 /* The guest is getting too far behind. Speed time up. */
877 icount_time_shift++;
879 last_delta = delta;
880 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
883 static void icount_adjust_rt(void * opaque)
885 qemu_mod_timer(icount_rt_timer,
886 qemu_get_clock(rt_clock) + 1000);
887 icount_adjust();
890 static void icount_adjust_vm(void * opaque)
892 qemu_mod_timer(icount_vm_timer,
893 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
894 icount_adjust();
897 static void init_icount_adjust(void)
899 /* Have both realtime and virtual time triggers for speed adjustment.
900 The realtime trigger catches emulated time passing too slowly,
901 the virtual time trigger catches emulated time passing too fast.
902 Realtime triggers occur even when idle, so use them less frequently
903 than VM triggers. */
904 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
905 qemu_mod_timer(icount_rt_timer,
906 qemu_get_clock(rt_clock) + 1000);
907 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
908 qemu_mod_timer(icount_vm_timer,
909 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
912 static struct qemu_alarm_timer alarm_timers[] = {
913 #ifndef _WIN32
914 #ifdef __linux__
915 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
916 dynticks_stop_timer, dynticks_rearm_timer, NULL},
917 /* HPET - if available - is preferred */
918 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
919 /* ...otherwise try RTC */
920 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
921 #endif
922 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
923 #else
924 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
925 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
926 {"win32", 0, win32_start_timer,
927 win32_stop_timer, NULL, &alarm_win32_data},
928 #endif
929 {NULL, }
932 static void show_available_alarms(void)
934 int i;
936 printf("Available alarm timers, in order of precedence:\n");
937 for (i = 0; alarm_timers[i].name; i++)
938 printf("%s\n", alarm_timers[i].name);
941 static void configure_alarms(char const *opt)
943 int i;
944 int cur = 0;
945 int count = ARRAY_SIZE(alarm_timers) - 1;
946 char *arg;
947 char *name;
948 struct qemu_alarm_timer tmp;
950 if (!strcmp(opt, "?")) {
951 show_available_alarms();
952 exit(0);
955 arg = qemu_strdup(opt);
957 /* Reorder the array */
958 name = strtok(arg, ",");
959 while (name) {
960 for (i = 0; i < count && alarm_timers[i].name; i++) {
961 if (!strcmp(alarm_timers[i].name, name))
962 break;
965 if (i == count) {
966 fprintf(stderr, "Unknown clock %s\n", name);
967 goto next;
970 if (i < cur)
971 /* Ignore */
972 goto next;
974 /* Swap */
975 tmp = alarm_timers[i];
976 alarm_timers[i] = alarm_timers[cur];
977 alarm_timers[cur] = tmp;
979 cur++;
980 next:
981 name = strtok(NULL, ",");
984 qemu_free(arg);
986 if (cur) {
987 /* Disable remaining timers */
988 for (i = cur; i < count; i++)
989 alarm_timers[i].name = NULL;
990 } else {
991 show_available_alarms();
992 exit(1);
996 #define QEMU_NUM_CLOCKS 3
998 QEMUClock *rt_clock;
999 QEMUClock *vm_clock;
1000 QEMUClock *host_clock;
1002 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
1004 static QEMUClock *qemu_new_clock(int type)
1006 QEMUClock *clock;
1007 clock = qemu_mallocz(sizeof(QEMUClock));
1008 clock->type = type;
1009 return clock;
1012 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1014 QEMUTimer *ts;
1016 ts = qemu_mallocz(sizeof(QEMUTimer));
1017 ts->clock = clock;
1018 ts->cb = cb;
1019 ts->opaque = opaque;
1020 return ts;
1023 void qemu_free_timer(QEMUTimer *ts)
1025 qemu_free(ts);
1028 /* stop a timer, but do not dealloc it */
1029 void qemu_del_timer(QEMUTimer *ts)
1031 QEMUTimer **pt, *t;
1033 /* NOTE: this code must be signal safe because
1034 qemu_timer_expired() can be called from a signal. */
1035 pt = &active_timers[ts->clock->type];
1036 for(;;) {
1037 t = *pt;
1038 if (!t)
1039 break;
1040 if (t == ts) {
1041 *pt = t->next;
1042 break;
1044 pt = &t->next;
1048 /* modify the current timer so that it will be fired when current_time
1049 >= expire_time. The corresponding callback will be called. */
1050 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1052 QEMUTimer **pt, *t;
1054 qemu_del_timer(ts);
1056 /* add the timer in the sorted list */
1057 /* NOTE: this code must be signal safe because
1058 qemu_timer_expired() can be called from a signal. */
1059 pt = &active_timers[ts->clock->type];
1060 for(;;) {
1061 t = *pt;
1062 if (!t)
1063 break;
1064 if (t->expire_time > expire_time)
1065 break;
1066 pt = &t->next;
1068 ts->expire_time = expire_time;
1069 ts->next = *pt;
1070 *pt = ts;
1072 /* Rearm if necessary */
1073 if (pt == &active_timers[ts->clock->type]) {
1074 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1075 qemu_rearm_alarm_timer(alarm_timer);
1077 /* Interrupt execution to force deadline recalculation. */
1078 if (use_icount)
1079 qemu_notify_event();
1083 int qemu_timer_pending(QEMUTimer *ts)
1085 QEMUTimer *t;
1086 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1087 if (t == ts)
1088 return 1;
1090 return 0;
1093 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1095 if (!timer_head)
1096 return 0;
1097 return (timer_head->expire_time <= current_time);
1100 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1102 QEMUTimer *ts;
1104 for(;;) {
1105 ts = *ptimer_head;
1106 if (!ts || ts->expire_time > current_time)
1107 break;
1108 /* remove timer from the list before calling the callback */
1109 *ptimer_head = ts->next;
1110 ts->next = NULL;
1112 /* run the callback (the timer list can be modified) */
1113 ts->cb(ts->opaque);
1117 int64_t qemu_get_clock(QEMUClock *clock)
1119 switch(clock->type) {
1120 case QEMU_CLOCK_REALTIME:
1121 return get_clock() / 1000000;
1122 default:
1123 case QEMU_CLOCK_VIRTUAL:
1124 if (use_icount) {
1125 return cpu_get_icount();
1126 } else {
1127 return cpu_get_clock();
1129 case QEMU_CLOCK_HOST:
1130 return get_clock_realtime();
1134 static void init_clocks(void)
1136 init_get_clock();
1137 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
1138 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
1139 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
1141 rtc_clock = host_clock;
1144 /* save a timer */
1145 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1147 uint64_t expire_time;
1149 if (qemu_timer_pending(ts)) {
1150 expire_time = ts->expire_time;
1151 } else {
1152 expire_time = -1;
1154 qemu_put_be64(f, expire_time);
1157 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1159 uint64_t expire_time;
1161 expire_time = qemu_get_be64(f);
1162 if (expire_time != -1) {
1163 qemu_mod_timer(ts, expire_time);
1164 } else {
1165 qemu_del_timer(ts);
1169 static const VMStateDescription vmstate_timers = {
1170 .name = "timer",
1171 .version_id = 2,
1172 .minimum_version_id = 1,
1173 .minimum_version_id_old = 1,
1174 .fields = (VMStateField []) {
1175 VMSTATE_INT64(cpu_ticks_offset, TimersState),
1176 VMSTATE_INT64(dummy, TimersState),
1177 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1178 VMSTATE_END_OF_LIST()
1182 static void qemu_event_increment(void);
1184 #ifdef _WIN32
1185 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1186 DWORD_PTR dwUser, DWORD_PTR dw1,
1187 DWORD_PTR dw2)
1188 #else
1189 static void host_alarm_handler(int host_signum)
1190 #endif
1192 #if 0
1193 #define DISP_FREQ 1000
1195 static int64_t delta_min = INT64_MAX;
1196 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1197 static int count;
1198 ti = qemu_get_clock(vm_clock);
1199 if (last_clock != 0) {
1200 delta = ti - last_clock;
1201 if (delta < delta_min)
1202 delta_min = delta;
1203 if (delta > delta_max)
1204 delta_max = delta;
1205 delta_cum += delta;
1206 if (++count == DISP_FREQ) {
1207 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1208 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1209 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1210 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1211 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1212 count = 0;
1213 delta_min = INT64_MAX;
1214 delta_max = 0;
1215 delta_cum = 0;
1218 last_clock = ti;
1220 #endif
1221 if (alarm_has_dynticks(alarm_timer) ||
1222 (!use_icount &&
1223 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1224 qemu_get_clock(vm_clock))) ||
1225 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1226 qemu_get_clock(rt_clock)) ||
1227 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1228 qemu_get_clock(host_clock))) {
1229 qemu_event_increment();
1230 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1232 #ifndef CONFIG_IOTHREAD
1233 if (next_cpu) {
1234 /* stop the currently executing cpu because a timer occured */
1235 cpu_exit(next_cpu);
1237 #endif
1238 timer_alarm_pending = 1;
1239 qemu_notify_event();
1243 static int64_t qemu_next_deadline(void)
1245 /* To avoid problems with overflow limit this to 2^32. */
1246 int64_t delta = INT32_MAX;
1248 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1249 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1250 qemu_get_clock(vm_clock);
1252 if (active_timers[QEMU_CLOCK_HOST]) {
1253 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1254 qemu_get_clock(host_clock);
1255 if (hdelta < delta)
1256 delta = hdelta;
1259 if (delta < 0)
1260 delta = 0;
1262 return delta;
1265 #if defined(__linux__)
1266 static uint64_t qemu_next_deadline_dyntick(void)
1268 int64_t delta;
1269 int64_t rtdelta;
1271 if (use_icount)
1272 delta = INT32_MAX;
1273 else
1274 delta = (qemu_next_deadline() + 999) / 1000;
1276 if (active_timers[QEMU_CLOCK_REALTIME]) {
1277 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1278 qemu_get_clock(rt_clock))*1000;
1279 if (rtdelta < delta)
1280 delta = rtdelta;
1283 if (delta < MIN_TIMER_REARM_US)
1284 delta = MIN_TIMER_REARM_US;
1286 return delta;
1288 #endif
1290 #ifndef _WIN32
1292 /* Sets a specific flag */
1293 static int fcntl_setfl(int fd, int flag)
1295 int flags;
1297 flags = fcntl(fd, F_GETFL);
1298 if (flags == -1)
1299 return -errno;
1301 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1302 return -errno;
1304 return 0;
1307 #if defined(__linux__)
1309 #define RTC_FREQ 1024
1311 static void enable_sigio_timer(int fd)
1313 struct sigaction act;
1315 /* timer signal */
1316 sigfillset(&act.sa_mask);
1317 act.sa_flags = 0;
1318 act.sa_handler = host_alarm_handler;
1320 sigaction(SIGIO, &act, NULL);
1321 fcntl_setfl(fd, O_ASYNC);
1322 fcntl(fd, F_SETOWN, getpid());
1325 static int hpet_start_timer(struct qemu_alarm_timer *t)
1327 struct hpet_info info;
1328 int r, fd;
1330 fd = qemu_open("/dev/hpet", O_RDONLY);
1331 if (fd < 0)
1332 return -1;
1334 /* Set frequency */
1335 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1336 if (r < 0) {
1337 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1338 "error, but for better emulation accuracy type:\n"
1339 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1340 goto fail;
1343 /* Check capabilities */
1344 r = ioctl(fd, HPET_INFO, &info);
1345 if (r < 0)
1346 goto fail;
1348 /* Enable periodic mode */
1349 r = ioctl(fd, HPET_EPI, 0);
1350 if (info.hi_flags && (r < 0))
1351 goto fail;
1353 /* Enable interrupt */
1354 r = ioctl(fd, HPET_IE_ON, 0);
1355 if (r < 0)
1356 goto fail;
1358 enable_sigio_timer(fd);
1359 t->priv = (void *)(long)fd;
1361 return 0;
1362 fail:
1363 close(fd);
1364 return -1;
1367 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1369 int fd = (long)t->priv;
1371 close(fd);
1374 static int rtc_start_timer(struct qemu_alarm_timer *t)
1376 int rtc_fd;
1377 unsigned long current_rtc_freq = 0;
1379 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1380 if (rtc_fd < 0)
1381 return -1;
1382 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1383 if (current_rtc_freq != RTC_FREQ &&
1384 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1385 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1386 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1387 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1388 goto fail;
1390 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1391 fail:
1392 close(rtc_fd);
1393 return -1;
1396 enable_sigio_timer(rtc_fd);
1398 t->priv = (void *)(long)rtc_fd;
1400 return 0;
1403 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1405 int rtc_fd = (long)t->priv;
1407 close(rtc_fd);
1410 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1412 struct sigevent ev;
1413 timer_t host_timer;
1414 struct sigaction act;
1416 sigfillset(&act.sa_mask);
1417 act.sa_flags = 0;
1418 act.sa_handler = host_alarm_handler;
1420 sigaction(SIGALRM, &act, NULL);
1423 * Initialize ev struct to 0 to avoid valgrind complaining
1424 * about uninitialized data in timer_create call
1426 memset(&ev, 0, sizeof(ev));
1427 ev.sigev_value.sival_int = 0;
1428 ev.sigev_notify = SIGEV_SIGNAL;
1429 ev.sigev_signo = SIGALRM;
1431 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1432 perror("timer_create");
1434 /* disable dynticks */
1435 fprintf(stderr, "Dynamic Ticks disabled\n");
1437 return -1;
1440 t->priv = (void *)(long)host_timer;
1442 return 0;
1445 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1447 timer_t host_timer = (timer_t)(long)t->priv;
1449 timer_delete(host_timer);
1452 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1454 timer_t host_timer = (timer_t)(long)t->priv;
1455 struct itimerspec timeout;
1456 int64_t nearest_delta_us = INT64_MAX;
1457 int64_t current_us;
1459 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1460 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1461 !active_timers[QEMU_CLOCK_HOST])
1462 return;
1464 nearest_delta_us = qemu_next_deadline_dyntick();
1466 /* check whether a timer is already running */
1467 if (timer_gettime(host_timer, &timeout)) {
1468 perror("gettime");
1469 fprintf(stderr, "Internal timer error: aborting\n");
1470 exit(1);
1472 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1473 if (current_us && current_us <= nearest_delta_us)
1474 return;
1476 timeout.it_interval.tv_sec = 0;
1477 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1478 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1479 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1480 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1481 perror("settime");
1482 fprintf(stderr, "Internal timer error: aborting\n");
1483 exit(1);
1487 #endif /* defined(__linux__) */
1489 static int unix_start_timer(struct qemu_alarm_timer *t)
1491 struct sigaction act;
1492 struct itimerval itv;
1493 int err;
1495 /* timer signal */
1496 sigfillset(&act.sa_mask);
1497 act.sa_flags = 0;
1498 act.sa_handler = host_alarm_handler;
1500 sigaction(SIGALRM, &act, NULL);
1502 itv.it_interval.tv_sec = 0;
1503 /* for i386 kernel 2.6 to get 1 ms */
1504 itv.it_interval.tv_usec = 999;
1505 itv.it_value.tv_sec = 0;
1506 itv.it_value.tv_usec = 10 * 1000;
1508 err = setitimer(ITIMER_REAL, &itv, NULL);
1509 if (err)
1510 return -1;
1512 return 0;
1515 static void unix_stop_timer(struct qemu_alarm_timer *t)
1517 struct itimerval itv;
1519 memset(&itv, 0, sizeof(itv));
1520 setitimer(ITIMER_REAL, &itv, NULL);
1523 #endif /* !defined(_WIN32) */
1526 #ifdef _WIN32
1528 static int win32_start_timer(struct qemu_alarm_timer *t)
1530 TIMECAPS tc;
1531 struct qemu_alarm_win32 *data = t->priv;
1532 UINT flags;
1534 memset(&tc, 0, sizeof(tc));
1535 timeGetDevCaps(&tc, sizeof(tc));
1537 if (data->period < tc.wPeriodMin)
1538 data->period = tc.wPeriodMin;
1540 timeBeginPeriod(data->period);
1542 flags = TIME_CALLBACK_FUNCTION;
1543 if (alarm_has_dynticks(t))
1544 flags |= TIME_ONESHOT;
1545 else
1546 flags |= TIME_PERIODIC;
1548 data->timerId = timeSetEvent(1, // interval (ms)
1549 data->period, // resolution
1550 host_alarm_handler, // function
1551 (DWORD)t, // parameter
1552 flags);
1554 if (!data->timerId) {
1555 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1556 GetLastError());
1557 timeEndPeriod(data->period);
1558 return -1;
1561 return 0;
1564 static void win32_stop_timer(struct qemu_alarm_timer *t)
1566 struct qemu_alarm_win32 *data = t->priv;
1568 timeKillEvent(data->timerId);
1569 timeEndPeriod(data->period);
1572 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1574 struct qemu_alarm_win32 *data = t->priv;
1576 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1577 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1578 !active_timers[QEMU_CLOCK_HOST])
1579 return;
1581 timeKillEvent(data->timerId);
1583 data->timerId = timeSetEvent(1,
1584 data->period,
1585 host_alarm_handler,
1586 (DWORD)t,
1587 TIME_ONESHOT | TIME_PERIODIC);
1589 if (!data->timerId) {
1590 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1591 GetLastError());
1593 timeEndPeriod(data->period);
1594 exit(1);
1598 #endif /* _WIN32 */
1600 static int init_timer_alarm(void)
1602 struct qemu_alarm_timer *t = NULL;
1603 int i, err = -1;
1605 for (i = 0; alarm_timers[i].name; i++) {
1606 t = &alarm_timers[i];
1608 err = t->start(t);
1609 if (!err)
1610 break;
1613 if (err) {
1614 err = -ENOENT;
1615 goto fail;
1618 alarm_timer = t;
1620 return 0;
1622 fail:
1623 return err;
1626 static void quit_timers(void)
1628 alarm_timer->stop(alarm_timer);
1629 alarm_timer = NULL;
1632 /***********************************************************/
1633 /* host time/date access */
1634 void qemu_get_timedate(struct tm *tm, int offset)
1636 time_t ti;
1637 struct tm *ret;
1639 time(&ti);
1640 ti += offset;
1641 if (rtc_date_offset == -1) {
1642 if (rtc_utc)
1643 ret = gmtime(&ti);
1644 else
1645 ret = localtime(&ti);
1646 } else {
1647 ti -= rtc_date_offset;
1648 ret = gmtime(&ti);
1651 memcpy(tm, ret, sizeof(struct tm));
1654 int qemu_timedate_diff(struct tm *tm)
1656 time_t seconds;
1658 if (rtc_date_offset == -1)
1659 if (rtc_utc)
1660 seconds = mktimegm(tm);
1661 else
1662 seconds = mktime(tm);
1663 else
1664 seconds = mktimegm(tm) + rtc_date_offset;
1666 return seconds - time(NULL);
1669 static void configure_rtc_date_offset(const char *startdate, int legacy)
1671 time_t rtc_start_date;
1672 struct tm tm;
1674 if (!strcmp(startdate, "now") && legacy) {
1675 rtc_date_offset = -1;
1676 } else {
1677 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1678 &tm.tm_year,
1679 &tm.tm_mon,
1680 &tm.tm_mday,
1681 &tm.tm_hour,
1682 &tm.tm_min,
1683 &tm.tm_sec) == 6) {
1684 /* OK */
1685 } else if (sscanf(startdate, "%d-%d-%d",
1686 &tm.tm_year,
1687 &tm.tm_mon,
1688 &tm.tm_mday) == 3) {
1689 tm.tm_hour = 0;
1690 tm.tm_min = 0;
1691 tm.tm_sec = 0;
1692 } else {
1693 goto date_fail;
1695 tm.tm_year -= 1900;
1696 tm.tm_mon--;
1697 rtc_start_date = mktimegm(&tm);
1698 if (rtc_start_date == -1) {
1699 date_fail:
1700 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1701 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1702 exit(1);
1704 rtc_date_offset = time(NULL) - rtc_start_date;
1708 static void configure_rtc(QemuOpts *opts)
1710 const char *value;
1712 value = qemu_opt_get(opts, "base");
1713 if (value) {
1714 if (!strcmp(value, "utc")) {
1715 rtc_utc = 1;
1716 } else if (!strcmp(value, "localtime")) {
1717 rtc_utc = 0;
1718 } else {
1719 configure_rtc_date_offset(value, 0);
1722 value = qemu_opt_get(opts, "clock");
1723 if (value) {
1724 if (!strcmp(value, "host")) {
1725 rtc_clock = host_clock;
1726 } else if (!strcmp(value, "vm")) {
1727 rtc_clock = vm_clock;
1728 } else {
1729 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1730 exit(1);
1733 #ifdef CONFIG_TARGET_I386
1734 value = qemu_opt_get(opts, "driftfix");
1735 if (value) {
1736 if (!strcmp(buf, "slew")) {
1737 rtc_td_hack = 1;
1738 } else if (!strcmp(buf, "none")) {
1739 rtc_td_hack = 0;
1740 } else {
1741 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1742 exit(1);
1745 #endif
1748 #ifdef _WIN32
1749 static void socket_cleanup(void)
1751 WSACleanup();
1754 static int socket_init(void)
1756 WSADATA Data;
1757 int ret, err;
1759 ret = WSAStartup(MAKEWORD(2,2), &Data);
1760 if (ret != 0) {
1761 err = WSAGetLastError();
1762 fprintf(stderr, "WSAStartup: %d\n", err);
1763 return -1;
1765 atexit(socket_cleanup);
1766 return 0;
1768 #endif
1770 /***********************************************************/
1771 /* Bluetooth support */
1772 static int nb_hcis;
1773 static int cur_hci;
1774 static struct HCIInfo *hci_table[MAX_NICS];
1776 static struct bt_vlan_s {
1777 struct bt_scatternet_s net;
1778 int id;
1779 struct bt_vlan_s *next;
1780 } *first_bt_vlan;
1782 /* find or alloc a new bluetooth "VLAN" */
1783 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1785 struct bt_vlan_s **pvlan, *vlan;
1786 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1787 if (vlan->id == id)
1788 return &vlan->net;
1790 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1791 vlan->id = id;
1792 pvlan = &first_bt_vlan;
1793 while (*pvlan != NULL)
1794 pvlan = &(*pvlan)->next;
1795 *pvlan = vlan;
1796 return &vlan->net;
1799 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1803 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1805 return -ENOTSUP;
1808 static struct HCIInfo null_hci = {
1809 .cmd_send = null_hci_send,
1810 .sco_send = null_hci_send,
1811 .acl_send = null_hci_send,
1812 .bdaddr_set = null_hci_addr_set,
1815 struct HCIInfo *qemu_next_hci(void)
1817 if (cur_hci == nb_hcis)
1818 return &null_hci;
1820 return hci_table[cur_hci++];
1823 static struct HCIInfo *hci_init(const char *str)
1825 char *endp;
1826 struct bt_scatternet_s *vlan = 0;
1828 if (!strcmp(str, "null"))
1829 /* null */
1830 return &null_hci;
1831 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1832 /* host[:hciN] */
1833 return bt_host_hci(str[4] ? str + 5 : "hci0");
1834 else if (!strncmp(str, "hci", 3)) {
1835 /* hci[,vlan=n] */
1836 if (str[3]) {
1837 if (!strncmp(str + 3, ",vlan=", 6)) {
1838 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1839 if (*endp)
1840 vlan = 0;
1842 } else
1843 vlan = qemu_find_bt_vlan(0);
1844 if (vlan)
1845 return bt_new_hci(vlan);
1848 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1850 return 0;
1853 static int bt_hci_parse(const char *str)
1855 struct HCIInfo *hci;
1856 bdaddr_t bdaddr;
1858 if (nb_hcis >= MAX_NICS) {
1859 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1860 return -1;
1863 hci = hci_init(str);
1864 if (!hci)
1865 return -1;
1867 bdaddr.b[0] = 0x52;
1868 bdaddr.b[1] = 0x54;
1869 bdaddr.b[2] = 0x00;
1870 bdaddr.b[3] = 0x12;
1871 bdaddr.b[4] = 0x34;
1872 bdaddr.b[5] = 0x56 + nb_hcis;
1873 hci->bdaddr_set(hci, bdaddr.b);
1875 hci_table[nb_hcis++] = hci;
1877 return 0;
1880 static void bt_vhci_add(int vlan_id)
1882 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1884 if (!vlan->slave)
1885 fprintf(stderr, "qemu: warning: adding a VHCI to "
1886 "an empty scatternet %i\n", vlan_id);
1888 bt_vhci_init(bt_new_hci(vlan));
1891 static struct bt_device_s *bt_device_add(const char *opt)
1893 struct bt_scatternet_s *vlan;
1894 int vlan_id = 0;
1895 char *endp = strstr(opt, ",vlan=");
1896 int len = (endp ? endp - opt : strlen(opt)) + 1;
1897 char devname[10];
1899 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1901 if (endp) {
1902 vlan_id = strtol(endp + 6, &endp, 0);
1903 if (*endp) {
1904 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1905 return 0;
1909 vlan = qemu_find_bt_vlan(vlan_id);
1911 if (!vlan->slave)
1912 fprintf(stderr, "qemu: warning: adding a slave device to "
1913 "an empty scatternet %i\n", vlan_id);
1915 if (!strcmp(devname, "keyboard"))
1916 return bt_keyboard_init(vlan);
1918 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1919 return 0;
1922 static int bt_parse(const char *opt)
1924 const char *endp, *p;
1925 int vlan;
1927 if (strstart(opt, "hci", &endp)) {
1928 if (!*endp || *endp == ',') {
1929 if (*endp)
1930 if (!strstart(endp, ",vlan=", 0))
1931 opt = endp + 1;
1933 return bt_hci_parse(opt);
1935 } else if (strstart(opt, "vhci", &endp)) {
1936 if (!*endp || *endp == ',') {
1937 if (*endp) {
1938 if (strstart(endp, ",vlan=", &p)) {
1939 vlan = strtol(p, (char **) &endp, 0);
1940 if (*endp) {
1941 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1942 return 1;
1944 } else {
1945 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1946 return 1;
1948 } else
1949 vlan = 0;
1951 bt_vhci_add(vlan);
1952 return 0;
1954 } else if (strstart(opt, "device:", &endp))
1955 return !bt_device_add(endp);
1957 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1958 return 1;
1961 /***********************************************************/
1962 /* QEMU Block devices */
1964 #define HD_ALIAS "index=%d,media=disk"
1965 #define CDROM_ALIAS "index=2,media=cdrom"
1966 #define FD_ALIAS "index=%d,if=floppy"
1967 #define PFLASH_ALIAS "if=pflash"
1968 #define MTD_ALIAS "if=mtd"
1969 #define SD_ALIAS "index=0,if=sd"
1971 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1973 va_list ap;
1974 char optstr[1024];
1975 QemuOpts *opts;
1977 va_start(ap, fmt);
1978 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1979 va_end(ap);
1981 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1982 if (!opts) {
1983 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1984 __FUNCTION__, optstr);
1985 return NULL;
1987 if (file)
1988 qemu_opt_set(opts, "file", file);
1989 return opts;
1992 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1994 DriveInfo *dinfo;
1996 /* seek interface, bus and unit */
1998 QTAILQ_FOREACH(dinfo, &drives, next) {
1999 if (dinfo->type == type &&
2000 dinfo->bus == bus &&
2001 dinfo->unit == unit)
2002 return dinfo;
2005 return NULL;
2008 DriveInfo *drive_get_by_id(const char *id)
2010 DriveInfo *dinfo;
2012 QTAILQ_FOREACH(dinfo, &drives, next) {
2013 if (strcmp(id, dinfo->id))
2014 continue;
2015 return dinfo;
2017 return NULL;
2020 int drive_get_max_bus(BlockInterfaceType type)
2022 int max_bus;
2023 DriveInfo *dinfo;
2025 max_bus = -1;
2026 QTAILQ_FOREACH(dinfo, &drives, next) {
2027 if(dinfo->type == type &&
2028 dinfo->bus > max_bus)
2029 max_bus = dinfo->bus;
2031 return max_bus;
2034 const char *drive_get_serial(BlockDriverState *bdrv)
2036 DriveInfo *dinfo;
2038 QTAILQ_FOREACH(dinfo, &drives, next) {
2039 if (dinfo->bdrv == bdrv)
2040 return dinfo->serial;
2043 return "\0";
2046 BlockInterfaceErrorAction drive_get_on_error(
2047 BlockDriverState *bdrv, int is_read)
2049 DriveInfo *dinfo;
2051 QTAILQ_FOREACH(dinfo, &drives, next) {
2052 if (dinfo->bdrv == bdrv)
2053 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
2056 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
2059 static void bdrv_format_print(void *opaque, const char *name)
2061 fprintf(stderr, " %s", name);
2064 void drive_uninit(DriveInfo *dinfo)
2066 qemu_opts_del(dinfo->opts);
2067 bdrv_delete(dinfo->bdrv);
2068 QTAILQ_REMOVE(&drives, dinfo, next);
2069 qemu_free(dinfo);
2072 static int parse_block_error_action(const char *buf, int is_read)
2074 if (!strcmp(buf, "ignore")) {
2075 return BLOCK_ERR_IGNORE;
2076 } else if (!is_read && !strcmp(buf, "enospc")) {
2077 return BLOCK_ERR_STOP_ENOSPC;
2078 } else if (!strcmp(buf, "stop")) {
2079 return BLOCK_ERR_STOP_ANY;
2080 } else if (!strcmp(buf, "report")) {
2081 return BLOCK_ERR_REPORT;
2082 } else {
2083 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
2084 buf, is_read ? "read" : "write");
2085 return -1;
2089 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
2090 int *fatal_error)
2092 const char *buf;
2093 const char *file = NULL;
2094 char devname[128];
2095 const char *serial;
2096 const char *mediastr = "";
2097 BlockInterfaceType type;
2098 enum { MEDIA_DISK, MEDIA_CDROM } media;
2099 int bus_id, unit_id;
2100 int cyls, heads, secs, translation;
2101 BlockDriver *drv = NULL;
2102 QEMUMachine *machine = opaque;
2103 int max_devs;
2104 int index;
2105 int cache;
2106 int aio = 0;
2107 int ro = 0;
2108 int bdrv_flags;
2109 int on_read_error, on_write_error;
2110 const char *devaddr;
2111 DriveInfo *dinfo;
2112 int snapshot = 0;
2114 *fatal_error = 1;
2116 translation = BIOS_ATA_TRANSLATION_AUTO;
2117 cache = 1;
2119 if (machine && machine->use_scsi) {
2120 type = IF_SCSI;
2121 max_devs = MAX_SCSI_DEVS;
2122 pstrcpy(devname, sizeof(devname), "scsi");
2123 } else {
2124 type = IF_IDE;
2125 max_devs = MAX_IDE_DEVS;
2126 pstrcpy(devname, sizeof(devname), "ide");
2128 media = MEDIA_DISK;
2130 /* extract parameters */
2131 bus_id = qemu_opt_get_number(opts, "bus", 0);
2132 unit_id = qemu_opt_get_number(opts, "unit", -1);
2133 index = qemu_opt_get_number(opts, "index", -1);
2135 cyls = qemu_opt_get_number(opts, "cyls", 0);
2136 heads = qemu_opt_get_number(opts, "heads", 0);
2137 secs = qemu_opt_get_number(opts, "secs", 0);
2139 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2140 ro = qemu_opt_get_bool(opts, "readonly", 0);
2142 file = qemu_opt_get(opts, "file");
2143 serial = qemu_opt_get(opts, "serial");
2145 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2146 pstrcpy(devname, sizeof(devname), buf);
2147 if (!strcmp(buf, "ide")) {
2148 type = IF_IDE;
2149 max_devs = MAX_IDE_DEVS;
2150 } else if (!strcmp(buf, "scsi")) {
2151 type = IF_SCSI;
2152 max_devs = MAX_SCSI_DEVS;
2153 } else if (!strcmp(buf, "floppy")) {
2154 type = IF_FLOPPY;
2155 max_devs = 0;
2156 } else if (!strcmp(buf, "pflash")) {
2157 type = IF_PFLASH;
2158 max_devs = 0;
2159 } else if (!strcmp(buf, "mtd")) {
2160 type = IF_MTD;
2161 max_devs = 0;
2162 } else if (!strcmp(buf, "sd")) {
2163 type = IF_SD;
2164 max_devs = 0;
2165 } else if (!strcmp(buf, "virtio")) {
2166 type = IF_VIRTIO;
2167 max_devs = 0;
2168 } else if (!strcmp(buf, "xen")) {
2169 type = IF_XEN;
2170 max_devs = 0;
2171 } else if (!strcmp(buf, "none")) {
2172 type = IF_NONE;
2173 max_devs = 0;
2174 } else {
2175 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2176 return NULL;
2180 if (cyls || heads || secs) {
2181 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2182 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2183 return NULL;
2185 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2186 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2187 return NULL;
2189 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2190 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2191 return NULL;
2195 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2196 if (!cyls) {
2197 fprintf(stderr,
2198 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2199 buf);
2200 return NULL;
2202 if (!strcmp(buf, "none"))
2203 translation = BIOS_ATA_TRANSLATION_NONE;
2204 else if (!strcmp(buf, "lba"))
2205 translation = BIOS_ATA_TRANSLATION_LBA;
2206 else if (!strcmp(buf, "auto"))
2207 translation = BIOS_ATA_TRANSLATION_AUTO;
2208 else {
2209 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2210 return NULL;
2214 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2215 if (!strcmp(buf, "disk")) {
2216 media = MEDIA_DISK;
2217 } else if (!strcmp(buf, "cdrom")) {
2218 if (cyls || secs || heads) {
2219 fprintf(stderr,
2220 "qemu: '%s' invalid physical CHS format\n", buf);
2221 return NULL;
2223 media = MEDIA_CDROM;
2224 } else {
2225 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2226 return NULL;
2230 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2231 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2232 cache = 0;
2233 else if (!strcmp(buf, "writethrough"))
2234 cache = 1;
2235 else if (!strcmp(buf, "writeback"))
2236 cache = 2;
2237 else {
2238 fprintf(stderr, "qemu: invalid cache option\n");
2239 return NULL;
2243 #ifdef CONFIG_LINUX_AIO
2244 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2245 if (!strcmp(buf, "threads"))
2246 aio = 0;
2247 else if (!strcmp(buf, "native"))
2248 aio = 1;
2249 else {
2250 fprintf(stderr, "qemu: invalid aio option\n");
2251 return NULL;
2254 #endif
2256 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2257 if (strcmp(buf, "?") == 0) {
2258 fprintf(stderr, "qemu: Supported formats:");
2259 bdrv_iterate_format(bdrv_format_print, NULL);
2260 fprintf(stderr, "\n");
2261 return NULL;
2263 drv = bdrv_find_whitelisted_format(buf);
2264 if (!drv) {
2265 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2266 return NULL;
2270 on_write_error = BLOCK_ERR_STOP_ENOSPC;
2271 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2272 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2273 fprintf(stderr, "werror is no supported by this format\n");
2274 return NULL;
2277 on_write_error = parse_block_error_action(buf, 0);
2278 if (on_write_error < 0) {
2279 return NULL;
2283 on_read_error = BLOCK_ERR_REPORT;
2284 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2285 if (type != IF_IDE && type != IF_VIRTIO) {
2286 fprintf(stderr, "rerror is no supported by this format\n");
2287 return NULL;
2290 on_read_error = parse_block_error_action(buf, 1);
2291 if (on_read_error < 0) {
2292 return NULL;
2296 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2297 if (type != IF_VIRTIO) {
2298 fprintf(stderr, "addr is not supported\n");
2299 return NULL;
2303 /* compute bus and unit according index */
2305 if (index != -1) {
2306 if (bus_id != 0 || unit_id != -1) {
2307 fprintf(stderr,
2308 "qemu: index cannot be used with bus and unit\n");
2309 return NULL;
2311 if (max_devs == 0)
2313 unit_id = index;
2314 bus_id = 0;
2315 } else {
2316 unit_id = index % max_devs;
2317 bus_id = index / max_devs;
2321 /* if user doesn't specify a unit_id,
2322 * try to find the first free
2325 if (unit_id == -1) {
2326 unit_id = 0;
2327 while (drive_get(type, bus_id, unit_id) != NULL) {
2328 unit_id++;
2329 if (max_devs && unit_id >= max_devs) {
2330 unit_id -= max_devs;
2331 bus_id++;
2336 /* check unit id */
2338 if (max_devs && unit_id >= max_devs) {
2339 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2340 unit_id, max_devs - 1);
2341 return NULL;
2345 * ignore multiple definitions
2348 if (drive_get(type, bus_id, unit_id) != NULL) {
2349 *fatal_error = 0;
2350 return NULL;
2353 /* init */
2355 dinfo = qemu_mallocz(sizeof(*dinfo));
2356 if ((buf = qemu_opts_id(opts)) != NULL) {
2357 dinfo->id = qemu_strdup(buf);
2358 } else {
2359 /* no id supplied -> create one */
2360 dinfo->id = qemu_mallocz(32);
2361 if (type == IF_IDE || type == IF_SCSI)
2362 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2363 if (max_devs)
2364 snprintf(dinfo->id, 32, "%s%i%s%i",
2365 devname, bus_id, mediastr, unit_id);
2366 else
2367 snprintf(dinfo->id, 32, "%s%s%i",
2368 devname, mediastr, unit_id);
2370 dinfo->bdrv = bdrv_new(dinfo->id);
2371 dinfo->devaddr = devaddr;
2372 dinfo->type = type;
2373 dinfo->bus = bus_id;
2374 dinfo->unit = unit_id;
2375 dinfo->on_read_error = on_read_error;
2376 dinfo->on_write_error = on_write_error;
2377 dinfo->opts = opts;
2378 if (serial)
2379 strncpy(dinfo->serial, serial, sizeof(serial));
2380 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2382 switch(type) {
2383 case IF_IDE:
2384 case IF_SCSI:
2385 case IF_XEN:
2386 case IF_NONE:
2387 switch(media) {
2388 case MEDIA_DISK:
2389 if (cyls != 0) {
2390 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2391 bdrv_set_translation_hint(dinfo->bdrv, translation);
2393 break;
2394 case MEDIA_CDROM:
2395 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2396 break;
2398 break;
2399 case IF_SD:
2400 /* FIXME: This isn't really a floppy, but it's a reasonable
2401 approximation. */
2402 case IF_FLOPPY:
2403 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2404 break;
2405 case IF_PFLASH:
2406 case IF_MTD:
2407 break;
2408 case IF_VIRTIO:
2409 /* add virtio block device */
2410 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2411 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2412 qemu_opt_set(opts, "drive", dinfo->id);
2413 if (devaddr)
2414 qemu_opt_set(opts, "addr", devaddr);
2415 break;
2416 case IF_COUNT:
2417 abort();
2419 if (!file) {
2420 *fatal_error = 0;
2421 return NULL;
2423 bdrv_flags = 0;
2424 if (snapshot) {
2425 bdrv_flags |= BDRV_O_SNAPSHOT;
2426 cache = 2; /* always use write-back with snapshot */
2428 if (cache == 0) /* no caching */
2429 bdrv_flags |= BDRV_O_NOCACHE;
2430 else if (cache == 2) /* write-back */
2431 bdrv_flags |= BDRV_O_CACHE_WB;
2433 if (aio == 1) {
2434 bdrv_flags |= BDRV_O_NATIVE_AIO;
2435 } else {
2436 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2439 if (ro == 1) {
2440 if (type == IF_IDE) {
2441 fprintf(stderr, "qemu: readonly flag not supported for drive with ide interface\n");
2442 return NULL;
2444 (void)bdrv_set_read_only(dinfo->bdrv, 1);
2447 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2448 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2449 file, strerror(errno));
2450 return NULL;
2453 if (bdrv_key_required(dinfo->bdrv))
2454 autostart = 0;
2455 *fatal_error = 0;
2456 return dinfo;
2459 static int drive_init_func(QemuOpts *opts, void *opaque)
2461 QEMUMachine *machine = opaque;
2462 int fatal_error = 0;
2464 if (drive_init(opts, machine, &fatal_error) == NULL) {
2465 if (fatal_error)
2466 return 1;
2468 return 0;
2471 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2473 if (NULL == qemu_opt_get(opts, "snapshot")) {
2474 qemu_opt_set(opts, "snapshot", "on");
2476 return 0;
2479 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2481 boot_set_handler = func;
2482 boot_set_opaque = opaque;
2485 int qemu_boot_set(const char *boot_devices)
2487 if (!boot_set_handler) {
2488 return -EINVAL;
2490 return boot_set_handler(boot_set_opaque, boot_devices);
2493 static int parse_bootdevices(char *devices)
2495 /* We just do some generic consistency checks */
2496 const char *p;
2497 int bitmap = 0;
2499 for (p = devices; *p != '\0'; p++) {
2500 /* Allowed boot devices are:
2501 * a-b: floppy disk drives
2502 * c-f: IDE disk drives
2503 * g-m: machine implementation dependant drives
2504 * n-p: network devices
2505 * It's up to each machine implementation to check if the given boot
2506 * devices match the actual hardware implementation and firmware
2507 * features.
2509 if (*p < 'a' || *p > 'p') {
2510 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2511 exit(1);
2513 if (bitmap & (1 << (*p - 'a'))) {
2514 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2515 exit(1);
2517 bitmap |= 1 << (*p - 'a');
2519 return bitmap;
2522 static void restore_boot_devices(void *opaque)
2524 char *standard_boot_devices = opaque;
2526 qemu_boot_set(standard_boot_devices);
2528 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2529 qemu_free(standard_boot_devices);
2532 static void numa_add(const char *optarg)
2534 char option[128];
2535 char *endptr;
2536 unsigned long long value, endvalue;
2537 int nodenr;
2539 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2540 if (!strcmp(option, "node")) {
2541 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2542 nodenr = nb_numa_nodes;
2543 } else {
2544 nodenr = strtoull(option, NULL, 10);
2547 if (get_param_value(option, 128, "mem", optarg) == 0) {
2548 node_mem[nodenr] = 0;
2549 } else {
2550 value = strtoull(option, &endptr, 0);
2551 switch (*endptr) {
2552 case 0: case 'M': case 'm':
2553 value <<= 20;
2554 break;
2555 case 'G': case 'g':
2556 value <<= 30;
2557 break;
2559 node_mem[nodenr] = value;
2561 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2562 node_cpumask[nodenr] = 0;
2563 } else {
2564 value = strtoull(option, &endptr, 10);
2565 if (value >= 64) {
2566 value = 63;
2567 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2568 } else {
2569 if (*endptr == '-') {
2570 endvalue = strtoull(endptr+1, &endptr, 10);
2571 if (endvalue >= 63) {
2572 endvalue = 62;
2573 fprintf(stderr,
2574 "only 63 CPUs in NUMA mode supported.\n");
2576 value = (1 << (endvalue + 1)) - (1 << value);
2577 } else {
2578 value = 1 << value;
2581 node_cpumask[nodenr] = value;
2583 nb_numa_nodes++;
2585 return;
2588 static void smp_parse(const char *optarg)
2590 int smp, sockets = 0, threads = 0, cores = 0;
2591 char *endptr;
2592 char option[128];
2594 smp = strtoul(optarg, &endptr, 10);
2595 if (endptr != optarg) {
2596 if (*endptr == ',') {
2597 endptr++;
2600 if (get_param_value(option, 128, "sockets", endptr) != 0)
2601 sockets = strtoull(option, NULL, 10);
2602 if (get_param_value(option, 128, "cores", endptr) != 0)
2603 cores = strtoull(option, NULL, 10);
2604 if (get_param_value(option, 128, "threads", endptr) != 0)
2605 threads = strtoull(option, NULL, 10);
2606 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2607 max_cpus = strtoull(option, NULL, 10);
2609 /* compute missing values, prefer sockets over cores over threads */
2610 if (smp == 0 || sockets == 0) {
2611 sockets = sockets > 0 ? sockets : 1;
2612 cores = cores > 0 ? cores : 1;
2613 threads = threads > 0 ? threads : 1;
2614 if (smp == 0) {
2615 smp = cores * threads * sockets;
2616 } else {
2617 sockets = smp / (cores * threads);
2619 } else {
2620 if (cores == 0) {
2621 threads = threads > 0 ? threads : 1;
2622 cores = smp / (sockets * threads);
2623 } else {
2624 if (sockets == 0) {
2625 sockets = smp / (cores * threads);
2626 } else {
2627 threads = smp / (cores * sockets);
2631 smp_cpus = smp;
2632 smp_cores = cores > 0 ? cores : 1;
2633 smp_threads = threads > 0 ? threads : 1;
2634 if (max_cpus == 0)
2635 max_cpus = smp_cpus;
2638 /***********************************************************/
2639 /* USB devices */
2641 static int usb_device_add(const char *devname, int is_hotplug)
2643 const char *p;
2644 USBDevice *dev = NULL;
2646 if (!usb_enabled)
2647 return -1;
2649 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2650 dev = usbdevice_create(devname);
2651 if (dev)
2652 goto done;
2654 /* the other ones */
2655 if (strstart(devname, "host:", &p)) {
2656 dev = usb_host_device_open(p);
2657 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2658 dev = usb_bt_init(devname[2] ? hci_init(p) :
2659 bt_new_hci(qemu_find_bt_vlan(0)));
2660 } else {
2661 return -1;
2663 if (!dev)
2664 return -1;
2666 done:
2667 return 0;
2670 static int usb_device_del(const char *devname)
2672 int bus_num, addr;
2673 const char *p;
2675 if (strstart(devname, "host:", &p))
2676 return usb_host_device_close(p);
2678 if (!usb_enabled)
2679 return -1;
2681 p = strchr(devname, '.');
2682 if (!p)
2683 return -1;
2684 bus_num = strtoul(devname, NULL, 0);
2685 addr = strtoul(p + 1, NULL, 0);
2687 return usb_device_delete_addr(bus_num, addr);
2690 static int usb_parse(const char *cmdline)
2692 return usb_device_add(cmdline, 0);
2695 void do_usb_add(Monitor *mon, const QDict *qdict)
2697 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2700 void do_usb_del(Monitor *mon, const QDict *qdict)
2702 usb_device_del(qdict_get_str(qdict, "devname"));
2705 /***********************************************************/
2706 /* PCMCIA/Cardbus */
2708 static struct pcmcia_socket_entry_s {
2709 PCMCIASocket *socket;
2710 struct pcmcia_socket_entry_s *next;
2711 } *pcmcia_sockets = 0;
2713 void pcmcia_socket_register(PCMCIASocket *socket)
2715 struct pcmcia_socket_entry_s *entry;
2717 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2718 entry->socket = socket;
2719 entry->next = pcmcia_sockets;
2720 pcmcia_sockets = entry;
2723 void pcmcia_socket_unregister(PCMCIASocket *socket)
2725 struct pcmcia_socket_entry_s *entry, **ptr;
2727 ptr = &pcmcia_sockets;
2728 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2729 if (entry->socket == socket) {
2730 *ptr = entry->next;
2731 qemu_free(entry);
2735 void pcmcia_info(Monitor *mon)
2737 struct pcmcia_socket_entry_s *iter;
2739 if (!pcmcia_sockets)
2740 monitor_printf(mon, "No PCMCIA sockets\n");
2742 for (iter = pcmcia_sockets; iter; iter = iter->next)
2743 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2744 iter->socket->attached ? iter->socket->card_string :
2745 "Empty");
2748 /***********************************************************/
2749 /* register display */
2751 struct DisplayAllocator default_allocator = {
2752 defaultallocator_create_displaysurface,
2753 defaultallocator_resize_displaysurface,
2754 defaultallocator_free_displaysurface
2757 void register_displaystate(DisplayState *ds)
2759 DisplayState **s;
2760 s = &display_state;
2761 while (*s != NULL)
2762 s = &(*s)->next;
2763 ds->next = NULL;
2764 *s = ds;
2767 DisplayState *get_displaystate(void)
2769 return display_state;
2772 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2774 if(ds->allocator == &default_allocator) ds->allocator = da;
2775 return ds->allocator;
2778 /* dumb display */
2780 static void dumb_display_init(void)
2782 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2783 ds->allocator = &default_allocator;
2784 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2785 register_displaystate(ds);
2788 /***********************************************************/
2789 /* I/O handling */
2791 typedef struct IOHandlerRecord {
2792 int fd;
2793 IOCanRWHandler *fd_read_poll;
2794 IOHandler *fd_read;
2795 IOHandler *fd_write;
2796 int deleted;
2797 void *opaque;
2798 /* temporary data */
2799 struct pollfd *ufd;
2800 struct IOHandlerRecord *next;
2801 } IOHandlerRecord;
2803 static IOHandlerRecord *first_io_handler;
2805 /* XXX: fd_read_poll should be suppressed, but an API change is
2806 necessary in the character devices to suppress fd_can_read(). */
2807 int qemu_set_fd_handler2(int fd,
2808 IOCanRWHandler *fd_read_poll,
2809 IOHandler *fd_read,
2810 IOHandler *fd_write,
2811 void *opaque)
2813 IOHandlerRecord **pioh, *ioh;
2815 if (!fd_read && !fd_write) {
2816 pioh = &first_io_handler;
2817 for(;;) {
2818 ioh = *pioh;
2819 if (ioh == NULL)
2820 break;
2821 if (ioh->fd == fd) {
2822 ioh->deleted = 1;
2823 break;
2825 pioh = &ioh->next;
2827 } else {
2828 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2829 if (ioh->fd == fd)
2830 goto found;
2832 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2833 ioh->next = first_io_handler;
2834 first_io_handler = ioh;
2835 found:
2836 ioh->fd = fd;
2837 ioh->fd_read_poll = fd_read_poll;
2838 ioh->fd_read = fd_read;
2839 ioh->fd_write = fd_write;
2840 ioh->opaque = opaque;
2841 ioh->deleted = 0;
2843 return 0;
2846 int qemu_set_fd_handler(int fd,
2847 IOHandler *fd_read,
2848 IOHandler *fd_write,
2849 void *opaque)
2851 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2854 #ifdef _WIN32
2855 /***********************************************************/
2856 /* Polling handling */
2858 typedef struct PollingEntry {
2859 PollingFunc *func;
2860 void *opaque;
2861 struct PollingEntry *next;
2862 } PollingEntry;
2864 static PollingEntry *first_polling_entry;
2866 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2868 PollingEntry **ppe, *pe;
2869 pe = qemu_mallocz(sizeof(PollingEntry));
2870 pe->func = func;
2871 pe->opaque = opaque;
2872 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2873 *ppe = pe;
2874 return 0;
2877 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2879 PollingEntry **ppe, *pe;
2880 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2881 pe = *ppe;
2882 if (pe->func == func && pe->opaque == opaque) {
2883 *ppe = pe->next;
2884 qemu_free(pe);
2885 break;
2890 /***********************************************************/
2891 /* Wait objects support */
2892 typedef struct WaitObjects {
2893 int num;
2894 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2895 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2896 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2897 } WaitObjects;
2899 static WaitObjects wait_objects = {0};
2901 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2903 WaitObjects *w = &wait_objects;
2905 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2906 return -1;
2907 w->events[w->num] = handle;
2908 w->func[w->num] = func;
2909 w->opaque[w->num] = opaque;
2910 w->num++;
2911 return 0;
2914 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2916 int i, found;
2917 WaitObjects *w = &wait_objects;
2919 found = 0;
2920 for (i = 0; i < w->num; i++) {
2921 if (w->events[i] == handle)
2922 found = 1;
2923 if (found) {
2924 w->events[i] = w->events[i + 1];
2925 w->func[i] = w->func[i + 1];
2926 w->opaque[i] = w->opaque[i + 1];
2929 if (found)
2930 w->num--;
2932 #endif
2934 /***********************************************************/
2935 /* ram save/restore */
2937 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2938 #define RAM_SAVE_FLAG_COMPRESS 0x02
2939 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2940 #define RAM_SAVE_FLAG_PAGE 0x08
2941 #define RAM_SAVE_FLAG_EOS 0x10
2943 static int is_dup_page(uint8_t *page, uint8_t ch)
2945 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2946 uint32_t *array = (uint32_t *)page;
2947 int i;
2949 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2950 if (array[i] != val)
2951 return 0;
2954 return 1;
2957 static int ram_save_block(QEMUFile *f)
2959 static ram_addr_t current_addr = 0;
2960 ram_addr_t saved_addr = current_addr;
2961 ram_addr_t addr = 0;
2962 int found = 0;
2964 while (addr < last_ram_offset) {
2965 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2966 uint8_t *p;
2968 cpu_physical_memory_reset_dirty(current_addr,
2969 current_addr + TARGET_PAGE_SIZE,
2970 MIGRATION_DIRTY_FLAG);
2972 p = qemu_get_ram_ptr(current_addr);
2974 if (is_dup_page(p, *p)) {
2975 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2976 qemu_put_byte(f, *p);
2977 } else {
2978 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2979 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2982 found = 1;
2983 break;
2985 addr += TARGET_PAGE_SIZE;
2986 current_addr = (saved_addr + addr) % last_ram_offset;
2989 return found;
2992 static uint64_t bytes_transferred;
2994 static ram_addr_t ram_save_remaining(void)
2996 ram_addr_t addr;
2997 ram_addr_t count = 0;
2999 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3000 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3001 count++;
3004 return count;
3007 uint64_t ram_bytes_remaining(void)
3009 return ram_save_remaining() * TARGET_PAGE_SIZE;
3012 uint64_t ram_bytes_transferred(void)
3014 return bytes_transferred;
3017 uint64_t ram_bytes_total(void)
3019 return last_ram_offset;
3022 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
3024 ram_addr_t addr;
3025 uint64_t bytes_transferred_last;
3026 double bwidth = 0;
3027 uint64_t expected_time = 0;
3029 if (stage < 0) {
3030 cpu_physical_memory_set_dirty_tracking(0);
3031 return 0;
3034 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3035 qemu_file_set_error(f);
3036 return 0;
3039 if (stage == 1) {
3040 bytes_transferred = 0;
3042 /* Make sure all dirty bits are set */
3043 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3044 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3045 cpu_physical_memory_set_dirty(addr);
3048 /* Enable dirty memory tracking */
3049 cpu_physical_memory_set_dirty_tracking(1);
3051 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3054 bytes_transferred_last = bytes_transferred;
3055 bwidth = get_clock();
3057 while (!qemu_file_rate_limit(f)) {
3058 int ret;
3060 ret = ram_save_block(f);
3061 bytes_transferred += ret * TARGET_PAGE_SIZE;
3062 if (ret == 0) /* no more blocks */
3063 break;
3066 bwidth = get_clock() - bwidth;
3067 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3069 /* if we haven't transferred anything this round, force expected_time to a
3070 * a very high value, but without crashing */
3071 if (bwidth == 0)
3072 bwidth = 0.000001;
3074 /* try transferring iterative blocks of memory */
3075 if (stage == 3) {
3076 /* flush all remaining blocks regardless of rate limiting */
3077 while (ram_save_block(f) != 0) {
3078 bytes_transferred += TARGET_PAGE_SIZE;
3080 cpu_physical_memory_set_dirty_tracking(0);
3083 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3085 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3087 return (stage == 2) && (expected_time <= migrate_max_downtime());
3090 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3092 ram_addr_t addr;
3093 int flags;
3095 if (version_id != 3)
3096 return -EINVAL;
3098 do {
3099 addr = qemu_get_be64(f);
3101 flags = addr & ~TARGET_PAGE_MASK;
3102 addr &= TARGET_PAGE_MASK;
3104 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3105 if (addr != last_ram_offset)
3106 return -EINVAL;
3109 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3110 uint8_t ch = qemu_get_byte(f);
3111 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3112 #ifndef _WIN32
3113 if (ch == 0 &&
3114 (!kvm_enabled() || kvm_has_sync_mmu())) {
3115 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3117 #endif
3118 } else if (flags & RAM_SAVE_FLAG_PAGE) {
3119 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3121 if (qemu_file_has_error(f)) {
3122 return -EIO;
3124 } while (!(flags & RAM_SAVE_FLAG_EOS));
3126 return 0;
3129 void qemu_service_io(void)
3131 qemu_notify_event();
3134 /***********************************************************/
3135 /* machine registration */
3137 static QEMUMachine *first_machine = NULL;
3138 QEMUMachine *current_machine = NULL;
3140 int qemu_register_machine(QEMUMachine *m)
3142 QEMUMachine **pm;
3143 pm = &first_machine;
3144 while (*pm != NULL)
3145 pm = &(*pm)->next;
3146 m->next = NULL;
3147 *pm = m;
3148 return 0;
3151 static QEMUMachine *find_machine(const char *name)
3153 QEMUMachine *m;
3155 for(m = first_machine; m != NULL; m = m->next) {
3156 if (!strcmp(m->name, name))
3157 return m;
3158 if (m->alias && !strcmp(m->alias, name))
3159 return m;
3161 return NULL;
3164 static QEMUMachine *find_default_machine(void)
3166 QEMUMachine *m;
3168 for(m = first_machine; m != NULL; m = m->next) {
3169 if (m->is_default) {
3170 return m;
3173 return NULL;
3176 /***********************************************************/
3177 /* main execution loop */
3179 static void gui_update(void *opaque)
3181 uint64_t interval = GUI_REFRESH_INTERVAL;
3182 DisplayState *ds = opaque;
3183 DisplayChangeListener *dcl = ds->listeners;
3185 dpy_refresh(ds);
3187 while (dcl != NULL) {
3188 if (dcl->gui_timer_interval &&
3189 dcl->gui_timer_interval < interval)
3190 interval = dcl->gui_timer_interval;
3191 dcl = dcl->next;
3193 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3196 static void nographic_update(void *opaque)
3198 uint64_t interval = GUI_REFRESH_INTERVAL;
3200 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3203 struct vm_change_state_entry {
3204 VMChangeStateHandler *cb;
3205 void *opaque;
3206 QLIST_ENTRY (vm_change_state_entry) entries;
3209 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3211 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3212 void *opaque)
3214 VMChangeStateEntry *e;
3216 e = qemu_mallocz(sizeof (*e));
3218 e->cb = cb;
3219 e->opaque = opaque;
3220 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3221 return e;
3224 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3226 QLIST_REMOVE (e, entries);
3227 qemu_free (e);
3230 static void vm_state_notify(int running, int reason)
3232 VMChangeStateEntry *e;
3234 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3235 e->cb(e->opaque, running, reason);
3239 static void resume_all_vcpus(void);
3240 static void pause_all_vcpus(void);
3242 void vm_start(void)
3244 if (!vm_running) {
3245 cpu_enable_ticks();
3246 vm_running = 1;
3247 vm_state_notify(1, 0);
3248 qemu_rearm_alarm_timer(alarm_timer);
3249 resume_all_vcpus();
3253 /* reset/shutdown handler */
3255 typedef struct QEMUResetEntry {
3256 QTAILQ_ENTRY(QEMUResetEntry) entry;
3257 QEMUResetHandler *func;
3258 void *opaque;
3259 } QEMUResetEntry;
3261 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3262 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3263 static int reset_requested;
3264 static int shutdown_requested;
3265 static int powerdown_requested;
3266 static int debug_requested;
3267 static int vmstop_requested;
3269 int qemu_shutdown_requested(void)
3271 int r = shutdown_requested;
3272 shutdown_requested = 0;
3273 return r;
3276 int qemu_reset_requested(void)
3278 int r = reset_requested;
3279 reset_requested = 0;
3280 return r;
3283 int qemu_powerdown_requested(void)
3285 int r = powerdown_requested;
3286 powerdown_requested = 0;
3287 return r;
3290 static int qemu_debug_requested(void)
3292 int r = debug_requested;
3293 debug_requested = 0;
3294 return r;
3297 static int qemu_vmstop_requested(void)
3299 int r = vmstop_requested;
3300 vmstop_requested = 0;
3301 return r;
3304 static void do_vm_stop(int reason)
3306 if (vm_running) {
3307 cpu_disable_ticks();
3308 vm_running = 0;
3309 pause_all_vcpus();
3310 vm_state_notify(0, reason);
3314 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3316 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3318 re->func = func;
3319 re->opaque = opaque;
3320 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3323 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3325 QEMUResetEntry *re;
3327 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3328 if (re->func == func && re->opaque == opaque) {
3329 QTAILQ_REMOVE(&reset_handlers, re, entry);
3330 qemu_free(re);
3331 return;
3336 void qemu_system_reset(void)
3338 QEMUResetEntry *re, *nre;
3340 /* reset all devices */
3341 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3342 re->func(re->opaque);
3346 void qemu_system_reset_request(void)
3348 if (no_reboot) {
3349 shutdown_requested = 1;
3350 } else {
3351 reset_requested = 1;
3353 qemu_notify_event();
3356 void qemu_system_shutdown_request(void)
3358 shutdown_requested = 1;
3359 qemu_notify_event();
3362 void qemu_system_powerdown_request(void)
3364 powerdown_requested = 1;
3365 qemu_notify_event();
3368 #ifdef CONFIG_IOTHREAD
3369 static void qemu_system_vmstop_request(int reason)
3371 vmstop_requested = reason;
3372 qemu_notify_event();
3374 #endif
3376 #ifndef _WIN32
3377 static int io_thread_fd = -1;
3379 static void qemu_event_increment(void)
3381 static const char byte = 0;
3383 if (io_thread_fd == -1)
3384 return;
3386 write(io_thread_fd, &byte, sizeof(byte));
3389 static void qemu_event_read(void *opaque)
3391 int fd = (unsigned long)opaque;
3392 ssize_t len;
3394 /* Drain the notify pipe */
3395 do {
3396 char buffer[512];
3397 len = read(fd, buffer, sizeof(buffer));
3398 } while ((len == -1 && errno == EINTR) || len > 0);
3401 static int qemu_event_init(void)
3403 int err;
3404 int fds[2];
3406 err = qemu_pipe(fds);
3407 if (err == -1)
3408 return -errno;
3410 err = fcntl_setfl(fds[0], O_NONBLOCK);
3411 if (err < 0)
3412 goto fail;
3414 err = fcntl_setfl(fds[1], O_NONBLOCK);
3415 if (err < 0)
3416 goto fail;
3418 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3419 (void *)(unsigned long)fds[0]);
3421 io_thread_fd = fds[1];
3422 return 0;
3424 fail:
3425 close(fds[0]);
3426 close(fds[1]);
3427 return err;
3429 #else
3430 HANDLE qemu_event_handle;
3432 static void dummy_event_handler(void *opaque)
3436 static int qemu_event_init(void)
3438 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3439 if (!qemu_event_handle) {
3440 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3441 return -1;
3443 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3444 return 0;
3447 static void qemu_event_increment(void)
3449 if (!SetEvent(qemu_event_handle)) {
3450 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3451 GetLastError());
3452 exit (1);
3455 #endif
3457 static int cpu_can_run(CPUState *env)
3459 if (env->stop)
3460 return 0;
3461 if (env->stopped)
3462 return 0;
3463 return 1;
3466 #ifndef CONFIG_IOTHREAD
3467 static int qemu_init_main_loop(void)
3469 return qemu_event_init();
3472 void qemu_init_vcpu(void *_env)
3474 CPUState *env = _env;
3476 if (kvm_enabled())
3477 kvm_init_vcpu(env);
3478 env->nr_cores = smp_cores;
3479 env->nr_threads = smp_threads;
3480 return;
3483 int qemu_cpu_self(void *env)
3485 return 1;
3488 static void resume_all_vcpus(void)
3492 static void pause_all_vcpus(void)
3496 void qemu_cpu_kick(void *env)
3498 return;
3501 void qemu_notify_event(void)
3503 CPUState *env = cpu_single_env;
3505 if (env) {
3506 cpu_exit(env);
3510 void qemu_mutex_lock_iothread(void) {}
3511 void qemu_mutex_unlock_iothread(void) {}
3513 void vm_stop(int reason)
3515 do_vm_stop(reason);
3518 #else /* CONFIG_IOTHREAD */
3520 #include "qemu-thread.h"
3522 QemuMutex qemu_global_mutex;
3523 static QemuMutex qemu_fair_mutex;
3525 static QemuThread io_thread;
3527 static QemuThread *tcg_cpu_thread;
3528 static QemuCond *tcg_halt_cond;
3530 static int qemu_system_ready;
3531 /* cpu creation */
3532 static QemuCond qemu_cpu_cond;
3533 /* system init */
3534 static QemuCond qemu_system_cond;
3535 static QemuCond qemu_pause_cond;
3537 static void block_io_signals(void);
3538 static void unblock_io_signals(void);
3539 static int tcg_has_work(void);
3541 static int qemu_init_main_loop(void)
3543 int ret;
3545 ret = qemu_event_init();
3546 if (ret)
3547 return ret;
3549 qemu_cond_init(&qemu_pause_cond);
3550 qemu_mutex_init(&qemu_fair_mutex);
3551 qemu_mutex_init(&qemu_global_mutex);
3552 qemu_mutex_lock(&qemu_global_mutex);
3554 unblock_io_signals();
3555 qemu_thread_self(&io_thread);
3557 return 0;
3560 static void qemu_wait_io_event(CPUState *env)
3562 while (!tcg_has_work())
3563 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3565 qemu_mutex_unlock(&qemu_global_mutex);
3568 * Users of qemu_global_mutex can be starved, having no chance
3569 * to acquire it since this path will get to it first.
3570 * So use another lock to provide fairness.
3572 qemu_mutex_lock(&qemu_fair_mutex);
3573 qemu_mutex_unlock(&qemu_fair_mutex);
3575 qemu_mutex_lock(&qemu_global_mutex);
3576 if (env->stop) {
3577 env->stop = 0;
3578 env->stopped = 1;
3579 qemu_cond_signal(&qemu_pause_cond);
3583 static int qemu_cpu_exec(CPUState *env);
3585 static void *kvm_cpu_thread_fn(void *arg)
3587 CPUState *env = arg;
3589 block_io_signals();
3590 qemu_thread_self(env->thread);
3591 if (kvm_enabled())
3592 kvm_init_vcpu(env);
3594 /* signal CPU creation */
3595 qemu_mutex_lock(&qemu_global_mutex);
3596 env->created = 1;
3597 qemu_cond_signal(&qemu_cpu_cond);
3599 /* and wait for machine initialization */
3600 while (!qemu_system_ready)
3601 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3603 while (1) {
3604 if (cpu_can_run(env))
3605 qemu_cpu_exec(env);
3606 qemu_wait_io_event(env);
3609 return NULL;
3612 static void tcg_cpu_exec(void);
3614 static void *tcg_cpu_thread_fn(void *arg)
3616 CPUState *env = arg;
3618 block_io_signals();
3619 qemu_thread_self(env->thread);
3621 /* signal CPU creation */
3622 qemu_mutex_lock(&qemu_global_mutex);
3623 for (env = first_cpu; env != NULL; env = env->next_cpu)
3624 env->created = 1;
3625 qemu_cond_signal(&qemu_cpu_cond);
3627 /* and wait for machine initialization */
3628 while (!qemu_system_ready)
3629 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3631 while (1) {
3632 tcg_cpu_exec();
3633 qemu_wait_io_event(cur_cpu);
3636 return NULL;
3639 void qemu_cpu_kick(void *_env)
3641 CPUState *env = _env;
3642 qemu_cond_broadcast(env->halt_cond);
3643 if (kvm_enabled())
3644 qemu_thread_signal(env->thread, SIGUSR1);
3647 int qemu_cpu_self(void *_env)
3649 CPUState *env = _env;
3650 QemuThread this;
3652 qemu_thread_self(&this);
3654 return qemu_thread_equal(&this, env->thread);
3657 static void cpu_signal(int sig)
3659 if (cpu_single_env)
3660 cpu_exit(cpu_single_env);
3663 static void block_io_signals(void)
3665 sigset_t set;
3666 struct sigaction sigact;
3668 sigemptyset(&set);
3669 sigaddset(&set, SIGUSR2);
3670 sigaddset(&set, SIGIO);
3671 sigaddset(&set, SIGALRM);
3672 pthread_sigmask(SIG_BLOCK, &set, NULL);
3674 sigemptyset(&set);
3675 sigaddset(&set, SIGUSR1);
3676 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3678 memset(&sigact, 0, sizeof(sigact));
3679 sigact.sa_handler = cpu_signal;
3680 sigaction(SIGUSR1, &sigact, NULL);
3683 static void unblock_io_signals(void)
3685 sigset_t set;
3687 sigemptyset(&set);
3688 sigaddset(&set, SIGUSR2);
3689 sigaddset(&set, SIGIO);
3690 sigaddset(&set, SIGALRM);
3691 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3693 sigemptyset(&set);
3694 sigaddset(&set, SIGUSR1);
3695 pthread_sigmask(SIG_BLOCK, &set, NULL);
3698 static void qemu_signal_lock(unsigned int msecs)
3700 qemu_mutex_lock(&qemu_fair_mutex);
3702 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3703 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3704 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3705 break;
3707 qemu_mutex_unlock(&qemu_fair_mutex);
3710 void qemu_mutex_lock_iothread(void)
3712 if (kvm_enabled()) {
3713 qemu_mutex_lock(&qemu_fair_mutex);
3714 qemu_mutex_lock(&qemu_global_mutex);
3715 qemu_mutex_unlock(&qemu_fair_mutex);
3716 } else
3717 qemu_signal_lock(100);
3720 void qemu_mutex_unlock_iothread(void)
3722 qemu_mutex_unlock(&qemu_global_mutex);
3725 static int all_vcpus_paused(void)
3727 CPUState *penv = first_cpu;
3729 while (penv) {
3730 if (!penv->stopped)
3731 return 0;
3732 penv = (CPUState *)penv->next_cpu;
3735 return 1;
3738 static void pause_all_vcpus(void)
3740 CPUState *penv = first_cpu;
3742 while (penv) {
3743 penv->stop = 1;
3744 qemu_thread_signal(penv->thread, SIGUSR1);
3745 qemu_cpu_kick(penv);
3746 penv = (CPUState *)penv->next_cpu;
3749 while (!all_vcpus_paused()) {
3750 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3751 penv = first_cpu;
3752 while (penv) {
3753 qemu_thread_signal(penv->thread, SIGUSR1);
3754 penv = (CPUState *)penv->next_cpu;
3759 static void resume_all_vcpus(void)
3761 CPUState *penv = first_cpu;
3763 while (penv) {
3764 penv->stop = 0;
3765 penv->stopped = 0;
3766 qemu_thread_signal(penv->thread, SIGUSR1);
3767 qemu_cpu_kick(penv);
3768 penv = (CPUState *)penv->next_cpu;
3772 static void tcg_init_vcpu(void *_env)
3774 CPUState *env = _env;
3775 /* share a single thread for all cpus with TCG */
3776 if (!tcg_cpu_thread) {
3777 env->thread = qemu_mallocz(sizeof(QemuThread));
3778 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3779 qemu_cond_init(env->halt_cond);
3780 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3781 while (env->created == 0)
3782 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3783 tcg_cpu_thread = env->thread;
3784 tcg_halt_cond = env->halt_cond;
3785 } else {
3786 env->thread = tcg_cpu_thread;
3787 env->halt_cond = tcg_halt_cond;
3791 static void kvm_start_vcpu(CPUState *env)
3793 env->thread = qemu_mallocz(sizeof(QemuThread));
3794 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3795 qemu_cond_init(env->halt_cond);
3796 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3797 while (env->created == 0)
3798 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3801 void qemu_init_vcpu(void *_env)
3803 CPUState *env = _env;
3805 if (kvm_enabled())
3806 kvm_start_vcpu(env);
3807 else
3808 tcg_init_vcpu(env);
3809 env->nr_cores = smp_cores;
3810 env->nr_threads = smp_threads;
3813 void qemu_notify_event(void)
3815 qemu_event_increment();
3818 void vm_stop(int reason)
3820 QemuThread me;
3821 qemu_thread_self(&me);
3823 if (!qemu_thread_equal(&me, &io_thread)) {
3824 qemu_system_vmstop_request(reason);
3826 * FIXME: should not return to device code in case
3827 * vm_stop() has been requested.
3829 if (cpu_single_env) {
3830 cpu_exit(cpu_single_env);
3831 cpu_single_env->stop = 1;
3833 return;
3835 do_vm_stop(reason);
3838 #endif
3841 #ifdef _WIN32
3842 static void host_main_loop_wait(int *timeout)
3844 int ret, ret2, i;
3845 PollingEntry *pe;
3848 /* XXX: need to suppress polling by better using win32 events */
3849 ret = 0;
3850 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3851 ret |= pe->func(pe->opaque);
3853 if (ret == 0) {
3854 int err;
3855 WaitObjects *w = &wait_objects;
3857 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3858 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3859 if (w->func[ret - WAIT_OBJECT_0])
3860 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3862 /* Check for additional signaled events */
3863 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3865 /* Check if event is signaled */
3866 ret2 = WaitForSingleObject(w->events[i], 0);
3867 if(ret2 == WAIT_OBJECT_0) {
3868 if (w->func[i])
3869 w->func[i](w->opaque[i]);
3870 } else if (ret2 == WAIT_TIMEOUT) {
3871 } else {
3872 err = GetLastError();
3873 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3876 } else if (ret == WAIT_TIMEOUT) {
3877 } else {
3878 err = GetLastError();
3879 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3883 *timeout = 0;
3885 #else
3886 static void host_main_loop_wait(int *timeout)
3889 #endif
3891 void main_loop_wait(int timeout)
3893 IOHandlerRecord *ioh;
3894 fd_set rfds, wfds, xfds;
3895 int ret, nfds;
3896 struct timeval tv;
3898 qemu_bh_update_timeout(&timeout);
3900 host_main_loop_wait(&timeout);
3902 /* poll any events */
3903 /* XXX: separate device handlers from system ones */
3904 nfds = -1;
3905 FD_ZERO(&rfds);
3906 FD_ZERO(&wfds);
3907 FD_ZERO(&xfds);
3908 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3909 if (ioh->deleted)
3910 continue;
3911 if (ioh->fd_read &&
3912 (!ioh->fd_read_poll ||
3913 ioh->fd_read_poll(ioh->opaque) != 0)) {
3914 FD_SET(ioh->fd, &rfds);
3915 if (ioh->fd > nfds)
3916 nfds = ioh->fd;
3918 if (ioh->fd_write) {
3919 FD_SET(ioh->fd, &wfds);
3920 if (ioh->fd > nfds)
3921 nfds = ioh->fd;
3925 tv.tv_sec = timeout / 1000;
3926 tv.tv_usec = (timeout % 1000) * 1000;
3928 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3930 qemu_mutex_unlock_iothread();
3931 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3932 qemu_mutex_lock_iothread();
3933 if (ret > 0) {
3934 IOHandlerRecord **pioh;
3936 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3937 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3938 ioh->fd_read(ioh->opaque);
3940 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3941 ioh->fd_write(ioh->opaque);
3945 /* remove deleted IO handlers */
3946 pioh = &first_io_handler;
3947 while (*pioh) {
3948 ioh = *pioh;
3949 if (ioh->deleted) {
3950 *pioh = ioh->next;
3951 qemu_free(ioh);
3952 } else
3953 pioh = &ioh->next;
3957 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3959 /* rearm timer, if not periodic */
3960 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3961 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3962 qemu_rearm_alarm_timer(alarm_timer);
3965 /* vm time timers */
3966 if (vm_running) {
3967 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3968 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3969 qemu_get_clock(vm_clock));
3972 /* real time timers */
3973 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3974 qemu_get_clock(rt_clock));
3976 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3977 qemu_get_clock(host_clock));
3979 /* Check bottom-halves last in case any of the earlier events triggered
3980 them. */
3981 qemu_bh_poll();
3985 static int qemu_cpu_exec(CPUState *env)
3987 int ret;
3988 #ifdef CONFIG_PROFILER
3989 int64_t ti;
3990 #endif
3992 #ifdef CONFIG_PROFILER
3993 ti = profile_getclock();
3994 #endif
3995 if (use_icount) {
3996 int64_t count;
3997 int decr;
3998 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3999 env->icount_decr.u16.low = 0;
4000 env->icount_extra = 0;
4001 count = qemu_next_deadline();
4002 count = (count + (1 << icount_time_shift) - 1)
4003 >> icount_time_shift;
4004 qemu_icount += count;
4005 decr = (count > 0xffff) ? 0xffff : count;
4006 count -= decr;
4007 env->icount_decr.u16.low = decr;
4008 env->icount_extra = count;
4010 ret = cpu_exec(env);
4011 #ifdef CONFIG_PROFILER
4012 qemu_time += profile_getclock() - ti;
4013 #endif
4014 if (use_icount) {
4015 /* Fold pending instructions back into the
4016 instruction counter, and clear the interrupt flag. */
4017 qemu_icount -= (env->icount_decr.u16.low
4018 + env->icount_extra);
4019 env->icount_decr.u32 = 0;
4020 env->icount_extra = 0;
4022 return ret;
4025 static void tcg_cpu_exec(void)
4027 int ret = 0;
4029 if (next_cpu == NULL)
4030 next_cpu = first_cpu;
4031 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4032 CPUState *env = cur_cpu = next_cpu;
4034 if (!vm_running)
4035 break;
4036 if (timer_alarm_pending) {
4037 timer_alarm_pending = 0;
4038 break;
4040 if (cpu_can_run(env))
4041 ret = qemu_cpu_exec(env);
4042 if (ret == EXCP_DEBUG) {
4043 gdb_set_stop_cpu(env);
4044 debug_requested = 1;
4045 break;
4050 static int cpu_has_work(CPUState *env)
4052 if (env->stop)
4053 return 1;
4054 if (env->stopped)
4055 return 0;
4056 if (!env->halted)
4057 return 1;
4058 if (qemu_cpu_has_work(env))
4059 return 1;
4060 return 0;
4063 static int tcg_has_work(void)
4065 CPUState *env;
4067 for (env = first_cpu; env != NULL; env = env->next_cpu)
4068 if (cpu_has_work(env))
4069 return 1;
4070 return 0;
4073 static int qemu_calculate_timeout(void)
4075 #ifndef CONFIG_IOTHREAD
4076 int timeout;
4078 if (!vm_running)
4079 timeout = 5000;
4080 else if (tcg_has_work())
4081 timeout = 0;
4082 else if (!use_icount)
4083 timeout = 5000;
4084 else {
4085 /* XXX: use timeout computed from timers */
4086 int64_t add;
4087 int64_t delta;
4088 /* Advance virtual time to the next event. */
4089 if (use_icount == 1) {
4090 /* When not using an adaptive execution frequency
4091 we tend to get badly out of sync with real time,
4092 so just delay for a reasonable amount of time. */
4093 delta = 0;
4094 } else {
4095 delta = cpu_get_icount() - cpu_get_clock();
4097 if (delta > 0) {
4098 /* If virtual time is ahead of real time then just
4099 wait for IO. */
4100 timeout = (delta / 1000000) + 1;
4101 } else {
4102 /* Wait for either IO to occur or the next
4103 timer event. */
4104 add = qemu_next_deadline();
4105 /* We advance the timer before checking for IO.
4106 Limit the amount we advance so that early IO
4107 activity won't get the guest too far ahead. */
4108 if (add > 10000000)
4109 add = 10000000;
4110 delta += add;
4111 add = (add + (1 << icount_time_shift) - 1)
4112 >> icount_time_shift;
4113 qemu_icount += add;
4114 timeout = delta / 1000000;
4115 if (timeout < 0)
4116 timeout = 0;
4120 return timeout;
4121 #else /* CONFIG_IOTHREAD */
4122 return 1000;
4123 #endif
4126 static int vm_can_run(void)
4128 if (powerdown_requested)
4129 return 0;
4130 if (reset_requested)
4131 return 0;
4132 if (shutdown_requested)
4133 return 0;
4134 if (debug_requested)
4135 return 0;
4136 return 1;
4139 qemu_irq qemu_system_powerdown;
4141 static void main_loop(void)
4143 int r;
4145 #ifdef CONFIG_IOTHREAD
4146 qemu_system_ready = 1;
4147 qemu_cond_broadcast(&qemu_system_cond);
4148 #endif
4150 for (;;) {
4151 do {
4152 #ifdef CONFIG_PROFILER
4153 int64_t ti;
4154 #endif
4155 #ifndef CONFIG_IOTHREAD
4156 tcg_cpu_exec();
4157 #endif
4158 #ifdef CONFIG_PROFILER
4159 ti = profile_getclock();
4160 #endif
4161 main_loop_wait(qemu_calculate_timeout());
4162 #ifdef CONFIG_PROFILER
4163 dev_time += profile_getclock() - ti;
4164 #endif
4165 } while (vm_can_run());
4167 if (qemu_debug_requested()) {
4168 monitor_protocol_event(QEVENT_DEBUG, NULL);
4169 vm_stop(EXCP_DEBUG);
4171 if (qemu_shutdown_requested()) {
4172 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4173 if (no_shutdown) {
4174 vm_stop(0);
4175 no_shutdown = 0;
4176 } else
4177 break;
4179 if (qemu_reset_requested()) {
4180 monitor_protocol_event(QEVENT_RESET, NULL);
4181 pause_all_vcpus();
4182 qemu_system_reset();
4183 resume_all_vcpus();
4185 if (qemu_powerdown_requested()) {
4186 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4187 qemu_irq_raise(qemu_system_powerdown);
4189 if ((r = qemu_vmstop_requested())) {
4190 monitor_protocol_event(QEVENT_STOP, NULL);
4191 vm_stop(r);
4194 pause_all_vcpus();
4197 static void version(void)
4199 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4202 static void help(int exitcode)
4204 version();
4205 printf("usage: %s [options] [disk_image]\n"
4206 "\n"
4207 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4208 "\n"
4209 #define DEF(option, opt_arg, opt_enum, opt_help) \
4210 opt_help
4211 #define DEFHEADING(text) stringify(text) "\n"
4212 #include "qemu-options.h"
4213 #undef DEF
4214 #undef DEFHEADING
4215 #undef GEN_DOCS
4216 "\n"
4217 "During emulation, the following keys are useful:\n"
4218 "ctrl-alt-f toggle full screen\n"
4219 "ctrl-alt-n switch to virtual console 'n'\n"
4220 "ctrl-alt toggle mouse and keyboard grab\n"
4221 "\n"
4222 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4224 "qemu",
4225 DEFAULT_RAM_SIZE,
4226 #ifndef _WIN32
4227 DEFAULT_NETWORK_SCRIPT,
4228 DEFAULT_NETWORK_DOWN_SCRIPT,
4229 #endif
4230 DEFAULT_GDBSTUB_PORT,
4231 "/tmp/qemu.log");
4232 exit(exitcode);
4235 #define HAS_ARG 0x0001
4237 enum {
4238 #define DEF(option, opt_arg, opt_enum, opt_help) \
4239 opt_enum,
4240 #define DEFHEADING(text)
4241 #include "qemu-options.h"
4242 #undef DEF
4243 #undef DEFHEADING
4244 #undef GEN_DOCS
4247 typedef struct QEMUOption {
4248 const char *name;
4249 int flags;
4250 int index;
4251 } QEMUOption;
4253 static const QEMUOption qemu_options[] = {
4254 { "h", 0, QEMU_OPTION_h },
4255 #define DEF(option, opt_arg, opt_enum, opt_help) \
4256 { option, opt_arg, opt_enum },
4257 #define DEFHEADING(text)
4258 #include "qemu-options.h"
4259 #undef DEF
4260 #undef DEFHEADING
4261 #undef GEN_DOCS
4262 { NULL },
4265 #ifdef HAS_AUDIO
4266 struct soundhw soundhw[] = {
4267 #ifdef HAS_AUDIO_CHOICE
4268 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4270 "pcspk",
4271 "PC speaker",
4274 { .init_isa = pcspk_audio_init }
4276 #endif
4278 #ifdef CONFIG_SB16
4280 "sb16",
4281 "Creative Sound Blaster 16",
4284 { .init_isa = SB16_init }
4286 #endif
4288 #ifdef CONFIG_CS4231A
4290 "cs4231a",
4291 "CS4231A",
4294 { .init_isa = cs4231a_init }
4296 #endif
4298 #ifdef CONFIG_ADLIB
4300 "adlib",
4301 #ifdef HAS_YMF262
4302 "Yamaha YMF262 (OPL3)",
4303 #else
4304 "Yamaha YM3812 (OPL2)",
4305 #endif
4308 { .init_isa = Adlib_init }
4310 #endif
4312 #ifdef CONFIG_GUS
4314 "gus",
4315 "Gravis Ultrasound GF1",
4318 { .init_isa = GUS_init }
4320 #endif
4322 #ifdef CONFIG_AC97
4324 "ac97",
4325 "Intel 82801AA AC97 Audio",
4328 { .init_pci = ac97_init }
4330 #endif
4332 #ifdef CONFIG_ES1370
4334 "es1370",
4335 "ENSONIQ AudioPCI ES1370",
4338 { .init_pci = es1370_init }
4340 #endif
4342 #endif /* HAS_AUDIO_CHOICE */
4344 { NULL, NULL, 0, 0, { NULL } }
4347 static void select_soundhw (const char *optarg)
4349 struct soundhw *c;
4351 if (*optarg == '?') {
4352 show_valid_cards:
4354 printf ("Valid sound card names (comma separated):\n");
4355 for (c = soundhw; c->name; ++c) {
4356 printf ("%-11s %s\n", c->name, c->descr);
4358 printf ("\n-soundhw all will enable all of the above\n");
4359 exit (*optarg != '?');
4361 else {
4362 size_t l;
4363 const char *p;
4364 char *e;
4365 int bad_card = 0;
4367 if (!strcmp (optarg, "all")) {
4368 for (c = soundhw; c->name; ++c) {
4369 c->enabled = 1;
4371 return;
4374 p = optarg;
4375 while (*p) {
4376 e = strchr (p, ',');
4377 l = !e ? strlen (p) : (size_t) (e - p);
4379 for (c = soundhw; c->name; ++c) {
4380 if (!strncmp (c->name, p, l) && !c->name[l]) {
4381 c->enabled = 1;
4382 break;
4386 if (!c->name) {
4387 if (l > 80) {
4388 fprintf (stderr,
4389 "Unknown sound card name (too big to show)\n");
4391 else {
4392 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4393 (int) l, p);
4395 bad_card = 1;
4397 p += l + (e != NULL);
4400 if (bad_card)
4401 goto show_valid_cards;
4404 #endif
4406 static void select_vgahw (const char *p)
4408 const char *opts;
4410 default_vga = 0;
4411 vga_interface_type = VGA_NONE;
4412 if (strstart(p, "std", &opts)) {
4413 vga_interface_type = VGA_STD;
4414 } else if (strstart(p, "cirrus", &opts)) {
4415 vga_interface_type = VGA_CIRRUS;
4416 } else if (strstart(p, "vmware", &opts)) {
4417 vga_interface_type = VGA_VMWARE;
4418 } else if (strstart(p, "xenfb", &opts)) {
4419 vga_interface_type = VGA_XENFB;
4420 } else if (!strstart(p, "none", &opts)) {
4421 invalid_vga:
4422 fprintf(stderr, "Unknown vga type: %s\n", p);
4423 exit(1);
4425 while (*opts) {
4426 const char *nextopt;
4428 if (strstart(opts, ",retrace=", &nextopt)) {
4429 opts = nextopt;
4430 if (strstart(opts, "dumb", &nextopt))
4431 vga_retrace_method = VGA_RETRACE_DUMB;
4432 else if (strstart(opts, "precise", &nextopt))
4433 vga_retrace_method = VGA_RETRACE_PRECISE;
4434 else goto invalid_vga;
4435 } else goto invalid_vga;
4436 opts = nextopt;
4440 #ifdef TARGET_I386
4441 static int balloon_parse(const char *arg)
4443 QemuOpts *opts;
4445 if (strcmp(arg, "none") == 0) {
4446 return 0;
4449 if (!strncmp(arg, "virtio", 6)) {
4450 if (arg[6] == ',') {
4451 /* have params -> parse them */
4452 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4453 if (!opts)
4454 return -1;
4455 } else {
4456 /* create empty opts */
4457 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4459 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4460 return 0;
4463 return -1;
4465 #endif
4467 #ifdef _WIN32
4468 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4470 exit(STATUS_CONTROL_C_EXIT);
4471 return TRUE;
4473 #endif
4475 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4477 int ret;
4479 if(strlen(str) != 36)
4480 return -1;
4482 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4483 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4484 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4486 if(ret != 16)
4487 return -1;
4489 #ifdef TARGET_I386
4490 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4491 #endif
4493 return 0;
4496 #ifndef _WIN32
4498 static void termsig_handler(int signal)
4500 qemu_system_shutdown_request();
4503 static void sigchld_handler(int signal)
4505 waitpid(-1, NULL, WNOHANG);
4508 static void sighandler_setup(void)
4510 struct sigaction act;
4512 memset(&act, 0, sizeof(act));
4513 act.sa_handler = termsig_handler;
4514 sigaction(SIGINT, &act, NULL);
4515 sigaction(SIGHUP, &act, NULL);
4516 sigaction(SIGTERM, &act, NULL);
4518 act.sa_handler = sigchld_handler;
4519 act.sa_flags = SA_NOCLDSTOP;
4520 sigaction(SIGCHLD, &act, NULL);
4523 #endif
4525 #ifdef _WIN32
4526 /* Look for support files in the same directory as the executable. */
4527 static char *find_datadir(const char *argv0)
4529 char *p;
4530 char buf[MAX_PATH];
4531 DWORD len;
4533 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4534 if (len == 0) {
4535 return NULL;
4538 buf[len] = 0;
4539 p = buf + len - 1;
4540 while (p != buf && *p != '\\')
4541 p--;
4542 *p = 0;
4543 if (access(buf, R_OK) == 0) {
4544 return qemu_strdup(buf);
4546 return NULL;
4548 #else /* !_WIN32 */
4550 /* Find a likely location for support files using the location of the binary.
4551 For installed binaries this will be "$bindir/../share/qemu". When
4552 running from the build tree this will be "$bindir/../pc-bios". */
4553 #define SHARE_SUFFIX "/share/qemu"
4554 #define BUILD_SUFFIX "/pc-bios"
4555 static char *find_datadir(const char *argv0)
4557 char *dir;
4558 char *p = NULL;
4559 char *res;
4560 char buf[PATH_MAX];
4561 size_t max_len;
4563 #if defined(__linux__)
4565 int len;
4566 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4567 if (len > 0) {
4568 buf[len] = 0;
4569 p = buf;
4572 #elif defined(__FreeBSD__)
4574 int len;
4575 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4576 if (len > 0) {
4577 buf[len] = 0;
4578 p = buf;
4581 #endif
4582 /* If we don't have any way of figuring out the actual executable
4583 location then try argv[0]. */
4584 if (!p) {
4585 p = realpath(argv0, buf);
4586 if (!p) {
4587 return NULL;
4590 dir = dirname(p);
4591 dir = dirname(dir);
4593 max_len = strlen(dir) +
4594 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4595 res = qemu_mallocz(max_len);
4596 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4597 if (access(res, R_OK)) {
4598 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4599 if (access(res, R_OK)) {
4600 qemu_free(res);
4601 res = NULL;
4605 return res;
4607 #undef SHARE_SUFFIX
4608 #undef BUILD_SUFFIX
4609 #endif
4611 char *qemu_find_file(int type, const char *name)
4613 int len;
4614 const char *subdir;
4615 char *buf;
4617 /* If name contains path separators then try it as a straight path. */
4618 if ((strchr(name, '/') || strchr(name, '\\'))
4619 && access(name, R_OK) == 0) {
4620 return qemu_strdup(name);
4622 switch (type) {
4623 case QEMU_FILE_TYPE_BIOS:
4624 subdir = "";
4625 break;
4626 case QEMU_FILE_TYPE_KEYMAP:
4627 subdir = "keymaps/";
4628 break;
4629 default:
4630 abort();
4632 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4633 buf = qemu_mallocz(len);
4634 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4635 if (access(buf, R_OK)) {
4636 qemu_free(buf);
4637 return NULL;
4639 return buf;
4642 static int device_init_func(QemuOpts *opts, void *opaque)
4644 DeviceState *dev;
4646 dev = qdev_device_add(opts);
4647 if (!dev)
4648 return -1;
4649 return 0;
4652 static int chardev_init_func(QemuOpts *opts, void *opaque)
4654 CharDriverState *chr;
4656 chr = qemu_chr_open_opts(opts, NULL);
4657 if (!chr)
4658 return -1;
4659 return 0;
4662 static int mon_init_func(QemuOpts *opts, void *opaque)
4664 CharDriverState *chr;
4665 const char *chardev;
4666 const char *mode;
4667 int flags;
4669 mode = qemu_opt_get(opts, "mode");
4670 if (mode == NULL) {
4671 mode = "readline";
4673 if (strcmp(mode, "readline") == 0) {
4674 flags = MONITOR_USE_READLINE;
4675 } else if (strcmp(mode, "control") == 0) {
4676 flags = MONITOR_USE_CONTROL;
4677 } else {
4678 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4679 exit(1);
4682 if (qemu_opt_get_bool(opts, "default", 0))
4683 flags |= MONITOR_IS_DEFAULT;
4685 chardev = qemu_opt_get(opts, "chardev");
4686 chr = qemu_chr_find(chardev);
4687 if (chr == NULL) {
4688 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4689 exit(1);
4692 monitor_init(chr, flags);
4693 return 0;
4696 static void monitor_parse(const char *optarg, const char *mode)
4698 static int monitor_device_index = 0;
4699 QemuOpts *opts;
4700 const char *p;
4701 char label[32];
4702 int def = 0;
4704 if (strstart(optarg, "chardev:", &p)) {
4705 snprintf(label, sizeof(label), "%s", p);
4706 } else {
4707 if (monitor_device_index) {
4708 snprintf(label, sizeof(label), "monitor%d",
4709 monitor_device_index);
4710 } else {
4711 snprintf(label, sizeof(label), "monitor");
4712 def = 1;
4714 opts = qemu_chr_parse_compat(label, optarg);
4715 if (!opts) {
4716 fprintf(stderr, "parse error: %s\n", optarg);
4717 exit(1);
4721 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4722 if (!opts) {
4723 fprintf(stderr, "duplicate chardev: %s\n", label);
4724 exit(1);
4726 qemu_opt_set(opts, "mode", mode);
4727 qemu_opt_set(opts, "chardev", label);
4728 if (def)
4729 qemu_opt_set(opts, "default", "on");
4730 monitor_device_index++;
4733 struct device_config {
4734 enum {
4735 DEV_USB, /* -usbdevice */
4736 DEV_BT, /* -bt */
4737 DEV_SERIAL, /* -serial */
4738 DEV_PARALLEL, /* -parallel */
4739 DEV_VIRTCON, /* -virtioconsole */
4740 } type;
4741 const char *cmdline;
4742 QTAILQ_ENTRY(device_config) next;
4744 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4746 static void add_device_config(int type, const char *cmdline)
4748 struct device_config *conf;
4750 conf = qemu_mallocz(sizeof(*conf));
4751 conf->type = type;
4752 conf->cmdline = cmdline;
4753 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4756 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4758 struct device_config *conf;
4759 int rc;
4761 QTAILQ_FOREACH(conf, &device_configs, next) {
4762 if (conf->type != type)
4763 continue;
4764 rc = func(conf->cmdline);
4765 if (0 != rc)
4766 return rc;
4768 return 0;
4771 static int serial_parse(const char *devname)
4773 static int index = 0;
4774 char label[32];
4776 if (strcmp(devname, "none") == 0)
4777 return 0;
4778 if (index == MAX_SERIAL_PORTS) {
4779 fprintf(stderr, "qemu: too many serial ports\n");
4780 exit(1);
4782 snprintf(label, sizeof(label), "serial%d", index);
4783 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4784 if (!serial_hds[index]) {
4785 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4786 devname, strerror(errno));
4787 return -1;
4789 index++;
4790 return 0;
4793 static int parallel_parse(const char *devname)
4795 static int index = 0;
4796 char label[32];
4798 if (strcmp(devname, "none") == 0)
4799 return 0;
4800 if (index == MAX_PARALLEL_PORTS) {
4801 fprintf(stderr, "qemu: too many parallel ports\n");
4802 exit(1);
4804 snprintf(label, sizeof(label), "parallel%d", index);
4805 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4806 if (!parallel_hds[index]) {
4807 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4808 devname, strerror(errno));
4809 return -1;
4811 index++;
4812 return 0;
4815 static int virtcon_parse(const char *devname)
4817 static int index = 0;
4818 char label[32];
4820 if (strcmp(devname, "none") == 0)
4821 return 0;
4822 if (index == MAX_VIRTIO_CONSOLES) {
4823 fprintf(stderr, "qemu: too many virtio consoles\n");
4824 exit(1);
4826 snprintf(label, sizeof(label), "virtcon%d", index);
4827 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4828 if (!virtcon_hds[index]) {
4829 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4830 devname, strerror(errno));
4831 return -1;
4833 index++;
4834 return 0;
4837 int main(int argc, char **argv, char **envp)
4839 const char *gdbstub_dev = NULL;
4840 uint32_t boot_devices_bitmap = 0;
4841 int i;
4842 int snapshot, linux_boot, net_boot;
4843 const char *initrd_filename;
4844 const char *kernel_filename, *kernel_cmdline;
4845 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4846 DisplayState *ds;
4847 DisplayChangeListener *dcl;
4848 int cyls, heads, secs, translation;
4849 QemuOpts *hda_opts = NULL, *opts;
4850 int optind;
4851 const char *r, *optarg;
4852 const char *loadvm = NULL;
4853 QEMUMachine *machine;
4854 const char *cpu_model;
4855 #ifndef _WIN32
4856 int fds[2];
4857 #endif
4858 int tb_size;
4859 const char *pid_file = NULL;
4860 const char *incoming = NULL;
4861 #ifndef _WIN32
4862 int fd = 0;
4863 struct passwd *pwd = NULL;
4864 const char *chroot_dir = NULL;
4865 const char *run_as = NULL;
4866 #endif
4867 CPUState *env;
4868 int show_vnc_port = 0;
4870 init_clocks();
4872 qemu_errors_to_file(stderr);
4873 qemu_cache_utils_init(envp);
4875 QLIST_INIT (&vm_change_state_head);
4876 #ifndef _WIN32
4878 struct sigaction act;
4879 sigfillset(&act.sa_mask);
4880 act.sa_flags = 0;
4881 act.sa_handler = SIG_IGN;
4882 sigaction(SIGPIPE, &act, NULL);
4884 #else
4885 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4886 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4887 QEMU to run on a single CPU */
4889 HANDLE h;
4890 DWORD mask, smask;
4891 int i;
4892 h = GetCurrentProcess();
4893 if (GetProcessAffinityMask(h, &mask, &smask)) {
4894 for(i = 0; i < 32; i++) {
4895 if (mask & (1 << i))
4896 break;
4898 if (i != 32) {
4899 mask = 1 << i;
4900 SetProcessAffinityMask(h, mask);
4904 #endif
4906 module_call_init(MODULE_INIT_MACHINE);
4907 machine = find_default_machine();
4908 cpu_model = NULL;
4909 initrd_filename = NULL;
4910 ram_size = 0;
4911 snapshot = 0;
4912 kernel_filename = NULL;
4913 kernel_cmdline = "";
4914 cyls = heads = secs = 0;
4915 translation = BIOS_ATA_TRANSLATION_AUTO;
4917 for (i = 0; i < MAX_NODES; i++) {
4918 node_mem[i] = 0;
4919 node_cpumask[i] = 0;
4922 nb_numa_nodes = 0;
4923 nb_nics = 0;
4925 tb_size = 0;
4926 autostart= 1;
4928 optind = 1;
4929 for(;;) {
4930 if (optind >= argc)
4931 break;
4932 r = argv[optind];
4933 if (r[0] != '-') {
4934 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4935 } else {
4936 const QEMUOption *popt;
4938 optind++;
4939 /* Treat --foo the same as -foo. */
4940 if (r[1] == '-')
4941 r++;
4942 popt = qemu_options;
4943 for(;;) {
4944 if (!popt->name) {
4945 fprintf(stderr, "%s: invalid option -- '%s'\n",
4946 argv[0], r);
4947 exit(1);
4949 if (!strcmp(popt->name, r + 1))
4950 break;
4951 popt++;
4953 if (popt->flags & HAS_ARG) {
4954 if (optind >= argc) {
4955 fprintf(stderr, "%s: option '%s' requires an argument\n",
4956 argv[0], r);
4957 exit(1);
4959 optarg = argv[optind++];
4960 } else {
4961 optarg = NULL;
4964 switch(popt->index) {
4965 case QEMU_OPTION_M:
4966 machine = find_machine(optarg);
4967 if (!machine) {
4968 QEMUMachine *m;
4969 printf("Supported machines are:\n");
4970 for(m = first_machine; m != NULL; m = m->next) {
4971 if (m->alias)
4972 printf("%-10s %s (alias of %s)\n",
4973 m->alias, m->desc, m->name);
4974 printf("%-10s %s%s\n",
4975 m->name, m->desc,
4976 m->is_default ? " (default)" : "");
4978 exit(*optarg != '?');
4980 break;
4981 case QEMU_OPTION_cpu:
4982 /* hw initialization will check this */
4983 if (*optarg == '?') {
4984 /* XXX: implement xxx_cpu_list for targets that still miss it */
4985 #if defined(cpu_list)
4986 cpu_list(stdout, &fprintf);
4987 #endif
4988 exit(0);
4989 } else {
4990 cpu_model = optarg;
4992 break;
4993 case QEMU_OPTION_initrd:
4994 initrd_filename = optarg;
4995 break;
4996 case QEMU_OPTION_hda:
4997 if (cyls == 0)
4998 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4999 else
5000 hda_opts = drive_add(optarg, HD_ALIAS
5001 ",cyls=%d,heads=%d,secs=%d%s",
5002 0, cyls, heads, secs,
5003 translation == BIOS_ATA_TRANSLATION_LBA ?
5004 ",trans=lba" :
5005 translation == BIOS_ATA_TRANSLATION_NONE ?
5006 ",trans=none" : "");
5007 break;
5008 case QEMU_OPTION_hdb:
5009 case QEMU_OPTION_hdc:
5010 case QEMU_OPTION_hdd:
5011 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5012 break;
5013 case QEMU_OPTION_drive:
5014 drive_add(NULL, "%s", optarg);
5015 break;
5016 case QEMU_OPTION_set:
5017 if (qemu_set_option(optarg) != 0)
5018 exit(1);
5019 break;
5020 case QEMU_OPTION_global:
5021 if (qemu_global_option(optarg) != 0)
5022 exit(1);
5023 break;
5024 case QEMU_OPTION_mtdblock:
5025 drive_add(optarg, MTD_ALIAS);
5026 break;
5027 case QEMU_OPTION_sd:
5028 drive_add(optarg, SD_ALIAS);
5029 break;
5030 case QEMU_OPTION_pflash:
5031 drive_add(optarg, PFLASH_ALIAS);
5032 break;
5033 case QEMU_OPTION_snapshot:
5034 snapshot = 1;
5035 break;
5036 case QEMU_OPTION_hdachs:
5038 const char *p;
5039 p = optarg;
5040 cyls = strtol(p, (char **)&p, 0);
5041 if (cyls < 1 || cyls > 16383)
5042 goto chs_fail;
5043 if (*p != ',')
5044 goto chs_fail;
5045 p++;
5046 heads = strtol(p, (char **)&p, 0);
5047 if (heads < 1 || heads > 16)
5048 goto chs_fail;
5049 if (*p != ',')
5050 goto chs_fail;
5051 p++;
5052 secs = strtol(p, (char **)&p, 0);
5053 if (secs < 1 || secs > 63)
5054 goto chs_fail;
5055 if (*p == ',') {
5056 p++;
5057 if (!strcmp(p, "none"))
5058 translation = BIOS_ATA_TRANSLATION_NONE;
5059 else if (!strcmp(p, "lba"))
5060 translation = BIOS_ATA_TRANSLATION_LBA;
5061 else if (!strcmp(p, "auto"))
5062 translation = BIOS_ATA_TRANSLATION_AUTO;
5063 else
5064 goto chs_fail;
5065 } else if (*p != '\0') {
5066 chs_fail:
5067 fprintf(stderr, "qemu: invalid physical CHS format\n");
5068 exit(1);
5070 if (hda_opts != NULL) {
5071 char num[16];
5072 snprintf(num, sizeof(num), "%d", cyls);
5073 qemu_opt_set(hda_opts, "cyls", num);
5074 snprintf(num, sizeof(num), "%d", heads);
5075 qemu_opt_set(hda_opts, "heads", num);
5076 snprintf(num, sizeof(num), "%d", secs);
5077 qemu_opt_set(hda_opts, "secs", num);
5078 if (translation == BIOS_ATA_TRANSLATION_LBA)
5079 qemu_opt_set(hda_opts, "trans", "lba");
5080 if (translation == BIOS_ATA_TRANSLATION_NONE)
5081 qemu_opt_set(hda_opts, "trans", "none");
5084 break;
5085 case QEMU_OPTION_numa:
5086 if (nb_numa_nodes >= MAX_NODES) {
5087 fprintf(stderr, "qemu: too many NUMA nodes\n");
5088 exit(1);
5090 numa_add(optarg);
5091 break;
5092 case QEMU_OPTION_nographic:
5093 display_type = DT_NOGRAPHIC;
5094 break;
5095 #ifdef CONFIG_CURSES
5096 case QEMU_OPTION_curses:
5097 display_type = DT_CURSES;
5098 break;
5099 #endif
5100 case QEMU_OPTION_portrait:
5101 graphic_rotate = 1;
5102 break;
5103 case QEMU_OPTION_kernel:
5104 kernel_filename = optarg;
5105 break;
5106 case QEMU_OPTION_append:
5107 kernel_cmdline = optarg;
5108 break;
5109 case QEMU_OPTION_cdrom:
5110 drive_add(optarg, CDROM_ALIAS);
5111 break;
5112 case QEMU_OPTION_boot:
5114 static const char * const params[] = {
5115 "order", "once", "menu", NULL
5117 char buf[sizeof(boot_devices)];
5118 char *standard_boot_devices;
5119 int legacy = 0;
5121 if (!strchr(optarg, '=')) {
5122 legacy = 1;
5123 pstrcpy(buf, sizeof(buf), optarg);
5124 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5125 fprintf(stderr,
5126 "qemu: unknown boot parameter '%s' in '%s'\n",
5127 buf, optarg);
5128 exit(1);
5131 if (legacy ||
5132 get_param_value(buf, sizeof(buf), "order", optarg)) {
5133 boot_devices_bitmap = parse_bootdevices(buf);
5134 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5136 if (!legacy) {
5137 if (get_param_value(buf, sizeof(buf),
5138 "once", optarg)) {
5139 boot_devices_bitmap |= parse_bootdevices(buf);
5140 standard_boot_devices = qemu_strdup(boot_devices);
5141 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5142 qemu_register_reset(restore_boot_devices,
5143 standard_boot_devices);
5145 if (get_param_value(buf, sizeof(buf),
5146 "menu", optarg)) {
5147 if (!strcmp(buf, "on")) {
5148 boot_menu = 1;
5149 } else if (!strcmp(buf, "off")) {
5150 boot_menu = 0;
5151 } else {
5152 fprintf(stderr,
5153 "qemu: invalid option value '%s'\n",
5154 buf);
5155 exit(1);
5160 break;
5161 case QEMU_OPTION_fda:
5162 case QEMU_OPTION_fdb:
5163 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5164 break;
5165 #ifdef TARGET_I386
5166 case QEMU_OPTION_no_fd_bootchk:
5167 fd_bootchk = 0;
5168 break;
5169 #endif
5170 case QEMU_OPTION_netdev:
5171 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5172 exit(1);
5174 break;
5175 case QEMU_OPTION_net:
5176 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5177 exit(1);
5179 break;
5180 #ifdef CONFIG_SLIRP
5181 case QEMU_OPTION_tftp:
5182 legacy_tftp_prefix = optarg;
5183 break;
5184 case QEMU_OPTION_bootp:
5185 legacy_bootp_filename = optarg;
5186 break;
5187 #ifndef _WIN32
5188 case QEMU_OPTION_smb:
5189 if (net_slirp_smb(optarg) < 0)
5190 exit(1);
5191 break;
5192 #endif
5193 case QEMU_OPTION_redir:
5194 if (net_slirp_redir(optarg) < 0)
5195 exit(1);
5196 break;
5197 #endif
5198 case QEMU_OPTION_bt:
5199 add_device_config(DEV_BT, optarg);
5200 break;
5201 #ifdef HAS_AUDIO
5202 case QEMU_OPTION_audio_help:
5203 AUD_help ();
5204 exit (0);
5205 break;
5206 case QEMU_OPTION_soundhw:
5207 select_soundhw (optarg);
5208 break;
5209 #endif
5210 case QEMU_OPTION_h:
5211 help(0);
5212 break;
5213 case QEMU_OPTION_version:
5214 version();
5215 exit(0);
5216 break;
5217 case QEMU_OPTION_m: {
5218 uint64_t value;
5219 char *ptr;
5221 value = strtoul(optarg, &ptr, 10);
5222 switch (*ptr) {
5223 case 0: case 'M': case 'm':
5224 value <<= 20;
5225 break;
5226 case 'G': case 'g':
5227 value <<= 30;
5228 break;
5229 default:
5230 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5231 exit(1);
5234 /* On 32-bit hosts, QEMU is limited by virtual address space */
5235 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5236 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5237 exit(1);
5239 if (value != (uint64_t)(ram_addr_t)value) {
5240 fprintf(stderr, "qemu: ram size too large\n");
5241 exit(1);
5243 ram_size = value;
5244 break;
5246 case QEMU_OPTION_d:
5248 int mask;
5249 const CPULogItem *item;
5251 mask = cpu_str_to_log_mask(optarg);
5252 if (!mask) {
5253 printf("Log items (comma separated):\n");
5254 for(item = cpu_log_items; item->mask != 0; item++) {
5255 printf("%-10s %s\n", item->name, item->help);
5257 exit(1);
5259 cpu_set_log(mask);
5261 break;
5262 case QEMU_OPTION_s:
5263 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5264 break;
5265 case QEMU_OPTION_gdb:
5266 gdbstub_dev = optarg;
5267 break;
5268 case QEMU_OPTION_L:
5269 data_dir = optarg;
5270 break;
5271 case QEMU_OPTION_bios:
5272 bios_name = optarg;
5273 break;
5274 case QEMU_OPTION_singlestep:
5275 singlestep = 1;
5276 break;
5277 case QEMU_OPTION_S:
5278 autostart = 0;
5279 break;
5280 case QEMU_OPTION_k:
5281 keyboard_layout = optarg;
5282 break;
5283 case QEMU_OPTION_localtime:
5284 rtc_utc = 0;
5285 break;
5286 case QEMU_OPTION_vga:
5287 select_vgahw (optarg);
5288 break;
5289 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5290 case QEMU_OPTION_g:
5292 const char *p;
5293 int w, h, depth;
5294 p = optarg;
5295 w = strtol(p, (char **)&p, 10);
5296 if (w <= 0) {
5297 graphic_error:
5298 fprintf(stderr, "qemu: invalid resolution or depth\n");
5299 exit(1);
5301 if (*p != 'x')
5302 goto graphic_error;
5303 p++;
5304 h = strtol(p, (char **)&p, 10);
5305 if (h <= 0)
5306 goto graphic_error;
5307 if (*p == 'x') {
5308 p++;
5309 depth = strtol(p, (char **)&p, 10);
5310 if (depth != 8 && depth != 15 && depth != 16 &&
5311 depth != 24 && depth != 32)
5312 goto graphic_error;
5313 } else if (*p == '\0') {
5314 depth = graphic_depth;
5315 } else {
5316 goto graphic_error;
5319 graphic_width = w;
5320 graphic_height = h;
5321 graphic_depth = depth;
5323 break;
5324 #endif
5325 case QEMU_OPTION_echr:
5327 char *r;
5328 term_escape_char = strtol(optarg, &r, 0);
5329 if (r == optarg)
5330 printf("Bad argument to echr\n");
5331 break;
5333 case QEMU_OPTION_monitor:
5334 monitor_parse(optarg, "readline");
5335 default_monitor = 0;
5336 break;
5337 case QEMU_OPTION_qmp:
5338 monitor_parse(optarg, "control");
5339 default_monitor = 0;
5340 break;
5341 case QEMU_OPTION_mon:
5342 opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5343 if (!opts) {
5344 fprintf(stderr, "parse error: %s\n", optarg);
5345 exit(1);
5347 default_monitor = 0;
5348 break;
5349 case QEMU_OPTION_chardev:
5350 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5351 if (!opts) {
5352 fprintf(stderr, "parse error: %s\n", optarg);
5353 exit(1);
5355 break;
5356 case QEMU_OPTION_serial:
5357 add_device_config(DEV_SERIAL, optarg);
5358 default_serial = 0;
5359 break;
5360 case QEMU_OPTION_watchdog:
5361 if (watchdog) {
5362 fprintf(stderr,
5363 "qemu: only one watchdog option may be given\n");
5364 return 1;
5366 watchdog = optarg;
5367 break;
5368 case QEMU_OPTION_watchdog_action:
5369 if (select_watchdog_action(optarg) == -1) {
5370 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5371 exit(1);
5373 break;
5374 case QEMU_OPTION_virtiocon:
5375 add_device_config(DEV_VIRTCON, optarg);
5376 default_virtcon = 0;
5377 break;
5378 case QEMU_OPTION_parallel:
5379 add_device_config(DEV_PARALLEL, optarg);
5380 default_parallel = 0;
5381 break;
5382 case QEMU_OPTION_loadvm:
5383 loadvm = optarg;
5384 break;
5385 case QEMU_OPTION_full_screen:
5386 full_screen = 1;
5387 break;
5388 #ifdef CONFIG_SDL
5389 case QEMU_OPTION_no_frame:
5390 no_frame = 1;
5391 break;
5392 case QEMU_OPTION_alt_grab:
5393 alt_grab = 1;
5394 break;
5395 case QEMU_OPTION_ctrl_grab:
5396 ctrl_grab = 1;
5397 break;
5398 case QEMU_OPTION_no_quit:
5399 no_quit = 1;
5400 break;
5401 case QEMU_OPTION_sdl:
5402 display_type = DT_SDL;
5403 break;
5404 #endif
5405 case QEMU_OPTION_pidfile:
5406 pid_file = optarg;
5407 break;
5408 #ifdef TARGET_I386
5409 case QEMU_OPTION_win2k_hack:
5410 win2k_install_hack = 1;
5411 break;
5412 case QEMU_OPTION_rtc_td_hack:
5413 rtc_td_hack = 1;
5414 break;
5415 case QEMU_OPTION_acpitable:
5416 if(acpi_table_add(optarg) < 0) {
5417 fprintf(stderr, "Wrong acpi table provided\n");
5418 exit(1);
5420 break;
5421 case QEMU_OPTION_smbios:
5422 if(smbios_entry_add(optarg) < 0) {
5423 fprintf(stderr, "Wrong smbios provided\n");
5424 exit(1);
5426 break;
5427 #endif
5428 #ifdef CONFIG_KVM
5429 case QEMU_OPTION_enable_kvm:
5430 kvm_allowed = 1;
5431 break;
5432 #endif
5433 case QEMU_OPTION_usb:
5434 usb_enabled = 1;
5435 break;
5436 case QEMU_OPTION_usbdevice:
5437 usb_enabled = 1;
5438 add_device_config(DEV_USB, optarg);
5439 break;
5440 case QEMU_OPTION_device:
5441 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5442 exit(1);
5444 break;
5445 case QEMU_OPTION_smp:
5446 smp_parse(optarg);
5447 if (smp_cpus < 1) {
5448 fprintf(stderr, "Invalid number of CPUs\n");
5449 exit(1);
5451 if (max_cpus < smp_cpus) {
5452 fprintf(stderr, "maxcpus must be equal to or greater than "
5453 "smp\n");
5454 exit(1);
5456 if (max_cpus > 255) {
5457 fprintf(stderr, "Unsupported number of maxcpus\n");
5458 exit(1);
5460 break;
5461 case QEMU_OPTION_vnc:
5462 display_type = DT_VNC;
5463 vnc_display = optarg;
5464 break;
5465 #ifdef TARGET_I386
5466 case QEMU_OPTION_no_acpi:
5467 acpi_enabled = 0;
5468 break;
5469 case QEMU_OPTION_no_hpet:
5470 no_hpet = 1;
5471 break;
5472 case QEMU_OPTION_balloon:
5473 if (balloon_parse(optarg) < 0) {
5474 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5475 exit(1);
5477 break;
5478 #endif
5479 case QEMU_OPTION_no_reboot:
5480 no_reboot = 1;
5481 break;
5482 case QEMU_OPTION_no_shutdown:
5483 no_shutdown = 1;
5484 break;
5485 case QEMU_OPTION_show_cursor:
5486 cursor_hide = 0;
5487 break;
5488 case QEMU_OPTION_uuid:
5489 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5490 fprintf(stderr, "Fail to parse UUID string."
5491 " Wrong format.\n");
5492 exit(1);
5494 break;
5495 #ifndef _WIN32
5496 case QEMU_OPTION_daemonize:
5497 daemonize = 1;
5498 break;
5499 #endif
5500 case QEMU_OPTION_option_rom:
5501 if (nb_option_roms >= MAX_OPTION_ROMS) {
5502 fprintf(stderr, "Too many option ROMs\n");
5503 exit(1);
5505 option_rom[nb_option_roms] = optarg;
5506 nb_option_roms++;
5507 break;
5508 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5509 case QEMU_OPTION_semihosting:
5510 semihosting_enabled = 1;
5511 break;
5512 #endif
5513 case QEMU_OPTION_name:
5514 qemu_name = qemu_strdup(optarg);
5516 char *p = strchr(qemu_name, ',');
5517 if (p != NULL) {
5518 *p++ = 0;
5519 if (strncmp(p, "process=", 8)) {
5520 fprintf(stderr, "Unknown subargument %s to -name", p);
5521 exit(1);
5523 p += 8;
5524 set_proc_name(p);
5527 break;
5528 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5529 case QEMU_OPTION_prom_env:
5530 if (nb_prom_envs >= MAX_PROM_ENVS) {
5531 fprintf(stderr, "Too many prom variables\n");
5532 exit(1);
5534 prom_envs[nb_prom_envs] = optarg;
5535 nb_prom_envs++;
5536 break;
5537 #endif
5538 #ifdef TARGET_ARM
5539 case QEMU_OPTION_old_param:
5540 old_param = 1;
5541 break;
5542 #endif
5543 case QEMU_OPTION_clock:
5544 configure_alarms(optarg);
5545 break;
5546 case QEMU_OPTION_startdate:
5547 configure_rtc_date_offset(optarg, 1);
5548 break;
5549 case QEMU_OPTION_rtc:
5550 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5551 if (!opts) {
5552 fprintf(stderr, "parse error: %s\n", optarg);
5553 exit(1);
5555 configure_rtc(opts);
5556 break;
5557 case QEMU_OPTION_tb_size:
5558 tb_size = strtol(optarg, NULL, 0);
5559 if (tb_size < 0)
5560 tb_size = 0;
5561 break;
5562 case QEMU_OPTION_icount:
5563 use_icount = 1;
5564 if (strcmp(optarg, "auto") == 0) {
5565 icount_time_shift = -1;
5566 } else {
5567 icount_time_shift = strtol(optarg, NULL, 0);
5569 break;
5570 case QEMU_OPTION_incoming:
5571 incoming = optarg;
5572 break;
5573 case QEMU_OPTION_nodefaults:
5574 default_serial = 0;
5575 default_parallel = 0;
5576 default_virtcon = 0;
5577 default_monitor = 0;
5578 default_vga = 0;
5579 default_net = 0;
5580 default_floppy = 0;
5581 default_cdrom = 0;
5582 default_sdcard = 0;
5583 break;
5584 #ifndef _WIN32
5585 case QEMU_OPTION_chroot:
5586 chroot_dir = optarg;
5587 break;
5588 case QEMU_OPTION_runas:
5589 run_as = optarg;
5590 break;
5591 #endif
5592 #ifdef CONFIG_XEN
5593 case QEMU_OPTION_xen_domid:
5594 xen_domid = atoi(optarg);
5595 break;
5596 case QEMU_OPTION_xen_create:
5597 xen_mode = XEN_CREATE;
5598 break;
5599 case QEMU_OPTION_xen_attach:
5600 xen_mode = XEN_ATTACH;
5601 break;
5602 #endif
5603 case QEMU_OPTION_readconfig:
5605 FILE *fp;
5606 fp = fopen(optarg, "r");
5607 if (fp == NULL) {
5608 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5609 exit(1);
5611 if (qemu_config_parse(fp) != 0) {
5612 exit(1);
5614 fclose(fp);
5615 break;
5617 case QEMU_OPTION_writeconfig:
5619 FILE *fp;
5620 if (strcmp(optarg, "-") == 0) {
5621 fp = stdout;
5622 } else {
5623 fp = fopen(optarg, "w");
5624 if (fp == NULL) {
5625 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5626 exit(1);
5629 qemu_config_write(fp);
5630 fclose(fp);
5631 break;
5637 /* If no data_dir is specified then try to find it relative to the
5638 executable path. */
5639 if (!data_dir) {
5640 data_dir = find_datadir(argv[0]);
5642 /* If all else fails use the install patch specified when building. */
5643 if (!data_dir) {
5644 data_dir = CONFIG_QEMU_SHAREDIR;
5648 * Default to max_cpus = smp_cpus, in case the user doesn't
5649 * specify a max_cpus value.
5651 if (!max_cpus)
5652 max_cpus = smp_cpus;
5654 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5655 if (smp_cpus > machine->max_cpus) {
5656 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5657 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5658 machine->max_cpus);
5659 exit(1);
5662 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5663 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5665 if (machine->no_serial) {
5666 default_serial = 0;
5668 if (machine->no_parallel) {
5669 default_parallel = 0;
5671 if (!machine->use_virtcon) {
5672 default_virtcon = 0;
5674 if (machine->no_vga) {
5675 default_vga = 0;
5677 if (machine->no_floppy) {
5678 default_floppy = 0;
5680 if (machine->no_cdrom) {
5681 default_cdrom = 0;
5683 if (machine->no_sdcard) {
5684 default_sdcard = 0;
5687 if (display_type == DT_NOGRAPHIC) {
5688 if (default_parallel)
5689 add_device_config(DEV_PARALLEL, "null");
5690 if (default_serial && default_monitor) {
5691 add_device_config(DEV_SERIAL, "mon:stdio");
5692 } else if (default_virtcon && default_monitor) {
5693 add_device_config(DEV_VIRTCON, "mon:stdio");
5694 } else {
5695 if (default_serial)
5696 add_device_config(DEV_SERIAL, "stdio");
5697 if (default_virtcon)
5698 add_device_config(DEV_VIRTCON, "stdio");
5699 if (default_monitor)
5700 monitor_parse("stdio", "readline");
5702 } else {
5703 if (default_serial)
5704 add_device_config(DEV_SERIAL, "vc:80Cx24C");
5705 if (default_parallel)
5706 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5707 if (default_monitor)
5708 monitor_parse("vc:80Cx24C", "readline");
5709 if (default_virtcon)
5710 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5712 if (default_vga)
5713 vga_interface_type = VGA_CIRRUS;
5715 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5716 exit(1);
5718 #ifndef _WIN32
5719 if (daemonize) {
5720 pid_t pid;
5722 if (pipe(fds) == -1)
5723 exit(1);
5725 pid = fork();
5726 if (pid > 0) {
5727 uint8_t status;
5728 ssize_t len;
5730 close(fds[1]);
5732 again:
5733 len = read(fds[0], &status, 1);
5734 if (len == -1 && (errno == EINTR))
5735 goto again;
5737 if (len != 1)
5738 exit(1);
5739 else if (status == 1) {
5740 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5741 exit(1);
5742 } else
5743 exit(0);
5744 } else if (pid < 0)
5745 exit(1);
5747 close(fds[0]);
5748 qemu_set_cloexec(fds[1]);
5750 setsid();
5752 pid = fork();
5753 if (pid > 0)
5754 exit(0);
5755 else if (pid < 0)
5756 exit(1);
5758 umask(027);
5760 signal(SIGTSTP, SIG_IGN);
5761 signal(SIGTTOU, SIG_IGN);
5762 signal(SIGTTIN, SIG_IGN);
5764 #endif
5766 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5767 #ifndef _WIN32
5768 if (daemonize) {
5769 uint8_t status = 1;
5770 write(fds[1], &status, 1);
5771 } else
5772 #endif
5773 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5774 exit(1);
5777 if (kvm_enabled()) {
5778 int ret;
5780 ret = kvm_init(smp_cpus);
5781 if (ret < 0) {
5782 fprintf(stderr, "failed to initialize KVM\n");
5783 exit(1);
5787 if (qemu_init_main_loop()) {
5788 fprintf(stderr, "qemu_init_main_loop failed\n");
5789 exit(1);
5791 linux_boot = (kernel_filename != NULL);
5793 if (!linux_boot && *kernel_cmdline != '\0') {
5794 fprintf(stderr, "-append only allowed with -kernel option\n");
5795 exit(1);
5798 if (!linux_boot && initrd_filename != NULL) {
5799 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5800 exit(1);
5803 #ifndef _WIN32
5804 /* Win32 doesn't support line-buffering and requires size >= 2 */
5805 setvbuf(stdout, NULL, _IOLBF, 0);
5806 #endif
5808 if (init_timer_alarm() < 0) {
5809 fprintf(stderr, "could not initialize alarm timer\n");
5810 exit(1);
5812 if (use_icount && icount_time_shift < 0) {
5813 use_icount = 2;
5814 /* 125MIPS seems a reasonable initial guess at the guest speed.
5815 It will be corrected fairly quickly anyway. */
5816 icount_time_shift = 3;
5817 init_icount_adjust();
5820 #ifdef _WIN32
5821 socket_init();
5822 #endif
5824 if (net_init_clients() < 0) {
5825 exit(1);
5828 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5829 net_set_boot_mask(net_boot);
5831 /* init the bluetooth world */
5832 if (foreach_device_config(DEV_BT, bt_parse))
5833 exit(1);
5835 /* init the memory */
5836 if (ram_size == 0)
5837 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5839 /* init the dynamic translator */
5840 cpu_exec_init_all(tb_size * 1024 * 1024);
5842 bdrv_init_with_whitelist();
5844 blk_mig_init();
5846 if (default_cdrom) {
5847 /* we always create the cdrom drive, even if no disk is there */
5848 drive_add(NULL, CDROM_ALIAS);
5851 if (default_floppy) {
5852 /* we always create at least one floppy */
5853 drive_add(NULL, FD_ALIAS, 0);
5856 if (default_sdcard) {
5857 /* we always create one sd slot, even if no card is in it */
5858 drive_add(NULL, SD_ALIAS);
5861 /* open the virtual block devices */
5862 if (snapshot)
5863 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5864 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5865 exit(1);
5867 vmstate_register(0, &vmstate_timers ,&timers_state);
5868 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5869 ram_load, NULL);
5871 if (nb_numa_nodes > 0) {
5872 int i;
5874 if (nb_numa_nodes > smp_cpus) {
5875 nb_numa_nodes = smp_cpus;
5878 /* If no memory size if given for any node, assume the default case
5879 * and distribute the available memory equally across all nodes
5881 for (i = 0; i < nb_numa_nodes; i++) {
5882 if (node_mem[i] != 0)
5883 break;
5885 if (i == nb_numa_nodes) {
5886 uint64_t usedmem = 0;
5888 /* On Linux, the each node's border has to be 8MB aligned,
5889 * the final node gets the rest.
5891 for (i = 0; i < nb_numa_nodes - 1; i++) {
5892 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5893 usedmem += node_mem[i];
5895 node_mem[i] = ram_size - usedmem;
5898 for (i = 0; i < nb_numa_nodes; i++) {
5899 if (node_cpumask[i] != 0)
5900 break;
5902 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5903 * must cope with this anyway, because there are BIOSes out there in
5904 * real machines which also use this scheme.
5906 if (i == nb_numa_nodes) {
5907 for (i = 0; i < smp_cpus; i++) {
5908 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5913 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5914 exit(1);
5915 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5916 exit(1);
5917 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5918 exit(1);
5920 module_call_init(MODULE_INIT_DEVICE);
5922 if (watchdog) {
5923 i = select_watchdog(watchdog);
5924 if (i > 0)
5925 exit (i == 1 ? 1 : 0);
5928 if (machine->compat_props) {
5929 qdev_prop_register_global_list(machine->compat_props);
5931 qemu_add_globals();
5933 machine->init(ram_size, boot_devices,
5934 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5937 #ifndef _WIN32
5938 /* must be after terminal init, SDL library changes signal handlers */
5939 sighandler_setup();
5940 #endif
5942 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5943 for (i = 0; i < nb_numa_nodes; i++) {
5944 if (node_cpumask[i] & (1 << env->cpu_index)) {
5945 env->numa_node = i;
5950 current_machine = machine;
5952 /* init USB devices */
5953 if (usb_enabled) {
5954 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5955 exit(1);
5958 /* init generic devices */
5959 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5960 exit(1);
5962 if (!display_state)
5963 dumb_display_init();
5964 /* just use the first displaystate for the moment */
5965 ds = display_state;
5967 if (display_type == DT_DEFAULT) {
5968 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5969 display_type = DT_SDL;
5970 #else
5971 display_type = DT_VNC;
5972 vnc_display = "localhost:0,to=99";
5973 show_vnc_port = 1;
5974 #endif
5978 switch (display_type) {
5979 case DT_NOGRAPHIC:
5980 break;
5981 #if defined(CONFIG_CURSES)
5982 case DT_CURSES:
5983 curses_display_init(ds, full_screen);
5984 break;
5985 #endif
5986 #if defined(CONFIG_SDL)
5987 case DT_SDL:
5988 sdl_display_init(ds, full_screen, no_frame);
5989 break;
5990 #elif defined(CONFIG_COCOA)
5991 case DT_SDL:
5992 cocoa_display_init(ds, full_screen);
5993 break;
5994 #endif
5995 case DT_VNC:
5996 vnc_display_init(ds);
5997 if (vnc_display_open(ds, vnc_display) < 0)
5998 exit(1);
6000 if (show_vnc_port) {
6001 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6003 break;
6004 default:
6005 break;
6007 dpy_resize(ds);
6009 dcl = ds->listeners;
6010 while (dcl != NULL) {
6011 if (dcl->dpy_refresh != NULL) {
6012 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6013 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6015 dcl = dcl->next;
6018 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6019 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6020 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6023 text_consoles_set_display(display_state);
6025 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6026 exit(1);
6028 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6029 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6030 gdbstub_dev);
6031 exit(1);
6034 qdev_machine_creation_done();
6036 if (rom_load_all() != 0) {
6037 fprintf(stderr, "rom loading failed\n");
6038 exit(1);
6041 qemu_system_reset();
6042 if (loadvm) {
6043 if (load_vmstate(cur_mon, loadvm) < 0) {
6044 autostart = 0;
6048 if (incoming) {
6049 qemu_start_incoming_migration(incoming);
6050 } else if (autostart) {
6051 vm_start();
6054 #ifndef _WIN32
6055 if (daemonize) {
6056 uint8_t status = 0;
6057 ssize_t len;
6059 again1:
6060 len = write(fds[1], &status, 1);
6061 if (len == -1 && (errno == EINTR))
6062 goto again1;
6064 if (len != 1)
6065 exit(1);
6067 chdir("/");
6068 TFR(fd = qemu_open("/dev/null", O_RDWR));
6069 if (fd == -1)
6070 exit(1);
6073 if (run_as) {
6074 pwd = getpwnam(run_as);
6075 if (!pwd) {
6076 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6077 exit(1);
6081 if (chroot_dir) {
6082 if (chroot(chroot_dir) < 0) {
6083 fprintf(stderr, "chroot failed\n");
6084 exit(1);
6086 chdir("/");
6089 if (run_as) {
6090 if (setgid(pwd->pw_gid) < 0) {
6091 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6092 exit(1);
6094 if (setuid(pwd->pw_uid) < 0) {
6095 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6096 exit(1);
6098 if (setuid(0) != -1) {
6099 fprintf(stderr, "Dropping privileges failed\n");
6100 exit(1);
6104 if (daemonize) {
6105 dup2(fd, 0);
6106 dup2(fd, 1);
6107 dup2(fd, 2);
6109 close(fd);
6111 #endif
6113 main_loop();
6114 quit_timers();
6115 net_cleanup();
6117 return 0;