honor -S on incoming migration
[qemu/wangdongxu.git] / vl.c
blob24173efefbaff5a33dbdf9c38ece96c5fc5eb90c
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 HOST_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 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
49 #endif
50 #ifdef __linux__
51 #include <linux/if_tun.h>
52 #endif
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef HOST_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
60 #include <libutil.h>
61 #else
62 #include <util.h>
63 #endif
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
66 #else
67 #ifdef __linux__
68 #include <pty.h>
69 #include <malloc.h>
70 #include <linux/rtc.h>
71 #include <sys/prctl.h>
73 /* For the benefit of older linux systems which don't supply it,
74 we use a local copy of hpet.h. */
75 /* #include <linux/hpet.h> */
76 #include "hpet.h"
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
80 #endif
81 #ifdef __sun__
82 #include <sys/stat.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
92 #include <net/if.h>
93 #include <syslog.h>
94 #include <stropts.h>
95 #endif
96 #endif
97 #endif
99 #if defined(__OpenBSD__)
100 #include <util.h>
101 #endif
103 #if defined(CONFIG_VDE)
104 #include <libvdeplug.h>
105 #endif
107 #ifdef _WIN32
108 #include <windows.h>
109 #include <malloc.h>
110 #include <sys/timeb.h>
111 #include <mmsystem.h>
112 #define getopt_long_only getopt_long
113 #define memalign(align, size) malloc(size)
114 #endif
116 #ifdef CONFIG_SDL
117 #if defined(__APPLE__) || defined(main)
118 #include <SDL.h>
119 int qemu_main(int argc, char **argv, char **envp);
120 int main(int argc, char **argv)
122 return qemu_main(argc, argv, NULL);
124 #undef main
125 #define main qemu_main
126 #endif
127 #endif /* CONFIG_SDL */
129 #ifdef CONFIG_COCOA
130 #undef main
131 #define main qemu_main
132 #endif /* CONFIG_COCOA */
134 #include "hw/hw.h"
135 #include "hw/boards.h"
136 #include "hw/usb.h"
137 #include "hw/pcmcia.h"
138 #include "hw/pc.h"
139 #include "hw/audiodev.h"
140 #include "hw/isa.h"
141 #include "hw/baum.h"
142 #include "hw/bt.h"
143 #include "hw/watchdog.h"
144 #include "hw/smbios.h"
145 #include "hw/xen.h"
146 #include "bt-host.h"
147 #include "net.h"
148 #include "monitor.h"
149 #include "console.h"
150 #include "sysemu.h"
151 #include "gdbstub.h"
152 #include "qemu-timer.h"
153 #include "qemu-char.h"
154 #include "cache-utils.h"
155 #include "block.h"
156 #include "dma.h"
157 #include "audio/audio.h"
158 #include "migration.h"
159 #include "kvm.h"
160 #include "balloon.h"
161 #include "qemu-option.h"
163 #include "disas.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #include "slirp/libslirp.h"
171 //#define DEBUG_NET
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 /* Max number of USB devices that can be specified on the commandline. */
177 #define MAX_USB_CMDLINE 8
179 /* Max number of bluetooth switches on the commandline. */
180 #define MAX_BT_CMDLINE 10
182 static const char *data_dir;
183 const char *bios_name = NULL;
184 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
185 to store the VM snapshots */
186 DriveInfo drives_table[MAX_DRIVES+1];
187 int nb_drives;
188 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
189 static DisplayState *display_state;
190 DisplayType display_type = DT_DEFAULT;
191 const char* keyboard_layout = NULL;
192 int64_t ticks_per_sec;
193 ram_addr_t ram_size;
194 int nb_nics;
195 NICInfo nd_table[MAX_NICS];
196 int vm_running;
197 static int autostart;
198 static int rtc_utc = 1;
199 static int rtc_date_offset = -1; /* -1 means no change */
200 int cirrus_vga_enabled = 1;
201 int std_vga_enabled = 0;
202 int vmsvga_enabled = 0;
203 int xenfb_enabled = 0;
204 #ifdef TARGET_SPARC
205 int graphic_width = 1024;
206 int graphic_height = 768;
207 int graphic_depth = 8;
208 #else
209 int graphic_width = 800;
210 int graphic_height = 600;
211 int graphic_depth = 15;
212 #endif
213 static int full_screen = 0;
214 #ifdef CONFIG_SDL
215 static int no_frame = 0;
216 #endif
217 int no_quit = 0;
218 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
219 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
220 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
221 #ifdef TARGET_I386
222 int win2k_install_hack = 0;
223 int rtc_td_hack = 0;
224 #endif
225 int usb_enabled = 0;
226 int singlestep = 0;
227 int smp_cpus = 1;
228 const char *vnc_display;
229 int acpi_enabled = 1;
230 int no_hpet = 0;
231 int virtio_balloon = 1;
232 const char *virtio_balloon_devaddr;
233 int fd_bootchk = 1;
234 int no_reboot = 0;
235 int no_shutdown = 0;
236 int cursor_hide = 1;
237 int graphic_rotate = 0;
238 #ifndef _WIN32
239 int daemonize = 0;
240 #endif
241 WatchdogTimerModel *watchdog = NULL;
242 int watchdog_action = WDT_RESET;
243 const char *option_rom[MAX_OPTION_ROMS];
244 int nb_option_roms;
245 int semihosting_enabled = 0;
246 #ifdef TARGET_ARM
247 int old_param = 0;
248 #endif
249 const char *qemu_name;
250 int alt_grab = 0;
251 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
252 unsigned int nb_prom_envs = 0;
253 const char *prom_envs[MAX_PROM_ENVS];
254 #endif
255 int nb_drives_opt;
256 struct drive_opt drives_opt[MAX_DRIVES];
257 int boot_menu;
259 int nb_numa_nodes;
260 uint64_t node_mem[MAX_NODES];
261 uint64_t node_cpumask[MAX_NODES];
263 static CPUState *cur_cpu;
264 static CPUState *next_cpu;
265 static int timer_alarm_pending = 1;
266 /* Conversion factor from emulated instructions to virtual clock ticks. */
267 static int icount_time_shift;
268 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
269 #define MAX_ICOUNT_SHIFT 10
270 /* Compensate for varying guest execution speed. */
271 static int64_t qemu_icount_bias;
272 static QEMUTimer *icount_rt_timer;
273 static QEMUTimer *icount_vm_timer;
274 static QEMUTimer *nographic_timer;
276 uint8_t qemu_uuid[16];
278 static QEMUBootSetHandler *boot_set_handler;
279 static void *boot_set_opaque;
281 /***********************************************************/
282 /* x86 ISA bus support */
284 target_phys_addr_t isa_mem_base = 0;
285 PicState2 *isa_pic;
287 /***********************************************************/
288 void hw_error(const char *fmt, ...)
290 va_list ap;
291 CPUState *env;
293 va_start(ap, fmt);
294 fprintf(stderr, "qemu: hardware error: ");
295 vfprintf(stderr, fmt, ap);
296 fprintf(stderr, "\n");
297 for(env = first_cpu; env != NULL; env = env->next_cpu) {
298 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
299 #ifdef TARGET_I386
300 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
301 #else
302 cpu_dump_state(env, stderr, fprintf, 0);
303 #endif
305 va_end(ap);
306 abort();
309 static void set_proc_name(const char *s)
311 #ifdef __linux__
312 char name[16];
313 if (!s)
314 return;
315 name[sizeof(name) - 1] = 0;
316 strncpy(name, s, sizeof(name));
317 /* Could rewrite argv[0] too, but that's a bit more complicated.
318 This simple way is enough for `top'. */
319 prctl(PR_SET_NAME, name);
320 #endif
323 /***************/
324 /* ballooning */
326 static QEMUBalloonEvent *qemu_balloon_event;
327 void *qemu_balloon_event_opaque;
329 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
331 qemu_balloon_event = func;
332 qemu_balloon_event_opaque = opaque;
335 void qemu_balloon(ram_addr_t target)
337 if (qemu_balloon_event)
338 qemu_balloon_event(qemu_balloon_event_opaque, target);
341 ram_addr_t qemu_balloon_status(void)
343 if (qemu_balloon_event)
344 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
345 return 0;
348 /***********************************************************/
349 /* keyboard/mouse */
351 static QEMUPutKBDEvent *qemu_put_kbd_event;
352 static void *qemu_put_kbd_event_opaque;
353 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
354 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
356 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
358 qemu_put_kbd_event_opaque = opaque;
359 qemu_put_kbd_event = func;
362 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
363 void *opaque, int absolute,
364 const char *name)
366 QEMUPutMouseEntry *s, *cursor;
368 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
370 s->qemu_put_mouse_event = func;
371 s->qemu_put_mouse_event_opaque = opaque;
372 s->qemu_put_mouse_event_absolute = absolute;
373 s->qemu_put_mouse_event_name = qemu_strdup(name);
374 s->next = NULL;
376 if (!qemu_put_mouse_event_head) {
377 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
378 return s;
381 cursor = qemu_put_mouse_event_head;
382 while (cursor->next != NULL)
383 cursor = cursor->next;
385 cursor->next = s;
386 qemu_put_mouse_event_current = s;
388 return s;
391 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
393 QEMUPutMouseEntry *prev = NULL, *cursor;
395 if (!qemu_put_mouse_event_head || entry == NULL)
396 return;
398 cursor = qemu_put_mouse_event_head;
399 while (cursor != NULL && cursor != entry) {
400 prev = cursor;
401 cursor = cursor->next;
404 if (cursor == NULL) // does not exist or list empty
405 return;
406 else if (prev == NULL) { // entry is head
407 qemu_put_mouse_event_head = cursor->next;
408 if (qemu_put_mouse_event_current == entry)
409 qemu_put_mouse_event_current = cursor->next;
410 qemu_free(entry->qemu_put_mouse_event_name);
411 qemu_free(entry);
412 return;
415 prev->next = entry->next;
417 if (qemu_put_mouse_event_current == entry)
418 qemu_put_mouse_event_current = prev;
420 qemu_free(entry->qemu_put_mouse_event_name);
421 qemu_free(entry);
424 void kbd_put_keycode(int keycode)
426 if (qemu_put_kbd_event) {
427 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
431 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
433 QEMUPutMouseEvent *mouse_event;
434 void *mouse_event_opaque;
435 int width;
437 if (!qemu_put_mouse_event_current) {
438 return;
441 mouse_event =
442 qemu_put_mouse_event_current->qemu_put_mouse_event;
443 mouse_event_opaque =
444 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
446 if (mouse_event) {
447 if (graphic_rotate) {
448 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
449 width = 0x7fff;
450 else
451 width = graphic_width - 1;
452 mouse_event(mouse_event_opaque,
453 width - dy, dx, dz, buttons_state);
454 } else
455 mouse_event(mouse_event_opaque,
456 dx, dy, dz, buttons_state);
460 int kbd_mouse_is_absolute(void)
462 if (!qemu_put_mouse_event_current)
463 return 0;
465 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
468 void do_info_mice(Monitor *mon)
470 QEMUPutMouseEntry *cursor;
471 int index = 0;
473 if (!qemu_put_mouse_event_head) {
474 monitor_printf(mon, "No mouse devices connected\n");
475 return;
478 monitor_printf(mon, "Mouse devices available:\n");
479 cursor = qemu_put_mouse_event_head;
480 while (cursor != NULL) {
481 monitor_printf(mon, "%c Mouse #%d: %s\n",
482 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
483 index, cursor->qemu_put_mouse_event_name);
484 index++;
485 cursor = cursor->next;
489 void do_mouse_set(Monitor *mon, int index)
491 QEMUPutMouseEntry *cursor;
492 int i = 0;
494 if (!qemu_put_mouse_event_head) {
495 monitor_printf(mon, "No mouse devices connected\n");
496 return;
499 cursor = qemu_put_mouse_event_head;
500 while (cursor != NULL && index != i) {
501 i++;
502 cursor = cursor->next;
505 if (cursor != NULL)
506 qemu_put_mouse_event_current = cursor;
507 else
508 monitor_printf(mon, "Mouse at given index not found\n");
511 /* compute with 96 bit intermediate result: (a*b)/c */
512 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
514 union {
515 uint64_t ll;
516 struct {
517 #ifdef WORDS_BIGENDIAN
518 uint32_t high, low;
519 #else
520 uint32_t low, high;
521 #endif
522 } l;
523 } u, res;
524 uint64_t rl, rh;
526 u.ll = a;
527 rl = (uint64_t)u.l.low * (uint64_t)b;
528 rh = (uint64_t)u.l.high * (uint64_t)b;
529 rh += (rl >> 32);
530 res.l.high = rh / c;
531 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
532 return res.ll;
535 /***********************************************************/
536 /* real time host monotonic timer */
538 #define QEMU_TIMER_BASE 1000000000LL
540 #ifdef WIN32
542 static int64_t clock_freq;
544 static void init_get_clock(void)
546 LARGE_INTEGER freq;
547 int ret;
548 ret = QueryPerformanceFrequency(&freq);
549 if (ret == 0) {
550 fprintf(stderr, "Could not calibrate ticks\n");
551 exit(1);
553 clock_freq = freq.QuadPart;
556 static int64_t get_clock(void)
558 LARGE_INTEGER ti;
559 QueryPerformanceCounter(&ti);
560 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
563 #else
565 static int use_rt_clock;
567 static void init_get_clock(void)
569 use_rt_clock = 0;
570 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
571 || defined(__DragonFly__)
573 struct timespec ts;
574 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
575 use_rt_clock = 1;
578 #endif
581 static int64_t get_clock(void)
583 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
584 || defined(__DragonFly__)
585 if (use_rt_clock) {
586 struct timespec ts;
587 clock_gettime(CLOCK_MONOTONIC, &ts);
588 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
589 } else
590 #endif
592 /* XXX: using gettimeofday leads to problems if the date
593 changes, so it should be avoided. */
594 struct timeval tv;
595 gettimeofday(&tv, NULL);
596 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
599 #endif
601 /* Return the virtual CPU time, based on the instruction counter. */
602 static int64_t cpu_get_icount(void)
604 int64_t icount;
605 CPUState *env = cpu_single_env;;
606 icount = qemu_icount;
607 if (env) {
608 if (!can_do_io(env))
609 fprintf(stderr, "Bad clock read\n");
610 icount -= (env->icount_decr.u16.low + env->icount_extra);
612 return qemu_icount_bias + (icount << icount_time_shift);
615 /***********************************************************/
616 /* guest cycle counter */
618 static int64_t cpu_ticks_prev;
619 static int64_t cpu_ticks_offset;
620 static int64_t cpu_clock_offset;
621 static int cpu_ticks_enabled;
623 /* return the host CPU cycle counter and handle stop/restart */
624 int64_t cpu_get_ticks(void)
626 if (use_icount) {
627 return cpu_get_icount();
629 if (!cpu_ticks_enabled) {
630 return cpu_ticks_offset;
631 } else {
632 int64_t ticks;
633 ticks = cpu_get_real_ticks();
634 if (cpu_ticks_prev > ticks) {
635 /* Note: non increasing ticks may happen if the host uses
636 software suspend */
637 cpu_ticks_offset += cpu_ticks_prev - ticks;
639 cpu_ticks_prev = ticks;
640 return ticks + cpu_ticks_offset;
644 /* return the host CPU monotonic timer and handle stop/restart */
645 static int64_t cpu_get_clock(void)
647 int64_t ti;
648 if (!cpu_ticks_enabled) {
649 return cpu_clock_offset;
650 } else {
651 ti = get_clock();
652 return ti + cpu_clock_offset;
656 /* enable cpu_get_ticks() */
657 void cpu_enable_ticks(void)
659 if (!cpu_ticks_enabled) {
660 cpu_ticks_offset -= cpu_get_real_ticks();
661 cpu_clock_offset -= get_clock();
662 cpu_ticks_enabled = 1;
666 /* disable cpu_get_ticks() : the clock is stopped. You must not call
667 cpu_get_ticks() after that. */
668 void cpu_disable_ticks(void)
670 if (cpu_ticks_enabled) {
671 cpu_ticks_offset = cpu_get_ticks();
672 cpu_clock_offset = cpu_get_clock();
673 cpu_ticks_enabled = 0;
677 /***********************************************************/
678 /* timers */
680 #define QEMU_TIMER_REALTIME 0
681 #define QEMU_TIMER_VIRTUAL 1
683 struct QEMUClock {
684 int type;
685 /* XXX: add frequency */
688 struct QEMUTimer {
689 QEMUClock *clock;
690 int64_t expire_time;
691 QEMUTimerCB *cb;
692 void *opaque;
693 struct QEMUTimer *next;
696 struct qemu_alarm_timer {
697 char const *name;
698 unsigned int flags;
700 int (*start)(struct qemu_alarm_timer *t);
701 void (*stop)(struct qemu_alarm_timer *t);
702 void (*rearm)(struct qemu_alarm_timer *t);
703 void *priv;
706 #define ALARM_FLAG_DYNTICKS 0x1
707 #define ALARM_FLAG_EXPIRED 0x2
709 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
711 return t && (t->flags & ALARM_FLAG_DYNTICKS);
714 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
716 if (!alarm_has_dynticks(t))
717 return;
719 t->rearm(t);
722 /* TODO: MIN_TIMER_REARM_US should be optimized */
723 #define MIN_TIMER_REARM_US 250
725 static struct qemu_alarm_timer *alarm_timer;
727 #ifdef _WIN32
729 struct qemu_alarm_win32 {
730 MMRESULT timerId;
731 unsigned int period;
732 } alarm_win32_data = {0, -1};
734 static int win32_start_timer(struct qemu_alarm_timer *t);
735 static void win32_stop_timer(struct qemu_alarm_timer *t);
736 static void win32_rearm_timer(struct qemu_alarm_timer *t);
738 #else
740 static int unix_start_timer(struct qemu_alarm_timer *t);
741 static void unix_stop_timer(struct qemu_alarm_timer *t);
743 #ifdef __linux__
745 static int dynticks_start_timer(struct qemu_alarm_timer *t);
746 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
747 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
749 static int hpet_start_timer(struct qemu_alarm_timer *t);
750 static void hpet_stop_timer(struct qemu_alarm_timer *t);
752 static int rtc_start_timer(struct qemu_alarm_timer *t);
753 static void rtc_stop_timer(struct qemu_alarm_timer *t);
755 #endif /* __linux__ */
757 #endif /* _WIN32 */
759 /* Correlation between real and virtual time is always going to be
760 fairly approximate, so ignore small variation.
761 When the guest is idle real and virtual time will be aligned in
762 the IO wait loop. */
763 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
765 static void icount_adjust(void)
767 int64_t cur_time;
768 int64_t cur_icount;
769 int64_t delta;
770 static int64_t last_delta;
771 /* If the VM is not running, then do nothing. */
772 if (!vm_running)
773 return;
775 cur_time = cpu_get_clock();
776 cur_icount = qemu_get_clock(vm_clock);
777 delta = cur_icount - cur_time;
778 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
779 if (delta > 0
780 && last_delta + ICOUNT_WOBBLE < delta * 2
781 && icount_time_shift > 0) {
782 /* The guest is getting too far ahead. Slow time down. */
783 icount_time_shift--;
785 if (delta < 0
786 && last_delta - ICOUNT_WOBBLE > delta * 2
787 && icount_time_shift < MAX_ICOUNT_SHIFT) {
788 /* The guest is getting too far behind. Speed time up. */
789 icount_time_shift++;
791 last_delta = delta;
792 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
795 static void icount_adjust_rt(void * opaque)
797 qemu_mod_timer(icount_rt_timer,
798 qemu_get_clock(rt_clock) + 1000);
799 icount_adjust();
802 static void icount_adjust_vm(void * opaque)
804 qemu_mod_timer(icount_vm_timer,
805 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
806 icount_adjust();
809 static void init_icount_adjust(void)
811 /* Have both realtime and virtual time triggers for speed adjustment.
812 The realtime trigger catches emulated time passing too slowly,
813 the virtual time trigger catches emulated time passing too fast.
814 Realtime triggers occur even when idle, so use them less frequently
815 than VM triggers. */
816 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
817 qemu_mod_timer(icount_rt_timer,
818 qemu_get_clock(rt_clock) + 1000);
819 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
820 qemu_mod_timer(icount_vm_timer,
821 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
824 static struct qemu_alarm_timer alarm_timers[] = {
825 #ifndef _WIN32
826 #ifdef __linux__
827 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
828 dynticks_stop_timer, dynticks_rearm_timer, NULL},
829 /* HPET - if available - is preferred */
830 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
831 /* ...otherwise try RTC */
832 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
833 #endif
834 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
835 #else
836 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
837 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
838 {"win32", 0, win32_start_timer,
839 win32_stop_timer, NULL, &alarm_win32_data},
840 #endif
841 {NULL, }
844 static void show_available_alarms(void)
846 int i;
848 printf("Available alarm timers, in order of precedence:\n");
849 for (i = 0; alarm_timers[i].name; i++)
850 printf("%s\n", alarm_timers[i].name);
853 static void configure_alarms(char const *opt)
855 int i;
856 int cur = 0;
857 int count = ARRAY_SIZE(alarm_timers) - 1;
858 char *arg;
859 char *name;
860 struct qemu_alarm_timer tmp;
862 if (!strcmp(opt, "?")) {
863 show_available_alarms();
864 exit(0);
867 arg = strdup(opt);
869 /* Reorder the array */
870 name = strtok(arg, ",");
871 while (name) {
872 for (i = 0; i < count && alarm_timers[i].name; i++) {
873 if (!strcmp(alarm_timers[i].name, name))
874 break;
877 if (i == count) {
878 fprintf(stderr, "Unknown clock %s\n", name);
879 goto next;
882 if (i < cur)
883 /* Ignore */
884 goto next;
886 /* Swap */
887 tmp = alarm_timers[i];
888 alarm_timers[i] = alarm_timers[cur];
889 alarm_timers[cur] = tmp;
891 cur++;
892 next:
893 name = strtok(NULL, ",");
896 free(arg);
898 if (cur) {
899 /* Disable remaining timers */
900 for (i = cur; i < count; i++)
901 alarm_timers[i].name = NULL;
902 } else {
903 show_available_alarms();
904 exit(1);
908 QEMUClock *rt_clock;
909 QEMUClock *vm_clock;
911 static QEMUTimer *active_timers[2];
913 static QEMUClock *qemu_new_clock(int type)
915 QEMUClock *clock;
916 clock = qemu_mallocz(sizeof(QEMUClock));
917 clock->type = type;
918 return clock;
921 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
923 QEMUTimer *ts;
925 ts = qemu_mallocz(sizeof(QEMUTimer));
926 ts->clock = clock;
927 ts->cb = cb;
928 ts->opaque = opaque;
929 return ts;
932 void qemu_free_timer(QEMUTimer *ts)
934 qemu_free(ts);
937 /* stop a timer, but do not dealloc it */
938 void qemu_del_timer(QEMUTimer *ts)
940 QEMUTimer **pt, *t;
942 /* NOTE: this code must be signal safe because
943 qemu_timer_expired() can be called from a signal. */
944 pt = &active_timers[ts->clock->type];
945 for(;;) {
946 t = *pt;
947 if (!t)
948 break;
949 if (t == ts) {
950 *pt = t->next;
951 break;
953 pt = &t->next;
957 /* modify the current timer so that it will be fired when current_time
958 >= expire_time. The corresponding callback will be called. */
959 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
961 QEMUTimer **pt, *t;
963 qemu_del_timer(ts);
965 /* add the timer in the sorted list */
966 /* NOTE: this code must be signal safe because
967 qemu_timer_expired() can be called from a signal. */
968 pt = &active_timers[ts->clock->type];
969 for(;;) {
970 t = *pt;
971 if (!t)
972 break;
973 if (t->expire_time > expire_time)
974 break;
975 pt = &t->next;
977 ts->expire_time = expire_time;
978 ts->next = *pt;
979 *pt = ts;
981 /* Rearm if necessary */
982 if (pt == &active_timers[ts->clock->type]) {
983 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
984 qemu_rearm_alarm_timer(alarm_timer);
986 /* Interrupt execution to force deadline recalculation. */
987 if (use_icount)
988 qemu_notify_event();
992 int qemu_timer_pending(QEMUTimer *ts)
994 QEMUTimer *t;
995 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
996 if (t == ts)
997 return 1;
999 return 0;
1002 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1004 if (!timer_head)
1005 return 0;
1006 return (timer_head->expire_time <= current_time);
1009 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1011 QEMUTimer *ts;
1013 for(;;) {
1014 ts = *ptimer_head;
1015 if (!ts || ts->expire_time > current_time)
1016 break;
1017 /* remove timer from the list before calling the callback */
1018 *ptimer_head = ts->next;
1019 ts->next = NULL;
1021 /* run the callback (the timer list can be modified) */
1022 ts->cb(ts->opaque);
1026 int64_t qemu_get_clock(QEMUClock *clock)
1028 switch(clock->type) {
1029 case QEMU_TIMER_REALTIME:
1030 return get_clock() / 1000000;
1031 default:
1032 case QEMU_TIMER_VIRTUAL:
1033 if (use_icount) {
1034 return cpu_get_icount();
1035 } else {
1036 return cpu_get_clock();
1041 static void init_timers(void)
1043 init_get_clock();
1044 ticks_per_sec = QEMU_TIMER_BASE;
1045 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1046 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1049 /* save a timer */
1050 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1052 uint64_t expire_time;
1054 if (qemu_timer_pending(ts)) {
1055 expire_time = ts->expire_time;
1056 } else {
1057 expire_time = -1;
1059 qemu_put_be64(f, expire_time);
1062 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1064 uint64_t expire_time;
1066 expire_time = qemu_get_be64(f);
1067 if (expire_time != -1) {
1068 qemu_mod_timer(ts, expire_time);
1069 } else {
1070 qemu_del_timer(ts);
1074 static void timer_save(QEMUFile *f, void *opaque)
1076 if (cpu_ticks_enabled) {
1077 hw_error("cannot save state if virtual timers are running");
1079 qemu_put_be64(f, cpu_ticks_offset);
1080 qemu_put_be64(f, ticks_per_sec);
1081 qemu_put_be64(f, cpu_clock_offset);
1084 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1086 if (version_id != 1 && version_id != 2)
1087 return -EINVAL;
1088 if (cpu_ticks_enabled) {
1089 return -EINVAL;
1091 cpu_ticks_offset=qemu_get_be64(f);
1092 ticks_per_sec=qemu_get_be64(f);
1093 if (version_id == 2) {
1094 cpu_clock_offset=qemu_get_be64(f);
1096 return 0;
1099 static void qemu_event_increment(void);
1101 #ifdef _WIN32
1102 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1103 DWORD_PTR dwUser, DWORD_PTR dw1,
1104 DWORD_PTR dw2)
1105 #else
1106 static void host_alarm_handler(int host_signum)
1107 #endif
1109 #if 0
1110 #define DISP_FREQ 1000
1112 static int64_t delta_min = INT64_MAX;
1113 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1114 static int count;
1115 ti = qemu_get_clock(vm_clock);
1116 if (last_clock != 0) {
1117 delta = ti - last_clock;
1118 if (delta < delta_min)
1119 delta_min = delta;
1120 if (delta > delta_max)
1121 delta_max = delta;
1122 delta_cum += delta;
1123 if (++count == DISP_FREQ) {
1124 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1125 muldiv64(delta_min, 1000000, ticks_per_sec),
1126 muldiv64(delta_max, 1000000, ticks_per_sec),
1127 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1128 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1129 count = 0;
1130 delta_min = INT64_MAX;
1131 delta_max = 0;
1132 delta_cum = 0;
1135 last_clock = ti;
1137 #endif
1138 if (alarm_has_dynticks(alarm_timer) ||
1139 (!use_icount &&
1140 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1141 qemu_get_clock(vm_clock))) ||
1142 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1143 qemu_get_clock(rt_clock))) {
1144 qemu_event_increment();
1145 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1147 #ifndef CONFIG_IOTHREAD
1148 if (next_cpu) {
1149 /* stop the currently executing cpu because a timer occured */
1150 cpu_exit(next_cpu);
1151 #ifdef CONFIG_KQEMU
1152 if (next_cpu->kqemu_enabled) {
1153 kqemu_cpu_interrupt(next_cpu);
1155 #endif
1157 #endif
1158 timer_alarm_pending = 1;
1159 qemu_notify_event();
1163 static int64_t qemu_next_deadline(void)
1165 int64_t delta;
1167 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1168 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1169 qemu_get_clock(vm_clock);
1170 } else {
1171 /* To avoid problems with overflow limit this to 2^32. */
1172 delta = INT32_MAX;
1175 if (delta < 0)
1176 delta = 0;
1178 return delta;
1181 #if defined(__linux__) || defined(_WIN32)
1182 static uint64_t qemu_next_deadline_dyntick(void)
1184 int64_t delta;
1185 int64_t rtdelta;
1187 if (use_icount)
1188 delta = INT32_MAX;
1189 else
1190 delta = (qemu_next_deadline() + 999) / 1000;
1192 if (active_timers[QEMU_TIMER_REALTIME]) {
1193 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1194 qemu_get_clock(rt_clock))*1000;
1195 if (rtdelta < delta)
1196 delta = rtdelta;
1199 if (delta < MIN_TIMER_REARM_US)
1200 delta = MIN_TIMER_REARM_US;
1202 return delta;
1204 #endif
1206 #ifndef _WIN32
1208 /* Sets a specific flag */
1209 static int fcntl_setfl(int fd, int flag)
1211 int flags;
1213 flags = fcntl(fd, F_GETFL);
1214 if (flags == -1)
1215 return -errno;
1217 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1218 return -errno;
1220 return 0;
1223 #if defined(__linux__)
1225 #define RTC_FREQ 1024
1227 static void enable_sigio_timer(int fd)
1229 struct sigaction act;
1231 /* timer signal */
1232 sigfillset(&act.sa_mask);
1233 act.sa_flags = 0;
1234 act.sa_handler = host_alarm_handler;
1236 sigaction(SIGIO, &act, NULL);
1237 fcntl_setfl(fd, O_ASYNC);
1238 fcntl(fd, F_SETOWN, getpid());
1241 static int hpet_start_timer(struct qemu_alarm_timer *t)
1243 struct hpet_info info;
1244 int r, fd;
1246 fd = open("/dev/hpet", O_RDONLY);
1247 if (fd < 0)
1248 return -1;
1250 /* Set frequency */
1251 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1252 if (r < 0) {
1253 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1254 "error, but for better emulation accuracy type:\n"
1255 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1256 goto fail;
1259 /* Check capabilities */
1260 r = ioctl(fd, HPET_INFO, &info);
1261 if (r < 0)
1262 goto fail;
1264 /* Enable periodic mode */
1265 r = ioctl(fd, HPET_EPI, 0);
1266 if (info.hi_flags && (r < 0))
1267 goto fail;
1269 /* Enable interrupt */
1270 r = ioctl(fd, HPET_IE_ON, 0);
1271 if (r < 0)
1272 goto fail;
1274 enable_sigio_timer(fd);
1275 t->priv = (void *)(long)fd;
1277 return 0;
1278 fail:
1279 close(fd);
1280 return -1;
1283 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1285 int fd = (long)t->priv;
1287 close(fd);
1290 static int rtc_start_timer(struct qemu_alarm_timer *t)
1292 int rtc_fd;
1293 unsigned long current_rtc_freq = 0;
1295 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1296 if (rtc_fd < 0)
1297 return -1;
1298 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1299 if (current_rtc_freq != RTC_FREQ &&
1300 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1301 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1302 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1303 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1304 goto fail;
1306 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1307 fail:
1308 close(rtc_fd);
1309 return -1;
1312 enable_sigio_timer(rtc_fd);
1314 t->priv = (void *)(long)rtc_fd;
1316 return 0;
1319 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1321 int rtc_fd = (long)t->priv;
1323 close(rtc_fd);
1326 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1328 struct sigevent ev;
1329 timer_t host_timer;
1330 struct sigaction act;
1332 sigfillset(&act.sa_mask);
1333 act.sa_flags = 0;
1334 act.sa_handler = host_alarm_handler;
1336 sigaction(SIGALRM, &act, NULL);
1339 * Initialize ev struct to 0 to avoid valgrind complaining
1340 * about uninitialized data in timer_create call
1342 memset(&ev, 0, sizeof(ev));
1343 ev.sigev_value.sival_int = 0;
1344 ev.sigev_notify = SIGEV_SIGNAL;
1345 ev.sigev_signo = SIGALRM;
1347 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1348 perror("timer_create");
1350 /* disable dynticks */
1351 fprintf(stderr, "Dynamic Ticks disabled\n");
1353 return -1;
1356 t->priv = (void *)(long)host_timer;
1358 return 0;
1361 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1363 timer_t host_timer = (timer_t)(long)t->priv;
1365 timer_delete(host_timer);
1368 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1370 timer_t host_timer = (timer_t)(long)t->priv;
1371 struct itimerspec timeout;
1372 int64_t nearest_delta_us = INT64_MAX;
1373 int64_t current_us;
1375 if (!active_timers[QEMU_TIMER_REALTIME] &&
1376 !active_timers[QEMU_TIMER_VIRTUAL])
1377 return;
1379 nearest_delta_us = qemu_next_deadline_dyntick();
1381 /* check whether a timer is already running */
1382 if (timer_gettime(host_timer, &timeout)) {
1383 perror("gettime");
1384 fprintf(stderr, "Internal timer error: aborting\n");
1385 exit(1);
1387 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1388 if (current_us && current_us <= nearest_delta_us)
1389 return;
1391 timeout.it_interval.tv_sec = 0;
1392 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1393 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1394 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1395 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1396 perror("settime");
1397 fprintf(stderr, "Internal timer error: aborting\n");
1398 exit(1);
1402 #endif /* defined(__linux__) */
1404 static int unix_start_timer(struct qemu_alarm_timer *t)
1406 struct sigaction act;
1407 struct itimerval itv;
1408 int err;
1410 /* timer signal */
1411 sigfillset(&act.sa_mask);
1412 act.sa_flags = 0;
1413 act.sa_handler = host_alarm_handler;
1415 sigaction(SIGALRM, &act, NULL);
1417 itv.it_interval.tv_sec = 0;
1418 /* for i386 kernel 2.6 to get 1 ms */
1419 itv.it_interval.tv_usec = 999;
1420 itv.it_value.tv_sec = 0;
1421 itv.it_value.tv_usec = 10 * 1000;
1423 err = setitimer(ITIMER_REAL, &itv, NULL);
1424 if (err)
1425 return -1;
1427 return 0;
1430 static void unix_stop_timer(struct qemu_alarm_timer *t)
1432 struct itimerval itv;
1434 memset(&itv, 0, sizeof(itv));
1435 setitimer(ITIMER_REAL, &itv, NULL);
1438 #endif /* !defined(_WIN32) */
1441 #ifdef _WIN32
1443 static int win32_start_timer(struct qemu_alarm_timer *t)
1445 TIMECAPS tc;
1446 struct qemu_alarm_win32 *data = t->priv;
1447 UINT flags;
1449 memset(&tc, 0, sizeof(tc));
1450 timeGetDevCaps(&tc, sizeof(tc));
1452 if (data->period < tc.wPeriodMin)
1453 data->period = tc.wPeriodMin;
1455 timeBeginPeriod(data->period);
1457 flags = TIME_CALLBACK_FUNCTION;
1458 if (alarm_has_dynticks(t))
1459 flags |= TIME_ONESHOT;
1460 else
1461 flags |= TIME_PERIODIC;
1463 data->timerId = timeSetEvent(1, // interval (ms)
1464 data->period, // resolution
1465 host_alarm_handler, // function
1466 (DWORD)t, // parameter
1467 flags);
1469 if (!data->timerId) {
1470 perror("Failed to initialize win32 alarm timer");
1471 timeEndPeriod(data->period);
1472 return -1;
1475 return 0;
1478 static void win32_stop_timer(struct qemu_alarm_timer *t)
1480 struct qemu_alarm_win32 *data = t->priv;
1482 timeKillEvent(data->timerId);
1483 timeEndPeriod(data->period);
1486 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1488 struct qemu_alarm_win32 *data = t->priv;
1489 uint64_t nearest_delta_us;
1491 if (!active_timers[QEMU_TIMER_REALTIME] &&
1492 !active_timers[QEMU_TIMER_VIRTUAL])
1493 return;
1495 nearest_delta_us = qemu_next_deadline_dyntick();
1496 nearest_delta_us /= 1000;
1498 timeKillEvent(data->timerId);
1500 data->timerId = timeSetEvent(1,
1501 data->period,
1502 host_alarm_handler,
1503 (DWORD)t,
1504 TIME_ONESHOT | TIME_PERIODIC);
1506 if (!data->timerId) {
1507 perror("Failed to re-arm win32 alarm timer");
1509 timeEndPeriod(data->period);
1510 exit(1);
1514 #endif /* _WIN32 */
1516 static int init_timer_alarm(void)
1518 struct qemu_alarm_timer *t = NULL;
1519 int i, err = -1;
1521 for (i = 0; alarm_timers[i].name; i++) {
1522 t = &alarm_timers[i];
1524 err = t->start(t);
1525 if (!err)
1526 break;
1529 if (err) {
1530 err = -ENOENT;
1531 goto fail;
1534 alarm_timer = t;
1536 return 0;
1538 fail:
1539 return err;
1542 static void quit_timers(void)
1544 alarm_timer->stop(alarm_timer);
1545 alarm_timer = NULL;
1548 /***********************************************************/
1549 /* host time/date access */
1550 void qemu_get_timedate(struct tm *tm, int offset)
1552 time_t ti;
1553 struct tm *ret;
1555 time(&ti);
1556 ti += offset;
1557 if (rtc_date_offset == -1) {
1558 if (rtc_utc)
1559 ret = gmtime(&ti);
1560 else
1561 ret = localtime(&ti);
1562 } else {
1563 ti -= rtc_date_offset;
1564 ret = gmtime(&ti);
1567 memcpy(tm, ret, sizeof(struct tm));
1570 int qemu_timedate_diff(struct tm *tm)
1572 time_t seconds;
1574 if (rtc_date_offset == -1)
1575 if (rtc_utc)
1576 seconds = mktimegm(tm);
1577 else
1578 seconds = mktime(tm);
1579 else
1580 seconds = mktimegm(tm) + rtc_date_offset;
1582 return seconds - time(NULL);
1585 #ifdef _WIN32
1586 static void socket_cleanup(void)
1588 WSACleanup();
1591 static int socket_init(void)
1593 WSADATA Data;
1594 int ret, err;
1596 ret = WSAStartup(MAKEWORD(2,2), &Data);
1597 if (ret != 0) {
1598 err = WSAGetLastError();
1599 fprintf(stderr, "WSAStartup: %d\n", err);
1600 return -1;
1602 atexit(socket_cleanup);
1603 return 0;
1605 #endif
1607 int get_next_param_value(char *buf, int buf_size,
1608 const char *tag, const char **pstr)
1610 const char *p;
1611 char option[128];
1613 p = *pstr;
1614 for(;;) {
1615 p = get_opt_name(option, sizeof(option), p, '=');
1616 if (*p != '=')
1617 break;
1618 p++;
1619 if (!strcmp(tag, option)) {
1620 *pstr = get_opt_value(buf, buf_size, p);
1621 if (**pstr == ',') {
1622 (*pstr)++;
1624 return strlen(buf);
1625 } else {
1626 p = get_opt_value(NULL, 0, p);
1628 if (*p != ',')
1629 break;
1630 p++;
1632 return 0;
1635 int get_param_value(char *buf, int buf_size,
1636 const char *tag, const char *str)
1638 return get_next_param_value(buf, buf_size, tag, &str);
1641 int check_params(char *buf, int buf_size,
1642 const char * const *params, const char *str)
1644 const char *p;
1645 int i;
1647 p = str;
1648 while (*p != '\0') {
1649 p = get_opt_name(buf, buf_size, p, '=');
1650 if (*p != '=') {
1651 return -1;
1653 p++;
1654 for (i = 0; params[i] != NULL; i++) {
1655 if (!strcmp(params[i], buf)) {
1656 break;
1659 if (params[i] == NULL) {
1660 return -1;
1662 p = get_opt_value(NULL, 0, p);
1663 if (*p != ',') {
1664 break;
1666 p++;
1668 return 0;
1671 /***********************************************************/
1672 /* Bluetooth support */
1673 static int nb_hcis;
1674 static int cur_hci;
1675 static struct HCIInfo *hci_table[MAX_NICS];
1677 static struct bt_vlan_s {
1678 struct bt_scatternet_s net;
1679 int id;
1680 struct bt_vlan_s *next;
1681 } *first_bt_vlan;
1683 /* find or alloc a new bluetooth "VLAN" */
1684 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1686 struct bt_vlan_s **pvlan, *vlan;
1687 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1688 if (vlan->id == id)
1689 return &vlan->net;
1691 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1692 vlan->id = id;
1693 pvlan = &first_bt_vlan;
1694 while (*pvlan != NULL)
1695 pvlan = &(*pvlan)->next;
1696 *pvlan = vlan;
1697 return &vlan->net;
1700 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1704 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1706 return -ENOTSUP;
1709 static struct HCIInfo null_hci = {
1710 .cmd_send = null_hci_send,
1711 .sco_send = null_hci_send,
1712 .acl_send = null_hci_send,
1713 .bdaddr_set = null_hci_addr_set,
1716 struct HCIInfo *qemu_next_hci(void)
1718 if (cur_hci == nb_hcis)
1719 return &null_hci;
1721 return hci_table[cur_hci++];
1724 static struct HCIInfo *hci_init(const char *str)
1726 char *endp;
1727 struct bt_scatternet_s *vlan = 0;
1729 if (!strcmp(str, "null"))
1730 /* null */
1731 return &null_hci;
1732 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1733 /* host[:hciN] */
1734 return bt_host_hci(str[4] ? str + 5 : "hci0");
1735 else if (!strncmp(str, "hci", 3)) {
1736 /* hci[,vlan=n] */
1737 if (str[3]) {
1738 if (!strncmp(str + 3, ",vlan=", 6)) {
1739 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1740 if (*endp)
1741 vlan = 0;
1743 } else
1744 vlan = qemu_find_bt_vlan(0);
1745 if (vlan)
1746 return bt_new_hci(vlan);
1749 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1751 return 0;
1754 static int bt_hci_parse(const char *str)
1756 struct HCIInfo *hci;
1757 bdaddr_t bdaddr;
1759 if (nb_hcis >= MAX_NICS) {
1760 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1761 return -1;
1764 hci = hci_init(str);
1765 if (!hci)
1766 return -1;
1768 bdaddr.b[0] = 0x52;
1769 bdaddr.b[1] = 0x54;
1770 bdaddr.b[2] = 0x00;
1771 bdaddr.b[3] = 0x12;
1772 bdaddr.b[4] = 0x34;
1773 bdaddr.b[5] = 0x56 + nb_hcis;
1774 hci->bdaddr_set(hci, bdaddr.b);
1776 hci_table[nb_hcis++] = hci;
1778 return 0;
1781 static void bt_vhci_add(int vlan_id)
1783 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1785 if (!vlan->slave)
1786 fprintf(stderr, "qemu: warning: adding a VHCI to "
1787 "an empty scatternet %i\n", vlan_id);
1789 bt_vhci_init(bt_new_hci(vlan));
1792 static struct bt_device_s *bt_device_add(const char *opt)
1794 struct bt_scatternet_s *vlan;
1795 int vlan_id = 0;
1796 char *endp = strstr(opt, ",vlan=");
1797 int len = (endp ? endp - opt : strlen(opt)) + 1;
1798 char devname[10];
1800 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1802 if (endp) {
1803 vlan_id = strtol(endp + 6, &endp, 0);
1804 if (*endp) {
1805 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1806 return 0;
1810 vlan = qemu_find_bt_vlan(vlan_id);
1812 if (!vlan->slave)
1813 fprintf(stderr, "qemu: warning: adding a slave device to "
1814 "an empty scatternet %i\n", vlan_id);
1816 if (!strcmp(devname, "keyboard"))
1817 return bt_keyboard_init(vlan);
1819 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1820 return 0;
1823 static int bt_parse(const char *opt)
1825 const char *endp, *p;
1826 int vlan;
1828 if (strstart(opt, "hci", &endp)) {
1829 if (!*endp || *endp == ',') {
1830 if (*endp)
1831 if (!strstart(endp, ",vlan=", 0))
1832 opt = endp + 1;
1834 return bt_hci_parse(opt);
1836 } else if (strstart(opt, "vhci", &endp)) {
1837 if (!*endp || *endp == ',') {
1838 if (*endp) {
1839 if (strstart(endp, ",vlan=", &p)) {
1840 vlan = strtol(p, (char **) &endp, 0);
1841 if (*endp) {
1842 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1843 return 1;
1845 } else {
1846 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1847 return 1;
1849 } else
1850 vlan = 0;
1852 bt_vhci_add(vlan);
1853 return 0;
1855 } else if (strstart(opt, "device:", &endp))
1856 return !bt_device_add(endp);
1858 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1859 return 1;
1862 /***********************************************************/
1863 /* QEMU Block devices */
1865 #define HD_ALIAS "index=%d,media=disk"
1866 #define CDROM_ALIAS "index=2,media=cdrom"
1867 #define FD_ALIAS "index=%d,if=floppy"
1868 #define PFLASH_ALIAS "if=pflash"
1869 #define MTD_ALIAS "if=mtd"
1870 #define SD_ALIAS "index=0,if=sd"
1872 static int drive_opt_get_free_idx(void)
1874 int index;
1876 for (index = 0; index < MAX_DRIVES; index++)
1877 if (!drives_opt[index].used) {
1878 drives_opt[index].used = 1;
1879 return index;
1882 return -1;
1885 static int drive_get_free_idx(void)
1887 int index;
1889 for (index = 0; index < MAX_DRIVES; index++)
1890 if (!drives_table[index].used) {
1891 drives_table[index].used = 1;
1892 return index;
1895 return -1;
1898 int drive_add(const char *file, const char *fmt, ...)
1900 va_list ap;
1901 int index = drive_opt_get_free_idx();
1903 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
1904 fprintf(stderr, "qemu: too many drives\n");
1905 return -1;
1908 drives_opt[index].file = file;
1909 va_start(ap, fmt);
1910 vsnprintf(drives_opt[index].opt,
1911 sizeof(drives_opt[0].opt), fmt, ap);
1912 va_end(ap);
1914 nb_drives_opt++;
1915 return index;
1918 void drive_remove(int index)
1920 drives_opt[index].used = 0;
1921 nb_drives_opt--;
1924 int drive_get_index(BlockInterfaceType type, int bus, int unit)
1926 int index;
1928 /* seek interface, bus and unit */
1930 for (index = 0; index < MAX_DRIVES; index++)
1931 if (drives_table[index].type == type &&
1932 drives_table[index].bus == bus &&
1933 drives_table[index].unit == unit &&
1934 drives_table[index].used)
1935 return index;
1937 return -1;
1940 int drive_get_max_bus(BlockInterfaceType type)
1942 int max_bus;
1943 int index;
1945 max_bus = -1;
1946 for (index = 0; index < nb_drives; index++) {
1947 if(drives_table[index].type == type &&
1948 drives_table[index].bus > max_bus)
1949 max_bus = drives_table[index].bus;
1951 return max_bus;
1954 const char *drive_get_serial(BlockDriverState *bdrv)
1956 int index;
1958 for (index = 0; index < nb_drives; index++)
1959 if (drives_table[index].bdrv == bdrv)
1960 return drives_table[index].serial;
1962 return "\0";
1965 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1967 int index;
1969 for (index = 0; index < nb_drives; index++)
1970 if (drives_table[index].bdrv == bdrv)
1971 return drives_table[index].onerror;
1973 return BLOCK_ERR_STOP_ENOSPC;
1976 static void bdrv_format_print(void *opaque, const char *name)
1978 fprintf(stderr, " %s", name);
1981 void drive_uninit(BlockDriverState *bdrv)
1983 int i;
1985 for (i = 0; i < MAX_DRIVES; i++)
1986 if (drives_table[i].bdrv == bdrv) {
1987 drives_table[i].bdrv = NULL;
1988 drives_table[i].used = 0;
1989 drive_remove(drives_table[i].drive_opt_idx);
1990 nb_drives--;
1991 break;
1995 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
1997 char buf[128];
1998 char file[1024];
1999 char devname[128];
2000 char serial[21];
2001 const char *mediastr = "";
2002 BlockInterfaceType type;
2003 enum { MEDIA_DISK, MEDIA_CDROM } media;
2004 int bus_id, unit_id;
2005 int cyls, heads, secs, translation;
2006 BlockDriverState *bdrv;
2007 BlockDriver *drv = NULL;
2008 QEMUMachine *machine = opaque;
2009 int max_devs;
2010 int index;
2011 int cache;
2012 int bdrv_flags, onerror;
2013 const char *devaddr;
2014 int drives_table_idx;
2015 char *str = arg->opt;
2016 static const char * const params[] = { "bus", "unit", "if", "index",
2017 "cyls", "heads", "secs", "trans",
2018 "media", "snapshot", "file",
2019 "cache", "format", "serial",
2020 "werror", "addr",
2021 NULL };
2023 if (check_params(buf, sizeof(buf), params, str) < 0) {
2024 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2025 buf, str);
2026 return -1;
2029 file[0] = 0;
2030 cyls = heads = secs = 0;
2031 bus_id = 0;
2032 unit_id = -1;
2033 translation = BIOS_ATA_TRANSLATION_AUTO;
2034 index = -1;
2035 cache = 1;
2037 if (machine->use_scsi) {
2038 type = IF_SCSI;
2039 max_devs = MAX_SCSI_DEVS;
2040 pstrcpy(devname, sizeof(devname), "scsi");
2041 } else {
2042 type = IF_IDE;
2043 max_devs = MAX_IDE_DEVS;
2044 pstrcpy(devname, sizeof(devname), "ide");
2046 media = MEDIA_DISK;
2048 /* extract parameters */
2050 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2051 bus_id = strtol(buf, NULL, 0);
2052 if (bus_id < 0) {
2053 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2054 return -1;
2058 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2059 unit_id = strtol(buf, NULL, 0);
2060 if (unit_id < 0) {
2061 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2062 return -1;
2066 if (get_param_value(buf, sizeof(buf), "if", str)) {
2067 pstrcpy(devname, sizeof(devname), buf);
2068 if (!strcmp(buf, "ide")) {
2069 type = IF_IDE;
2070 max_devs = MAX_IDE_DEVS;
2071 } else if (!strcmp(buf, "scsi")) {
2072 type = IF_SCSI;
2073 max_devs = MAX_SCSI_DEVS;
2074 } else if (!strcmp(buf, "floppy")) {
2075 type = IF_FLOPPY;
2076 max_devs = 0;
2077 } else if (!strcmp(buf, "pflash")) {
2078 type = IF_PFLASH;
2079 max_devs = 0;
2080 } else if (!strcmp(buf, "mtd")) {
2081 type = IF_MTD;
2082 max_devs = 0;
2083 } else if (!strcmp(buf, "sd")) {
2084 type = IF_SD;
2085 max_devs = 0;
2086 } else if (!strcmp(buf, "virtio")) {
2087 type = IF_VIRTIO;
2088 max_devs = 0;
2089 } else if (!strcmp(buf, "xen")) {
2090 type = IF_XEN;
2091 max_devs = 0;
2092 } else {
2093 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2094 return -1;
2098 if (get_param_value(buf, sizeof(buf), "index", str)) {
2099 index = strtol(buf, NULL, 0);
2100 if (index < 0) {
2101 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2102 return -1;
2106 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2107 cyls = strtol(buf, NULL, 0);
2110 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2111 heads = strtol(buf, NULL, 0);
2114 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2115 secs = strtol(buf, NULL, 0);
2118 if (cyls || heads || secs) {
2119 if (cyls < 1 || cyls > 16383) {
2120 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2121 return -1;
2123 if (heads < 1 || heads > 16) {
2124 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2125 return -1;
2127 if (secs < 1 || secs > 63) {
2128 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2129 return -1;
2133 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2134 if (!cyls) {
2135 fprintf(stderr,
2136 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2137 str);
2138 return -1;
2140 if (!strcmp(buf, "none"))
2141 translation = BIOS_ATA_TRANSLATION_NONE;
2142 else if (!strcmp(buf, "lba"))
2143 translation = BIOS_ATA_TRANSLATION_LBA;
2144 else if (!strcmp(buf, "auto"))
2145 translation = BIOS_ATA_TRANSLATION_AUTO;
2146 else {
2147 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2148 return -1;
2152 if (get_param_value(buf, sizeof(buf), "media", str)) {
2153 if (!strcmp(buf, "disk")) {
2154 media = MEDIA_DISK;
2155 } else if (!strcmp(buf, "cdrom")) {
2156 if (cyls || secs || heads) {
2157 fprintf(stderr,
2158 "qemu: '%s' invalid physical CHS format\n", str);
2159 return -1;
2161 media = MEDIA_CDROM;
2162 } else {
2163 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2164 return -1;
2168 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2169 if (!strcmp(buf, "on"))
2170 snapshot = 1;
2171 else if (!strcmp(buf, "off"))
2172 snapshot = 0;
2173 else {
2174 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2175 return -1;
2179 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2180 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2181 cache = 0;
2182 else if (!strcmp(buf, "writethrough"))
2183 cache = 1;
2184 else if (!strcmp(buf, "writeback"))
2185 cache = 2;
2186 else {
2187 fprintf(stderr, "qemu: invalid cache option\n");
2188 return -1;
2192 if (get_param_value(buf, sizeof(buf), "format", str)) {
2193 if (strcmp(buf, "?") == 0) {
2194 fprintf(stderr, "qemu: Supported formats:");
2195 bdrv_iterate_format(bdrv_format_print, NULL);
2196 fprintf(stderr, "\n");
2197 return -1;
2199 drv = bdrv_find_format(buf);
2200 if (!drv) {
2201 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2202 return -1;
2206 if (arg->file == NULL)
2207 get_param_value(file, sizeof(file), "file", str);
2208 else
2209 pstrcpy(file, sizeof(file), arg->file);
2211 if (!get_param_value(serial, sizeof(serial), "serial", str))
2212 memset(serial, 0, sizeof(serial));
2214 onerror = BLOCK_ERR_STOP_ENOSPC;
2215 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2216 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2217 fprintf(stderr, "werror is no supported by this format\n");
2218 return -1;
2220 if (!strcmp(buf, "ignore"))
2221 onerror = BLOCK_ERR_IGNORE;
2222 else if (!strcmp(buf, "enospc"))
2223 onerror = BLOCK_ERR_STOP_ENOSPC;
2224 else if (!strcmp(buf, "stop"))
2225 onerror = BLOCK_ERR_STOP_ANY;
2226 else if (!strcmp(buf, "report"))
2227 onerror = BLOCK_ERR_REPORT;
2228 else {
2229 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2230 return -1;
2234 devaddr = NULL;
2235 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2236 if (type != IF_VIRTIO) {
2237 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2238 return -1;
2240 devaddr = strdup(buf);
2243 /* compute bus and unit according index */
2245 if (index != -1) {
2246 if (bus_id != 0 || unit_id != -1) {
2247 fprintf(stderr,
2248 "qemu: '%s' index cannot be used with bus and unit\n", str);
2249 return -1;
2251 if (max_devs == 0)
2253 unit_id = index;
2254 bus_id = 0;
2255 } else {
2256 unit_id = index % max_devs;
2257 bus_id = index / max_devs;
2261 /* if user doesn't specify a unit_id,
2262 * try to find the first free
2265 if (unit_id == -1) {
2266 unit_id = 0;
2267 while (drive_get_index(type, bus_id, unit_id) != -1) {
2268 unit_id++;
2269 if (max_devs && unit_id >= max_devs) {
2270 unit_id -= max_devs;
2271 bus_id++;
2276 /* check unit id */
2278 if (max_devs && unit_id >= max_devs) {
2279 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2280 str, unit_id, max_devs - 1);
2281 return -1;
2285 * ignore multiple definitions
2288 if (drive_get_index(type, bus_id, unit_id) != -1)
2289 return -2;
2291 /* init */
2293 if (type == IF_IDE || type == IF_SCSI)
2294 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2295 if (max_devs)
2296 snprintf(buf, sizeof(buf), "%s%i%s%i",
2297 devname, bus_id, mediastr, unit_id);
2298 else
2299 snprintf(buf, sizeof(buf), "%s%s%i",
2300 devname, mediastr, unit_id);
2301 bdrv = bdrv_new(buf);
2302 drives_table_idx = drive_get_free_idx();
2303 drives_table[drives_table_idx].bdrv = bdrv;
2304 drives_table[drives_table_idx].devaddr = devaddr;
2305 drives_table[drives_table_idx].type = type;
2306 drives_table[drives_table_idx].bus = bus_id;
2307 drives_table[drives_table_idx].unit = unit_id;
2308 drives_table[drives_table_idx].onerror = onerror;
2309 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2310 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2311 nb_drives++;
2313 switch(type) {
2314 case IF_IDE:
2315 case IF_SCSI:
2316 case IF_XEN:
2317 switch(media) {
2318 case MEDIA_DISK:
2319 if (cyls != 0) {
2320 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2321 bdrv_set_translation_hint(bdrv, translation);
2323 break;
2324 case MEDIA_CDROM:
2325 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2326 break;
2328 break;
2329 case IF_SD:
2330 /* FIXME: This isn't really a floppy, but it's a reasonable
2331 approximation. */
2332 case IF_FLOPPY:
2333 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2334 break;
2335 case IF_PFLASH:
2336 case IF_MTD:
2337 case IF_VIRTIO:
2338 break;
2339 case IF_COUNT:
2340 abort();
2342 if (!file[0])
2343 return -2;
2344 bdrv_flags = 0;
2345 if (snapshot) {
2346 bdrv_flags |= BDRV_O_SNAPSHOT;
2347 cache = 2; /* always use write-back with snapshot */
2349 if (cache == 0) /* no caching */
2350 bdrv_flags |= BDRV_O_NOCACHE;
2351 else if (cache == 2) /* write-back */
2352 bdrv_flags |= BDRV_O_CACHE_WB;
2353 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2354 fprintf(stderr, "qemu: could not open disk image %s\n",
2355 file);
2356 return -1;
2358 if (bdrv_key_required(bdrv))
2359 autostart = 0;
2360 return drives_table_idx;
2363 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2365 boot_set_handler = func;
2366 boot_set_opaque = opaque;
2369 int qemu_boot_set(const char *boot_devices)
2371 if (!boot_set_handler) {
2372 return -EINVAL;
2374 return boot_set_handler(boot_set_opaque, boot_devices);
2377 static int parse_bootdevices(char *devices)
2379 /* We just do some generic consistency checks */
2380 const char *p;
2381 int bitmap = 0;
2383 for (p = devices; *p != '\0'; p++) {
2384 /* Allowed boot devices are:
2385 * a-b: floppy disk drives
2386 * c-f: IDE disk drives
2387 * g-m: machine implementation dependant drives
2388 * n-p: network devices
2389 * It's up to each machine implementation to check if the given boot
2390 * devices match the actual hardware implementation and firmware
2391 * features.
2393 if (*p < 'a' || *p > 'p') {
2394 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2395 exit(1);
2397 if (bitmap & (1 << (*p - 'a'))) {
2398 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2399 exit(1);
2401 bitmap |= 1 << (*p - 'a');
2403 return bitmap;
2406 static void restore_boot_devices(void *opaque)
2408 char *standard_boot_devices = opaque;
2410 qemu_boot_set(standard_boot_devices);
2412 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2413 qemu_free(standard_boot_devices);
2416 static void numa_add(const char *optarg)
2418 char option[128];
2419 char *endptr;
2420 unsigned long long value, endvalue;
2421 int nodenr;
2423 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2424 if (!strcmp(option, "node")) {
2425 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2426 nodenr = nb_numa_nodes;
2427 } else {
2428 nodenr = strtoull(option, NULL, 10);
2431 if (get_param_value(option, 128, "mem", optarg) == 0) {
2432 node_mem[nodenr] = 0;
2433 } else {
2434 value = strtoull(option, &endptr, 0);
2435 switch (*endptr) {
2436 case 0: case 'M': case 'm':
2437 value <<= 20;
2438 break;
2439 case 'G': case 'g':
2440 value <<= 30;
2441 break;
2443 node_mem[nodenr] = value;
2445 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2446 node_cpumask[nodenr] = 0;
2447 } else {
2448 value = strtoull(option, &endptr, 10);
2449 if (value >= 64) {
2450 value = 63;
2451 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2452 } else {
2453 if (*endptr == '-') {
2454 endvalue = strtoull(endptr+1, &endptr, 10);
2455 if (endvalue >= 63) {
2456 endvalue = 62;
2457 fprintf(stderr,
2458 "only 63 CPUs in NUMA mode supported.\n");
2460 value = (1 << (endvalue + 1)) - (1 << value);
2461 } else {
2462 value = 1 << value;
2465 node_cpumask[nodenr] = value;
2467 nb_numa_nodes++;
2469 return;
2472 /***********************************************************/
2473 /* USB devices */
2475 static USBPort *used_usb_ports;
2476 static USBPort *free_usb_ports;
2478 /* ??? Maybe change this to register a hub to keep track of the topology. */
2479 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2480 usb_attachfn attach)
2482 port->opaque = opaque;
2483 port->index = index;
2484 port->attach = attach;
2485 port->next = free_usb_ports;
2486 free_usb_ports = port;
2489 int usb_device_add_dev(USBDevice *dev)
2491 USBPort *port;
2493 /* Find a USB port to add the device to. */
2494 port = free_usb_ports;
2495 if (!port->next) {
2496 USBDevice *hub;
2498 /* Create a new hub and chain it on. */
2499 free_usb_ports = NULL;
2500 port->next = used_usb_ports;
2501 used_usb_ports = port;
2503 hub = usb_hub_init(VM_USB_HUB_SIZE);
2504 usb_attach(port, hub);
2505 port = free_usb_ports;
2508 free_usb_ports = port->next;
2509 port->next = used_usb_ports;
2510 used_usb_ports = port;
2511 usb_attach(port, dev);
2512 return 0;
2515 static void usb_msd_password_cb(void *opaque, int err)
2517 USBDevice *dev = opaque;
2519 if (!err)
2520 usb_device_add_dev(dev);
2521 else
2522 dev->handle_destroy(dev);
2525 static int usb_device_add(const char *devname, int is_hotplug)
2527 const char *p;
2528 USBDevice *dev;
2530 if (!free_usb_ports)
2531 return -1;
2533 if (strstart(devname, "host:", &p)) {
2534 dev = usb_host_device_open(p);
2535 } else if (!strcmp(devname, "mouse")) {
2536 dev = usb_mouse_init();
2537 } else if (!strcmp(devname, "tablet")) {
2538 dev = usb_tablet_init();
2539 } else if (!strcmp(devname, "keyboard")) {
2540 dev = usb_keyboard_init();
2541 } else if (strstart(devname, "disk:", &p)) {
2542 BlockDriverState *bs;
2544 dev = usb_msd_init(p);
2545 if (!dev)
2546 return -1;
2547 bs = usb_msd_get_bdrv(dev);
2548 if (bdrv_key_required(bs)) {
2549 autostart = 0;
2550 if (is_hotplug) {
2551 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2552 dev);
2553 return 0;
2556 } else if (!strcmp(devname, "wacom-tablet")) {
2557 dev = usb_wacom_init();
2558 } else if (strstart(devname, "serial:", &p)) {
2559 dev = usb_serial_init(p);
2560 #ifdef CONFIG_BRLAPI
2561 } else if (!strcmp(devname, "braille")) {
2562 dev = usb_baum_init();
2563 #endif
2564 } else if (strstart(devname, "net:", &p)) {
2565 int nic = nb_nics;
2567 if (net_client_init(NULL, "nic", p) < 0)
2568 return -1;
2569 nd_table[nic].model = "usb";
2570 dev = usb_net_init(&nd_table[nic]);
2571 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2572 dev = usb_bt_init(devname[2] ? hci_init(p) :
2573 bt_new_hci(qemu_find_bt_vlan(0)));
2574 } else {
2575 return -1;
2577 if (!dev)
2578 return -1;
2580 return usb_device_add_dev(dev);
2583 int usb_device_del_addr(int bus_num, int addr)
2585 USBPort *port;
2586 USBPort **lastp;
2587 USBDevice *dev;
2589 if (!used_usb_ports)
2590 return -1;
2592 if (bus_num != 0)
2593 return -1;
2595 lastp = &used_usb_ports;
2596 port = used_usb_ports;
2597 while (port && port->dev->addr != addr) {
2598 lastp = &port->next;
2599 port = port->next;
2602 if (!port)
2603 return -1;
2605 dev = port->dev;
2606 *lastp = port->next;
2607 usb_attach(port, NULL);
2608 dev->handle_destroy(dev);
2609 port->next = free_usb_ports;
2610 free_usb_ports = port;
2611 return 0;
2614 static int usb_device_del(const char *devname)
2616 int bus_num, addr;
2617 const char *p;
2619 if (strstart(devname, "host:", &p))
2620 return usb_host_device_close(p);
2622 if (!used_usb_ports)
2623 return -1;
2625 p = strchr(devname, '.');
2626 if (!p)
2627 return -1;
2628 bus_num = strtoul(devname, NULL, 0);
2629 addr = strtoul(p + 1, NULL, 0);
2631 return usb_device_del_addr(bus_num, addr);
2634 void do_usb_add(Monitor *mon, const char *devname)
2636 usb_device_add(devname, 1);
2639 void do_usb_del(Monitor *mon, const char *devname)
2641 usb_device_del(devname);
2644 void usb_info(Monitor *mon)
2646 USBDevice *dev;
2647 USBPort *port;
2648 const char *speed_str;
2650 if (!usb_enabled) {
2651 monitor_printf(mon, "USB support not enabled\n");
2652 return;
2655 for (port = used_usb_ports; port; port = port->next) {
2656 dev = port->dev;
2657 if (!dev)
2658 continue;
2659 switch(dev->speed) {
2660 case USB_SPEED_LOW:
2661 speed_str = "1.5";
2662 break;
2663 case USB_SPEED_FULL:
2664 speed_str = "12";
2665 break;
2666 case USB_SPEED_HIGH:
2667 speed_str = "480";
2668 break;
2669 default:
2670 speed_str = "?";
2671 break;
2673 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2674 0, dev->addr, speed_str, dev->devname);
2678 /***********************************************************/
2679 /* PCMCIA/Cardbus */
2681 static struct pcmcia_socket_entry_s {
2682 PCMCIASocket *socket;
2683 struct pcmcia_socket_entry_s *next;
2684 } *pcmcia_sockets = 0;
2686 void pcmcia_socket_register(PCMCIASocket *socket)
2688 struct pcmcia_socket_entry_s *entry;
2690 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2691 entry->socket = socket;
2692 entry->next = pcmcia_sockets;
2693 pcmcia_sockets = entry;
2696 void pcmcia_socket_unregister(PCMCIASocket *socket)
2698 struct pcmcia_socket_entry_s *entry, **ptr;
2700 ptr = &pcmcia_sockets;
2701 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2702 if (entry->socket == socket) {
2703 *ptr = entry->next;
2704 qemu_free(entry);
2708 void pcmcia_info(Monitor *mon)
2710 struct pcmcia_socket_entry_s *iter;
2712 if (!pcmcia_sockets)
2713 monitor_printf(mon, "No PCMCIA sockets\n");
2715 for (iter = pcmcia_sockets; iter; iter = iter->next)
2716 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2717 iter->socket->attached ? iter->socket->card_string :
2718 "Empty");
2721 /***********************************************************/
2722 /* register display */
2724 struct DisplayAllocator default_allocator = {
2725 defaultallocator_create_displaysurface,
2726 defaultallocator_resize_displaysurface,
2727 defaultallocator_free_displaysurface
2730 void register_displaystate(DisplayState *ds)
2732 DisplayState **s;
2733 s = &display_state;
2734 while (*s != NULL)
2735 s = &(*s)->next;
2736 ds->next = NULL;
2737 *s = ds;
2740 DisplayState *get_displaystate(void)
2742 return display_state;
2745 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2747 if(ds->allocator == &default_allocator) ds->allocator = da;
2748 return ds->allocator;
2751 /* dumb display */
2753 static void dumb_display_init(void)
2755 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2756 ds->allocator = &default_allocator;
2757 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2758 register_displaystate(ds);
2761 /***********************************************************/
2762 /* I/O handling */
2764 typedef struct IOHandlerRecord {
2765 int fd;
2766 IOCanRWHandler *fd_read_poll;
2767 IOHandler *fd_read;
2768 IOHandler *fd_write;
2769 int deleted;
2770 void *opaque;
2771 /* temporary data */
2772 struct pollfd *ufd;
2773 struct IOHandlerRecord *next;
2774 } IOHandlerRecord;
2776 static IOHandlerRecord *first_io_handler;
2778 /* XXX: fd_read_poll should be suppressed, but an API change is
2779 necessary in the character devices to suppress fd_can_read(). */
2780 int qemu_set_fd_handler2(int fd,
2781 IOCanRWHandler *fd_read_poll,
2782 IOHandler *fd_read,
2783 IOHandler *fd_write,
2784 void *opaque)
2786 IOHandlerRecord **pioh, *ioh;
2788 if (!fd_read && !fd_write) {
2789 pioh = &first_io_handler;
2790 for(;;) {
2791 ioh = *pioh;
2792 if (ioh == NULL)
2793 break;
2794 if (ioh->fd == fd) {
2795 ioh->deleted = 1;
2796 break;
2798 pioh = &ioh->next;
2800 } else {
2801 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2802 if (ioh->fd == fd)
2803 goto found;
2805 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2806 ioh->next = first_io_handler;
2807 first_io_handler = ioh;
2808 found:
2809 ioh->fd = fd;
2810 ioh->fd_read_poll = fd_read_poll;
2811 ioh->fd_read = fd_read;
2812 ioh->fd_write = fd_write;
2813 ioh->opaque = opaque;
2814 ioh->deleted = 0;
2816 return 0;
2819 int qemu_set_fd_handler(int fd,
2820 IOHandler *fd_read,
2821 IOHandler *fd_write,
2822 void *opaque)
2824 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2827 #ifdef _WIN32
2828 /***********************************************************/
2829 /* Polling handling */
2831 typedef struct PollingEntry {
2832 PollingFunc *func;
2833 void *opaque;
2834 struct PollingEntry *next;
2835 } PollingEntry;
2837 static PollingEntry *first_polling_entry;
2839 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2841 PollingEntry **ppe, *pe;
2842 pe = qemu_mallocz(sizeof(PollingEntry));
2843 pe->func = func;
2844 pe->opaque = opaque;
2845 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2846 *ppe = pe;
2847 return 0;
2850 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2852 PollingEntry **ppe, *pe;
2853 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2854 pe = *ppe;
2855 if (pe->func == func && pe->opaque == opaque) {
2856 *ppe = pe->next;
2857 qemu_free(pe);
2858 break;
2863 /***********************************************************/
2864 /* Wait objects support */
2865 typedef struct WaitObjects {
2866 int num;
2867 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2868 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2869 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2870 } WaitObjects;
2872 static WaitObjects wait_objects = {0};
2874 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2876 WaitObjects *w = &wait_objects;
2878 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2879 return -1;
2880 w->events[w->num] = handle;
2881 w->func[w->num] = func;
2882 w->opaque[w->num] = opaque;
2883 w->num++;
2884 return 0;
2887 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2889 int i, found;
2890 WaitObjects *w = &wait_objects;
2892 found = 0;
2893 for (i = 0; i < w->num; i++) {
2894 if (w->events[i] == handle)
2895 found = 1;
2896 if (found) {
2897 w->events[i] = w->events[i + 1];
2898 w->func[i] = w->func[i + 1];
2899 w->opaque[i] = w->opaque[i + 1];
2902 if (found)
2903 w->num--;
2905 #endif
2907 /***********************************************************/
2908 /* ram save/restore */
2910 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2912 int v;
2914 v = qemu_get_byte(f);
2915 switch(v) {
2916 case 0:
2917 if (qemu_get_buffer(f, buf, len) != len)
2918 return -EIO;
2919 break;
2920 case 1:
2921 v = qemu_get_byte(f);
2922 memset(buf, v, len);
2923 break;
2924 default:
2925 return -EINVAL;
2928 if (qemu_file_has_error(f))
2929 return -EIO;
2931 return 0;
2934 static int ram_load_v1(QEMUFile *f, void *opaque)
2936 int ret;
2937 ram_addr_t i;
2939 if (qemu_get_be32(f) != last_ram_offset)
2940 return -EINVAL;
2941 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2942 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2943 if (ret)
2944 return ret;
2946 return 0;
2949 #define BDRV_HASH_BLOCK_SIZE 1024
2950 #define IOBUF_SIZE 4096
2951 #define RAM_CBLOCK_MAGIC 0xfabe
2953 typedef struct RamDecompressState {
2954 z_stream zstream;
2955 QEMUFile *f;
2956 uint8_t buf[IOBUF_SIZE];
2957 } RamDecompressState;
2959 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2961 int ret;
2962 memset(s, 0, sizeof(*s));
2963 s->f = f;
2964 ret = inflateInit(&s->zstream);
2965 if (ret != Z_OK)
2966 return -1;
2967 return 0;
2970 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2972 int ret, clen;
2974 s->zstream.avail_out = len;
2975 s->zstream.next_out = buf;
2976 while (s->zstream.avail_out > 0) {
2977 if (s->zstream.avail_in == 0) {
2978 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2979 return -1;
2980 clen = qemu_get_be16(s->f);
2981 if (clen > IOBUF_SIZE)
2982 return -1;
2983 qemu_get_buffer(s->f, s->buf, clen);
2984 s->zstream.avail_in = clen;
2985 s->zstream.next_in = s->buf;
2987 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2988 if (ret != Z_OK && ret != Z_STREAM_END) {
2989 return -1;
2992 return 0;
2995 static void ram_decompress_close(RamDecompressState *s)
2997 inflateEnd(&s->zstream);
3000 #define RAM_SAVE_FLAG_FULL 0x01
3001 #define RAM_SAVE_FLAG_COMPRESS 0x02
3002 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3003 #define RAM_SAVE_FLAG_PAGE 0x08
3004 #define RAM_SAVE_FLAG_EOS 0x10
3006 static int is_dup_page(uint8_t *page, uint8_t ch)
3008 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3009 uint32_t *array = (uint32_t *)page;
3010 int i;
3012 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3013 if (array[i] != val)
3014 return 0;
3017 return 1;
3020 static int ram_save_block(QEMUFile *f)
3022 static ram_addr_t current_addr = 0;
3023 ram_addr_t saved_addr = current_addr;
3024 ram_addr_t addr = 0;
3025 int found = 0;
3027 while (addr < last_ram_offset) {
3028 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3029 uint8_t *p;
3031 cpu_physical_memory_reset_dirty(current_addr,
3032 current_addr + TARGET_PAGE_SIZE,
3033 MIGRATION_DIRTY_FLAG);
3035 p = qemu_get_ram_ptr(current_addr);
3037 if (is_dup_page(p, *p)) {
3038 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3039 qemu_put_byte(f, *p);
3040 } else {
3041 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3042 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3045 found = 1;
3046 break;
3048 addr += TARGET_PAGE_SIZE;
3049 current_addr = (saved_addr + addr) % last_ram_offset;
3052 return found;
3055 static uint64_t bytes_transferred = 0;
3057 static ram_addr_t ram_save_remaining(void)
3059 ram_addr_t addr;
3060 ram_addr_t count = 0;
3062 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3063 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3064 count++;
3067 return count;
3070 uint64_t ram_bytes_remaining(void)
3072 return ram_save_remaining() * TARGET_PAGE_SIZE;
3075 uint64_t ram_bytes_transferred(void)
3077 return bytes_transferred;
3080 uint64_t ram_bytes_total(void)
3082 return last_ram_offset;
3085 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3087 ram_addr_t addr;
3088 uint64_t bytes_transferred_last;
3089 double bwidth = 0;
3090 uint64_t expected_time = 0;
3092 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3093 qemu_file_set_error(f);
3094 return 0;
3097 if (stage == 1) {
3098 /* Make sure all dirty bits are set */
3099 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3100 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3101 cpu_physical_memory_set_dirty(addr);
3104 /* Enable dirty memory tracking */
3105 cpu_physical_memory_set_dirty_tracking(1);
3107 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3110 bytes_transferred_last = bytes_transferred;
3111 bwidth = get_clock();
3113 while (!qemu_file_rate_limit(f)) {
3114 int ret;
3116 ret = ram_save_block(f);
3117 bytes_transferred += ret * TARGET_PAGE_SIZE;
3118 if (ret == 0) /* no more blocks */
3119 break;
3122 bwidth = get_clock() - bwidth;
3123 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3125 /* if we haven't transferred anything this round, force expected_time to a
3126 * a very high value, but without crashing */
3127 if (bwidth == 0)
3128 bwidth = 0.000001;
3130 /* try transferring iterative blocks of memory */
3132 if (stage == 3) {
3134 /* flush all remaining blocks regardless of rate limiting */
3135 while (ram_save_block(f) != 0) {
3136 bytes_transferred += TARGET_PAGE_SIZE;
3138 cpu_physical_memory_set_dirty_tracking(0);
3141 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3143 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3145 return (stage == 2) && (expected_time <= migrate_max_downtime());
3148 static int ram_load_dead(QEMUFile *f, void *opaque)
3150 RamDecompressState s1, *s = &s1;
3151 uint8_t buf[10];
3152 ram_addr_t i;
3154 if (ram_decompress_open(s, f) < 0)
3155 return -EINVAL;
3156 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3157 if (ram_decompress_buf(s, buf, 1) < 0) {
3158 fprintf(stderr, "Error while reading ram block header\n");
3159 goto error;
3161 if (buf[0] == 0) {
3162 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3163 BDRV_HASH_BLOCK_SIZE) < 0) {
3164 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3165 goto error;
3167 } else {
3168 error:
3169 printf("Error block header\n");
3170 return -EINVAL;
3173 ram_decompress_close(s);
3175 return 0;
3178 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3180 ram_addr_t addr;
3181 int flags;
3183 if (version_id == 1)
3184 return ram_load_v1(f, opaque);
3186 if (version_id == 2) {
3187 if (qemu_get_be32(f) != last_ram_offset)
3188 return -EINVAL;
3189 return ram_load_dead(f, opaque);
3192 if (version_id != 3)
3193 return -EINVAL;
3195 do {
3196 addr = qemu_get_be64(f);
3198 flags = addr & ~TARGET_PAGE_MASK;
3199 addr &= TARGET_PAGE_MASK;
3201 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3202 if (addr != last_ram_offset)
3203 return -EINVAL;
3206 if (flags & RAM_SAVE_FLAG_FULL) {
3207 if (ram_load_dead(f, opaque) < 0)
3208 return -EINVAL;
3211 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3212 uint8_t ch = qemu_get_byte(f);
3213 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3214 #ifndef _WIN32
3215 if (ch == 0 &&
3216 (!kvm_enabled() || kvm_has_sync_mmu())) {
3217 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3219 #endif
3220 } else if (flags & RAM_SAVE_FLAG_PAGE)
3221 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3222 } while (!(flags & RAM_SAVE_FLAG_EOS));
3224 return 0;
3227 void qemu_service_io(void)
3229 qemu_notify_event();
3232 /***********************************************************/
3233 /* bottom halves (can be seen as timers which expire ASAP) */
3235 struct QEMUBH {
3236 QEMUBHFunc *cb;
3237 void *opaque;
3238 int scheduled;
3239 int idle;
3240 int deleted;
3241 QEMUBH *next;
3244 static QEMUBH *first_bh = NULL;
3246 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3248 QEMUBH *bh;
3249 bh = qemu_mallocz(sizeof(QEMUBH));
3250 bh->cb = cb;
3251 bh->opaque = opaque;
3252 bh->next = first_bh;
3253 first_bh = bh;
3254 return bh;
3257 int qemu_bh_poll(void)
3259 QEMUBH *bh, **bhp;
3260 int ret;
3262 ret = 0;
3263 for (bh = first_bh; bh; bh = bh->next) {
3264 if (!bh->deleted && bh->scheduled) {
3265 bh->scheduled = 0;
3266 if (!bh->idle)
3267 ret = 1;
3268 bh->idle = 0;
3269 bh->cb(bh->opaque);
3273 /* remove deleted bhs */
3274 bhp = &first_bh;
3275 while (*bhp) {
3276 bh = *bhp;
3277 if (bh->deleted) {
3278 *bhp = bh->next;
3279 qemu_free(bh);
3280 } else
3281 bhp = &bh->next;
3284 return ret;
3287 void qemu_bh_schedule_idle(QEMUBH *bh)
3289 if (bh->scheduled)
3290 return;
3291 bh->scheduled = 1;
3292 bh->idle = 1;
3295 void qemu_bh_schedule(QEMUBH *bh)
3297 if (bh->scheduled)
3298 return;
3299 bh->scheduled = 1;
3300 bh->idle = 0;
3301 /* stop the currently executing CPU to execute the BH ASAP */
3302 qemu_notify_event();
3305 void qemu_bh_cancel(QEMUBH *bh)
3307 bh->scheduled = 0;
3310 void qemu_bh_delete(QEMUBH *bh)
3312 bh->scheduled = 0;
3313 bh->deleted = 1;
3316 static void qemu_bh_update_timeout(int *timeout)
3318 QEMUBH *bh;
3320 for (bh = first_bh; bh; bh = bh->next) {
3321 if (!bh->deleted && bh->scheduled) {
3322 if (bh->idle) {
3323 /* idle bottom halves will be polled at least
3324 * every 10ms */
3325 *timeout = MIN(10, *timeout);
3326 } else {
3327 /* non-idle bottom halves will be executed
3328 * immediately */
3329 *timeout = 0;
3330 break;
3336 /***********************************************************/
3337 /* machine registration */
3339 static QEMUMachine *first_machine = NULL;
3340 QEMUMachine *current_machine = NULL;
3342 int qemu_register_machine(QEMUMachine *m)
3344 QEMUMachine **pm;
3345 pm = &first_machine;
3346 while (*pm != NULL)
3347 pm = &(*pm)->next;
3348 m->next = NULL;
3349 *pm = m;
3350 return 0;
3353 static QEMUMachine *find_machine(const char *name)
3355 QEMUMachine *m;
3357 for(m = first_machine; m != NULL; m = m->next) {
3358 if (!strcmp(m->name, name))
3359 return m;
3361 return NULL;
3364 static QEMUMachine *find_default_machine(void)
3366 QEMUMachine *m;
3368 for(m = first_machine; m != NULL; m = m->next) {
3369 if (m->is_default) {
3370 return m;
3373 return NULL;
3376 /***********************************************************/
3377 /* main execution loop */
3379 static void gui_update(void *opaque)
3381 uint64_t interval = GUI_REFRESH_INTERVAL;
3382 DisplayState *ds = opaque;
3383 DisplayChangeListener *dcl = ds->listeners;
3385 dpy_refresh(ds);
3387 while (dcl != NULL) {
3388 if (dcl->gui_timer_interval &&
3389 dcl->gui_timer_interval < interval)
3390 interval = dcl->gui_timer_interval;
3391 dcl = dcl->next;
3393 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3396 static void nographic_update(void *opaque)
3398 uint64_t interval = GUI_REFRESH_INTERVAL;
3400 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3403 struct vm_change_state_entry {
3404 VMChangeStateHandler *cb;
3405 void *opaque;
3406 LIST_ENTRY (vm_change_state_entry) entries;
3409 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3411 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3412 void *opaque)
3414 VMChangeStateEntry *e;
3416 e = qemu_mallocz(sizeof (*e));
3418 e->cb = cb;
3419 e->opaque = opaque;
3420 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3421 return e;
3424 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3426 LIST_REMOVE (e, entries);
3427 qemu_free (e);
3430 static void vm_state_notify(int running, int reason)
3432 VMChangeStateEntry *e;
3434 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3435 e->cb(e->opaque, running, reason);
3439 static void resume_all_vcpus(void);
3440 static void pause_all_vcpus(void);
3442 void vm_start(void)
3444 if (!vm_running) {
3445 cpu_enable_ticks();
3446 vm_running = 1;
3447 vm_state_notify(1, 0);
3448 qemu_rearm_alarm_timer(alarm_timer);
3449 resume_all_vcpus();
3453 /* reset/shutdown handler */
3455 typedef struct QEMUResetEntry {
3456 TAILQ_ENTRY(QEMUResetEntry) entry;
3457 QEMUResetHandler *func;
3458 void *opaque;
3459 } QEMUResetEntry;
3461 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3462 TAILQ_HEAD_INITIALIZER(reset_handlers);
3463 static int reset_requested;
3464 static int shutdown_requested;
3465 static int powerdown_requested;
3466 static int debug_requested;
3467 static int vmstop_requested;
3469 int qemu_shutdown_requested(void)
3471 int r = shutdown_requested;
3472 shutdown_requested = 0;
3473 return r;
3476 int qemu_reset_requested(void)
3478 int r = reset_requested;
3479 reset_requested = 0;
3480 return r;
3483 int qemu_powerdown_requested(void)
3485 int r = powerdown_requested;
3486 powerdown_requested = 0;
3487 return r;
3490 static int qemu_debug_requested(void)
3492 int r = debug_requested;
3493 debug_requested = 0;
3494 return r;
3497 static int qemu_vmstop_requested(void)
3499 int r = vmstop_requested;
3500 vmstop_requested = 0;
3501 return r;
3504 static void do_vm_stop(int reason)
3506 if (vm_running) {
3507 cpu_disable_ticks();
3508 vm_running = 0;
3509 pause_all_vcpus();
3510 vm_state_notify(0, reason);
3514 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3516 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3518 re->func = func;
3519 re->opaque = opaque;
3520 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3523 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3525 QEMUResetEntry *re;
3527 TAILQ_FOREACH(re, &reset_handlers, entry) {
3528 if (re->func == func && re->opaque == opaque) {
3529 TAILQ_REMOVE(&reset_handlers, re, entry);
3530 qemu_free(re);
3531 return;
3536 void qemu_system_reset(void)
3538 QEMUResetEntry *re, *nre;
3540 /* reset all devices */
3541 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3542 re->func(re->opaque);
3546 void qemu_system_reset_request(void)
3548 if (no_reboot) {
3549 shutdown_requested = 1;
3550 } else {
3551 reset_requested = 1;
3553 qemu_notify_event();
3556 void qemu_system_shutdown_request(void)
3558 shutdown_requested = 1;
3559 qemu_notify_event();
3562 void qemu_system_powerdown_request(void)
3564 powerdown_requested = 1;
3565 qemu_notify_event();
3568 #ifdef CONFIG_IOTHREAD
3569 static void qemu_system_vmstop_request(int reason)
3571 vmstop_requested = reason;
3572 qemu_notify_event();
3574 #endif
3576 #ifndef _WIN32
3577 static int io_thread_fd = -1;
3579 static void qemu_event_increment(void)
3581 static const char byte = 0;
3583 if (io_thread_fd == -1)
3584 return;
3586 write(io_thread_fd, &byte, sizeof(byte));
3589 static void qemu_event_read(void *opaque)
3591 int fd = (unsigned long)opaque;
3592 ssize_t len;
3594 /* Drain the notify pipe */
3595 do {
3596 char buffer[512];
3597 len = read(fd, buffer, sizeof(buffer));
3598 } while ((len == -1 && errno == EINTR) || len > 0);
3601 static int qemu_event_init(void)
3603 int err;
3604 int fds[2];
3606 err = pipe(fds);
3607 if (err == -1)
3608 return -errno;
3610 err = fcntl_setfl(fds[0], O_NONBLOCK);
3611 if (err < 0)
3612 goto fail;
3614 err = fcntl_setfl(fds[1], O_NONBLOCK);
3615 if (err < 0)
3616 goto fail;
3618 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3619 (void *)(unsigned long)fds[0]);
3621 io_thread_fd = fds[1];
3622 return 0;
3624 fail:
3625 close(fds[0]);
3626 close(fds[1]);
3627 return err;
3629 #else
3630 HANDLE qemu_event_handle;
3632 static void dummy_event_handler(void *opaque)
3636 static int qemu_event_init(void)
3638 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3639 if (!qemu_event_handle) {
3640 perror("Failed CreateEvent");
3641 return -1;
3643 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3644 return 0;
3647 static void qemu_event_increment(void)
3649 SetEvent(qemu_event_handle);
3651 #endif
3653 static int cpu_can_run(CPUState *env)
3655 if (env->stop)
3656 return 0;
3657 if (env->stopped)
3658 return 0;
3659 return 1;
3662 #ifndef CONFIG_IOTHREAD
3663 static int qemu_init_main_loop(void)
3665 return qemu_event_init();
3668 void qemu_init_vcpu(void *_env)
3670 CPUState *env = _env;
3672 if (kvm_enabled())
3673 kvm_init_vcpu(env);
3674 return;
3677 int qemu_cpu_self(void *env)
3679 return 1;
3682 static void resume_all_vcpus(void)
3686 static void pause_all_vcpus(void)
3690 void qemu_cpu_kick(void *env)
3692 return;
3695 void qemu_notify_event(void)
3697 CPUState *env = cpu_single_env;
3699 if (env) {
3700 cpu_exit(env);
3701 #ifdef USE_KQEMU
3702 if (env->kqemu_enabled)
3703 kqemu_cpu_interrupt(env);
3704 #endif
3708 #define qemu_mutex_lock_iothread() do { } while (0)
3709 #define qemu_mutex_unlock_iothread() do { } while (0)
3711 void vm_stop(int reason)
3713 do_vm_stop(reason);
3716 #else /* CONFIG_IOTHREAD */
3718 #include "qemu-thread.h"
3720 QemuMutex qemu_global_mutex;
3721 static QemuMutex qemu_fair_mutex;
3723 static QemuThread io_thread;
3725 static QemuThread *tcg_cpu_thread;
3726 static QemuCond *tcg_halt_cond;
3728 static int qemu_system_ready;
3729 /* cpu creation */
3730 static QemuCond qemu_cpu_cond;
3731 /* system init */
3732 static QemuCond qemu_system_cond;
3733 static QemuCond qemu_pause_cond;
3735 static void block_io_signals(void);
3736 static void unblock_io_signals(void);
3737 static int tcg_has_work(void);
3739 static int qemu_init_main_loop(void)
3741 int ret;
3743 ret = qemu_event_init();
3744 if (ret)
3745 return ret;
3747 qemu_cond_init(&qemu_pause_cond);
3748 qemu_mutex_init(&qemu_fair_mutex);
3749 qemu_mutex_init(&qemu_global_mutex);
3750 qemu_mutex_lock(&qemu_global_mutex);
3752 unblock_io_signals();
3753 qemu_thread_self(&io_thread);
3755 return 0;
3758 static void qemu_wait_io_event(CPUState *env)
3760 while (!tcg_has_work())
3761 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3763 qemu_mutex_unlock(&qemu_global_mutex);
3766 * Users of qemu_global_mutex can be starved, having no chance
3767 * to acquire it since this path will get to it first.
3768 * So use another lock to provide fairness.
3770 qemu_mutex_lock(&qemu_fair_mutex);
3771 qemu_mutex_unlock(&qemu_fair_mutex);
3773 qemu_mutex_lock(&qemu_global_mutex);
3774 if (env->stop) {
3775 env->stop = 0;
3776 env->stopped = 1;
3777 qemu_cond_signal(&qemu_pause_cond);
3781 static int qemu_cpu_exec(CPUState *env);
3783 static void *kvm_cpu_thread_fn(void *arg)
3785 CPUState *env = arg;
3787 block_io_signals();
3788 qemu_thread_self(env->thread);
3790 /* signal CPU creation */
3791 qemu_mutex_lock(&qemu_global_mutex);
3792 env->created = 1;
3793 qemu_cond_signal(&qemu_cpu_cond);
3795 /* and wait for machine initialization */
3796 while (!qemu_system_ready)
3797 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3799 while (1) {
3800 if (cpu_can_run(env))
3801 qemu_cpu_exec(env);
3802 qemu_wait_io_event(env);
3805 return NULL;
3808 static void tcg_cpu_exec(void);
3810 static void *tcg_cpu_thread_fn(void *arg)
3812 CPUState *env = arg;
3814 block_io_signals();
3815 qemu_thread_self(env->thread);
3817 /* signal CPU creation */
3818 qemu_mutex_lock(&qemu_global_mutex);
3819 for (env = first_cpu; env != NULL; env = env->next_cpu)
3820 env->created = 1;
3821 qemu_cond_signal(&qemu_cpu_cond);
3823 /* and wait for machine initialization */
3824 while (!qemu_system_ready)
3825 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3827 while (1) {
3828 tcg_cpu_exec();
3829 qemu_wait_io_event(cur_cpu);
3832 return NULL;
3835 void qemu_cpu_kick(void *_env)
3837 CPUState *env = _env;
3838 qemu_cond_broadcast(env->halt_cond);
3839 if (kvm_enabled())
3840 qemu_thread_signal(env->thread, SIGUSR1);
3843 int qemu_cpu_self(void *env)
3845 return (cpu_single_env != NULL);
3848 static void cpu_signal(int sig)
3850 if (cpu_single_env)
3851 cpu_exit(cpu_single_env);
3854 static void block_io_signals(void)
3856 sigset_t set;
3857 struct sigaction sigact;
3859 sigemptyset(&set);
3860 sigaddset(&set, SIGUSR2);
3861 sigaddset(&set, SIGIO);
3862 sigaddset(&set, SIGALRM);
3863 pthread_sigmask(SIG_BLOCK, &set, NULL);
3865 sigemptyset(&set);
3866 sigaddset(&set, SIGUSR1);
3867 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3869 memset(&sigact, 0, sizeof(sigact));
3870 sigact.sa_handler = cpu_signal;
3871 sigaction(SIGUSR1, &sigact, NULL);
3874 static void unblock_io_signals(void)
3876 sigset_t set;
3878 sigemptyset(&set);
3879 sigaddset(&set, SIGUSR2);
3880 sigaddset(&set, SIGIO);
3881 sigaddset(&set, SIGALRM);
3882 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3884 sigemptyset(&set);
3885 sigaddset(&set, SIGUSR1);
3886 pthread_sigmask(SIG_BLOCK, &set, NULL);
3889 static void qemu_signal_lock(unsigned int msecs)
3891 qemu_mutex_lock(&qemu_fair_mutex);
3893 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3894 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3895 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3896 break;
3898 qemu_mutex_unlock(&qemu_fair_mutex);
3901 static void qemu_mutex_lock_iothread(void)
3903 if (kvm_enabled()) {
3904 qemu_mutex_lock(&qemu_fair_mutex);
3905 qemu_mutex_lock(&qemu_global_mutex);
3906 qemu_mutex_unlock(&qemu_fair_mutex);
3907 } else
3908 qemu_signal_lock(100);
3911 static void qemu_mutex_unlock_iothread(void)
3913 qemu_mutex_unlock(&qemu_global_mutex);
3916 static int all_vcpus_paused(void)
3918 CPUState *penv = first_cpu;
3920 while (penv) {
3921 if (!penv->stopped)
3922 return 0;
3923 penv = (CPUState *)penv->next_cpu;
3926 return 1;
3929 static void pause_all_vcpus(void)
3931 CPUState *penv = first_cpu;
3933 while (penv) {
3934 penv->stop = 1;
3935 qemu_thread_signal(penv->thread, SIGUSR1);
3936 qemu_cpu_kick(penv);
3937 penv = (CPUState *)penv->next_cpu;
3940 while (!all_vcpus_paused()) {
3941 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3942 penv = first_cpu;
3943 while (penv) {
3944 qemu_thread_signal(penv->thread, SIGUSR1);
3945 penv = (CPUState *)penv->next_cpu;
3950 static void resume_all_vcpus(void)
3952 CPUState *penv = first_cpu;
3954 while (penv) {
3955 penv->stop = 0;
3956 penv->stopped = 0;
3957 qemu_thread_signal(penv->thread, SIGUSR1);
3958 qemu_cpu_kick(penv);
3959 penv = (CPUState *)penv->next_cpu;
3963 static void tcg_init_vcpu(void *_env)
3965 CPUState *env = _env;
3966 /* share a single thread for all cpus with TCG */
3967 if (!tcg_cpu_thread) {
3968 env->thread = qemu_mallocz(sizeof(QemuThread));
3969 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3970 qemu_cond_init(env->halt_cond);
3971 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3972 while (env->created == 0)
3973 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3974 tcg_cpu_thread = env->thread;
3975 tcg_halt_cond = env->halt_cond;
3976 } else {
3977 env->thread = tcg_cpu_thread;
3978 env->halt_cond = tcg_halt_cond;
3982 static void kvm_start_vcpu(CPUState *env)
3984 kvm_init_vcpu(env);
3985 env->thread = qemu_mallocz(sizeof(QemuThread));
3986 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3987 qemu_cond_init(env->halt_cond);
3988 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3989 while (env->created == 0)
3990 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3993 void qemu_init_vcpu(void *_env)
3995 CPUState *env = _env;
3997 if (kvm_enabled())
3998 kvm_start_vcpu(env);
3999 else
4000 tcg_init_vcpu(env);
4003 void qemu_notify_event(void)
4005 qemu_event_increment();
4008 void vm_stop(int reason)
4010 QemuThread me;
4011 qemu_thread_self(&me);
4013 if (!qemu_thread_equal(&me, &io_thread)) {
4014 qemu_system_vmstop_request(reason);
4016 * FIXME: should not return to device code in case
4017 * vm_stop() has been requested.
4019 if (cpu_single_env) {
4020 cpu_exit(cpu_single_env);
4021 cpu_single_env->stop = 1;
4023 return;
4025 do_vm_stop(reason);
4028 #endif
4031 #ifdef _WIN32
4032 static void host_main_loop_wait(int *timeout)
4034 int ret, ret2, i;
4035 PollingEntry *pe;
4038 /* XXX: need to suppress polling by better using win32 events */
4039 ret = 0;
4040 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4041 ret |= pe->func(pe->opaque);
4043 if (ret == 0) {
4044 int err;
4045 WaitObjects *w = &wait_objects;
4047 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4048 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4049 if (w->func[ret - WAIT_OBJECT_0])
4050 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4052 /* Check for additional signaled events */
4053 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4055 /* Check if event is signaled */
4056 ret2 = WaitForSingleObject(w->events[i], 0);
4057 if(ret2 == WAIT_OBJECT_0) {
4058 if (w->func[i])
4059 w->func[i](w->opaque[i]);
4060 } else if (ret2 == WAIT_TIMEOUT) {
4061 } else {
4062 err = GetLastError();
4063 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4066 } else if (ret == WAIT_TIMEOUT) {
4067 } else {
4068 err = GetLastError();
4069 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4073 *timeout = 0;
4075 #else
4076 static void host_main_loop_wait(int *timeout)
4079 #endif
4081 void main_loop_wait(int timeout)
4083 IOHandlerRecord *ioh;
4084 fd_set rfds, wfds, xfds;
4085 int ret, nfds;
4086 struct timeval tv;
4088 qemu_bh_update_timeout(&timeout);
4090 host_main_loop_wait(&timeout);
4092 /* poll any events */
4093 /* XXX: separate device handlers from system ones */
4094 nfds = -1;
4095 FD_ZERO(&rfds);
4096 FD_ZERO(&wfds);
4097 FD_ZERO(&xfds);
4098 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4099 if (ioh->deleted)
4100 continue;
4101 if (ioh->fd_read &&
4102 (!ioh->fd_read_poll ||
4103 ioh->fd_read_poll(ioh->opaque) != 0)) {
4104 FD_SET(ioh->fd, &rfds);
4105 if (ioh->fd > nfds)
4106 nfds = ioh->fd;
4108 if (ioh->fd_write) {
4109 FD_SET(ioh->fd, &wfds);
4110 if (ioh->fd > nfds)
4111 nfds = ioh->fd;
4115 tv.tv_sec = timeout / 1000;
4116 tv.tv_usec = (timeout % 1000) * 1000;
4118 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4120 qemu_mutex_unlock_iothread();
4121 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4122 qemu_mutex_lock_iothread();
4123 if (ret > 0) {
4124 IOHandlerRecord **pioh;
4126 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4127 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4128 ioh->fd_read(ioh->opaque);
4130 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4131 ioh->fd_write(ioh->opaque);
4135 /* remove deleted IO handlers */
4136 pioh = &first_io_handler;
4137 while (*pioh) {
4138 ioh = *pioh;
4139 if (ioh->deleted) {
4140 *pioh = ioh->next;
4141 qemu_free(ioh);
4142 } else
4143 pioh = &ioh->next;
4147 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4149 /* rearm timer, if not periodic */
4150 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4151 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4152 qemu_rearm_alarm_timer(alarm_timer);
4155 /* vm time timers */
4156 if (vm_running) {
4157 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4158 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4159 qemu_get_clock(vm_clock));
4162 /* real time timers */
4163 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4164 qemu_get_clock(rt_clock));
4166 /* Check bottom-halves last in case any of the earlier events triggered
4167 them. */
4168 qemu_bh_poll();
4172 static int qemu_cpu_exec(CPUState *env)
4174 int ret;
4175 #ifdef CONFIG_PROFILER
4176 int64_t ti;
4177 #endif
4179 #ifdef CONFIG_PROFILER
4180 ti = profile_getclock();
4181 #endif
4182 if (use_icount) {
4183 int64_t count;
4184 int decr;
4185 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4186 env->icount_decr.u16.low = 0;
4187 env->icount_extra = 0;
4188 count = qemu_next_deadline();
4189 count = (count + (1 << icount_time_shift) - 1)
4190 >> icount_time_shift;
4191 qemu_icount += count;
4192 decr = (count > 0xffff) ? 0xffff : count;
4193 count -= decr;
4194 env->icount_decr.u16.low = decr;
4195 env->icount_extra = count;
4197 ret = cpu_exec(env);
4198 #ifdef CONFIG_PROFILER
4199 qemu_time += profile_getclock() - ti;
4200 #endif
4201 if (use_icount) {
4202 /* Fold pending instructions back into the
4203 instruction counter, and clear the interrupt flag. */
4204 qemu_icount -= (env->icount_decr.u16.low
4205 + env->icount_extra);
4206 env->icount_decr.u32 = 0;
4207 env->icount_extra = 0;
4209 return ret;
4212 static void tcg_cpu_exec(void)
4214 int ret = 0;
4216 if (next_cpu == NULL)
4217 next_cpu = first_cpu;
4218 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4219 CPUState *env = cur_cpu = next_cpu;
4221 if (!vm_running)
4222 break;
4223 if (timer_alarm_pending) {
4224 timer_alarm_pending = 0;
4225 break;
4227 if (cpu_can_run(env))
4228 ret = qemu_cpu_exec(env);
4229 if (ret == EXCP_DEBUG) {
4230 gdb_set_stop_cpu(env);
4231 debug_requested = 1;
4232 break;
4237 static int cpu_has_work(CPUState *env)
4239 if (env->stop)
4240 return 1;
4241 if (env->stopped)
4242 return 0;
4243 if (!env->halted)
4244 return 1;
4245 if (qemu_cpu_has_work(env))
4246 return 1;
4247 return 0;
4250 static int tcg_has_work(void)
4252 CPUState *env;
4254 for (env = first_cpu; env != NULL; env = env->next_cpu)
4255 if (cpu_has_work(env))
4256 return 1;
4257 return 0;
4260 static int qemu_calculate_timeout(void)
4262 #ifndef CONFIG_IOTHREAD
4263 int timeout;
4265 if (!vm_running)
4266 timeout = 5000;
4267 else if (tcg_has_work())
4268 timeout = 0;
4269 else if (!use_icount)
4270 timeout = 5000;
4271 else {
4272 /* XXX: use timeout computed from timers */
4273 int64_t add;
4274 int64_t delta;
4275 /* Advance virtual time to the next event. */
4276 if (use_icount == 1) {
4277 /* When not using an adaptive execution frequency
4278 we tend to get badly out of sync with real time,
4279 so just delay for a reasonable amount of time. */
4280 delta = 0;
4281 } else {
4282 delta = cpu_get_icount() - cpu_get_clock();
4284 if (delta > 0) {
4285 /* If virtual time is ahead of real time then just
4286 wait for IO. */
4287 timeout = (delta / 1000000) + 1;
4288 } else {
4289 /* Wait for either IO to occur or the next
4290 timer event. */
4291 add = qemu_next_deadline();
4292 /* We advance the timer before checking for IO.
4293 Limit the amount we advance so that early IO
4294 activity won't get the guest too far ahead. */
4295 if (add > 10000000)
4296 add = 10000000;
4297 delta += add;
4298 add = (add + (1 << icount_time_shift) - 1)
4299 >> icount_time_shift;
4300 qemu_icount += add;
4301 timeout = delta / 1000000;
4302 if (timeout < 0)
4303 timeout = 0;
4307 return timeout;
4308 #else /* CONFIG_IOTHREAD */
4309 return 1000;
4310 #endif
4313 static int vm_can_run(void)
4315 if (powerdown_requested)
4316 return 0;
4317 if (reset_requested)
4318 return 0;
4319 if (shutdown_requested)
4320 return 0;
4321 if (debug_requested)
4322 return 0;
4323 return 1;
4326 static void main_loop(void)
4328 int r;
4330 #ifdef CONFIG_IOTHREAD
4331 qemu_system_ready = 1;
4332 qemu_cond_broadcast(&qemu_system_cond);
4333 #endif
4335 for (;;) {
4336 do {
4337 #ifdef CONFIG_PROFILER
4338 int64_t ti;
4339 #endif
4340 #ifndef CONFIG_IOTHREAD
4341 tcg_cpu_exec();
4342 #endif
4343 #ifdef CONFIG_PROFILER
4344 ti = profile_getclock();
4345 #endif
4346 main_loop_wait(qemu_calculate_timeout());
4347 #ifdef CONFIG_PROFILER
4348 dev_time += profile_getclock() - ti;
4349 #endif
4350 } while (vm_can_run());
4352 if (qemu_debug_requested())
4353 vm_stop(EXCP_DEBUG);
4354 if (qemu_shutdown_requested()) {
4355 if (no_shutdown) {
4356 vm_stop(0);
4357 no_shutdown = 0;
4358 } else
4359 break;
4361 if (qemu_reset_requested()) {
4362 pause_all_vcpus();
4363 qemu_system_reset();
4364 resume_all_vcpus();
4366 if (qemu_powerdown_requested())
4367 qemu_system_powerdown();
4368 if ((r = qemu_vmstop_requested()))
4369 vm_stop(r);
4371 pause_all_vcpus();
4374 static void version(void)
4376 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4379 static void help(int exitcode)
4381 version();
4382 printf("usage: %s [options] [disk_image]\n"
4383 "\n"
4384 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4385 "\n"
4386 #define DEF(option, opt_arg, opt_enum, opt_help) \
4387 opt_help
4388 #define DEFHEADING(text) stringify(text) "\n"
4389 #include "qemu-options.h"
4390 #undef DEF
4391 #undef DEFHEADING
4392 #undef GEN_DOCS
4393 "\n"
4394 "During emulation, the following keys are useful:\n"
4395 "ctrl-alt-f toggle full screen\n"
4396 "ctrl-alt-n switch to virtual console 'n'\n"
4397 "ctrl-alt toggle mouse and keyboard grab\n"
4398 "\n"
4399 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4401 "qemu",
4402 DEFAULT_RAM_SIZE,
4403 #ifndef _WIN32
4404 DEFAULT_NETWORK_SCRIPT,
4405 DEFAULT_NETWORK_DOWN_SCRIPT,
4406 #endif
4407 DEFAULT_GDBSTUB_PORT,
4408 "/tmp/qemu.log");
4409 exit(exitcode);
4412 #define HAS_ARG 0x0001
4414 enum {
4415 #define DEF(option, opt_arg, opt_enum, opt_help) \
4416 opt_enum,
4417 #define DEFHEADING(text)
4418 #include "qemu-options.h"
4419 #undef DEF
4420 #undef DEFHEADING
4421 #undef GEN_DOCS
4424 typedef struct QEMUOption {
4425 const char *name;
4426 int flags;
4427 int index;
4428 } QEMUOption;
4430 static const QEMUOption qemu_options[] = {
4431 { "h", 0, QEMU_OPTION_h },
4432 #define DEF(option, opt_arg, opt_enum, opt_help) \
4433 { option, opt_arg, opt_enum },
4434 #define DEFHEADING(text)
4435 #include "qemu-options.h"
4436 #undef DEF
4437 #undef DEFHEADING
4438 #undef GEN_DOCS
4439 { NULL },
4442 #ifdef HAS_AUDIO
4443 struct soundhw soundhw[] = {
4444 #ifdef HAS_AUDIO_CHOICE
4445 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4447 "pcspk",
4448 "PC speaker",
4451 { .init_isa = pcspk_audio_init }
4453 #endif
4455 #ifdef CONFIG_SB16
4457 "sb16",
4458 "Creative Sound Blaster 16",
4461 { .init_isa = SB16_init }
4463 #endif
4465 #ifdef CONFIG_CS4231A
4467 "cs4231a",
4468 "CS4231A",
4471 { .init_isa = cs4231a_init }
4473 #endif
4475 #ifdef CONFIG_ADLIB
4477 "adlib",
4478 #ifdef HAS_YMF262
4479 "Yamaha YMF262 (OPL3)",
4480 #else
4481 "Yamaha YM3812 (OPL2)",
4482 #endif
4485 { .init_isa = Adlib_init }
4487 #endif
4489 #ifdef CONFIG_GUS
4491 "gus",
4492 "Gravis Ultrasound GF1",
4495 { .init_isa = GUS_init }
4497 #endif
4499 #ifdef CONFIG_AC97
4501 "ac97",
4502 "Intel 82801AA AC97 Audio",
4505 { .init_pci = ac97_init }
4507 #endif
4509 #ifdef CONFIG_ES1370
4511 "es1370",
4512 "ENSONIQ AudioPCI ES1370",
4515 { .init_pci = es1370_init }
4517 #endif
4519 #endif /* HAS_AUDIO_CHOICE */
4521 { NULL, NULL, 0, 0, { NULL } }
4524 static void select_soundhw (const char *optarg)
4526 struct soundhw *c;
4528 if (*optarg == '?') {
4529 show_valid_cards:
4531 printf ("Valid sound card names (comma separated):\n");
4532 for (c = soundhw; c->name; ++c) {
4533 printf ("%-11s %s\n", c->name, c->descr);
4535 printf ("\n-soundhw all will enable all of the above\n");
4536 exit (*optarg != '?');
4538 else {
4539 size_t l;
4540 const char *p;
4541 char *e;
4542 int bad_card = 0;
4544 if (!strcmp (optarg, "all")) {
4545 for (c = soundhw; c->name; ++c) {
4546 c->enabled = 1;
4548 return;
4551 p = optarg;
4552 while (*p) {
4553 e = strchr (p, ',');
4554 l = !e ? strlen (p) : (size_t) (e - p);
4556 for (c = soundhw; c->name; ++c) {
4557 if (!strncmp (c->name, p, l)) {
4558 c->enabled = 1;
4559 break;
4563 if (!c->name) {
4564 if (l > 80) {
4565 fprintf (stderr,
4566 "Unknown sound card name (too big to show)\n");
4568 else {
4569 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4570 (int) l, p);
4572 bad_card = 1;
4574 p += l + (e != NULL);
4577 if (bad_card)
4578 goto show_valid_cards;
4581 #endif
4583 static void select_vgahw (const char *p)
4585 const char *opts;
4587 cirrus_vga_enabled = 0;
4588 std_vga_enabled = 0;
4589 vmsvga_enabled = 0;
4590 xenfb_enabled = 0;
4591 if (strstart(p, "std", &opts)) {
4592 std_vga_enabled = 1;
4593 } else if (strstart(p, "cirrus", &opts)) {
4594 cirrus_vga_enabled = 1;
4595 } else if (strstart(p, "vmware", &opts)) {
4596 vmsvga_enabled = 1;
4597 } else if (strstart(p, "xenfb", &opts)) {
4598 xenfb_enabled = 1;
4599 } else if (!strstart(p, "none", &opts)) {
4600 invalid_vga:
4601 fprintf(stderr, "Unknown vga type: %s\n", p);
4602 exit(1);
4604 while (*opts) {
4605 const char *nextopt;
4607 if (strstart(opts, ",retrace=", &nextopt)) {
4608 opts = nextopt;
4609 if (strstart(opts, "dumb", &nextopt))
4610 vga_retrace_method = VGA_RETRACE_DUMB;
4611 else if (strstart(opts, "precise", &nextopt))
4612 vga_retrace_method = VGA_RETRACE_PRECISE;
4613 else goto invalid_vga;
4614 } else goto invalid_vga;
4615 opts = nextopt;
4619 #ifdef TARGET_I386
4620 static int balloon_parse(const char *arg)
4622 char buf[128];
4623 const char *p;
4625 if (!strcmp(arg, "none")) {
4626 virtio_balloon = 0;
4627 } else if (!strncmp(arg, "virtio", 6)) {
4628 virtio_balloon = 1;
4629 if (arg[6] == ',') {
4630 p = arg + 7;
4631 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4632 virtio_balloon_devaddr = strdup(buf);
4635 } else {
4636 return -1;
4638 return 0;
4640 #endif
4642 #ifdef _WIN32
4643 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4645 exit(STATUS_CONTROL_C_EXIT);
4646 return TRUE;
4648 #endif
4650 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4652 int ret;
4654 if(strlen(str) != 36)
4655 return -1;
4657 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4658 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4659 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4661 if(ret != 16)
4662 return -1;
4664 #ifdef TARGET_I386
4665 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4666 #endif
4668 return 0;
4671 #define MAX_NET_CLIENTS 32
4673 #ifndef _WIN32
4675 static void termsig_handler(int signal)
4677 qemu_system_shutdown_request();
4680 static void sigchld_handler(int signal)
4682 waitpid(-1, NULL, WNOHANG);
4685 static void sighandler_setup(void)
4687 struct sigaction act;
4689 memset(&act, 0, sizeof(act));
4690 act.sa_handler = termsig_handler;
4691 sigaction(SIGINT, &act, NULL);
4692 sigaction(SIGHUP, &act, NULL);
4693 sigaction(SIGTERM, &act, NULL);
4695 act.sa_handler = sigchld_handler;
4696 act.sa_flags = SA_NOCLDSTOP;
4697 sigaction(SIGCHLD, &act, NULL);
4700 #endif
4702 #ifdef _WIN32
4703 /* Look for support files in the same directory as the executable. */
4704 static char *find_datadir(const char *argv0)
4706 char *p;
4707 char buf[MAX_PATH];
4708 DWORD len;
4710 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4711 if (len == 0) {
4712 return NULL;
4715 buf[len] = 0;
4716 p = buf + len - 1;
4717 while (p != buf && *p != '\\')
4718 p--;
4719 *p = 0;
4720 if (access(buf, R_OK) == 0) {
4721 return qemu_strdup(buf);
4723 return NULL;
4725 #else /* !_WIN32 */
4727 /* Find a likely location for support files using the location of the binary.
4728 For installed binaries this will be "$bindir/../share/qemu". When
4729 running from the build tree this will be "$bindir/../pc-bios". */
4730 #define SHARE_SUFFIX "/share/qemu"
4731 #define BUILD_SUFFIX "/pc-bios"
4732 static char *find_datadir(const char *argv0)
4734 char *dir;
4735 char *p = NULL;
4736 char *res;
4737 #ifdef PATH_MAX
4738 char buf[PATH_MAX];
4739 #endif
4740 size_t max_len;
4742 #if defined(__linux__)
4744 int len;
4745 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4746 if (len > 0) {
4747 buf[len] = 0;
4748 p = buf;
4751 #elif defined(__FreeBSD__)
4753 int len;
4754 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4755 if (len > 0) {
4756 buf[len] = 0;
4757 p = buf;
4760 #endif
4761 /* If we don't have any way of figuring out the actual executable
4762 location then try argv[0]. */
4763 if (!p) {
4764 #ifdef PATH_MAX
4765 p = buf;
4766 #endif
4767 p = realpath(argv0, p);
4768 if (!p) {
4769 return NULL;
4772 dir = dirname(p);
4773 dir = dirname(dir);
4775 max_len = strlen(dir) +
4776 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4777 res = qemu_mallocz(max_len);
4778 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4779 if (access(res, R_OK)) {
4780 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4781 if (access(res, R_OK)) {
4782 qemu_free(res);
4783 res = NULL;
4786 #ifndef PATH_MAX
4787 free(p);
4788 #endif
4789 return res;
4791 #undef SHARE_SUFFIX
4792 #undef BUILD_SUFFIX
4793 #endif
4795 char *qemu_find_file(int type, const char *name)
4797 int len;
4798 const char *subdir;
4799 char *buf;
4801 /* If name contains path separators then try it as a straight path. */
4802 if ((strchr(name, '/') || strchr(name, '\\'))
4803 && access(name, R_OK) == 0) {
4804 return strdup(name);
4806 switch (type) {
4807 case QEMU_FILE_TYPE_BIOS:
4808 subdir = "";
4809 break;
4810 case QEMU_FILE_TYPE_KEYMAP:
4811 subdir = "keymaps/";
4812 break;
4813 default:
4814 abort();
4816 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4817 buf = qemu_mallocz(len);
4818 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4819 if (access(buf, R_OK)) {
4820 qemu_free(buf);
4821 return NULL;
4823 return buf;
4826 int main(int argc, char **argv, char **envp)
4828 const char *gdbstub_dev = NULL;
4829 uint32_t boot_devices_bitmap = 0;
4830 int i;
4831 int snapshot, linux_boot, net_boot;
4832 const char *initrd_filename;
4833 const char *kernel_filename, *kernel_cmdline;
4834 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4835 DisplayState *ds;
4836 DisplayChangeListener *dcl;
4837 int cyls, heads, secs, translation;
4838 const char *net_clients[MAX_NET_CLIENTS];
4839 int nb_net_clients;
4840 const char *bt_opts[MAX_BT_CMDLINE];
4841 int nb_bt_opts;
4842 int hda_index;
4843 int optind;
4844 const char *r, *optarg;
4845 CharDriverState *monitor_hd = NULL;
4846 const char *monitor_device;
4847 const char *serial_devices[MAX_SERIAL_PORTS];
4848 int serial_device_index;
4849 const char *parallel_devices[MAX_PARALLEL_PORTS];
4850 int parallel_device_index;
4851 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4852 int virtio_console_index;
4853 const char *loadvm = NULL;
4854 QEMUMachine *machine;
4855 const char *cpu_model;
4856 const char *usb_devices[MAX_USB_CMDLINE];
4857 int usb_devices_index;
4858 #ifndef _WIN32
4859 int fds[2];
4860 #endif
4861 int tb_size;
4862 const char *pid_file = NULL;
4863 const char *incoming = NULL;
4864 #ifndef _WIN32
4865 int fd = 0;
4866 struct passwd *pwd = NULL;
4867 const char *chroot_dir = NULL;
4868 const char *run_as = NULL;
4869 #endif
4870 CPUState *env;
4871 int show_vnc_port = 0;
4873 qemu_cache_utils_init(envp);
4875 LIST_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;
4916 monitor_device = "vc:80Cx24C";
4918 serial_devices[0] = "vc:80Cx24C";
4919 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4920 serial_devices[i] = NULL;
4921 serial_device_index = 0;
4923 parallel_devices[0] = "vc:80Cx24C";
4924 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4925 parallel_devices[i] = NULL;
4926 parallel_device_index = 0;
4928 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4929 virtio_consoles[i] = NULL;
4930 virtio_console_index = 0;
4932 for (i = 0; i < MAX_NODES; i++) {
4933 node_mem[i] = 0;
4934 node_cpumask[i] = 0;
4937 usb_devices_index = 0;
4939 nb_net_clients = 0;
4940 nb_bt_opts = 0;
4941 nb_drives = 0;
4942 nb_drives_opt = 0;
4943 nb_numa_nodes = 0;
4944 hda_index = -1;
4946 nb_nics = 0;
4948 tb_size = 0;
4949 autostart= 1;
4951 register_watchdogs();
4953 optind = 1;
4954 for(;;) {
4955 if (optind >= argc)
4956 break;
4957 r = argv[optind];
4958 if (r[0] != '-') {
4959 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4960 } else {
4961 const QEMUOption *popt;
4963 optind++;
4964 /* Treat --foo the same as -foo. */
4965 if (r[1] == '-')
4966 r++;
4967 popt = qemu_options;
4968 for(;;) {
4969 if (!popt->name) {
4970 fprintf(stderr, "%s: invalid option -- '%s'\n",
4971 argv[0], r);
4972 exit(1);
4974 if (!strcmp(popt->name, r + 1))
4975 break;
4976 popt++;
4978 if (popt->flags & HAS_ARG) {
4979 if (optind >= argc) {
4980 fprintf(stderr, "%s: option '%s' requires an argument\n",
4981 argv[0], r);
4982 exit(1);
4984 optarg = argv[optind++];
4985 } else {
4986 optarg = NULL;
4989 switch(popt->index) {
4990 case QEMU_OPTION_M:
4991 machine = find_machine(optarg);
4992 if (!machine) {
4993 QEMUMachine *m;
4994 printf("Supported machines are:\n");
4995 for(m = first_machine; m != NULL; m = m->next) {
4996 printf("%-10s %s%s\n",
4997 m->name, m->desc,
4998 m->is_default ? " (default)" : "");
5000 exit(*optarg != '?');
5002 break;
5003 case QEMU_OPTION_cpu:
5004 /* hw initialization will check this */
5005 if (*optarg == '?') {
5006 /* XXX: implement xxx_cpu_list for targets that still miss it */
5007 #if defined(cpu_list)
5008 cpu_list(stdout, &fprintf);
5009 #endif
5010 exit(0);
5011 } else {
5012 cpu_model = optarg;
5014 break;
5015 case QEMU_OPTION_initrd:
5016 initrd_filename = optarg;
5017 break;
5018 case QEMU_OPTION_hda:
5019 if (cyls == 0)
5020 hda_index = drive_add(optarg, HD_ALIAS, 0);
5021 else
5022 hda_index = drive_add(optarg, HD_ALIAS
5023 ",cyls=%d,heads=%d,secs=%d%s",
5024 0, cyls, heads, secs,
5025 translation == BIOS_ATA_TRANSLATION_LBA ?
5026 ",trans=lba" :
5027 translation == BIOS_ATA_TRANSLATION_NONE ?
5028 ",trans=none" : "");
5029 break;
5030 case QEMU_OPTION_hdb:
5031 case QEMU_OPTION_hdc:
5032 case QEMU_OPTION_hdd:
5033 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5034 break;
5035 case QEMU_OPTION_drive:
5036 drive_add(NULL, "%s", optarg);
5037 break;
5038 case QEMU_OPTION_mtdblock:
5039 drive_add(optarg, MTD_ALIAS);
5040 break;
5041 case QEMU_OPTION_sd:
5042 drive_add(optarg, SD_ALIAS);
5043 break;
5044 case QEMU_OPTION_pflash:
5045 drive_add(optarg, PFLASH_ALIAS);
5046 break;
5047 case QEMU_OPTION_snapshot:
5048 snapshot = 1;
5049 break;
5050 case QEMU_OPTION_hdachs:
5052 const char *p;
5053 p = optarg;
5054 cyls = strtol(p, (char **)&p, 0);
5055 if (cyls < 1 || cyls > 16383)
5056 goto chs_fail;
5057 if (*p != ',')
5058 goto chs_fail;
5059 p++;
5060 heads = strtol(p, (char **)&p, 0);
5061 if (heads < 1 || heads > 16)
5062 goto chs_fail;
5063 if (*p != ',')
5064 goto chs_fail;
5065 p++;
5066 secs = strtol(p, (char **)&p, 0);
5067 if (secs < 1 || secs > 63)
5068 goto chs_fail;
5069 if (*p == ',') {
5070 p++;
5071 if (!strcmp(p, "none"))
5072 translation = BIOS_ATA_TRANSLATION_NONE;
5073 else if (!strcmp(p, "lba"))
5074 translation = BIOS_ATA_TRANSLATION_LBA;
5075 else if (!strcmp(p, "auto"))
5076 translation = BIOS_ATA_TRANSLATION_AUTO;
5077 else
5078 goto chs_fail;
5079 } else if (*p != '\0') {
5080 chs_fail:
5081 fprintf(stderr, "qemu: invalid physical CHS format\n");
5082 exit(1);
5084 if (hda_index != -1)
5085 snprintf(drives_opt[hda_index].opt,
5086 sizeof(drives_opt[hda_index].opt),
5087 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5088 0, cyls, heads, secs,
5089 translation == BIOS_ATA_TRANSLATION_LBA ?
5090 ",trans=lba" :
5091 translation == BIOS_ATA_TRANSLATION_NONE ?
5092 ",trans=none" : "");
5094 break;
5095 case QEMU_OPTION_numa:
5096 if (nb_numa_nodes >= MAX_NODES) {
5097 fprintf(stderr, "qemu: too many NUMA nodes\n");
5098 exit(1);
5100 numa_add(optarg);
5101 break;
5102 case QEMU_OPTION_nographic:
5103 display_type = DT_NOGRAPHIC;
5104 break;
5105 #ifdef CONFIG_CURSES
5106 case QEMU_OPTION_curses:
5107 display_type = DT_CURSES;
5108 break;
5109 #endif
5110 case QEMU_OPTION_portrait:
5111 graphic_rotate = 1;
5112 break;
5113 case QEMU_OPTION_kernel:
5114 kernel_filename = optarg;
5115 break;
5116 case QEMU_OPTION_append:
5117 kernel_cmdline = optarg;
5118 break;
5119 case QEMU_OPTION_cdrom:
5120 drive_add(optarg, CDROM_ALIAS);
5121 break;
5122 case QEMU_OPTION_boot:
5124 static const char * const params[] = {
5125 "order", "once", "menu", NULL
5127 char buf[sizeof(boot_devices)];
5128 char *standard_boot_devices;
5129 int legacy = 0;
5131 if (!strchr(optarg, '=')) {
5132 legacy = 1;
5133 pstrcpy(buf, sizeof(buf), optarg);
5134 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5135 fprintf(stderr,
5136 "qemu: unknown boot parameter '%s' in '%s'\n",
5137 buf, optarg);
5138 exit(1);
5141 if (legacy ||
5142 get_param_value(buf, sizeof(buf), "order", optarg)) {
5143 boot_devices_bitmap = parse_bootdevices(buf);
5144 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5146 if (!legacy) {
5147 if (get_param_value(buf, sizeof(buf),
5148 "once", optarg)) {
5149 boot_devices_bitmap |= parse_bootdevices(buf);
5150 standard_boot_devices = qemu_strdup(boot_devices);
5151 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5152 qemu_register_reset(restore_boot_devices,
5153 standard_boot_devices);
5155 if (get_param_value(buf, sizeof(buf),
5156 "menu", optarg)) {
5157 if (!strcmp(buf, "on")) {
5158 boot_menu = 1;
5159 } else if (!strcmp(buf, "off")) {
5160 boot_menu = 0;
5161 } else {
5162 fprintf(stderr,
5163 "qemu: invalid option value '%s'\n",
5164 buf);
5165 exit(1);
5170 break;
5171 case QEMU_OPTION_fda:
5172 case QEMU_OPTION_fdb:
5173 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5174 break;
5175 #ifdef TARGET_I386
5176 case QEMU_OPTION_no_fd_bootchk:
5177 fd_bootchk = 0;
5178 break;
5179 #endif
5180 case QEMU_OPTION_net:
5181 if (nb_net_clients >= MAX_NET_CLIENTS) {
5182 fprintf(stderr, "qemu: too many network clients\n");
5183 exit(1);
5185 net_clients[nb_net_clients] = optarg;
5186 nb_net_clients++;
5187 break;
5188 #ifdef CONFIG_SLIRP
5189 case QEMU_OPTION_tftp:
5190 legacy_tftp_prefix = optarg;
5191 break;
5192 case QEMU_OPTION_bootp:
5193 legacy_bootp_filename = optarg;
5194 break;
5195 #ifndef _WIN32
5196 case QEMU_OPTION_smb:
5197 net_slirp_smb(optarg);
5198 break;
5199 #endif
5200 case QEMU_OPTION_redir:
5201 net_slirp_redir(optarg);
5202 break;
5203 #endif
5204 case QEMU_OPTION_bt:
5205 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5206 fprintf(stderr, "qemu: too many bluetooth options\n");
5207 exit(1);
5209 bt_opts[nb_bt_opts++] = optarg;
5210 break;
5211 #ifdef HAS_AUDIO
5212 case QEMU_OPTION_audio_help:
5213 AUD_help ();
5214 exit (0);
5215 break;
5216 case QEMU_OPTION_soundhw:
5217 select_soundhw (optarg);
5218 break;
5219 #endif
5220 case QEMU_OPTION_h:
5221 help(0);
5222 break;
5223 case QEMU_OPTION_version:
5224 version();
5225 exit(0);
5226 break;
5227 case QEMU_OPTION_m: {
5228 uint64_t value;
5229 char *ptr;
5231 value = strtoul(optarg, &ptr, 10);
5232 switch (*ptr) {
5233 case 0: case 'M': case 'm':
5234 value <<= 20;
5235 break;
5236 case 'G': case 'g':
5237 value <<= 30;
5238 break;
5239 default:
5240 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5241 exit(1);
5244 /* On 32-bit hosts, QEMU is limited by virtual address space */
5245 if (value > (2047 << 20)
5246 #ifndef CONFIG_KQEMU
5247 && HOST_LONG_BITS == 32
5248 #endif
5250 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5251 exit(1);
5253 if (value != (uint64_t)(ram_addr_t)value) {
5254 fprintf(stderr, "qemu: ram size too large\n");
5255 exit(1);
5257 ram_size = value;
5258 break;
5260 case QEMU_OPTION_d:
5262 int mask;
5263 const CPULogItem *item;
5265 mask = cpu_str_to_log_mask(optarg);
5266 if (!mask) {
5267 printf("Log items (comma separated):\n");
5268 for(item = cpu_log_items; item->mask != 0; item++) {
5269 printf("%-10s %s\n", item->name, item->help);
5271 exit(1);
5273 cpu_set_log(mask);
5275 break;
5276 case QEMU_OPTION_s:
5277 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5278 break;
5279 case QEMU_OPTION_gdb:
5280 gdbstub_dev = optarg;
5281 break;
5282 case QEMU_OPTION_L:
5283 data_dir = optarg;
5284 break;
5285 case QEMU_OPTION_bios:
5286 bios_name = optarg;
5287 break;
5288 case QEMU_OPTION_singlestep:
5289 singlestep = 1;
5290 break;
5291 case QEMU_OPTION_S:
5292 autostart = 0;
5293 break;
5294 #ifndef _WIN32
5295 case QEMU_OPTION_k:
5296 keyboard_layout = optarg;
5297 break;
5298 #endif
5299 case QEMU_OPTION_localtime:
5300 rtc_utc = 0;
5301 break;
5302 case QEMU_OPTION_vga:
5303 select_vgahw (optarg);
5304 break;
5305 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5306 case QEMU_OPTION_g:
5308 const char *p;
5309 int w, h, depth;
5310 p = optarg;
5311 w = strtol(p, (char **)&p, 10);
5312 if (w <= 0) {
5313 graphic_error:
5314 fprintf(stderr, "qemu: invalid resolution or depth\n");
5315 exit(1);
5317 if (*p != 'x')
5318 goto graphic_error;
5319 p++;
5320 h = strtol(p, (char **)&p, 10);
5321 if (h <= 0)
5322 goto graphic_error;
5323 if (*p == 'x') {
5324 p++;
5325 depth = strtol(p, (char **)&p, 10);
5326 if (depth != 8 && depth != 15 && depth != 16 &&
5327 depth != 24 && depth != 32)
5328 goto graphic_error;
5329 } else if (*p == '\0') {
5330 depth = graphic_depth;
5331 } else {
5332 goto graphic_error;
5335 graphic_width = w;
5336 graphic_height = h;
5337 graphic_depth = depth;
5339 break;
5340 #endif
5341 case QEMU_OPTION_echr:
5343 char *r;
5344 term_escape_char = strtol(optarg, &r, 0);
5345 if (r == optarg)
5346 printf("Bad argument to echr\n");
5347 break;
5349 case QEMU_OPTION_monitor:
5350 monitor_device = optarg;
5351 break;
5352 case QEMU_OPTION_serial:
5353 if (serial_device_index >= MAX_SERIAL_PORTS) {
5354 fprintf(stderr, "qemu: too many serial ports\n");
5355 exit(1);
5357 serial_devices[serial_device_index] = optarg;
5358 serial_device_index++;
5359 break;
5360 case QEMU_OPTION_watchdog:
5361 i = select_watchdog(optarg);
5362 if (i > 0)
5363 exit (i == 1 ? 1 : 0);
5364 break;
5365 case QEMU_OPTION_watchdog_action:
5366 if (select_watchdog_action(optarg) == -1) {
5367 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5368 exit(1);
5370 break;
5371 case QEMU_OPTION_virtiocon:
5372 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5373 fprintf(stderr, "qemu: too many virtio consoles\n");
5374 exit(1);
5376 virtio_consoles[virtio_console_index] = optarg;
5377 virtio_console_index++;
5378 break;
5379 case QEMU_OPTION_parallel:
5380 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5381 fprintf(stderr, "qemu: too many parallel ports\n");
5382 exit(1);
5384 parallel_devices[parallel_device_index] = optarg;
5385 parallel_device_index++;
5386 break;
5387 case QEMU_OPTION_loadvm:
5388 loadvm = optarg;
5389 break;
5390 case QEMU_OPTION_full_screen:
5391 full_screen = 1;
5392 break;
5393 #ifdef CONFIG_SDL
5394 case QEMU_OPTION_no_frame:
5395 no_frame = 1;
5396 break;
5397 case QEMU_OPTION_alt_grab:
5398 alt_grab = 1;
5399 break;
5400 case QEMU_OPTION_no_quit:
5401 no_quit = 1;
5402 break;
5403 case QEMU_OPTION_sdl:
5404 display_type = DT_SDL;
5405 break;
5406 #endif
5407 case QEMU_OPTION_pidfile:
5408 pid_file = optarg;
5409 break;
5410 #ifdef TARGET_I386
5411 case QEMU_OPTION_win2k_hack:
5412 win2k_install_hack = 1;
5413 break;
5414 case QEMU_OPTION_rtc_td_hack:
5415 rtc_td_hack = 1;
5416 break;
5417 case QEMU_OPTION_acpitable:
5418 if(acpi_table_add(optarg) < 0) {
5419 fprintf(stderr, "Wrong acpi table provided\n");
5420 exit(1);
5422 break;
5423 case QEMU_OPTION_smbios:
5424 if(smbios_entry_add(optarg) < 0) {
5425 fprintf(stderr, "Wrong smbios provided\n");
5426 exit(1);
5428 break;
5429 #endif
5430 #ifdef CONFIG_KQEMU
5431 case QEMU_OPTION_enable_kqemu:
5432 kqemu_allowed = 1;
5433 break;
5434 case QEMU_OPTION_kernel_kqemu:
5435 kqemu_allowed = 2;
5436 break;
5437 #endif
5438 #ifdef CONFIG_KVM
5439 case QEMU_OPTION_enable_kvm:
5440 kvm_allowed = 1;
5441 #ifdef CONFIG_KQEMU
5442 kqemu_allowed = 0;
5443 #endif
5444 break;
5445 #endif
5446 case QEMU_OPTION_usb:
5447 usb_enabled = 1;
5448 break;
5449 case QEMU_OPTION_usbdevice:
5450 usb_enabled = 1;
5451 if (usb_devices_index >= MAX_USB_CMDLINE) {
5452 fprintf(stderr, "Too many USB devices\n");
5453 exit(1);
5455 usb_devices[usb_devices_index] = optarg;
5456 usb_devices_index++;
5457 break;
5458 case QEMU_OPTION_smp:
5459 smp_cpus = atoi(optarg);
5460 if (smp_cpus < 1) {
5461 fprintf(stderr, "Invalid number of CPUs\n");
5462 exit(1);
5464 break;
5465 case QEMU_OPTION_vnc:
5466 display_type = DT_VNC;
5467 vnc_display = optarg;
5468 break;
5469 #ifdef TARGET_I386
5470 case QEMU_OPTION_no_acpi:
5471 acpi_enabled = 0;
5472 break;
5473 case QEMU_OPTION_no_hpet:
5474 no_hpet = 1;
5475 break;
5476 case QEMU_OPTION_balloon:
5477 if (balloon_parse(optarg) < 0) {
5478 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5479 exit(1);
5481 break;
5482 #endif
5483 case QEMU_OPTION_no_reboot:
5484 no_reboot = 1;
5485 break;
5486 case QEMU_OPTION_no_shutdown:
5487 no_shutdown = 1;
5488 break;
5489 case QEMU_OPTION_show_cursor:
5490 cursor_hide = 0;
5491 break;
5492 case QEMU_OPTION_uuid:
5493 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5494 fprintf(stderr, "Fail to parse UUID string."
5495 " Wrong format.\n");
5496 exit(1);
5498 break;
5499 #ifndef _WIN32
5500 case QEMU_OPTION_daemonize:
5501 daemonize = 1;
5502 break;
5503 #endif
5504 case QEMU_OPTION_option_rom:
5505 if (nb_option_roms >= MAX_OPTION_ROMS) {
5506 fprintf(stderr, "Too many option ROMs\n");
5507 exit(1);
5509 option_rom[nb_option_roms] = optarg;
5510 nb_option_roms++;
5511 break;
5512 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5513 case QEMU_OPTION_semihosting:
5514 semihosting_enabled = 1;
5515 break;
5516 #endif
5517 case QEMU_OPTION_name:
5518 qemu_name = qemu_strdup(optarg);
5520 char *p = strchr(qemu_name, ',');
5521 if (p != NULL) {
5522 *p++ = 0;
5523 if (strncmp(p, "process=", 8)) {
5524 fprintf(stderr, "Unknown subargument %s to -name", p);
5525 exit(1);
5527 p += 8;
5528 set_proc_name(p);
5531 break;
5532 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5533 case QEMU_OPTION_prom_env:
5534 if (nb_prom_envs >= MAX_PROM_ENVS) {
5535 fprintf(stderr, "Too many prom variables\n");
5536 exit(1);
5538 prom_envs[nb_prom_envs] = optarg;
5539 nb_prom_envs++;
5540 break;
5541 #endif
5542 #ifdef TARGET_ARM
5543 case QEMU_OPTION_old_param:
5544 old_param = 1;
5545 break;
5546 #endif
5547 case QEMU_OPTION_clock:
5548 configure_alarms(optarg);
5549 break;
5550 case QEMU_OPTION_startdate:
5552 struct tm tm;
5553 time_t rtc_start_date;
5554 if (!strcmp(optarg, "now")) {
5555 rtc_date_offset = -1;
5556 } else {
5557 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5558 &tm.tm_year,
5559 &tm.tm_mon,
5560 &tm.tm_mday,
5561 &tm.tm_hour,
5562 &tm.tm_min,
5563 &tm.tm_sec) == 6) {
5564 /* OK */
5565 } else if (sscanf(optarg, "%d-%d-%d",
5566 &tm.tm_year,
5567 &tm.tm_mon,
5568 &tm.tm_mday) == 3) {
5569 tm.tm_hour = 0;
5570 tm.tm_min = 0;
5571 tm.tm_sec = 0;
5572 } else {
5573 goto date_fail;
5575 tm.tm_year -= 1900;
5576 tm.tm_mon--;
5577 rtc_start_date = mktimegm(&tm);
5578 if (rtc_start_date == -1) {
5579 date_fail:
5580 fprintf(stderr, "Invalid date format. Valid format are:\n"
5581 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5582 exit(1);
5584 rtc_date_offset = time(NULL) - rtc_start_date;
5587 break;
5588 case QEMU_OPTION_tb_size:
5589 tb_size = strtol(optarg, NULL, 0);
5590 if (tb_size < 0)
5591 tb_size = 0;
5592 break;
5593 case QEMU_OPTION_icount:
5594 use_icount = 1;
5595 if (strcmp(optarg, "auto") == 0) {
5596 icount_time_shift = -1;
5597 } else {
5598 icount_time_shift = strtol(optarg, NULL, 0);
5600 break;
5601 case QEMU_OPTION_incoming:
5602 incoming = optarg;
5603 break;
5604 #ifndef _WIN32
5605 case QEMU_OPTION_chroot:
5606 chroot_dir = optarg;
5607 break;
5608 case QEMU_OPTION_runas:
5609 run_as = optarg;
5610 break;
5611 #endif
5612 #ifdef CONFIG_XEN
5613 case QEMU_OPTION_xen_domid:
5614 xen_domid = atoi(optarg);
5615 break;
5616 case QEMU_OPTION_xen_create:
5617 xen_mode = XEN_CREATE;
5618 break;
5619 case QEMU_OPTION_xen_attach:
5620 xen_mode = XEN_ATTACH;
5621 break;
5622 #endif
5627 /* If no data_dir is specified then try to find it relative to the
5628 executable path. */
5629 if (!data_dir) {
5630 data_dir = find_datadir(argv[0]);
5632 /* If all else fails use the install patch specified when building. */
5633 if (!data_dir) {
5634 data_dir = CONFIG_QEMU_SHAREDIR;
5637 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5638 if (kvm_allowed && kqemu_allowed) {
5639 fprintf(stderr,
5640 "You can not enable both KVM and kqemu at the same time\n");
5641 exit(1);
5643 #endif
5645 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5646 if (smp_cpus > machine->max_cpus) {
5647 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5648 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5649 machine->max_cpus);
5650 exit(1);
5653 if (display_type == DT_NOGRAPHIC) {
5654 if (serial_device_index == 0)
5655 serial_devices[0] = "stdio";
5656 if (parallel_device_index == 0)
5657 parallel_devices[0] = "null";
5658 if (strncmp(monitor_device, "vc", 2) == 0)
5659 monitor_device = "stdio";
5662 #ifndef _WIN32
5663 if (daemonize) {
5664 pid_t pid;
5666 if (pipe(fds) == -1)
5667 exit(1);
5669 pid = fork();
5670 if (pid > 0) {
5671 uint8_t status;
5672 ssize_t len;
5674 close(fds[1]);
5676 again:
5677 len = read(fds[0], &status, 1);
5678 if (len == -1 && (errno == EINTR))
5679 goto again;
5681 if (len != 1)
5682 exit(1);
5683 else if (status == 1) {
5684 fprintf(stderr, "Could not acquire pidfile\n");
5685 exit(1);
5686 } else
5687 exit(0);
5688 } else if (pid < 0)
5689 exit(1);
5691 setsid();
5693 pid = fork();
5694 if (pid > 0)
5695 exit(0);
5696 else if (pid < 0)
5697 exit(1);
5699 umask(027);
5701 signal(SIGTSTP, SIG_IGN);
5702 signal(SIGTTOU, SIG_IGN);
5703 signal(SIGTTIN, SIG_IGN);
5706 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5707 if (daemonize) {
5708 uint8_t status = 1;
5709 write(fds[1], &status, 1);
5710 } else
5711 fprintf(stderr, "Could not acquire pid file\n");
5712 exit(1);
5714 #endif
5716 #ifdef CONFIG_KQEMU
5717 if (smp_cpus > 1)
5718 kqemu_allowed = 0;
5719 #endif
5720 if (qemu_init_main_loop()) {
5721 fprintf(stderr, "qemu_init_main_loop failed\n");
5722 exit(1);
5724 linux_boot = (kernel_filename != NULL);
5726 if (!linux_boot && *kernel_cmdline != '\0') {
5727 fprintf(stderr, "-append only allowed with -kernel option\n");
5728 exit(1);
5731 if (!linux_boot && initrd_filename != NULL) {
5732 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5733 exit(1);
5736 setvbuf(stdout, NULL, _IOLBF, 0);
5738 init_timers();
5739 if (init_timer_alarm() < 0) {
5740 fprintf(stderr, "could not initialize alarm timer\n");
5741 exit(1);
5743 if (use_icount && icount_time_shift < 0) {
5744 use_icount = 2;
5745 /* 125MIPS seems a reasonable initial guess at the guest speed.
5746 It will be corrected fairly quickly anyway. */
5747 icount_time_shift = 3;
5748 init_icount_adjust();
5751 #ifdef _WIN32
5752 socket_init();
5753 #endif
5755 /* init network clients */
5756 if (nb_net_clients == 0) {
5757 /* if no clients, we use a default config */
5758 net_clients[nb_net_clients++] = "nic";
5759 #ifdef CONFIG_SLIRP
5760 net_clients[nb_net_clients++] = "user";
5761 #endif
5764 for(i = 0;i < nb_net_clients; i++) {
5765 if (net_client_parse(net_clients[i]) < 0)
5766 exit(1);
5769 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5770 net_set_boot_mask(net_boot);
5772 net_client_check();
5774 /* init the bluetooth world */
5775 for (i = 0; i < nb_bt_opts; i++)
5776 if (bt_parse(bt_opts[i]))
5777 exit(1);
5779 /* init the memory */
5780 if (ram_size == 0)
5781 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5783 #ifdef CONFIG_KQEMU
5784 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5785 guest ram allocation. It needs to go away. */
5786 if (kqemu_allowed) {
5787 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5788 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5789 if (!kqemu_phys_ram_base) {
5790 fprintf(stderr, "Could not allocate physical memory\n");
5791 exit(1);
5794 #endif
5796 /* init the dynamic translator */
5797 cpu_exec_init_all(tb_size * 1024 * 1024);
5799 bdrv_init();
5801 /* we always create the cdrom drive, even if no disk is there */
5803 if (nb_drives_opt < MAX_DRIVES)
5804 drive_add(NULL, CDROM_ALIAS);
5806 /* we always create at least one floppy */
5808 if (nb_drives_opt < MAX_DRIVES)
5809 drive_add(NULL, FD_ALIAS, 0);
5811 /* we always create one sd slot, even if no card is in it */
5813 if (nb_drives_opt < MAX_DRIVES)
5814 drive_add(NULL, SD_ALIAS);
5816 /* open the virtual block devices */
5818 for(i = 0; i < nb_drives_opt; i++)
5819 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5820 exit(1);
5822 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5823 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5825 #ifndef _WIN32
5826 /* must be after terminal init, SDL library changes signal handlers */
5827 sighandler_setup();
5828 #endif
5830 /* Maintain compatibility with multiple stdio monitors */
5831 if (!strcmp(monitor_device,"stdio")) {
5832 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5833 const char *devname = serial_devices[i];
5834 if (devname && !strcmp(devname,"mon:stdio")) {
5835 monitor_device = NULL;
5836 break;
5837 } else if (devname && !strcmp(devname,"stdio")) {
5838 monitor_device = NULL;
5839 serial_devices[i] = "mon:stdio";
5840 break;
5845 if (nb_numa_nodes > 0) {
5846 int i;
5848 if (nb_numa_nodes > smp_cpus) {
5849 nb_numa_nodes = smp_cpus;
5852 /* If no memory size if given for any node, assume the default case
5853 * and distribute the available memory equally across all nodes
5855 for (i = 0; i < nb_numa_nodes; i++) {
5856 if (node_mem[i] != 0)
5857 break;
5859 if (i == nb_numa_nodes) {
5860 uint64_t usedmem = 0;
5862 /* On Linux, the each node's border has to be 8MB aligned,
5863 * the final node gets the rest.
5865 for (i = 0; i < nb_numa_nodes - 1; i++) {
5866 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5867 usedmem += node_mem[i];
5869 node_mem[i] = ram_size - usedmem;
5872 for (i = 0; i < nb_numa_nodes; i++) {
5873 if (node_cpumask[i] != 0)
5874 break;
5876 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5877 * must cope with this anyway, because there are BIOSes out there in
5878 * real machines which also use this scheme.
5880 if (i == nb_numa_nodes) {
5881 for (i = 0; i < smp_cpus; i++) {
5882 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5887 if (kvm_enabled()) {
5888 int ret;
5890 ret = kvm_init(smp_cpus);
5891 if (ret < 0) {
5892 fprintf(stderr, "failed to initialize KVM\n");
5893 exit(1);
5897 if (monitor_device) {
5898 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5899 if (!monitor_hd) {
5900 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5901 exit(1);
5905 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5906 const char *devname = serial_devices[i];
5907 if (devname && strcmp(devname, "none")) {
5908 char label[32];
5909 snprintf(label, sizeof(label), "serial%d", i);
5910 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5911 if (!serial_hds[i]) {
5912 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5913 devname);
5914 exit(1);
5919 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5920 const char *devname = parallel_devices[i];
5921 if (devname && strcmp(devname, "none")) {
5922 char label[32];
5923 snprintf(label, sizeof(label), "parallel%d", i);
5924 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5925 if (!parallel_hds[i]) {
5926 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5927 devname);
5928 exit(1);
5933 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5934 const char *devname = virtio_consoles[i];
5935 if (devname && strcmp(devname, "none")) {
5936 char label[32];
5937 snprintf(label, sizeof(label), "virtcon%d", i);
5938 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5939 if (!virtcon_hds[i]) {
5940 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5941 devname);
5942 exit(1);
5947 module_call_init(MODULE_INIT_DEVICE);
5949 machine->init(ram_size, boot_devices,
5950 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5953 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5954 for (i = 0; i < nb_numa_nodes; i++) {
5955 if (node_cpumask[i] & (1 << env->cpu_index)) {
5956 env->numa_node = i;
5961 current_machine = machine;
5963 /* init USB devices */
5964 if (usb_enabled) {
5965 for(i = 0; i < usb_devices_index; i++) {
5966 if (usb_device_add(usb_devices[i], 0) < 0) {
5967 fprintf(stderr, "Warning: could not add USB device %s\n",
5968 usb_devices[i]);
5973 if (!display_state)
5974 dumb_display_init();
5975 /* just use the first displaystate for the moment */
5976 ds = display_state;
5978 if (display_type == DT_DEFAULT) {
5979 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5980 display_type = DT_SDL;
5981 #else
5982 display_type = DT_VNC;
5983 vnc_display = "localhost:0,to=99";
5984 show_vnc_port = 1;
5985 #endif
5989 switch (display_type) {
5990 case DT_NOGRAPHIC:
5991 break;
5992 #if defined(CONFIG_CURSES)
5993 case DT_CURSES:
5994 curses_display_init(ds, full_screen);
5995 break;
5996 #endif
5997 #if defined(CONFIG_SDL)
5998 case DT_SDL:
5999 sdl_display_init(ds, full_screen, no_frame);
6000 break;
6001 #elif defined(CONFIG_COCOA)
6002 case DT_SDL:
6003 cocoa_display_init(ds, full_screen);
6004 break;
6005 #endif
6006 case DT_VNC:
6007 vnc_display_init(ds);
6008 if (vnc_display_open(ds, vnc_display) < 0)
6009 exit(1);
6011 if (show_vnc_port) {
6012 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6014 break;
6015 default:
6016 break;
6018 dpy_resize(ds);
6020 dcl = ds->listeners;
6021 while (dcl != NULL) {
6022 if (dcl->dpy_refresh != NULL) {
6023 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6024 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6026 dcl = dcl->next;
6029 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6030 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6031 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6034 text_consoles_set_display(display_state);
6035 qemu_chr_initial_reset();
6037 if (monitor_device && monitor_hd)
6038 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6040 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6041 const char *devname = serial_devices[i];
6042 if (devname && strcmp(devname, "none")) {
6043 if (strstart(devname, "vc", 0))
6044 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6048 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6049 const char *devname = parallel_devices[i];
6050 if (devname && strcmp(devname, "none")) {
6051 if (strstart(devname, "vc", 0))
6052 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6056 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6057 const char *devname = virtio_consoles[i];
6058 if (virtcon_hds[i] && devname) {
6059 if (strstart(devname, "vc", 0))
6060 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6064 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6065 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6066 gdbstub_dev);
6067 exit(1);
6070 if (loadvm)
6071 do_loadvm(cur_mon, loadvm);
6073 if (incoming)
6074 qemu_start_incoming_migration(incoming);
6076 if (autostart)
6077 vm_start();
6079 #ifndef _WIN32
6080 if (daemonize) {
6081 uint8_t status = 0;
6082 ssize_t len;
6084 again1:
6085 len = write(fds[1], &status, 1);
6086 if (len == -1 && (errno == EINTR))
6087 goto again1;
6089 if (len != 1)
6090 exit(1);
6092 chdir("/");
6093 TFR(fd = open("/dev/null", O_RDWR));
6094 if (fd == -1)
6095 exit(1);
6098 if (run_as) {
6099 pwd = getpwnam(run_as);
6100 if (!pwd) {
6101 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6102 exit(1);
6106 if (chroot_dir) {
6107 if (chroot(chroot_dir) < 0) {
6108 fprintf(stderr, "chroot failed\n");
6109 exit(1);
6111 chdir("/");
6114 if (run_as) {
6115 if (setgid(pwd->pw_gid) < 0) {
6116 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6117 exit(1);
6119 if (setuid(pwd->pw_uid) < 0) {
6120 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6121 exit(1);
6123 if (setuid(0) != -1) {
6124 fprintf(stderr, "Dropping privileges failed\n");
6125 exit(1);
6129 if (daemonize) {
6130 dup2(fd, 0);
6131 dup2(fd, 1);
6132 dup2(fd, 2);
6134 close(fd);
6136 #endif
6138 main_loop();
6139 quit_timers();
6140 net_cleanup();
6142 return 0;