move parser functions from vl.c to qemu-option.c
[qemu.git] / vl.c
blob591186806b972fb05a145943da443770ef305e3b
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"
34 /* Needed early to override system queue definitions on BSD */
35 #include "sys-queue.h"
37 #ifndef _WIN32
38 #include <libgen.h>
39 #include <pwd.h>
40 #include <sys/times.h>
41 #include <sys/wait.h>
42 #include <termios.h>
43 #include <sys/mman.h>
44 #include <sys/ioctl.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <net/if.h>
49 #if defined(__NetBSD__)
50 #include <net/if_tap.h>
51 #endif
52 #ifdef __linux__
53 #include <linux/if_tun.h>
54 #endif
55 #include <arpa/inet.h>
56 #include <dirent.h>
57 #include <netdb.h>
58 #include <sys/select.h>
59 #ifdef HOST_BSD
60 #include <sys/stat.h>
61 #if defined(__FreeBSD__) || defined(__DragonFly__)
62 #include <libutil.h>
63 #else
64 #include <util.h>
65 #endif
66 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
67 #include <freebsd/stdlib.h>
68 #else
69 #ifdef __linux__
70 #include <pty.h>
71 #include <malloc.h>
72 #include <linux/rtc.h>
73 #include <sys/prctl.h>
75 /* For the benefit of older linux systems which don't supply it,
76 we use a local copy of hpet.h. */
77 /* #include <linux/hpet.h> */
78 #include "hpet.h"
80 #include <linux/ppdev.h>
81 #include <linux/parport.h>
82 #endif
83 #ifdef __sun__
84 #include <sys/stat.h>
85 #include <sys/ethernet.h>
86 #include <sys/sockio.h>
87 #include <netinet/arp.h>
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_icmp.h> // must come after ip.h
92 #include <netinet/udp.h>
93 #include <netinet/tcp.h>
94 #include <net/if.h>
95 #include <syslog.h>
96 #include <stropts.h>
97 #endif
98 #endif
99 #endif
101 #if defined(__OpenBSD__)
102 #include <util.h>
103 #endif
105 #if defined(CONFIG_VDE)
106 #include <libvdeplug.h>
107 #endif
109 #ifdef _WIN32
110 #include <windows.h>
111 #include <malloc.h>
112 #include <sys/timeb.h>
113 #include <mmsystem.h>
114 #define getopt_long_only getopt_long
115 #define memalign(align, size) malloc(size)
116 #endif
118 #ifdef CONFIG_SDL
119 #if defined(__APPLE__) || defined(main)
120 #include <SDL.h>
121 int qemu_main(int argc, char **argv, char **envp);
122 int main(int argc, char **argv)
124 return qemu_main(argc, argv, NULL);
126 #undef main
127 #define main qemu_main
128 #endif
129 #endif /* CONFIG_SDL */
131 #ifdef CONFIG_COCOA
132 #undef main
133 #define main qemu_main
134 #endif /* CONFIG_COCOA */
136 #include "hw/hw.h"
137 #include "hw/boards.h"
138 #include "hw/usb.h"
139 #include "hw/pcmcia.h"
140 #include "hw/pc.h"
141 #include "hw/audiodev.h"
142 #include "hw/isa.h"
143 #include "hw/baum.h"
144 #include "hw/bt.h"
145 #include "hw/watchdog.h"
146 #include "hw/smbios.h"
147 #include "hw/xen.h"
148 #include "hw/qdev.h"
149 #include "bt-host.h"
150 #include "net.h"
151 #include "monitor.h"
152 #include "console.h"
153 #include "sysemu.h"
154 #include "gdbstub.h"
155 #include "qemu-timer.h"
156 #include "qemu-char.h"
157 #include "cache-utils.h"
158 #include "block.h"
159 #include "dma.h"
160 #include "audio/audio.h"
161 #include "migration.h"
162 #include "kvm.h"
163 #include "balloon.h"
164 #include "qemu-option.h"
166 #include "disas.h"
168 #include "exec-all.h"
170 #include "qemu_socket.h"
172 #include "slirp/libslirp.h"
174 //#define DEBUG_NET
175 //#define DEBUG_SLIRP
177 #define DEFAULT_RAM_SIZE 128
179 static const char *data_dir;
180 const char *bios_name = NULL;
181 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
182 to store the VM snapshots */
183 struct drivelist drives = TAILQ_HEAD_INITIALIZER(drives);
184 struct driveoptlist driveopts = TAILQ_HEAD_INITIALIZER(driveopts);
185 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
186 static DisplayState *display_state;
187 DisplayType display_type = DT_DEFAULT;
188 const char* keyboard_layout = NULL;
189 int64_t ticks_per_sec;
190 ram_addr_t ram_size;
191 int nb_nics;
192 NICInfo nd_table[MAX_NICS];
193 int vm_running;
194 static int autostart;
195 static int rtc_utc = 1;
196 static int rtc_date_offset = -1; /* -1 means no change */
197 int cirrus_vga_enabled = 1;
198 int std_vga_enabled = 0;
199 int vmsvga_enabled = 0;
200 int xenfb_enabled = 0;
201 #ifdef TARGET_SPARC
202 int graphic_width = 1024;
203 int graphic_height = 768;
204 int graphic_depth = 8;
205 #else
206 int graphic_width = 800;
207 int graphic_height = 600;
208 int graphic_depth = 15;
209 #endif
210 static int full_screen = 0;
211 #ifdef CONFIG_SDL
212 static int no_frame = 0;
213 #endif
214 int no_quit = 0;
215 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
216 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
217 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
218 #ifdef TARGET_I386
219 int win2k_install_hack = 0;
220 int rtc_td_hack = 0;
221 #endif
222 int usb_enabled = 0;
223 int singlestep = 0;
224 int smp_cpus = 1;
225 const char *vnc_display;
226 int acpi_enabled = 1;
227 int no_hpet = 0;
228 int virtio_balloon = 1;
229 const char *virtio_balloon_devaddr;
230 int fd_bootchk = 1;
231 int no_reboot = 0;
232 int no_shutdown = 0;
233 int cursor_hide = 1;
234 int graphic_rotate = 0;
235 #ifndef _WIN32
236 int daemonize = 0;
237 #endif
238 WatchdogTimerModel *watchdog = NULL;
239 int watchdog_action = WDT_RESET;
240 const char *option_rom[MAX_OPTION_ROMS];
241 int nb_option_roms;
242 int semihosting_enabled = 0;
243 #ifdef TARGET_ARM
244 int old_param = 0;
245 #endif
246 const char *qemu_name;
247 int alt_grab = 0;
248 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
249 unsigned int nb_prom_envs = 0;
250 const char *prom_envs[MAX_PROM_ENVS];
251 #endif
252 int boot_menu;
254 int nb_numa_nodes;
255 uint64_t node_mem[MAX_NODES];
256 uint64_t node_cpumask[MAX_NODES];
258 static CPUState *cur_cpu;
259 static CPUState *next_cpu;
260 static int timer_alarm_pending = 1;
261 /* Conversion factor from emulated instructions to virtual clock ticks. */
262 static int icount_time_shift;
263 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
264 #define MAX_ICOUNT_SHIFT 10
265 /* Compensate for varying guest execution speed. */
266 static int64_t qemu_icount_bias;
267 static QEMUTimer *icount_rt_timer;
268 static QEMUTimer *icount_vm_timer;
269 static QEMUTimer *nographic_timer;
271 uint8_t qemu_uuid[16];
273 static QEMUBootSetHandler *boot_set_handler;
274 static void *boot_set_opaque;
276 /***********************************************************/
277 /* x86 ISA bus support */
279 target_phys_addr_t isa_mem_base = 0;
280 PicState2 *isa_pic;
282 /***********************************************************/
283 void hw_error(const char *fmt, ...)
285 va_list ap;
286 CPUState *env;
288 va_start(ap, fmt);
289 fprintf(stderr, "qemu: hardware error: ");
290 vfprintf(stderr, fmt, ap);
291 fprintf(stderr, "\n");
292 for(env = first_cpu; env != NULL; env = env->next_cpu) {
293 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
294 #ifdef TARGET_I386
295 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
296 #else
297 cpu_dump_state(env, stderr, fprintf, 0);
298 #endif
300 va_end(ap);
301 abort();
304 static void set_proc_name(const char *s)
306 #ifdef __linux__
307 char name[16];
308 if (!s)
309 return;
310 name[sizeof(name) - 1] = 0;
311 strncpy(name, s, sizeof(name));
312 /* Could rewrite argv[0] too, but that's a bit more complicated.
313 This simple way is enough for `top'. */
314 prctl(PR_SET_NAME, name);
315 #endif
318 /***************/
319 /* ballooning */
321 static QEMUBalloonEvent *qemu_balloon_event;
322 void *qemu_balloon_event_opaque;
324 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
326 qemu_balloon_event = func;
327 qemu_balloon_event_opaque = opaque;
330 void qemu_balloon(ram_addr_t target)
332 if (qemu_balloon_event)
333 qemu_balloon_event(qemu_balloon_event_opaque, target);
336 ram_addr_t qemu_balloon_status(void)
338 if (qemu_balloon_event)
339 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
340 return 0;
343 /***********************************************************/
344 /* keyboard/mouse */
346 static QEMUPutKBDEvent *qemu_put_kbd_event;
347 static void *qemu_put_kbd_event_opaque;
348 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
349 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
351 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
353 qemu_put_kbd_event_opaque = opaque;
354 qemu_put_kbd_event = func;
357 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
358 void *opaque, int absolute,
359 const char *name)
361 QEMUPutMouseEntry *s, *cursor;
363 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
365 s->qemu_put_mouse_event = func;
366 s->qemu_put_mouse_event_opaque = opaque;
367 s->qemu_put_mouse_event_absolute = absolute;
368 s->qemu_put_mouse_event_name = qemu_strdup(name);
369 s->next = NULL;
371 if (!qemu_put_mouse_event_head) {
372 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
373 return s;
376 cursor = qemu_put_mouse_event_head;
377 while (cursor->next != NULL)
378 cursor = cursor->next;
380 cursor->next = s;
381 qemu_put_mouse_event_current = s;
383 return s;
386 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
388 QEMUPutMouseEntry *prev = NULL, *cursor;
390 if (!qemu_put_mouse_event_head || entry == NULL)
391 return;
393 cursor = qemu_put_mouse_event_head;
394 while (cursor != NULL && cursor != entry) {
395 prev = cursor;
396 cursor = cursor->next;
399 if (cursor == NULL) // does not exist or list empty
400 return;
401 else if (prev == NULL) { // entry is head
402 qemu_put_mouse_event_head = cursor->next;
403 if (qemu_put_mouse_event_current == entry)
404 qemu_put_mouse_event_current = cursor->next;
405 qemu_free(entry->qemu_put_mouse_event_name);
406 qemu_free(entry);
407 return;
410 prev->next = entry->next;
412 if (qemu_put_mouse_event_current == entry)
413 qemu_put_mouse_event_current = prev;
415 qemu_free(entry->qemu_put_mouse_event_name);
416 qemu_free(entry);
419 void kbd_put_keycode(int keycode)
421 if (qemu_put_kbd_event) {
422 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
426 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
428 QEMUPutMouseEvent *mouse_event;
429 void *mouse_event_opaque;
430 int width;
432 if (!qemu_put_mouse_event_current) {
433 return;
436 mouse_event =
437 qemu_put_mouse_event_current->qemu_put_mouse_event;
438 mouse_event_opaque =
439 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
441 if (mouse_event) {
442 if (graphic_rotate) {
443 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
444 width = 0x7fff;
445 else
446 width = graphic_width - 1;
447 mouse_event(mouse_event_opaque,
448 width - dy, dx, dz, buttons_state);
449 } else
450 mouse_event(mouse_event_opaque,
451 dx, dy, dz, buttons_state);
455 int kbd_mouse_is_absolute(void)
457 if (!qemu_put_mouse_event_current)
458 return 0;
460 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
463 void do_info_mice(Monitor *mon)
465 QEMUPutMouseEntry *cursor;
466 int index = 0;
468 if (!qemu_put_mouse_event_head) {
469 monitor_printf(mon, "No mouse devices connected\n");
470 return;
473 monitor_printf(mon, "Mouse devices available:\n");
474 cursor = qemu_put_mouse_event_head;
475 while (cursor != NULL) {
476 monitor_printf(mon, "%c Mouse #%d: %s\n",
477 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
478 index, cursor->qemu_put_mouse_event_name);
479 index++;
480 cursor = cursor->next;
484 void do_mouse_set(Monitor *mon, int index)
486 QEMUPutMouseEntry *cursor;
487 int i = 0;
489 if (!qemu_put_mouse_event_head) {
490 monitor_printf(mon, "No mouse devices connected\n");
491 return;
494 cursor = qemu_put_mouse_event_head;
495 while (cursor != NULL && index != i) {
496 i++;
497 cursor = cursor->next;
500 if (cursor != NULL)
501 qemu_put_mouse_event_current = cursor;
502 else
503 monitor_printf(mon, "Mouse at given index not found\n");
506 /* compute with 96 bit intermediate result: (a*b)/c */
507 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
509 union {
510 uint64_t ll;
511 struct {
512 #ifdef WORDS_BIGENDIAN
513 uint32_t high, low;
514 #else
515 uint32_t low, high;
516 #endif
517 } l;
518 } u, res;
519 uint64_t rl, rh;
521 u.ll = a;
522 rl = (uint64_t)u.l.low * (uint64_t)b;
523 rh = (uint64_t)u.l.high * (uint64_t)b;
524 rh += (rl >> 32);
525 res.l.high = rh / c;
526 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
527 return res.ll;
530 /***********************************************************/
531 /* real time host monotonic timer */
533 #define QEMU_TIMER_BASE 1000000000LL
535 #ifdef WIN32
537 static int64_t clock_freq;
539 static void init_get_clock(void)
541 LARGE_INTEGER freq;
542 int ret;
543 ret = QueryPerformanceFrequency(&freq);
544 if (ret == 0) {
545 fprintf(stderr, "Could not calibrate ticks\n");
546 exit(1);
548 clock_freq = freq.QuadPart;
551 static int64_t get_clock(void)
553 LARGE_INTEGER ti;
554 QueryPerformanceCounter(&ti);
555 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
558 #else
560 static int use_rt_clock;
562 static void init_get_clock(void)
564 use_rt_clock = 0;
565 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
566 || defined(__DragonFly__)
568 struct timespec ts;
569 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
570 use_rt_clock = 1;
573 #endif
576 static int64_t get_clock(void)
578 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
579 || defined(__DragonFly__)
580 if (use_rt_clock) {
581 struct timespec ts;
582 clock_gettime(CLOCK_MONOTONIC, &ts);
583 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
584 } else
585 #endif
587 /* XXX: using gettimeofday leads to problems if the date
588 changes, so it should be avoided. */
589 struct timeval tv;
590 gettimeofday(&tv, NULL);
591 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
594 #endif
596 /* Return the virtual CPU time, based on the instruction counter. */
597 static int64_t cpu_get_icount(void)
599 int64_t icount;
600 CPUState *env = cpu_single_env;;
601 icount = qemu_icount;
602 if (env) {
603 if (!can_do_io(env))
604 fprintf(stderr, "Bad clock read\n");
605 icount -= (env->icount_decr.u16.low + env->icount_extra);
607 return qemu_icount_bias + (icount << icount_time_shift);
610 /***********************************************************/
611 /* guest cycle counter */
613 static int64_t cpu_ticks_prev;
614 static int64_t cpu_ticks_offset;
615 static int64_t cpu_clock_offset;
616 static int cpu_ticks_enabled;
618 /* return the host CPU cycle counter and handle stop/restart */
619 int64_t cpu_get_ticks(void)
621 if (use_icount) {
622 return cpu_get_icount();
624 if (!cpu_ticks_enabled) {
625 return cpu_ticks_offset;
626 } else {
627 int64_t ticks;
628 ticks = cpu_get_real_ticks();
629 if (cpu_ticks_prev > ticks) {
630 /* Note: non increasing ticks may happen if the host uses
631 software suspend */
632 cpu_ticks_offset += cpu_ticks_prev - ticks;
634 cpu_ticks_prev = ticks;
635 return ticks + cpu_ticks_offset;
639 /* return the host CPU monotonic timer and handle stop/restart */
640 static int64_t cpu_get_clock(void)
642 int64_t ti;
643 if (!cpu_ticks_enabled) {
644 return cpu_clock_offset;
645 } else {
646 ti = get_clock();
647 return ti + cpu_clock_offset;
651 /* enable cpu_get_ticks() */
652 void cpu_enable_ticks(void)
654 if (!cpu_ticks_enabled) {
655 cpu_ticks_offset -= cpu_get_real_ticks();
656 cpu_clock_offset -= get_clock();
657 cpu_ticks_enabled = 1;
661 /* disable cpu_get_ticks() : the clock is stopped. You must not call
662 cpu_get_ticks() after that. */
663 void cpu_disable_ticks(void)
665 if (cpu_ticks_enabled) {
666 cpu_ticks_offset = cpu_get_ticks();
667 cpu_clock_offset = cpu_get_clock();
668 cpu_ticks_enabled = 0;
672 /***********************************************************/
673 /* timers */
675 #define QEMU_TIMER_REALTIME 0
676 #define QEMU_TIMER_VIRTUAL 1
678 struct QEMUClock {
679 int type;
680 /* XXX: add frequency */
683 struct QEMUTimer {
684 QEMUClock *clock;
685 int64_t expire_time;
686 QEMUTimerCB *cb;
687 void *opaque;
688 struct QEMUTimer *next;
691 struct qemu_alarm_timer {
692 char const *name;
693 unsigned int flags;
695 int (*start)(struct qemu_alarm_timer *t);
696 void (*stop)(struct qemu_alarm_timer *t);
697 void (*rearm)(struct qemu_alarm_timer *t);
698 void *priv;
701 #define ALARM_FLAG_DYNTICKS 0x1
702 #define ALARM_FLAG_EXPIRED 0x2
704 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
706 return t && (t->flags & ALARM_FLAG_DYNTICKS);
709 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
711 if (!alarm_has_dynticks(t))
712 return;
714 t->rearm(t);
717 /* TODO: MIN_TIMER_REARM_US should be optimized */
718 #define MIN_TIMER_REARM_US 250
720 static struct qemu_alarm_timer *alarm_timer;
722 #ifdef _WIN32
724 struct qemu_alarm_win32 {
725 MMRESULT timerId;
726 unsigned int period;
727 } alarm_win32_data = {0, -1};
729 static int win32_start_timer(struct qemu_alarm_timer *t);
730 static void win32_stop_timer(struct qemu_alarm_timer *t);
731 static void win32_rearm_timer(struct qemu_alarm_timer *t);
733 #else
735 static int unix_start_timer(struct qemu_alarm_timer *t);
736 static void unix_stop_timer(struct qemu_alarm_timer *t);
738 #ifdef __linux__
740 static int dynticks_start_timer(struct qemu_alarm_timer *t);
741 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
742 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
744 static int hpet_start_timer(struct qemu_alarm_timer *t);
745 static void hpet_stop_timer(struct qemu_alarm_timer *t);
747 static int rtc_start_timer(struct qemu_alarm_timer *t);
748 static void rtc_stop_timer(struct qemu_alarm_timer *t);
750 #endif /* __linux__ */
752 #endif /* _WIN32 */
754 /* Correlation between real and virtual time is always going to be
755 fairly approximate, so ignore small variation.
756 When the guest is idle real and virtual time will be aligned in
757 the IO wait loop. */
758 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
760 static void icount_adjust(void)
762 int64_t cur_time;
763 int64_t cur_icount;
764 int64_t delta;
765 static int64_t last_delta;
766 /* If the VM is not running, then do nothing. */
767 if (!vm_running)
768 return;
770 cur_time = cpu_get_clock();
771 cur_icount = qemu_get_clock(vm_clock);
772 delta = cur_icount - cur_time;
773 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
774 if (delta > 0
775 && last_delta + ICOUNT_WOBBLE < delta * 2
776 && icount_time_shift > 0) {
777 /* The guest is getting too far ahead. Slow time down. */
778 icount_time_shift--;
780 if (delta < 0
781 && last_delta - ICOUNT_WOBBLE > delta * 2
782 && icount_time_shift < MAX_ICOUNT_SHIFT) {
783 /* The guest is getting too far behind. Speed time up. */
784 icount_time_shift++;
786 last_delta = delta;
787 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
790 static void icount_adjust_rt(void * opaque)
792 qemu_mod_timer(icount_rt_timer,
793 qemu_get_clock(rt_clock) + 1000);
794 icount_adjust();
797 static void icount_adjust_vm(void * opaque)
799 qemu_mod_timer(icount_vm_timer,
800 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
801 icount_adjust();
804 static void init_icount_adjust(void)
806 /* Have both realtime and virtual time triggers for speed adjustment.
807 The realtime trigger catches emulated time passing too slowly,
808 the virtual time trigger catches emulated time passing too fast.
809 Realtime triggers occur even when idle, so use them less frequently
810 than VM triggers. */
811 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
812 qemu_mod_timer(icount_rt_timer,
813 qemu_get_clock(rt_clock) + 1000);
814 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
815 qemu_mod_timer(icount_vm_timer,
816 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
819 static struct qemu_alarm_timer alarm_timers[] = {
820 #ifndef _WIN32
821 #ifdef __linux__
822 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
823 dynticks_stop_timer, dynticks_rearm_timer, NULL},
824 /* HPET - if available - is preferred */
825 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
826 /* ...otherwise try RTC */
827 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
828 #endif
829 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
830 #else
831 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
832 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
833 {"win32", 0, win32_start_timer,
834 win32_stop_timer, NULL, &alarm_win32_data},
835 #endif
836 {NULL, }
839 static void show_available_alarms(void)
841 int i;
843 printf("Available alarm timers, in order of precedence:\n");
844 for (i = 0; alarm_timers[i].name; i++)
845 printf("%s\n", alarm_timers[i].name);
848 static void configure_alarms(char const *opt)
850 int i;
851 int cur = 0;
852 int count = ARRAY_SIZE(alarm_timers) - 1;
853 char *arg;
854 char *name;
855 struct qemu_alarm_timer tmp;
857 if (!strcmp(opt, "?")) {
858 show_available_alarms();
859 exit(0);
862 arg = strdup(opt);
864 /* Reorder the array */
865 name = strtok(arg, ",");
866 while (name) {
867 for (i = 0; i < count && alarm_timers[i].name; i++) {
868 if (!strcmp(alarm_timers[i].name, name))
869 break;
872 if (i == count) {
873 fprintf(stderr, "Unknown clock %s\n", name);
874 goto next;
877 if (i < cur)
878 /* Ignore */
879 goto next;
881 /* Swap */
882 tmp = alarm_timers[i];
883 alarm_timers[i] = alarm_timers[cur];
884 alarm_timers[cur] = tmp;
886 cur++;
887 next:
888 name = strtok(NULL, ",");
891 free(arg);
893 if (cur) {
894 /* Disable remaining timers */
895 for (i = cur; i < count; i++)
896 alarm_timers[i].name = NULL;
897 } else {
898 show_available_alarms();
899 exit(1);
903 QEMUClock *rt_clock;
904 QEMUClock *vm_clock;
906 static QEMUTimer *active_timers[2];
908 static QEMUClock *qemu_new_clock(int type)
910 QEMUClock *clock;
911 clock = qemu_mallocz(sizeof(QEMUClock));
912 clock->type = type;
913 return clock;
916 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
918 QEMUTimer *ts;
920 ts = qemu_mallocz(sizeof(QEMUTimer));
921 ts->clock = clock;
922 ts->cb = cb;
923 ts->opaque = opaque;
924 return ts;
927 void qemu_free_timer(QEMUTimer *ts)
929 qemu_free(ts);
932 /* stop a timer, but do not dealloc it */
933 void qemu_del_timer(QEMUTimer *ts)
935 QEMUTimer **pt, *t;
937 /* NOTE: this code must be signal safe because
938 qemu_timer_expired() can be called from a signal. */
939 pt = &active_timers[ts->clock->type];
940 for(;;) {
941 t = *pt;
942 if (!t)
943 break;
944 if (t == ts) {
945 *pt = t->next;
946 break;
948 pt = &t->next;
952 /* modify the current timer so that it will be fired when current_time
953 >= expire_time. The corresponding callback will be called. */
954 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
956 QEMUTimer **pt, *t;
958 qemu_del_timer(ts);
960 /* add the timer in the sorted list */
961 /* NOTE: this code must be signal safe because
962 qemu_timer_expired() can be called from a signal. */
963 pt = &active_timers[ts->clock->type];
964 for(;;) {
965 t = *pt;
966 if (!t)
967 break;
968 if (t->expire_time > expire_time)
969 break;
970 pt = &t->next;
972 ts->expire_time = expire_time;
973 ts->next = *pt;
974 *pt = ts;
976 /* Rearm if necessary */
977 if (pt == &active_timers[ts->clock->type]) {
978 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
979 qemu_rearm_alarm_timer(alarm_timer);
981 /* Interrupt execution to force deadline recalculation. */
982 if (use_icount)
983 qemu_notify_event();
987 int qemu_timer_pending(QEMUTimer *ts)
989 QEMUTimer *t;
990 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
991 if (t == ts)
992 return 1;
994 return 0;
997 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
999 if (!timer_head)
1000 return 0;
1001 return (timer_head->expire_time <= current_time);
1004 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1006 QEMUTimer *ts;
1008 for(;;) {
1009 ts = *ptimer_head;
1010 if (!ts || ts->expire_time > current_time)
1011 break;
1012 /* remove timer from the list before calling the callback */
1013 *ptimer_head = ts->next;
1014 ts->next = NULL;
1016 /* run the callback (the timer list can be modified) */
1017 ts->cb(ts->opaque);
1021 int64_t qemu_get_clock(QEMUClock *clock)
1023 switch(clock->type) {
1024 case QEMU_TIMER_REALTIME:
1025 return get_clock() / 1000000;
1026 default:
1027 case QEMU_TIMER_VIRTUAL:
1028 if (use_icount) {
1029 return cpu_get_icount();
1030 } else {
1031 return cpu_get_clock();
1036 static void init_timers(void)
1038 init_get_clock();
1039 ticks_per_sec = QEMU_TIMER_BASE;
1040 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1041 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1044 /* save a timer */
1045 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1047 uint64_t expire_time;
1049 if (qemu_timer_pending(ts)) {
1050 expire_time = ts->expire_time;
1051 } else {
1052 expire_time = -1;
1054 qemu_put_be64(f, expire_time);
1057 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1059 uint64_t expire_time;
1061 expire_time = qemu_get_be64(f);
1062 if (expire_time != -1) {
1063 qemu_mod_timer(ts, expire_time);
1064 } else {
1065 qemu_del_timer(ts);
1069 static void timer_save(QEMUFile *f, void *opaque)
1071 if (cpu_ticks_enabled) {
1072 hw_error("cannot save state if virtual timers are running");
1074 qemu_put_be64(f, cpu_ticks_offset);
1075 qemu_put_be64(f, ticks_per_sec);
1076 qemu_put_be64(f, cpu_clock_offset);
1079 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1081 if (version_id != 1 && version_id != 2)
1082 return -EINVAL;
1083 if (cpu_ticks_enabled) {
1084 return -EINVAL;
1086 cpu_ticks_offset=qemu_get_be64(f);
1087 ticks_per_sec=qemu_get_be64(f);
1088 if (version_id == 2) {
1089 cpu_clock_offset=qemu_get_be64(f);
1091 return 0;
1094 static void qemu_event_increment(void);
1096 #ifdef _WIN32
1097 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1098 DWORD_PTR dwUser, DWORD_PTR dw1,
1099 DWORD_PTR dw2)
1100 #else
1101 static void host_alarm_handler(int host_signum)
1102 #endif
1104 #if 0
1105 #define DISP_FREQ 1000
1107 static int64_t delta_min = INT64_MAX;
1108 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1109 static int count;
1110 ti = qemu_get_clock(vm_clock);
1111 if (last_clock != 0) {
1112 delta = ti - last_clock;
1113 if (delta < delta_min)
1114 delta_min = delta;
1115 if (delta > delta_max)
1116 delta_max = delta;
1117 delta_cum += delta;
1118 if (++count == DISP_FREQ) {
1119 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1120 muldiv64(delta_min, 1000000, ticks_per_sec),
1121 muldiv64(delta_max, 1000000, ticks_per_sec),
1122 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1123 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1124 count = 0;
1125 delta_min = INT64_MAX;
1126 delta_max = 0;
1127 delta_cum = 0;
1130 last_clock = ti;
1132 #endif
1133 if (alarm_has_dynticks(alarm_timer) ||
1134 (!use_icount &&
1135 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1136 qemu_get_clock(vm_clock))) ||
1137 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1138 qemu_get_clock(rt_clock))) {
1139 qemu_event_increment();
1140 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1142 #ifndef CONFIG_IOTHREAD
1143 if (next_cpu) {
1144 /* stop the currently executing cpu because a timer occured */
1145 cpu_exit(next_cpu);
1146 #ifdef CONFIG_KQEMU
1147 if (next_cpu->kqemu_enabled) {
1148 kqemu_cpu_interrupt(next_cpu);
1150 #endif
1152 #endif
1153 timer_alarm_pending = 1;
1154 qemu_notify_event();
1158 static int64_t qemu_next_deadline(void)
1160 int64_t delta;
1162 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1163 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1164 qemu_get_clock(vm_clock);
1165 } else {
1166 /* To avoid problems with overflow limit this to 2^32. */
1167 delta = INT32_MAX;
1170 if (delta < 0)
1171 delta = 0;
1173 return delta;
1176 #if defined(__linux__) || defined(_WIN32)
1177 static uint64_t qemu_next_deadline_dyntick(void)
1179 int64_t delta;
1180 int64_t rtdelta;
1182 if (use_icount)
1183 delta = INT32_MAX;
1184 else
1185 delta = (qemu_next_deadline() + 999) / 1000;
1187 if (active_timers[QEMU_TIMER_REALTIME]) {
1188 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1189 qemu_get_clock(rt_clock))*1000;
1190 if (rtdelta < delta)
1191 delta = rtdelta;
1194 if (delta < MIN_TIMER_REARM_US)
1195 delta = MIN_TIMER_REARM_US;
1197 return delta;
1199 #endif
1201 #ifndef _WIN32
1203 /* Sets a specific flag */
1204 static int fcntl_setfl(int fd, int flag)
1206 int flags;
1208 flags = fcntl(fd, F_GETFL);
1209 if (flags == -1)
1210 return -errno;
1212 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1213 return -errno;
1215 return 0;
1218 #if defined(__linux__)
1220 #define RTC_FREQ 1024
1222 static void enable_sigio_timer(int fd)
1224 struct sigaction act;
1226 /* timer signal */
1227 sigfillset(&act.sa_mask);
1228 act.sa_flags = 0;
1229 act.sa_handler = host_alarm_handler;
1231 sigaction(SIGIO, &act, NULL);
1232 fcntl_setfl(fd, O_ASYNC);
1233 fcntl(fd, F_SETOWN, getpid());
1236 static int hpet_start_timer(struct qemu_alarm_timer *t)
1238 struct hpet_info info;
1239 int r, fd;
1241 fd = open("/dev/hpet", O_RDONLY);
1242 if (fd < 0)
1243 return -1;
1245 /* Set frequency */
1246 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1247 if (r < 0) {
1248 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1249 "error, but for better emulation accuracy type:\n"
1250 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1251 goto fail;
1254 /* Check capabilities */
1255 r = ioctl(fd, HPET_INFO, &info);
1256 if (r < 0)
1257 goto fail;
1259 /* Enable periodic mode */
1260 r = ioctl(fd, HPET_EPI, 0);
1261 if (info.hi_flags && (r < 0))
1262 goto fail;
1264 /* Enable interrupt */
1265 r = ioctl(fd, HPET_IE_ON, 0);
1266 if (r < 0)
1267 goto fail;
1269 enable_sigio_timer(fd);
1270 t->priv = (void *)(long)fd;
1272 return 0;
1273 fail:
1274 close(fd);
1275 return -1;
1278 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1280 int fd = (long)t->priv;
1282 close(fd);
1285 static int rtc_start_timer(struct qemu_alarm_timer *t)
1287 int rtc_fd;
1288 unsigned long current_rtc_freq = 0;
1290 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1291 if (rtc_fd < 0)
1292 return -1;
1293 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1294 if (current_rtc_freq != RTC_FREQ &&
1295 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1296 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1297 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1298 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1299 goto fail;
1301 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1302 fail:
1303 close(rtc_fd);
1304 return -1;
1307 enable_sigio_timer(rtc_fd);
1309 t->priv = (void *)(long)rtc_fd;
1311 return 0;
1314 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1316 int rtc_fd = (long)t->priv;
1318 close(rtc_fd);
1321 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1323 struct sigevent ev;
1324 timer_t host_timer;
1325 struct sigaction act;
1327 sigfillset(&act.sa_mask);
1328 act.sa_flags = 0;
1329 act.sa_handler = host_alarm_handler;
1331 sigaction(SIGALRM, &act, NULL);
1334 * Initialize ev struct to 0 to avoid valgrind complaining
1335 * about uninitialized data in timer_create call
1337 memset(&ev, 0, sizeof(ev));
1338 ev.sigev_value.sival_int = 0;
1339 ev.sigev_notify = SIGEV_SIGNAL;
1340 ev.sigev_signo = SIGALRM;
1342 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1343 perror("timer_create");
1345 /* disable dynticks */
1346 fprintf(stderr, "Dynamic Ticks disabled\n");
1348 return -1;
1351 t->priv = (void *)(long)host_timer;
1353 return 0;
1356 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1358 timer_t host_timer = (timer_t)(long)t->priv;
1360 timer_delete(host_timer);
1363 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1365 timer_t host_timer = (timer_t)(long)t->priv;
1366 struct itimerspec timeout;
1367 int64_t nearest_delta_us = INT64_MAX;
1368 int64_t current_us;
1370 if (!active_timers[QEMU_TIMER_REALTIME] &&
1371 !active_timers[QEMU_TIMER_VIRTUAL])
1372 return;
1374 nearest_delta_us = qemu_next_deadline_dyntick();
1376 /* check whether a timer is already running */
1377 if (timer_gettime(host_timer, &timeout)) {
1378 perror("gettime");
1379 fprintf(stderr, "Internal timer error: aborting\n");
1380 exit(1);
1382 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1383 if (current_us && current_us <= nearest_delta_us)
1384 return;
1386 timeout.it_interval.tv_sec = 0;
1387 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1388 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1389 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1390 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1391 perror("settime");
1392 fprintf(stderr, "Internal timer error: aborting\n");
1393 exit(1);
1397 #endif /* defined(__linux__) */
1399 static int unix_start_timer(struct qemu_alarm_timer *t)
1401 struct sigaction act;
1402 struct itimerval itv;
1403 int err;
1405 /* timer signal */
1406 sigfillset(&act.sa_mask);
1407 act.sa_flags = 0;
1408 act.sa_handler = host_alarm_handler;
1410 sigaction(SIGALRM, &act, NULL);
1412 itv.it_interval.tv_sec = 0;
1413 /* for i386 kernel 2.6 to get 1 ms */
1414 itv.it_interval.tv_usec = 999;
1415 itv.it_value.tv_sec = 0;
1416 itv.it_value.tv_usec = 10 * 1000;
1418 err = setitimer(ITIMER_REAL, &itv, NULL);
1419 if (err)
1420 return -1;
1422 return 0;
1425 static void unix_stop_timer(struct qemu_alarm_timer *t)
1427 struct itimerval itv;
1429 memset(&itv, 0, sizeof(itv));
1430 setitimer(ITIMER_REAL, &itv, NULL);
1433 #endif /* !defined(_WIN32) */
1436 #ifdef _WIN32
1438 static int win32_start_timer(struct qemu_alarm_timer *t)
1440 TIMECAPS tc;
1441 struct qemu_alarm_win32 *data = t->priv;
1442 UINT flags;
1444 memset(&tc, 0, sizeof(tc));
1445 timeGetDevCaps(&tc, sizeof(tc));
1447 if (data->period < tc.wPeriodMin)
1448 data->period = tc.wPeriodMin;
1450 timeBeginPeriod(data->period);
1452 flags = TIME_CALLBACK_FUNCTION;
1453 if (alarm_has_dynticks(t))
1454 flags |= TIME_ONESHOT;
1455 else
1456 flags |= TIME_PERIODIC;
1458 data->timerId = timeSetEvent(1, // interval (ms)
1459 data->period, // resolution
1460 host_alarm_handler, // function
1461 (DWORD)t, // parameter
1462 flags);
1464 if (!data->timerId) {
1465 perror("Failed to initialize win32 alarm timer");
1466 timeEndPeriod(data->period);
1467 return -1;
1470 return 0;
1473 static void win32_stop_timer(struct qemu_alarm_timer *t)
1475 struct qemu_alarm_win32 *data = t->priv;
1477 timeKillEvent(data->timerId);
1478 timeEndPeriod(data->period);
1481 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1483 struct qemu_alarm_win32 *data = t->priv;
1484 uint64_t nearest_delta_us;
1486 if (!active_timers[QEMU_TIMER_REALTIME] &&
1487 !active_timers[QEMU_TIMER_VIRTUAL])
1488 return;
1490 nearest_delta_us = qemu_next_deadline_dyntick();
1491 nearest_delta_us /= 1000;
1493 timeKillEvent(data->timerId);
1495 data->timerId = timeSetEvent(1,
1496 data->period,
1497 host_alarm_handler,
1498 (DWORD)t,
1499 TIME_ONESHOT | TIME_PERIODIC);
1501 if (!data->timerId) {
1502 perror("Failed to re-arm win32 alarm timer");
1504 timeEndPeriod(data->period);
1505 exit(1);
1509 #endif /* _WIN32 */
1511 static int init_timer_alarm(void)
1513 struct qemu_alarm_timer *t = NULL;
1514 int i, err = -1;
1516 for (i = 0; alarm_timers[i].name; i++) {
1517 t = &alarm_timers[i];
1519 err = t->start(t);
1520 if (!err)
1521 break;
1524 if (err) {
1525 err = -ENOENT;
1526 goto fail;
1529 alarm_timer = t;
1531 return 0;
1533 fail:
1534 return err;
1537 static void quit_timers(void)
1539 alarm_timer->stop(alarm_timer);
1540 alarm_timer = NULL;
1543 /***********************************************************/
1544 /* host time/date access */
1545 void qemu_get_timedate(struct tm *tm, int offset)
1547 time_t ti;
1548 struct tm *ret;
1550 time(&ti);
1551 ti += offset;
1552 if (rtc_date_offset == -1) {
1553 if (rtc_utc)
1554 ret = gmtime(&ti);
1555 else
1556 ret = localtime(&ti);
1557 } else {
1558 ti -= rtc_date_offset;
1559 ret = gmtime(&ti);
1562 memcpy(tm, ret, sizeof(struct tm));
1565 int qemu_timedate_diff(struct tm *tm)
1567 time_t seconds;
1569 if (rtc_date_offset == -1)
1570 if (rtc_utc)
1571 seconds = mktimegm(tm);
1572 else
1573 seconds = mktime(tm);
1574 else
1575 seconds = mktimegm(tm) + rtc_date_offset;
1577 return seconds - time(NULL);
1580 #ifdef _WIN32
1581 static void socket_cleanup(void)
1583 WSACleanup();
1586 static int socket_init(void)
1588 WSADATA Data;
1589 int ret, err;
1591 ret = WSAStartup(MAKEWORD(2,2), &Data);
1592 if (ret != 0) {
1593 err = WSAGetLastError();
1594 fprintf(stderr, "WSAStartup: %d\n", err);
1595 return -1;
1597 atexit(socket_cleanup);
1598 return 0;
1600 #endif
1602 /***********************************************************/
1603 /* Bluetooth support */
1604 static int nb_hcis;
1605 static int cur_hci;
1606 static struct HCIInfo *hci_table[MAX_NICS];
1608 static struct bt_vlan_s {
1609 struct bt_scatternet_s net;
1610 int id;
1611 struct bt_vlan_s *next;
1612 } *first_bt_vlan;
1614 /* find or alloc a new bluetooth "VLAN" */
1615 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1617 struct bt_vlan_s **pvlan, *vlan;
1618 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1619 if (vlan->id == id)
1620 return &vlan->net;
1622 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1623 vlan->id = id;
1624 pvlan = &first_bt_vlan;
1625 while (*pvlan != NULL)
1626 pvlan = &(*pvlan)->next;
1627 *pvlan = vlan;
1628 return &vlan->net;
1631 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1635 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1637 return -ENOTSUP;
1640 static struct HCIInfo null_hci = {
1641 .cmd_send = null_hci_send,
1642 .sco_send = null_hci_send,
1643 .acl_send = null_hci_send,
1644 .bdaddr_set = null_hci_addr_set,
1647 struct HCIInfo *qemu_next_hci(void)
1649 if (cur_hci == nb_hcis)
1650 return &null_hci;
1652 return hci_table[cur_hci++];
1655 static struct HCIInfo *hci_init(const char *str)
1657 char *endp;
1658 struct bt_scatternet_s *vlan = 0;
1660 if (!strcmp(str, "null"))
1661 /* null */
1662 return &null_hci;
1663 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1664 /* host[:hciN] */
1665 return bt_host_hci(str[4] ? str + 5 : "hci0");
1666 else if (!strncmp(str, "hci", 3)) {
1667 /* hci[,vlan=n] */
1668 if (str[3]) {
1669 if (!strncmp(str + 3, ",vlan=", 6)) {
1670 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1671 if (*endp)
1672 vlan = 0;
1674 } else
1675 vlan = qemu_find_bt_vlan(0);
1676 if (vlan)
1677 return bt_new_hci(vlan);
1680 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1682 return 0;
1685 static int bt_hci_parse(const char *str)
1687 struct HCIInfo *hci;
1688 bdaddr_t bdaddr;
1690 if (nb_hcis >= MAX_NICS) {
1691 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1692 return -1;
1695 hci = hci_init(str);
1696 if (!hci)
1697 return -1;
1699 bdaddr.b[0] = 0x52;
1700 bdaddr.b[1] = 0x54;
1701 bdaddr.b[2] = 0x00;
1702 bdaddr.b[3] = 0x12;
1703 bdaddr.b[4] = 0x34;
1704 bdaddr.b[5] = 0x56 + nb_hcis;
1705 hci->bdaddr_set(hci, bdaddr.b);
1707 hci_table[nb_hcis++] = hci;
1709 return 0;
1712 static void bt_vhci_add(int vlan_id)
1714 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1716 if (!vlan->slave)
1717 fprintf(stderr, "qemu: warning: adding a VHCI to "
1718 "an empty scatternet %i\n", vlan_id);
1720 bt_vhci_init(bt_new_hci(vlan));
1723 static struct bt_device_s *bt_device_add(const char *opt)
1725 struct bt_scatternet_s *vlan;
1726 int vlan_id = 0;
1727 char *endp = strstr(opt, ",vlan=");
1728 int len = (endp ? endp - opt : strlen(opt)) + 1;
1729 char devname[10];
1731 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1733 if (endp) {
1734 vlan_id = strtol(endp + 6, &endp, 0);
1735 if (*endp) {
1736 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1737 return 0;
1741 vlan = qemu_find_bt_vlan(vlan_id);
1743 if (!vlan->slave)
1744 fprintf(stderr, "qemu: warning: adding a slave device to "
1745 "an empty scatternet %i\n", vlan_id);
1747 if (!strcmp(devname, "keyboard"))
1748 return bt_keyboard_init(vlan);
1750 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1751 return 0;
1754 static int bt_parse(const char *opt)
1756 const char *endp, *p;
1757 int vlan;
1759 if (strstart(opt, "hci", &endp)) {
1760 if (!*endp || *endp == ',') {
1761 if (*endp)
1762 if (!strstart(endp, ",vlan=", 0))
1763 opt = endp + 1;
1765 return bt_hci_parse(opt);
1767 } else if (strstart(opt, "vhci", &endp)) {
1768 if (!*endp || *endp == ',') {
1769 if (*endp) {
1770 if (strstart(endp, ",vlan=", &p)) {
1771 vlan = strtol(p, (char **) &endp, 0);
1772 if (*endp) {
1773 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1774 return 1;
1776 } else {
1777 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1778 return 1;
1780 } else
1781 vlan = 0;
1783 bt_vhci_add(vlan);
1784 return 0;
1786 } else if (strstart(opt, "device:", &endp))
1787 return !bt_device_add(endp);
1789 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1790 return 1;
1793 /***********************************************************/
1794 /* QEMU Block devices */
1796 #define HD_ALIAS "index=%d,media=disk"
1797 #define CDROM_ALIAS "index=2,media=cdrom"
1798 #define FD_ALIAS "index=%d,if=floppy"
1799 #define PFLASH_ALIAS "if=pflash"
1800 #define MTD_ALIAS "if=mtd"
1801 #define SD_ALIAS "index=0,if=sd"
1803 DriveOpt *drive_add(const char *file, const char *fmt, ...)
1805 va_list ap;
1806 DriveOpt *dopt;
1808 dopt = qemu_mallocz(sizeof(*dopt));
1810 dopt->file = file;
1811 va_start(ap, fmt);
1812 vsnprintf(dopt->opt,
1813 sizeof(dopt->opt), fmt, ap);
1814 va_end(ap);
1816 TAILQ_INSERT_TAIL(&driveopts, dopt, next);
1817 return dopt;
1820 void drive_remove(DriveOpt *dopt)
1822 TAILQ_REMOVE(&driveopts, dopt, next);
1823 qemu_free(dopt);
1826 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1828 DriveInfo *dinfo;
1830 /* seek interface, bus and unit */
1832 TAILQ_FOREACH(dinfo, &drives, next) {
1833 if (dinfo->type == type &&
1834 dinfo->bus == bus &&
1835 dinfo->unit == unit)
1836 return dinfo;
1839 return NULL;
1842 DriveInfo *drive_get_by_id(char *id)
1844 DriveInfo *dinfo;
1846 TAILQ_FOREACH(dinfo, &drives, next) {
1847 if (strcmp(id, dinfo->id))
1848 continue;
1849 return dinfo;
1851 return NULL;
1854 int drive_get_max_bus(BlockInterfaceType type)
1856 int max_bus;
1857 DriveInfo *dinfo;
1859 max_bus = -1;
1860 TAILQ_FOREACH(dinfo, &drives, next) {
1861 if(dinfo->type == type &&
1862 dinfo->bus > max_bus)
1863 max_bus = dinfo->bus;
1865 return max_bus;
1868 const char *drive_get_serial(BlockDriverState *bdrv)
1870 DriveInfo *dinfo;
1872 TAILQ_FOREACH(dinfo, &drives, next) {
1873 if (dinfo->bdrv == bdrv)
1874 return dinfo->serial;
1877 return "\0";
1880 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1882 DriveInfo *dinfo;
1884 TAILQ_FOREACH(dinfo, &drives, next) {
1885 if (dinfo->bdrv == bdrv)
1886 return dinfo->onerror;
1889 return BLOCK_ERR_STOP_ENOSPC;
1892 static void bdrv_format_print(void *opaque, const char *name)
1894 fprintf(stderr, " %s", name);
1897 void drive_uninit(BlockDriverState *bdrv)
1899 DriveInfo *dinfo;
1901 TAILQ_FOREACH(dinfo, &drives, next) {
1902 if (dinfo->bdrv != bdrv)
1903 continue;
1904 drive_remove(dinfo->opt);
1905 TAILQ_REMOVE(&drives, dinfo, next);
1906 qemu_free(dinfo);
1907 break;
1911 DriveInfo *drive_init(DriveOpt *arg, int snapshot, void *opaque,
1912 int *fatal_error)
1914 char buf[128];
1915 char file[1024];
1916 char devname[128];
1917 char serial[21];
1918 const char *mediastr = "";
1919 BlockInterfaceType type;
1920 enum { MEDIA_DISK, MEDIA_CDROM } media;
1921 int bus_id, unit_id;
1922 int cyls, heads, secs, translation;
1923 BlockDriver *drv = NULL;
1924 QEMUMachine *machine = opaque;
1925 int max_devs;
1926 int index;
1927 int cache;
1928 int bdrv_flags, onerror;
1929 const char *devaddr;
1930 DriveInfo *dinfo;
1931 char *str = arg->opt;
1932 static const char * const params[] = { "bus", "unit", "if", "index",
1933 "cyls", "heads", "secs", "trans",
1934 "media", "snapshot", "file",
1935 "cache", "format", "serial",
1936 "werror", "addr", "id",
1937 NULL };
1938 *fatal_error = 1;
1940 if (check_params(buf, sizeof(buf), params, str) < 0) {
1941 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
1942 buf, str);
1943 return NULL;
1946 file[0] = 0;
1947 cyls = heads = secs = 0;
1948 bus_id = 0;
1949 unit_id = -1;
1950 translation = BIOS_ATA_TRANSLATION_AUTO;
1951 index = -1;
1952 cache = 1;
1954 if (machine->use_scsi) {
1955 type = IF_SCSI;
1956 max_devs = MAX_SCSI_DEVS;
1957 pstrcpy(devname, sizeof(devname), "scsi");
1958 } else {
1959 type = IF_IDE;
1960 max_devs = MAX_IDE_DEVS;
1961 pstrcpy(devname, sizeof(devname), "ide");
1963 media = MEDIA_DISK;
1965 /* extract parameters */
1967 if (get_param_value(buf, sizeof(buf), "bus", str)) {
1968 bus_id = strtol(buf, NULL, 0);
1969 if (bus_id < 0) {
1970 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
1971 return NULL;
1975 if (get_param_value(buf, sizeof(buf), "unit", str)) {
1976 unit_id = strtol(buf, NULL, 0);
1977 if (unit_id < 0) {
1978 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
1979 return NULL;
1983 if (get_param_value(buf, sizeof(buf), "if", str)) {
1984 pstrcpy(devname, sizeof(devname), buf);
1985 if (!strcmp(buf, "ide")) {
1986 type = IF_IDE;
1987 max_devs = MAX_IDE_DEVS;
1988 } else if (!strcmp(buf, "scsi")) {
1989 type = IF_SCSI;
1990 max_devs = MAX_SCSI_DEVS;
1991 } else if (!strcmp(buf, "floppy")) {
1992 type = IF_FLOPPY;
1993 max_devs = 0;
1994 } else if (!strcmp(buf, "pflash")) {
1995 type = IF_PFLASH;
1996 max_devs = 0;
1997 } else if (!strcmp(buf, "mtd")) {
1998 type = IF_MTD;
1999 max_devs = 0;
2000 } else if (!strcmp(buf, "sd")) {
2001 type = IF_SD;
2002 max_devs = 0;
2003 } else if (!strcmp(buf, "virtio")) {
2004 type = IF_VIRTIO;
2005 max_devs = 0;
2006 } else if (!strcmp(buf, "xen")) {
2007 type = IF_XEN;
2008 max_devs = 0;
2009 } else {
2010 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2011 return NULL;
2015 if (get_param_value(buf, sizeof(buf), "index", str)) {
2016 index = strtol(buf, NULL, 0);
2017 if (index < 0) {
2018 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2019 return NULL;
2023 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2024 cyls = strtol(buf, NULL, 0);
2027 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2028 heads = strtol(buf, NULL, 0);
2031 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2032 secs = strtol(buf, NULL, 0);
2035 if (cyls || heads || secs) {
2036 if (cyls < 1 || cyls > 16383) {
2037 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2038 return NULL;
2040 if (heads < 1 || heads > 16) {
2041 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2042 return NULL;
2044 if (secs < 1 || secs > 63) {
2045 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2046 return NULL;
2050 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2051 if (!cyls) {
2052 fprintf(stderr,
2053 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2054 str);
2055 return NULL;
2057 if (!strcmp(buf, "none"))
2058 translation = BIOS_ATA_TRANSLATION_NONE;
2059 else if (!strcmp(buf, "lba"))
2060 translation = BIOS_ATA_TRANSLATION_LBA;
2061 else if (!strcmp(buf, "auto"))
2062 translation = BIOS_ATA_TRANSLATION_AUTO;
2063 else {
2064 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2065 return NULL;
2069 if (get_param_value(buf, sizeof(buf), "media", str)) {
2070 if (!strcmp(buf, "disk")) {
2071 media = MEDIA_DISK;
2072 } else if (!strcmp(buf, "cdrom")) {
2073 if (cyls || secs || heads) {
2074 fprintf(stderr,
2075 "qemu: '%s' invalid physical CHS format\n", str);
2076 return NULL;
2078 media = MEDIA_CDROM;
2079 } else {
2080 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2081 return NULL;
2085 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2086 if (!strcmp(buf, "on"))
2087 snapshot = 1;
2088 else if (!strcmp(buf, "off"))
2089 snapshot = 0;
2090 else {
2091 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2092 return NULL;
2096 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2097 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2098 cache = 0;
2099 else if (!strcmp(buf, "writethrough"))
2100 cache = 1;
2101 else if (!strcmp(buf, "writeback"))
2102 cache = 2;
2103 else {
2104 fprintf(stderr, "qemu: invalid cache option\n");
2105 return NULL;
2109 if (get_param_value(buf, sizeof(buf), "format", str)) {
2110 if (strcmp(buf, "?") == 0) {
2111 fprintf(stderr, "qemu: Supported formats:");
2112 bdrv_iterate_format(bdrv_format_print, NULL);
2113 fprintf(stderr, "\n");
2114 return NULL;
2116 drv = bdrv_find_format(buf);
2117 if (!drv) {
2118 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2119 return NULL;
2123 if (arg->file == NULL)
2124 get_param_value(file, sizeof(file), "file", str);
2125 else
2126 pstrcpy(file, sizeof(file), arg->file);
2128 if (!get_param_value(serial, sizeof(serial), "serial", str))
2129 memset(serial, 0, sizeof(serial));
2131 onerror = BLOCK_ERR_STOP_ENOSPC;
2132 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2133 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2134 fprintf(stderr, "werror is no supported by this format\n");
2135 return NULL;
2137 if (!strcmp(buf, "ignore"))
2138 onerror = BLOCK_ERR_IGNORE;
2139 else if (!strcmp(buf, "enospc"))
2140 onerror = BLOCK_ERR_STOP_ENOSPC;
2141 else if (!strcmp(buf, "stop"))
2142 onerror = BLOCK_ERR_STOP_ANY;
2143 else if (!strcmp(buf, "report"))
2144 onerror = BLOCK_ERR_REPORT;
2145 else {
2146 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2147 return NULL;
2151 devaddr = NULL;
2152 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2153 if (type != IF_VIRTIO) {
2154 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2155 return NULL;
2157 devaddr = strdup(buf);
2160 /* compute bus and unit according index */
2162 if (index != -1) {
2163 if (bus_id != 0 || unit_id != -1) {
2164 fprintf(stderr,
2165 "qemu: '%s' index cannot be used with bus and unit\n", str);
2166 return NULL;
2168 if (max_devs == 0)
2170 unit_id = index;
2171 bus_id = 0;
2172 } else {
2173 unit_id = index % max_devs;
2174 bus_id = index / max_devs;
2178 /* if user doesn't specify a unit_id,
2179 * try to find the first free
2182 if (unit_id == -1) {
2183 unit_id = 0;
2184 while (drive_get(type, bus_id, unit_id) != NULL) {
2185 unit_id++;
2186 if (max_devs && unit_id >= max_devs) {
2187 unit_id -= max_devs;
2188 bus_id++;
2193 /* check unit id */
2195 if (max_devs && unit_id >= max_devs) {
2196 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2197 str, unit_id, max_devs - 1);
2198 return NULL;
2202 * ignore multiple definitions
2205 if (drive_get(type, bus_id, unit_id) != NULL) {
2206 *fatal_error = 0;
2207 return NULL;
2210 /* init */
2212 dinfo = qemu_mallocz(sizeof(*dinfo));
2213 if (!get_param_value(buf, sizeof(buf), "id", str)) {
2214 /* no id supplied -> create one */
2215 if (type == IF_IDE || type == IF_SCSI)
2216 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2217 if (max_devs)
2218 snprintf(buf, sizeof(buf), "%s%i%s%i",
2219 devname, bus_id, mediastr, unit_id);
2220 else
2221 snprintf(buf, sizeof(buf), "%s%s%i",
2222 devname, mediastr, unit_id);
2224 dinfo->id = qemu_strdup(buf);
2225 dinfo->bdrv = bdrv_new(dinfo->id);
2226 dinfo->devaddr = devaddr;
2227 dinfo->type = type;
2228 dinfo->bus = bus_id;
2229 dinfo->unit = unit_id;
2230 dinfo->onerror = onerror;
2231 dinfo->opt = arg;
2232 strncpy(dinfo->serial, serial, sizeof(serial));
2233 TAILQ_INSERT_TAIL(&drives, dinfo, next);
2235 switch(type) {
2236 case IF_IDE:
2237 case IF_SCSI:
2238 case IF_XEN:
2239 switch(media) {
2240 case MEDIA_DISK:
2241 if (cyls != 0) {
2242 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2243 bdrv_set_translation_hint(dinfo->bdrv, translation);
2245 break;
2246 case MEDIA_CDROM:
2247 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2248 break;
2250 break;
2251 case IF_SD:
2252 /* FIXME: This isn't really a floppy, but it's a reasonable
2253 approximation. */
2254 case IF_FLOPPY:
2255 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2256 break;
2257 case IF_PFLASH:
2258 case IF_MTD:
2259 case IF_VIRTIO:
2260 break;
2261 case IF_COUNT:
2262 abort();
2264 if (!file[0]) {
2265 *fatal_error = 0;
2266 return NULL;
2268 bdrv_flags = 0;
2269 if (snapshot) {
2270 bdrv_flags |= BDRV_O_SNAPSHOT;
2271 cache = 2; /* always use write-back with snapshot */
2273 if (cache == 0) /* no caching */
2274 bdrv_flags |= BDRV_O_NOCACHE;
2275 else if (cache == 2) /* write-back */
2276 bdrv_flags |= BDRV_O_CACHE_WB;
2277 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2278 fprintf(stderr, "qemu: could not open disk image %s\n",
2279 file);
2280 return NULL;
2282 if (bdrv_key_required(dinfo->bdrv))
2283 autostart = 0;
2284 *fatal_error = 0;
2285 return dinfo;
2288 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2290 boot_set_handler = func;
2291 boot_set_opaque = opaque;
2294 int qemu_boot_set(const char *boot_devices)
2296 if (!boot_set_handler) {
2297 return -EINVAL;
2299 return boot_set_handler(boot_set_opaque, boot_devices);
2302 static int parse_bootdevices(char *devices)
2304 /* We just do some generic consistency checks */
2305 const char *p;
2306 int bitmap = 0;
2308 for (p = devices; *p != '\0'; p++) {
2309 /* Allowed boot devices are:
2310 * a-b: floppy disk drives
2311 * c-f: IDE disk drives
2312 * g-m: machine implementation dependant drives
2313 * n-p: network devices
2314 * It's up to each machine implementation to check if the given boot
2315 * devices match the actual hardware implementation and firmware
2316 * features.
2318 if (*p < 'a' || *p > 'p') {
2319 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2320 exit(1);
2322 if (bitmap & (1 << (*p - 'a'))) {
2323 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2324 exit(1);
2326 bitmap |= 1 << (*p - 'a');
2328 return bitmap;
2331 static void restore_boot_devices(void *opaque)
2333 char *standard_boot_devices = opaque;
2335 qemu_boot_set(standard_boot_devices);
2337 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2338 qemu_free(standard_boot_devices);
2341 static void numa_add(const char *optarg)
2343 char option[128];
2344 char *endptr;
2345 unsigned long long value, endvalue;
2346 int nodenr;
2348 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2349 if (!strcmp(option, "node")) {
2350 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2351 nodenr = nb_numa_nodes;
2352 } else {
2353 nodenr = strtoull(option, NULL, 10);
2356 if (get_param_value(option, 128, "mem", optarg) == 0) {
2357 node_mem[nodenr] = 0;
2358 } else {
2359 value = strtoull(option, &endptr, 0);
2360 switch (*endptr) {
2361 case 0: case 'M': case 'm':
2362 value <<= 20;
2363 break;
2364 case 'G': case 'g':
2365 value <<= 30;
2366 break;
2368 node_mem[nodenr] = value;
2370 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2371 node_cpumask[nodenr] = 0;
2372 } else {
2373 value = strtoull(option, &endptr, 10);
2374 if (value >= 64) {
2375 value = 63;
2376 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2377 } else {
2378 if (*endptr == '-') {
2379 endvalue = strtoull(endptr+1, &endptr, 10);
2380 if (endvalue >= 63) {
2381 endvalue = 62;
2382 fprintf(stderr,
2383 "only 63 CPUs in NUMA mode supported.\n");
2385 value = (1 << (endvalue + 1)) - (1 << value);
2386 } else {
2387 value = 1 << value;
2390 node_cpumask[nodenr] = value;
2392 nb_numa_nodes++;
2394 return;
2397 /***********************************************************/
2398 /* USB devices */
2400 static USBPort *used_usb_ports;
2401 static USBPort *free_usb_ports;
2403 /* ??? Maybe change this to register a hub to keep track of the topology. */
2404 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2405 usb_attachfn attach)
2407 port->opaque = opaque;
2408 port->index = index;
2409 port->attach = attach;
2410 port->next = free_usb_ports;
2411 free_usb_ports = port;
2414 int usb_device_add_dev(USBDevice *dev)
2416 USBPort *port;
2418 /* Find a USB port to add the device to. */
2419 port = free_usb_ports;
2420 if (!port->next) {
2421 USBDevice *hub;
2423 /* Create a new hub and chain it on. */
2424 free_usb_ports = NULL;
2425 port->next = used_usb_ports;
2426 used_usb_ports = port;
2428 hub = usb_hub_init(VM_USB_HUB_SIZE);
2429 usb_attach(port, hub);
2430 port = free_usb_ports;
2433 free_usb_ports = port->next;
2434 port->next = used_usb_ports;
2435 used_usb_ports = port;
2436 usb_attach(port, dev);
2437 return 0;
2440 static void usb_msd_password_cb(void *opaque, int err)
2442 USBDevice *dev = opaque;
2444 if (!err)
2445 usb_device_add_dev(dev);
2446 else
2447 dev->handle_destroy(dev);
2450 static int usb_device_add(const char *devname, int is_hotplug)
2452 const char *p;
2453 USBDevice *dev;
2455 if (!free_usb_ports)
2456 return -1;
2458 if (strstart(devname, "host:", &p)) {
2459 dev = usb_host_device_open(p);
2460 } else if (!strcmp(devname, "mouse")) {
2461 dev = usb_mouse_init();
2462 } else if (!strcmp(devname, "tablet")) {
2463 dev = usb_tablet_init();
2464 } else if (!strcmp(devname, "keyboard")) {
2465 dev = usb_keyboard_init();
2466 } else if (strstart(devname, "disk:", &p)) {
2467 BlockDriverState *bs;
2469 dev = usb_msd_init(p);
2470 if (!dev)
2471 return -1;
2472 bs = usb_msd_get_bdrv(dev);
2473 if (bdrv_key_required(bs)) {
2474 autostart = 0;
2475 if (is_hotplug) {
2476 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2477 dev);
2478 return 0;
2481 } else if (!strcmp(devname, "wacom-tablet")) {
2482 dev = usb_wacom_init();
2483 } else if (strstart(devname, "serial:", &p)) {
2484 dev = usb_serial_init(p);
2485 #ifdef CONFIG_BRLAPI
2486 } else if (!strcmp(devname, "braille")) {
2487 dev = usb_baum_init();
2488 #endif
2489 } else if (strstart(devname, "net:", &p)) {
2490 int nic = nb_nics;
2492 if (net_client_init(NULL, "nic", p) < 0)
2493 return -1;
2494 nd_table[nic].model = "usb";
2495 dev = usb_net_init(&nd_table[nic]);
2496 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2497 dev = usb_bt_init(devname[2] ? hci_init(p) :
2498 bt_new_hci(qemu_find_bt_vlan(0)));
2499 } else {
2500 return -1;
2502 if (!dev)
2503 return -1;
2505 return usb_device_add_dev(dev);
2508 int usb_device_del_addr(int bus_num, int addr)
2510 USBPort *port;
2511 USBPort **lastp;
2512 USBDevice *dev;
2514 if (!used_usb_ports)
2515 return -1;
2517 if (bus_num != 0)
2518 return -1;
2520 lastp = &used_usb_ports;
2521 port = used_usb_ports;
2522 while (port && port->dev->addr != addr) {
2523 lastp = &port->next;
2524 port = port->next;
2527 if (!port)
2528 return -1;
2530 dev = port->dev;
2531 *lastp = port->next;
2532 usb_attach(port, NULL);
2533 dev->handle_destroy(dev);
2534 port->next = free_usb_ports;
2535 free_usb_ports = port;
2536 return 0;
2539 static int usb_device_del(const char *devname)
2541 int bus_num, addr;
2542 const char *p;
2544 if (strstart(devname, "host:", &p))
2545 return usb_host_device_close(p);
2547 if (!used_usb_ports)
2548 return -1;
2550 p = strchr(devname, '.');
2551 if (!p)
2552 return -1;
2553 bus_num = strtoul(devname, NULL, 0);
2554 addr = strtoul(p + 1, NULL, 0);
2556 return usb_device_del_addr(bus_num, addr);
2559 static int usb_parse(const char *cmdline)
2561 return usb_device_add(cmdline, 0);
2564 void do_usb_add(Monitor *mon, const char *devname)
2566 usb_device_add(devname, 1);
2569 void do_usb_del(Monitor *mon, const char *devname)
2571 usb_device_del(devname);
2574 void usb_info(Monitor *mon)
2576 USBDevice *dev;
2577 USBPort *port;
2578 const char *speed_str;
2580 if (!usb_enabled) {
2581 monitor_printf(mon, "USB support not enabled\n");
2582 return;
2585 for (port = used_usb_ports; port; port = port->next) {
2586 dev = port->dev;
2587 if (!dev)
2588 continue;
2589 switch(dev->speed) {
2590 case USB_SPEED_LOW:
2591 speed_str = "1.5";
2592 break;
2593 case USB_SPEED_FULL:
2594 speed_str = "12";
2595 break;
2596 case USB_SPEED_HIGH:
2597 speed_str = "480";
2598 break;
2599 default:
2600 speed_str = "?";
2601 break;
2603 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2604 0, dev->addr, speed_str, dev->devname);
2608 /***********************************************************/
2609 /* PCMCIA/Cardbus */
2611 static struct pcmcia_socket_entry_s {
2612 PCMCIASocket *socket;
2613 struct pcmcia_socket_entry_s *next;
2614 } *pcmcia_sockets = 0;
2616 void pcmcia_socket_register(PCMCIASocket *socket)
2618 struct pcmcia_socket_entry_s *entry;
2620 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2621 entry->socket = socket;
2622 entry->next = pcmcia_sockets;
2623 pcmcia_sockets = entry;
2626 void pcmcia_socket_unregister(PCMCIASocket *socket)
2628 struct pcmcia_socket_entry_s *entry, **ptr;
2630 ptr = &pcmcia_sockets;
2631 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2632 if (entry->socket == socket) {
2633 *ptr = entry->next;
2634 qemu_free(entry);
2638 void pcmcia_info(Monitor *mon)
2640 struct pcmcia_socket_entry_s *iter;
2642 if (!pcmcia_sockets)
2643 monitor_printf(mon, "No PCMCIA sockets\n");
2645 for (iter = pcmcia_sockets; iter; iter = iter->next)
2646 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2647 iter->socket->attached ? iter->socket->card_string :
2648 "Empty");
2651 /***********************************************************/
2652 /* register display */
2654 struct DisplayAllocator default_allocator = {
2655 defaultallocator_create_displaysurface,
2656 defaultallocator_resize_displaysurface,
2657 defaultallocator_free_displaysurface
2660 void register_displaystate(DisplayState *ds)
2662 DisplayState **s;
2663 s = &display_state;
2664 while (*s != NULL)
2665 s = &(*s)->next;
2666 ds->next = NULL;
2667 *s = ds;
2670 DisplayState *get_displaystate(void)
2672 return display_state;
2675 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2677 if(ds->allocator == &default_allocator) ds->allocator = da;
2678 return ds->allocator;
2681 /* dumb display */
2683 static void dumb_display_init(void)
2685 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2686 ds->allocator = &default_allocator;
2687 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2688 register_displaystate(ds);
2691 /***********************************************************/
2692 /* I/O handling */
2694 typedef struct IOHandlerRecord {
2695 int fd;
2696 IOCanRWHandler *fd_read_poll;
2697 IOHandler *fd_read;
2698 IOHandler *fd_write;
2699 int deleted;
2700 void *opaque;
2701 /* temporary data */
2702 struct pollfd *ufd;
2703 struct IOHandlerRecord *next;
2704 } IOHandlerRecord;
2706 static IOHandlerRecord *first_io_handler;
2708 /* XXX: fd_read_poll should be suppressed, but an API change is
2709 necessary in the character devices to suppress fd_can_read(). */
2710 int qemu_set_fd_handler2(int fd,
2711 IOCanRWHandler *fd_read_poll,
2712 IOHandler *fd_read,
2713 IOHandler *fd_write,
2714 void *opaque)
2716 IOHandlerRecord **pioh, *ioh;
2718 if (!fd_read && !fd_write) {
2719 pioh = &first_io_handler;
2720 for(;;) {
2721 ioh = *pioh;
2722 if (ioh == NULL)
2723 break;
2724 if (ioh->fd == fd) {
2725 ioh->deleted = 1;
2726 break;
2728 pioh = &ioh->next;
2730 } else {
2731 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2732 if (ioh->fd == fd)
2733 goto found;
2735 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2736 ioh->next = first_io_handler;
2737 first_io_handler = ioh;
2738 found:
2739 ioh->fd = fd;
2740 ioh->fd_read_poll = fd_read_poll;
2741 ioh->fd_read = fd_read;
2742 ioh->fd_write = fd_write;
2743 ioh->opaque = opaque;
2744 ioh->deleted = 0;
2746 return 0;
2749 int qemu_set_fd_handler(int fd,
2750 IOHandler *fd_read,
2751 IOHandler *fd_write,
2752 void *opaque)
2754 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2757 #ifdef _WIN32
2758 /***********************************************************/
2759 /* Polling handling */
2761 typedef struct PollingEntry {
2762 PollingFunc *func;
2763 void *opaque;
2764 struct PollingEntry *next;
2765 } PollingEntry;
2767 static PollingEntry *first_polling_entry;
2769 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2771 PollingEntry **ppe, *pe;
2772 pe = qemu_mallocz(sizeof(PollingEntry));
2773 pe->func = func;
2774 pe->opaque = opaque;
2775 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2776 *ppe = pe;
2777 return 0;
2780 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2782 PollingEntry **ppe, *pe;
2783 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2784 pe = *ppe;
2785 if (pe->func == func && pe->opaque == opaque) {
2786 *ppe = pe->next;
2787 qemu_free(pe);
2788 break;
2793 /***********************************************************/
2794 /* Wait objects support */
2795 typedef struct WaitObjects {
2796 int num;
2797 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2798 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2799 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2800 } WaitObjects;
2802 static WaitObjects wait_objects = {0};
2804 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2806 WaitObjects *w = &wait_objects;
2808 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2809 return -1;
2810 w->events[w->num] = handle;
2811 w->func[w->num] = func;
2812 w->opaque[w->num] = opaque;
2813 w->num++;
2814 return 0;
2817 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2819 int i, found;
2820 WaitObjects *w = &wait_objects;
2822 found = 0;
2823 for (i = 0; i < w->num; i++) {
2824 if (w->events[i] == handle)
2825 found = 1;
2826 if (found) {
2827 w->events[i] = w->events[i + 1];
2828 w->func[i] = w->func[i + 1];
2829 w->opaque[i] = w->opaque[i + 1];
2832 if (found)
2833 w->num--;
2835 #endif
2837 /***********************************************************/
2838 /* ram save/restore */
2840 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2842 int v;
2844 v = qemu_get_byte(f);
2845 switch(v) {
2846 case 0:
2847 if (qemu_get_buffer(f, buf, len) != len)
2848 return -EIO;
2849 break;
2850 case 1:
2851 v = qemu_get_byte(f);
2852 memset(buf, v, len);
2853 break;
2854 default:
2855 return -EINVAL;
2858 if (qemu_file_has_error(f))
2859 return -EIO;
2861 return 0;
2864 static int ram_load_v1(QEMUFile *f, void *opaque)
2866 int ret;
2867 ram_addr_t i;
2869 if (qemu_get_be32(f) != last_ram_offset)
2870 return -EINVAL;
2871 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2872 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2873 if (ret)
2874 return ret;
2876 return 0;
2879 #define BDRV_HASH_BLOCK_SIZE 1024
2880 #define IOBUF_SIZE 4096
2881 #define RAM_CBLOCK_MAGIC 0xfabe
2883 typedef struct RamDecompressState {
2884 z_stream zstream;
2885 QEMUFile *f;
2886 uint8_t buf[IOBUF_SIZE];
2887 } RamDecompressState;
2889 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2891 int ret;
2892 memset(s, 0, sizeof(*s));
2893 s->f = f;
2894 ret = inflateInit(&s->zstream);
2895 if (ret != Z_OK)
2896 return -1;
2897 return 0;
2900 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2902 int ret, clen;
2904 s->zstream.avail_out = len;
2905 s->zstream.next_out = buf;
2906 while (s->zstream.avail_out > 0) {
2907 if (s->zstream.avail_in == 0) {
2908 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2909 return -1;
2910 clen = qemu_get_be16(s->f);
2911 if (clen > IOBUF_SIZE)
2912 return -1;
2913 qemu_get_buffer(s->f, s->buf, clen);
2914 s->zstream.avail_in = clen;
2915 s->zstream.next_in = s->buf;
2917 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2918 if (ret != Z_OK && ret != Z_STREAM_END) {
2919 return -1;
2922 return 0;
2925 static void ram_decompress_close(RamDecompressState *s)
2927 inflateEnd(&s->zstream);
2930 #define RAM_SAVE_FLAG_FULL 0x01
2931 #define RAM_SAVE_FLAG_COMPRESS 0x02
2932 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2933 #define RAM_SAVE_FLAG_PAGE 0x08
2934 #define RAM_SAVE_FLAG_EOS 0x10
2936 static int is_dup_page(uint8_t *page, uint8_t ch)
2938 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2939 uint32_t *array = (uint32_t *)page;
2940 int i;
2942 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2943 if (array[i] != val)
2944 return 0;
2947 return 1;
2950 static int ram_save_block(QEMUFile *f)
2952 static ram_addr_t current_addr = 0;
2953 ram_addr_t saved_addr = current_addr;
2954 ram_addr_t addr = 0;
2955 int found = 0;
2957 while (addr < last_ram_offset) {
2958 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2959 uint8_t *p;
2961 cpu_physical_memory_reset_dirty(current_addr,
2962 current_addr + TARGET_PAGE_SIZE,
2963 MIGRATION_DIRTY_FLAG);
2965 p = qemu_get_ram_ptr(current_addr);
2967 if (is_dup_page(p, *p)) {
2968 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2969 qemu_put_byte(f, *p);
2970 } else {
2971 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2972 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2975 found = 1;
2976 break;
2978 addr += TARGET_PAGE_SIZE;
2979 current_addr = (saved_addr + addr) % last_ram_offset;
2982 return found;
2985 static uint64_t bytes_transferred = 0;
2987 static ram_addr_t ram_save_remaining(void)
2989 ram_addr_t addr;
2990 ram_addr_t count = 0;
2992 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2993 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2994 count++;
2997 return count;
3000 uint64_t ram_bytes_remaining(void)
3002 return ram_save_remaining() * TARGET_PAGE_SIZE;
3005 uint64_t ram_bytes_transferred(void)
3007 return bytes_transferred;
3010 uint64_t ram_bytes_total(void)
3012 return last_ram_offset;
3015 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3017 ram_addr_t addr;
3018 uint64_t bytes_transferred_last;
3019 double bwidth = 0;
3020 uint64_t expected_time = 0;
3022 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3023 qemu_file_set_error(f);
3024 return 0;
3027 if (stage == 1) {
3028 /* Make sure all dirty bits are set */
3029 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3030 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3031 cpu_physical_memory_set_dirty(addr);
3034 /* Enable dirty memory tracking */
3035 cpu_physical_memory_set_dirty_tracking(1);
3037 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3040 bytes_transferred_last = bytes_transferred;
3041 bwidth = get_clock();
3043 while (!qemu_file_rate_limit(f)) {
3044 int ret;
3046 ret = ram_save_block(f);
3047 bytes_transferred += ret * TARGET_PAGE_SIZE;
3048 if (ret == 0) /* no more blocks */
3049 break;
3052 bwidth = get_clock() - bwidth;
3053 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3055 /* if we haven't transferred anything this round, force expected_time to a
3056 * a very high value, but without crashing */
3057 if (bwidth == 0)
3058 bwidth = 0.000001;
3060 /* try transferring iterative blocks of memory */
3062 if (stage == 3) {
3064 /* flush all remaining blocks regardless of rate limiting */
3065 while (ram_save_block(f) != 0) {
3066 bytes_transferred += TARGET_PAGE_SIZE;
3068 cpu_physical_memory_set_dirty_tracking(0);
3071 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3073 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3075 return (stage == 2) && (expected_time <= migrate_max_downtime());
3078 static int ram_load_dead(QEMUFile *f, void *opaque)
3080 RamDecompressState s1, *s = &s1;
3081 uint8_t buf[10];
3082 ram_addr_t i;
3084 if (ram_decompress_open(s, f) < 0)
3085 return -EINVAL;
3086 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3087 if (ram_decompress_buf(s, buf, 1) < 0) {
3088 fprintf(stderr, "Error while reading ram block header\n");
3089 goto error;
3091 if (buf[0] == 0) {
3092 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3093 BDRV_HASH_BLOCK_SIZE) < 0) {
3094 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3095 goto error;
3097 } else {
3098 error:
3099 printf("Error block header\n");
3100 return -EINVAL;
3103 ram_decompress_close(s);
3105 return 0;
3108 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3110 ram_addr_t addr;
3111 int flags;
3113 if (version_id == 1)
3114 return ram_load_v1(f, opaque);
3116 if (version_id == 2) {
3117 if (qemu_get_be32(f) != last_ram_offset)
3118 return -EINVAL;
3119 return ram_load_dead(f, opaque);
3122 if (version_id != 3)
3123 return -EINVAL;
3125 do {
3126 addr = qemu_get_be64(f);
3128 flags = addr & ~TARGET_PAGE_MASK;
3129 addr &= TARGET_PAGE_MASK;
3131 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3132 if (addr != last_ram_offset)
3133 return -EINVAL;
3136 if (flags & RAM_SAVE_FLAG_FULL) {
3137 if (ram_load_dead(f, opaque) < 0)
3138 return -EINVAL;
3141 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3142 uint8_t ch = qemu_get_byte(f);
3143 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3144 #ifndef _WIN32
3145 if (ch == 0 &&
3146 (!kvm_enabled() || kvm_has_sync_mmu())) {
3147 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3149 #endif
3150 } else if (flags & RAM_SAVE_FLAG_PAGE)
3151 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3152 } while (!(flags & RAM_SAVE_FLAG_EOS));
3154 return 0;
3157 void qemu_service_io(void)
3159 qemu_notify_event();
3162 /***********************************************************/
3163 /* bottom halves (can be seen as timers which expire ASAP) */
3165 struct QEMUBH {
3166 QEMUBHFunc *cb;
3167 void *opaque;
3168 int scheduled;
3169 int idle;
3170 int deleted;
3171 QEMUBH *next;
3174 static QEMUBH *first_bh = NULL;
3176 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3178 QEMUBH *bh;
3179 bh = qemu_mallocz(sizeof(QEMUBH));
3180 bh->cb = cb;
3181 bh->opaque = opaque;
3182 bh->next = first_bh;
3183 first_bh = bh;
3184 return bh;
3187 int qemu_bh_poll(void)
3189 QEMUBH *bh, **bhp;
3190 int ret;
3192 ret = 0;
3193 for (bh = first_bh; bh; bh = bh->next) {
3194 if (!bh->deleted && bh->scheduled) {
3195 bh->scheduled = 0;
3196 if (!bh->idle)
3197 ret = 1;
3198 bh->idle = 0;
3199 bh->cb(bh->opaque);
3203 /* remove deleted bhs */
3204 bhp = &first_bh;
3205 while (*bhp) {
3206 bh = *bhp;
3207 if (bh->deleted) {
3208 *bhp = bh->next;
3209 qemu_free(bh);
3210 } else
3211 bhp = &bh->next;
3214 return ret;
3217 void qemu_bh_schedule_idle(QEMUBH *bh)
3219 if (bh->scheduled)
3220 return;
3221 bh->scheduled = 1;
3222 bh->idle = 1;
3225 void qemu_bh_schedule(QEMUBH *bh)
3227 if (bh->scheduled)
3228 return;
3229 bh->scheduled = 1;
3230 bh->idle = 0;
3231 /* stop the currently executing CPU to execute the BH ASAP */
3232 qemu_notify_event();
3235 void qemu_bh_cancel(QEMUBH *bh)
3237 bh->scheduled = 0;
3240 void qemu_bh_delete(QEMUBH *bh)
3242 bh->scheduled = 0;
3243 bh->deleted = 1;
3246 static void qemu_bh_update_timeout(int *timeout)
3248 QEMUBH *bh;
3250 for (bh = first_bh; bh; bh = bh->next) {
3251 if (!bh->deleted && bh->scheduled) {
3252 if (bh->idle) {
3253 /* idle bottom halves will be polled at least
3254 * every 10ms */
3255 *timeout = MIN(10, *timeout);
3256 } else {
3257 /* non-idle bottom halves will be executed
3258 * immediately */
3259 *timeout = 0;
3260 break;
3266 /***********************************************************/
3267 /* machine registration */
3269 static QEMUMachine *first_machine = NULL;
3270 QEMUMachine *current_machine = NULL;
3272 int qemu_register_machine(QEMUMachine *m)
3274 QEMUMachine **pm;
3275 pm = &first_machine;
3276 while (*pm != NULL)
3277 pm = &(*pm)->next;
3278 m->next = NULL;
3279 *pm = m;
3280 return 0;
3283 static QEMUMachine *find_machine(const char *name)
3285 QEMUMachine *m;
3287 for(m = first_machine; m != NULL; m = m->next) {
3288 if (!strcmp(m->name, name))
3289 return m;
3290 if (m->alias && !strcmp(m->alias, name))
3291 return m;
3293 return NULL;
3296 static QEMUMachine *find_default_machine(void)
3298 QEMUMachine *m;
3300 for(m = first_machine; m != NULL; m = m->next) {
3301 if (m->is_default) {
3302 return m;
3305 return NULL;
3308 /***********************************************************/
3309 /* main execution loop */
3311 static void gui_update(void *opaque)
3313 uint64_t interval = GUI_REFRESH_INTERVAL;
3314 DisplayState *ds = opaque;
3315 DisplayChangeListener *dcl = ds->listeners;
3317 dpy_refresh(ds);
3319 while (dcl != NULL) {
3320 if (dcl->gui_timer_interval &&
3321 dcl->gui_timer_interval < interval)
3322 interval = dcl->gui_timer_interval;
3323 dcl = dcl->next;
3325 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3328 static void nographic_update(void *opaque)
3330 uint64_t interval = GUI_REFRESH_INTERVAL;
3332 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3335 struct vm_change_state_entry {
3336 VMChangeStateHandler *cb;
3337 void *opaque;
3338 LIST_ENTRY (vm_change_state_entry) entries;
3341 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3343 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3344 void *opaque)
3346 VMChangeStateEntry *e;
3348 e = qemu_mallocz(sizeof (*e));
3350 e->cb = cb;
3351 e->opaque = opaque;
3352 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3353 return e;
3356 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3358 LIST_REMOVE (e, entries);
3359 qemu_free (e);
3362 static void vm_state_notify(int running, int reason)
3364 VMChangeStateEntry *e;
3366 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3367 e->cb(e->opaque, running, reason);
3371 static void resume_all_vcpus(void);
3372 static void pause_all_vcpus(void);
3374 void vm_start(void)
3376 if (!vm_running) {
3377 cpu_enable_ticks();
3378 vm_running = 1;
3379 vm_state_notify(1, 0);
3380 qemu_rearm_alarm_timer(alarm_timer);
3381 resume_all_vcpus();
3385 /* reset/shutdown handler */
3387 typedef struct QEMUResetEntry {
3388 TAILQ_ENTRY(QEMUResetEntry) entry;
3389 QEMUResetHandler *func;
3390 void *opaque;
3391 } QEMUResetEntry;
3393 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3394 TAILQ_HEAD_INITIALIZER(reset_handlers);
3395 static int reset_requested;
3396 static int shutdown_requested;
3397 static int powerdown_requested;
3398 static int debug_requested;
3399 static int vmstop_requested;
3401 int qemu_shutdown_requested(void)
3403 int r = shutdown_requested;
3404 shutdown_requested = 0;
3405 return r;
3408 int qemu_reset_requested(void)
3410 int r = reset_requested;
3411 reset_requested = 0;
3412 return r;
3415 int qemu_powerdown_requested(void)
3417 int r = powerdown_requested;
3418 powerdown_requested = 0;
3419 return r;
3422 static int qemu_debug_requested(void)
3424 int r = debug_requested;
3425 debug_requested = 0;
3426 return r;
3429 static int qemu_vmstop_requested(void)
3431 int r = vmstop_requested;
3432 vmstop_requested = 0;
3433 return r;
3436 static void do_vm_stop(int reason)
3438 if (vm_running) {
3439 cpu_disable_ticks();
3440 vm_running = 0;
3441 pause_all_vcpus();
3442 vm_state_notify(0, reason);
3446 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3448 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3450 re->func = func;
3451 re->opaque = opaque;
3452 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3455 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3457 QEMUResetEntry *re;
3459 TAILQ_FOREACH(re, &reset_handlers, entry) {
3460 if (re->func == func && re->opaque == opaque) {
3461 TAILQ_REMOVE(&reset_handlers, re, entry);
3462 qemu_free(re);
3463 return;
3468 void qemu_system_reset(void)
3470 QEMUResetEntry *re, *nre;
3472 /* reset all devices */
3473 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3474 re->func(re->opaque);
3478 void qemu_system_reset_request(void)
3480 if (no_reboot) {
3481 shutdown_requested = 1;
3482 } else {
3483 reset_requested = 1;
3485 qemu_notify_event();
3488 void qemu_system_shutdown_request(void)
3490 shutdown_requested = 1;
3491 qemu_notify_event();
3494 void qemu_system_powerdown_request(void)
3496 powerdown_requested = 1;
3497 qemu_notify_event();
3500 #ifdef CONFIG_IOTHREAD
3501 static void qemu_system_vmstop_request(int reason)
3503 vmstop_requested = reason;
3504 qemu_notify_event();
3506 #endif
3508 #ifndef _WIN32
3509 static int io_thread_fd = -1;
3511 static void qemu_event_increment(void)
3513 static const char byte = 0;
3515 if (io_thread_fd == -1)
3516 return;
3518 write(io_thread_fd, &byte, sizeof(byte));
3521 static void qemu_event_read(void *opaque)
3523 int fd = (unsigned long)opaque;
3524 ssize_t len;
3526 /* Drain the notify pipe */
3527 do {
3528 char buffer[512];
3529 len = read(fd, buffer, sizeof(buffer));
3530 } while ((len == -1 && errno == EINTR) || len > 0);
3533 static int qemu_event_init(void)
3535 int err;
3536 int fds[2];
3538 err = pipe(fds);
3539 if (err == -1)
3540 return -errno;
3542 err = fcntl_setfl(fds[0], O_NONBLOCK);
3543 if (err < 0)
3544 goto fail;
3546 err = fcntl_setfl(fds[1], O_NONBLOCK);
3547 if (err < 0)
3548 goto fail;
3550 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3551 (void *)(unsigned long)fds[0]);
3553 io_thread_fd = fds[1];
3554 return 0;
3556 fail:
3557 close(fds[0]);
3558 close(fds[1]);
3559 return err;
3561 #else
3562 HANDLE qemu_event_handle;
3564 static void dummy_event_handler(void *opaque)
3568 static int qemu_event_init(void)
3570 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3571 if (!qemu_event_handle) {
3572 perror("Failed CreateEvent");
3573 return -1;
3575 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3576 return 0;
3579 static void qemu_event_increment(void)
3581 SetEvent(qemu_event_handle);
3583 #endif
3585 static int cpu_can_run(CPUState *env)
3587 if (env->stop)
3588 return 0;
3589 if (env->stopped)
3590 return 0;
3591 return 1;
3594 #ifndef CONFIG_IOTHREAD
3595 static int qemu_init_main_loop(void)
3597 return qemu_event_init();
3600 void qemu_init_vcpu(void *_env)
3602 CPUState *env = _env;
3604 if (kvm_enabled())
3605 kvm_init_vcpu(env);
3606 return;
3609 int qemu_cpu_self(void *env)
3611 return 1;
3614 static void resume_all_vcpus(void)
3618 static void pause_all_vcpus(void)
3622 void qemu_cpu_kick(void *env)
3624 return;
3627 void qemu_notify_event(void)
3629 CPUState *env = cpu_single_env;
3631 if (env) {
3632 cpu_exit(env);
3633 #ifdef USE_KQEMU
3634 if (env->kqemu_enabled)
3635 kqemu_cpu_interrupt(env);
3636 #endif
3640 #define qemu_mutex_lock_iothread() do { } while (0)
3641 #define qemu_mutex_unlock_iothread() do { } while (0)
3643 void vm_stop(int reason)
3645 do_vm_stop(reason);
3648 #else /* CONFIG_IOTHREAD */
3650 #include "qemu-thread.h"
3652 QemuMutex qemu_global_mutex;
3653 static QemuMutex qemu_fair_mutex;
3655 static QemuThread io_thread;
3657 static QemuThread *tcg_cpu_thread;
3658 static QemuCond *tcg_halt_cond;
3660 static int qemu_system_ready;
3661 /* cpu creation */
3662 static QemuCond qemu_cpu_cond;
3663 /* system init */
3664 static QemuCond qemu_system_cond;
3665 static QemuCond qemu_pause_cond;
3667 static void block_io_signals(void);
3668 static void unblock_io_signals(void);
3669 static int tcg_has_work(void);
3671 static int qemu_init_main_loop(void)
3673 int ret;
3675 ret = qemu_event_init();
3676 if (ret)
3677 return ret;
3679 qemu_cond_init(&qemu_pause_cond);
3680 qemu_mutex_init(&qemu_fair_mutex);
3681 qemu_mutex_init(&qemu_global_mutex);
3682 qemu_mutex_lock(&qemu_global_mutex);
3684 unblock_io_signals();
3685 qemu_thread_self(&io_thread);
3687 return 0;
3690 static void qemu_wait_io_event(CPUState *env)
3692 while (!tcg_has_work())
3693 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3695 qemu_mutex_unlock(&qemu_global_mutex);
3698 * Users of qemu_global_mutex can be starved, having no chance
3699 * to acquire it since this path will get to it first.
3700 * So use another lock to provide fairness.
3702 qemu_mutex_lock(&qemu_fair_mutex);
3703 qemu_mutex_unlock(&qemu_fair_mutex);
3705 qemu_mutex_lock(&qemu_global_mutex);
3706 if (env->stop) {
3707 env->stop = 0;
3708 env->stopped = 1;
3709 qemu_cond_signal(&qemu_pause_cond);
3713 static int qemu_cpu_exec(CPUState *env);
3715 static void *kvm_cpu_thread_fn(void *arg)
3717 CPUState *env = arg;
3719 block_io_signals();
3720 qemu_thread_self(env->thread);
3722 /* signal CPU creation */
3723 qemu_mutex_lock(&qemu_global_mutex);
3724 env->created = 1;
3725 qemu_cond_signal(&qemu_cpu_cond);
3727 /* and wait for machine initialization */
3728 while (!qemu_system_ready)
3729 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3731 while (1) {
3732 if (cpu_can_run(env))
3733 qemu_cpu_exec(env);
3734 qemu_wait_io_event(env);
3737 return NULL;
3740 static void tcg_cpu_exec(void);
3742 static void *tcg_cpu_thread_fn(void *arg)
3744 CPUState *env = arg;
3746 block_io_signals();
3747 qemu_thread_self(env->thread);
3749 /* signal CPU creation */
3750 qemu_mutex_lock(&qemu_global_mutex);
3751 for (env = first_cpu; env != NULL; env = env->next_cpu)
3752 env->created = 1;
3753 qemu_cond_signal(&qemu_cpu_cond);
3755 /* and wait for machine initialization */
3756 while (!qemu_system_ready)
3757 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3759 while (1) {
3760 tcg_cpu_exec();
3761 qemu_wait_io_event(cur_cpu);
3764 return NULL;
3767 void qemu_cpu_kick(void *_env)
3769 CPUState *env = _env;
3770 qemu_cond_broadcast(env->halt_cond);
3771 if (kvm_enabled())
3772 qemu_thread_signal(env->thread, SIGUSR1);
3775 int qemu_cpu_self(void *env)
3777 return (cpu_single_env != NULL);
3780 static void cpu_signal(int sig)
3782 if (cpu_single_env)
3783 cpu_exit(cpu_single_env);
3786 static void block_io_signals(void)
3788 sigset_t set;
3789 struct sigaction sigact;
3791 sigemptyset(&set);
3792 sigaddset(&set, SIGUSR2);
3793 sigaddset(&set, SIGIO);
3794 sigaddset(&set, SIGALRM);
3795 pthread_sigmask(SIG_BLOCK, &set, NULL);
3797 sigemptyset(&set);
3798 sigaddset(&set, SIGUSR1);
3799 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3801 memset(&sigact, 0, sizeof(sigact));
3802 sigact.sa_handler = cpu_signal;
3803 sigaction(SIGUSR1, &sigact, NULL);
3806 static void unblock_io_signals(void)
3808 sigset_t set;
3810 sigemptyset(&set);
3811 sigaddset(&set, SIGUSR2);
3812 sigaddset(&set, SIGIO);
3813 sigaddset(&set, SIGALRM);
3814 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3816 sigemptyset(&set);
3817 sigaddset(&set, SIGUSR1);
3818 pthread_sigmask(SIG_BLOCK, &set, NULL);
3821 static void qemu_signal_lock(unsigned int msecs)
3823 qemu_mutex_lock(&qemu_fair_mutex);
3825 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3826 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3827 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3828 break;
3830 qemu_mutex_unlock(&qemu_fair_mutex);
3833 static void qemu_mutex_lock_iothread(void)
3835 if (kvm_enabled()) {
3836 qemu_mutex_lock(&qemu_fair_mutex);
3837 qemu_mutex_lock(&qemu_global_mutex);
3838 qemu_mutex_unlock(&qemu_fair_mutex);
3839 } else
3840 qemu_signal_lock(100);
3843 static void qemu_mutex_unlock_iothread(void)
3845 qemu_mutex_unlock(&qemu_global_mutex);
3848 static int all_vcpus_paused(void)
3850 CPUState *penv = first_cpu;
3852 while (penv) {
3853 if (!penv->stopped)
3854 return 0;
3855 penv = (CPUState *)penv->next_cpu;
3858 return 1;
3861 static void pause_all_vcpus(void)
3863 CPUState *penv = first_cpu;
3865 while (penv) {
3866 penv->stop = 1;
3867 qemu_thread_signal(penv->thread, SIGUSR1);
3868 qemu_cpu_kick(penv);
3869 penv = (CPUState *)penv->next_cpu;
3872 while (!all_vcpus_paused()) {
3873 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3874 penv = first_cpu;
3875 while (penv) {
3876 qemu_thread_signal(penv->thread, SIGUSR1);
3877 penv = (CPUState *)penv->next_cpu;
3882 static void resume_all_vcpus(void)
3884 CPUState *penv = first_cpu;
3886 while (penv) {
3887 penv->stop = 0;
3888 penv->stopped = 0;
3889 qemu_thread_signal(penv->thread, SIGUSR1);
3890 qemu_cpu_kick(penv);
3891 penv = (CPUState *)penv->next_cpu;
3895 static void tcg_init_vcpu(void *_env)
3897 CPUState *env = _env;
3898 /* share a single thread for all cpus with TCG */
3899 if (!tcg_cpu_thread) {
3900 env->thread = qemu_mallocz(sizeof(QemuThread));
3901 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3902 qemu_cond_init(env->halt_cond);
3903 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3904 while (env->created == 0)
3905 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3906 tcg_cpu_thread = env->thread;
3907 tcg_halt_cond = env->halt_cond;
3908 } else {
3909 env->thread = tcg_cpu_thread;
3910 env->halt_cond = tcg_halt_cond;
3914 static void kvm_start_vcpu(CPUState *env)
3916 kvm_init_vcpu(env);
3917 env->thread = qemu_mallocz(sizeof(QemuThread));
3918 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3919 qemu_cond_init(env->halt_cond);
3920 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3921 while (env->created == 0)
3922 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3925 void qemu_init_vcpu(void *_env)
3927 CPUState *env = _env;
3929 if (kvm_enabled())
3930 kvm_start_vcpu(env);
3931 else
3932 tcg_init_vcpu(env);
3935 void qemu_notify_event(void)
3937 qemu_event_increment();
3940 void vm_stop(int reason)
3942 QemuThread me;
3943 qemu_thread_self(&me);
3945 if (!qemu_thread_equal(&me, &io_thread)) {
3946 qemu_system_vmstop_request(reason);
3948 * FIXME: should not return to device code in case
3949 * vm_stop() has been requested.
3951 if (cpu_single_env) {
3952 cpu_exit(cpu_single_env);
3953 cpu_single_env->stop = 1;
3955 return;
3957 do_vm_stop(reason);
3960 #endif
3963 #ifdef _WIN32
3964 static void host_main_loop_wait(int *timeout)
3966 int ret, ret2, i;
3967 PollingEntry *pe;
3970 /* XXX: need to suppress polling by better using win32 events */
3971 ret = 0;
3972 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3973 ret |= pe->func(pe->opaque);
3975 if (ret == 0) {
3976 int err;
3977 WaitObjects *w = &wait_objects;
3979 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3980 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3981 if (w->func[ret - WAIT_OBJECT_0])
3982 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3984 /* Check for additional signaled events */
3985 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3987 /* Check if event is signaled */
3988 ret2 = WaitForSingleObject(w->events[i], 0);
3989 if(ret2 == WAIT_OBJECT_0) {
3990 if (w->func[i])
3991 w->func[i](w->opaque[i]);
3992 } else if (ret2 == WAIT_TIMEOUT) {
3993 } else {
3994 err = GetLastError();
3995 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3998 } else if (ret == WAIT_TIMEOUT) {
3999 } else {
4000 err = GetLastError();
4001 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4005 *timeout = 0;
4007 #else
4008 static void host_main_loop_wait(int *timeout)
4011 #endif
4013 void main_loop_wait(int timeout)
4015 IOHandlerRecord *ioh;
4016 fd_set rfds, wfds, xfds;
4017 int ret, nfds;
4018 struct timeval tv;
4020 qemu_bh_update_timeout(&timeout);
4022 host_main_loop_wait(&timeout);
4024 /* poll any events */
4025 /* XXX: separate device handlers from system ones */
4026 nfds = -1;
4027 FD_ZERO(&rfds);
4028 FD_ZERO(&wfds);
4029 FD_ZERO(&xfds);
4030 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4031 if (ioh->deleted)
4032 continue;
4033 if (ioh->fd_read &&
4034 (!ioh->fd_read_poll ||
4035 ioh->fd_read_poll(ioh->opaque) != 0)) {
4036 FD_SET(ioh->fd, &rfds);
4037 if (ioh->fd > nfds)
4038 nfds = ioh->fd;
4040 if (ioh->fd_write) {
4041 FD_SET(ioh->fd, &wfds);
4042 if (ioh->fd > nfds)
4043 nfds = ioh->fd;
4047 tv.tv_sec = timeout / 1000;
4048 tv.tv_usec = (timeout % 1000) * 1000;
4050 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4052 qemu_mutex_unlock_iothread();
4053 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4054 qemu_mutex_lock_iothread();
4055 if (ret > 0) {
4056 IOHandlerRecord **pioh;
4058 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4059 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4060 ioh->fd_read(ioh->opaque);
4062 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4063 ioh->fd_write(ioh->opaque);
4067 /* remove deleted IO handlers */
4068 pioh = &first_io_handler;
4069 while (*pioh) {
4070 ioh = *pioh;
4071 if (ioh->deleted) {
4072 *pioh = ioh->next;
4073 qemu_free(ioh);
4074 } else
4075 pioh = &ioh->next;
4079 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4081 /* rearm timer, if not periodic */
4082 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4083 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4084 qemu_rearm_alarm_timer(alarm_timer);
4087 /* vm time timers */
4088 if (vm_running) {
4089 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4090 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4091 qemu_get_clock(vm_clock));
4094 /* real time timers */
4095 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4096 qemu_get_clock(rt_clock));
4098 /* Check bottom-halves last in case any of the earlier events triggered
4099 them. */
4100 qemu_bh_poll();
4104 static int qemu_cpu_exec(CPUState *env)
4106 int ret;
4107 #ifdef CONFIG_PROFILER
4108 int64_t ti;
4109 #endif
4111 #ifdef CONFIG_PROFILER
4112 ti = profile_getclock();
4113 #endif
4114 if (use_icount) {
4115 int64_t count;
4116 int decr;
4117 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4118 env->icount_decr.u16.low = 0;
4119 env->icount_extra = 0;
4120 count = qemu_next_deadline();
4121 count = (count + (1 << icount_time_shift) - 1)
4122 >> icount_time_shift;
4123 qemu_icount += count;
4124 decr = (count > 0xffff) ? 0xffff : count;
4125 count -= decr;
4126 env->icount_decr.u16.low = decr;
4127 env->icount_extra = count;
4129 ret = cpu_exec(env);
4130 #ifdef CONFIG_PROFILER
4131 qemu_time += profile_getclock() - ti;
4132 #endif
4133 if (use_icount) {
4134 /* Fold pending instructions back into the
4135 instruction counter, and clear the interrupt flag. */
4136 qemu_icount -= (env->icount_decr.u16.low
4137 + env->icount_extra);
4138 env->icount_decr.u32 = 0;
4139 env->icount_extra = 0;
4141 return ret;
4144 static void tcg_cpu_exec(void)
4146 int ret = 0;
4148 if (next_cpu == NULL)
4149 next_cpu = first_cpu;
4150 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4151 CPUState *env = cur_cpu = next_cpu;
4153 if (!vm_running)
4154 break;
4155 if (timer_alarm_pending) {
4156 timer_alarm_pending = 0;
4157 break;
4159 if (cpu_can_run(env))
4160 ret = qemu_cpu_exec(env);
4161 if (ret == EXCP_DEBUG) {
4162 gdb_set_stop_cpu(env);
4163 debug_requested = 1;
4164 break;
4169 static int cpu_has_work(CPUState *env)
4171 if (env->stop)
4172 return 1;
4173 if (env->stopped)
4174 return 0;
4175 if (!env->halted)
4176 return 1;
4177 if (qemu_cpu_has_work(env))
4178 return 1;
4179 return 0;
4182 static int tcg_has_work(void)
4184 CPUState *env;
4186 for (env = first_cpu; env != NULL; env = env->next_cpu)
4187 if (cpu_has_work(env))
4188 return 1;
4189 return 0;
4192 static int qemu_calculate_timeout(void)
4194 #ifndef CONFIG_IOTHREAD
4195 int timeout;
4197 if (!vm_running)
4198 timeout = 5000;
4199 else if (tcg_has_work())
4200 timeout = 0;
4201 else if (!use_icount)
4202 timeout = 5000;
4203 else {
4204 /* XXX: use timeout computed from timers */
4205 int64_t add;
4206 int64_t delta;
4207 /* Advance virtual time to the next event. */
4208 if (use_icount == 1) {
4209 /* When not using an adaptive execution frequency
4210 we tend to get badly out of sync with real time,
4211 so just delay for a reasonable amount of time. */
4212 delta = 0;
4213 } else {
4214 delta = cpu_get_icount() - cpu_get_clock();
4216 if (delta > 0) {
4217 /* If virtual time is ahead of real time then just
4218 wait for IO. */
4219 timeout = (delta / 1000000) + 1;
4220 } else {
4221 /* Wait for either IO to occur or the next
4222 timer event. */
4223 add = qemu_next_deadline();
4224 /* We advance the timer before checking for IO.
4225 Limit the amount we advance so that early IO
4226 activity won't get the guest too far ahead. */
4227 if (add > 10000000)
4228 add = 10000000;
4229 delta += add;
4230 add = (add + (1 << icount_time_shift) - 1)
4231 >> icount_time_shift;
4232 qemu_icount += add;
4233 timeout = delta / 1000000;
4234 if (timeout < 0)
4235 timeout = 0;
4239 return timeout;
4240 #else /* CONFIG_IOTHREAD */
4241 return 1000;
4242 #endif
4245 static int vm_can_run(void)
4247 if (powerdown_requested)
4248 return 0;
4249 if (reset_requested)
4250 return 0;
4251 if (shutdown_requested)
4252 return 0;
4253 if (debug_requested)
4254 return 0;
4255 return 1;
4258 static void main_loop(void)
4260 int r;
4262 #ifdef CONFIG_IOTHREAD
4263 qemu_system_ready = 1;
4264 qemu_cond_broadcast(&qemu_system_cond);
4265 #endif
4267 for (;;) {
4268 do {
4269 #ifdef CONFIG_PROFILER
4270 int64_t ti;
4271 #endif
4272 #ifndef CONFIG_IOTHREAD
4273 tcg_cpu_exec();
4274 #endif
4275 #ifdef CONFIG_PROFILER
4276 ti = profile_getclock();
4277 #endif
4278 main_loop_wait(qemu_calculate_timeout());
4279 #ifdef CONFIG_PROFILER
4280 dev_time += profile_getclock() - ti;
4281 #endif
4282 } while (vm_can_run());
4284 if (qemu_debug_requested())
4285 vm_stop(EXCP_DEBUG);
4286 if (qemu_shutdown_requested()) {
4287 if (no_shutdown) {
4288 vm_stop(0);
4289 no_shutdown = 0;
4290 } else
4291 break;
4293 if (qemu_reset_requested()) {
4294 pause_all_vcpus();
4295 qemu_system_reset();
4296 resume_all_vcpus();
4298 if (qemu_powerdown_requested())
4299 qemu_system_powerdown();
4300 if ((r = qemu_vmstop_requested()))
4301 vm_stop(r);
4303 pause_all_vcpus();
4306 static void version(void)
4308 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4311 static void help(int exitcode)
4313 version();
4314 printf("usage: %s [options] [disk_image]\n"
4315 "\n"
4316 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4317 "\n"
4318 #define DEF(option, opt_arg, opt_enum, opt_help) \
4319 opt_help
4320 #define DEFHEADING(text) stringify(text) "\n"
4321 #include "qemu-options.h"
4322 #undef DEF
4323 #undef DEFHEADING
4324 #undef GEN_DOCS
4325 "\n"
4326 "During emulation, the following keys are useful:\n"
4327 "ctrl-alt-f toggle full screen\n"
4328 "ctrl-alt-n switch to virtual console 'n'\n"
4329 "ctrl-alt toggle mouse and keyboard grab\n"
4330 "\n"
4331 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4333 "qemu",
4334 DEFAULT_RAM_SIZE,
4335 #ifndef _WIN32
4336 DEFAULT_NETWORK_SCRIPT,
4337 DEFAULT_NETWORK_DOWN_SCRIPT,
4338 #endif
4339 DEFAULT_GDBSTUB_PORT,
4340 "/tmp/qemu.log");
4341 exit(exitcode);
4344 #define HAS_ARG 0x0001
4346 enum {
4347 #define DEF(option, opt_arg, opt_enum, opt_help) \
4348 opt_enum,
4349 #define DEFHEADING(text)
4350 #include "qemu-options.h"
4351 #undef DEF
4352 #undef DEFHEADING
4353 #undef GEN_DOCS
4356 typedef struct QEMUOption {
4357 const char *name;
4358 int flags;
4359 int index;
4360 } QEMUOption;
4362 static const QEMUOption qemu_options[] = {
4363 { "h", 0, QEMU_OPTION_h },
4364 #define DEF(option, opt_arg, opt_enum, opt_help) \
4365 { option, opt_arg, opt_enum },
4366 #define DEFHEADING(text)
4367 #include "qemu-options.h"
4368 #undef DEF
4369 #undef DEFHEADING
4370 #undef GEN_DOCS
4371 { NULL },
4374 #ifdef HAS_AUDIO
4375 struct soundhw soundhw[] = {
4376 #ifdef HAS_AUDIO_CHOICE
4377 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4379 "pcspk",
4380 "PC speaker",
4383 { .init_isa = pcspk_audio_init }
4385 #endif
4387 #ifdef CONFIG_SB16
4389 "sb16",
4390 "Creative Sound Blaster 16",
4393 { .init_isa = SB16_init }
4395 #endif
4397 #ifdef CONFIG_CS4231A
4399 "cs4231a",
4400 "CS4231A",
4403 { .init_isa = cs4231a_init }
4405 #endif
4407 #ifdef CONFIG_ADLIB
4409 "adlib",
4410 #ifdef HAS_YMF262
4411 "Yamaha YMF262 (OPL3)",
4412 #else
4413 "Yamaha YM3812 (OPL2)",
4414 #endif
4417 { .init_isa = Adlib_init }
4419 #endif
4421 #ifdef CONFIG_GUS
4423 "gus",
4424 "Gravis Ultrasound GF1",
4427 { .init_isa = GUS_init }
4429 #endif
4431 #ifdef CONFIG_AC97
4433 "ac97",
4434 "Intel 82801AA AC97 Audio",
4437 { .init_pci = ac97_init }
4439 #endif
4441 #ifdef CONFIG_ES1370
4443 "es1370",
4444 "ENSONIQ AudioPCI ES1370",
4447 { .init_pci = es1370_init }
4449 #endif
4451 #endif /* HAS_AUDIO_CHOICE */
4453 { NULL, NULL, 0, 0, { NULL } }
4456 static void select_soundhw (const char *optarg)
4458 struct soundhw *c;
4460 if (*optarg == '?') {
4461 show_valid_cards:
4463 printf ("Valid sound card names (comma separated):\n");
4464 for (c = soundhw; c->name; ++c) {
4465 printf ("%-11s %s\n", c->name, c->descr);
4467 printf ("\n-soundhw all will enable all of the above\n");
4468 exit (*optarg != '?');
4470 else {
4471 size_t l;
4472 const char *p;
4473 char *e;
4474 int bad_card = 0;
4476 if (!strcmp (optarg, "all")) {
4477 for (c = soundhw; c->name; ++c) {
4478 c->enabled = 1;
4480 return;
4483 p = optarg;
4484 while (*p) {
4485 e = strchr (p, ',');
4486 l = !e ? strlen (p) : (size_t) (e - p);
4488 for (c = soundhw; c->name; ++c) {
4489 if (!strncmp (c->name, p, l)) {
4490 c->enabled = 1;
4491 break;
4495 if (!c->name) {
4496 if (l > 80) {
4497 fprintf (stderr,
4498 "Unknown sound card name (too big to show)\n");
4500 else {
4501 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4502 (int) l, p);
4504 bad_card = 1;
4506 p += l + (e != NULL);
4509 if (bad_card)
4510 goto show_valid_cards;
4513 #endif
4515 static void select_vgahw (const char *p)
4517 const char *opts;
4519 cirrus_vga_enabled = 0;
4520 std_vga_enabled = 0;
4521 vmsvga_enabled = 0;
4522 xenfb_enabled = 0;
4523 if (strstart(p, "std", &opts)) {
4524 std_vga_enabled = 1;
4525 } else if (strstart(p, "cirrus", &opts)) {
4526 cirrus_vga_enabled = 1;
4527 } else if (strstart(p, "vmware", &opts)) {
4528 vmsvga_enabled = 1;
4529 } else if (strstart(p, "xenfb", &opts)) {
4530 xenfb_enabled = 1;
4531 } else if (!strstart(p, "none", &opts)) {
4532 invalid_vga:
4533 fprintf(stderr, "Unknown vga type: %s\n", p);
4534 exit(1);
4536 while (*opts) {
4537 const char *nextopt;
4539 if (strstart(opts, ",retrace=", &nextopt)) {
4540 opts = nextopt;
4541 if (strstart(opts, "dumb", &nextopt))
4542 vga_retrace_method = VGA_RETRACE_DUMB;
4543 else if (strstart(opts, "precise", &nextopt))
4544 vga_retrace_method = VGA_RETRACE_PRECISE;
4545 else goto invalid_vga;
4546 } else goto invalid_vga;
4547 opts = nextopt;
4551 #ifdef TARGET_I386
4552 static int balloon_parse(const char *arg)
4554 char buf[128];
4555 const char *p;
4557 if (!strcmp(arg, "none")) {
4558 virtio_balloon = 0;
4559 } else if (!strncmp(arg, "virtio", 6)) {
4560 virtio_balloon = 1;
4561 if (arg[6] == ',') {
4562 p = arg + 7;
4563 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4564 virtio_balloon_devaddr = strdup(buf);
4567 } else {
4568 return -1;
4570 return 0;
4572 #endif
4574 #ifdef _WIN32
4575 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4577 exit(STATUS_CONTROL_C_EXIT);
4578 return TRUE;
4580 #endif
4582 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4584 int ret;
4586 if(strlen(str) != 36)
4587 return -1;
4589 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4590 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4591 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4593 if(ret != 16)
4594 return -1;
4596 #ifdef TARGET_I386
4597 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4598 #endif
4600 return 0;
4603 #define MAX_NET_CLIENTS 32
4605 #ifndef _WIN32
4607 static void termsig_handler(int signal)
4609 qemu_system_shutdown_request();
4612 static void sigchld_handler(int signal)
4614 waitpid(-1, NULL, WNOHANG);
4617 static void sighandler_setup(void)
4619 struct sigaction act;
4621 memset(&act, 0, sizeof(act));
4622 act.sa_handler = termsig_handler;
4623 sigaction(SIGINT, &act, NULL);
4624 sigaction(SIGHUP, &act, NULL);
4625 sigaction(SIGTERM, &act, NULL);
4627 act.sa_handler = sigchld_handler;
4628 act.sa_flags = SA_NOCLDSTOP;
4629 sigaction(SIGCHLD, &act, NULL);
4632 #endif
4634 #ifdef _WIN32
4635 /* Look for support files in the same directory as the executable. */
4636 static char *find_datadir(const char *argv0)
4638 char *p;
4639 char buf[MAX_PATH];
4640 DWORD len;
4642 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4643 if (len == 0) {
4644 return NULL;
4647 buf[len] = 0;
4648 p = buf + len - 1;
4649 while (p != buf && *p != '\\')
4650 p--;
4651 *p = 0;
4652 if (access(buf, R_OK) == 0) {
4653 return qemu_strdup(buf);
4655 return NULL;
4657 #else /* !_WIN32 */
4659 /* Find a likely location for support files using the location of the binary.
4660 For installed binaries this will be "$bindir/../share/qemu". When
4661 running from the build tree this will be "$bindir/../pc-bios". */
4662 #define SHARE_SUFFIX "/share/qemu"
4663 #define BUILD_SUFFIX "/pc-bios"
4664 static char *find_datadir(const char *argv0)
4666 char *dir;
4667 char *p = NULL;
4668 char *res;
4669 #ifdef PATH_MAX
4670 char buf[PATH_MAX];
4671 #endif
4672 size_t max_len;
4674 #if defined(__linux__)
4676 int len;
4677 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4678 if (len > 0) {
4679 buf[len] = 0;
4680 p = buf;
4683 #elif defined(__FreeBSD__)
4685 int len;
4686 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4687 if (len > 0) {
4688 buf[len] = 0;
4689 p = buf;
4692 #endif
4693 /* If we don't have any way of figuring out the actual executable
4694 location then try argv[0]. */
4695 if (!p) {
4696 #ifdef PATH_MAX
4697 p = buf;
4698 #endif
4699 p = realpath(argv0, p);
4700 if (!p) {
4701 return NULL;
4704 dir = dirname(p);
4705 dir = dirname(dir);
4707 max_len = strlen(dir) +
4708 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4709 res = qemu_mallocz(max_len);
4710 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4711 if (access(res, R_OK)) {
4712 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4713 if (access(res, R_OK)) {
4714 qemu_free(res);
4715 res = NULL;
4718 #ifndef PATH_MAX
4719 free(p);
4720 #endif
4721 return res;
4723 #undef SHARE_SUFFIX
4724 #undef BUILD_SUFFIX
4725 #endif
4727 char *qemu_find_file(int type, const char *name)
4729 int len;
4730 const char *subdir;
4731 char *buf;
4733 /* If name contains path separators then try it as a straight path. */
4734 if ((strchr(name, '/') || strchr(name, '\\'))
4735 && access(name, R_OK) == 0) {
4736 return strdup(name);
4738 switch (type) {
4739 case QEMU_FILE_TYPE_BIOS:
4740 subdir = "";
4741 break;
4742 case QEMU_FILE_TYPE_KEYMAP:
4743 subdir = "keymaps/";
4744 break;
4745 default:
4746 abort();
4748 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4749 buf = qemu_mallocz(len);
4750 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4751 if (access(buf, R_OK)) {
4752 qemu_free(buf);
4753 return NULL;
4755 return buf;
4758 struct device_config {
4759 enum {
4760 DEV_GENERIC, /* -device */
4761 DEV_USB, /* -usbdevice */
4762 DEV_BT, /* -bt */
4763 } type;
4764 const char *cmdline;
4765 TAILQ_ENTRY(device_config) next;
4767 TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4769 static void add_device_config(int type, const char *cmdline)
4771 struct device_config *conf;
4773 conf = qemu_mallocz(sizeof(*conf));
4774 conf->type = type;
4775 conf->cmdline = cmdline;
4776 TAILQ_INSERT_TAIL(&device_configs, conf, next);
4779 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4781 struct device_config *conf;
4782 int rc;
4784 TAILQ_FOREACH(conf, &device_configs, next) {
4785 if (conf->type != type)
4786 continue;
4787 rc = func(conf->cmdline);
4788 if (0 != rc)
4789 return rc;
4791 return 0;
4794 static int generic_parse(const char *cmdline)
4796 DeviceState *dev;
4798 dev = qdev_device_add(cmdline);
4799 if (!dev)
4800 return -1;
4801 return 0;
4804 int main(int argc, char **argv, char **envp)
4806 const char *gdbstub_dev = NULL;
4807 uint32_t boot_devices_bitmap = 0;
4808 int i;
4809 int snapshot, linux_boot, net_boot;
4810 const char *initrd_filename;
4811 const char *kernel_filename, *kernel_cmdline;
4812 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4813 DisplayState *ds;
4814 DisplayChangeListener *dcl;
4815 int cyls, heads, secs, translation;
4816 const char *net_clients[MAX_NET_CLIENTS];
4817 int nb_net_clients;
4818 DriveOpt *dopt, *hda_opt = NULL;
4819 int optind;
4820 const char *r, *optarg;
4821 CharDriverState *monitor_hd = NULL;
4822 const char *monitor_device;
4823 const char *serial_devices[MAX_SERIAL_PORTS];
4824 int serial_device_index;
4825 const char *parallel_devices[MAX_PARALLEL_PORTS];
4826 int parallel_device_index;
4827 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4828 int virtio_console_index;
4829 const char *loadvm = NULL;
4830 QEMUMachine *machine;
4831 const char *cpu_model;
4832 #ifndef _WIN32
4833 int fds[2];
4834 #endif
4835 int tb_size;
4836 const char *pid_file = NULL;
4837 const char *incoming = NULL;
4838 #ifndef _WIN32
4839 int fd = 0;
4840 struct passwd *pwd = NULL;
4841 const char *chroot_dir = NULL;
4842 const char *run_as = NULL;
4843 #endif
4844 CPUState *env;
4845 int show_vnc_port = 0;
4847 qemu_cache_utils_init(envp);
4849 LIST_INIT (&vm_change_state_head);
4850 #ifndef _WIN32
4852 struct sigaction act;
4853 sigfillset(&act.sa_mask);
4854 act.sa_flags = 0;
4855 act.sa_handler = SIG_IGN;
4856 sigaction(SIGPIPE, &act, NULL);
4858 #else
4859 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4860 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4861 QEMU to run on a single CPU */
4863 HANDLE h;
4864 DWORD mask, smask;
4865 int i;
4866 h = GetCurrentProcess();
4867 if (GetProcessAffinityMask(h, &mask, &smask)) {
4868 for(i = 0; i < 32; i++) {
4869 if (mask & (1 << i))
4870 break;
4872 if (i != 32) {
4873 mask = 1 << i;
4874 SetProcessAffinityMask(h, mask);
4878 #endif
4880 module_call_init(MODULE_INIT_MACHINE);
4881 machine = find_default_machine();
4882 cpu_model = NULL;
4883 initrd_filename = NULL;
4884 ram_size = 0;
4885 snapshot = 0;
4886 kernel_filename = NULL;
4887 kernel_cmdline = "";
4888 cyls = heads = secs = 0;
4889 translation = BIOS_ATA_TRANSLATION_AUTO;
4890 monitor_device = "vc:80Cx24C";
4892 serial_devices[0] = "vc:80Cx24C";
4893 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4894 serial_devices[i] = NULL;
4895 serial_device_index = 0;
4897 parallel_devices[0] = "vc:80Cx24C";
4898 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4899 parallel_devices[i] = NULL;
4900 parallel_device_index = 0;
4902 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4903 virtio_consoles[i] = NULL;
4904 virtio_console_index = 0;
4906 for (i = 0; i < MAX_NODES; i++) {
4907 node_mem[i] = 0;
4908 node_cpumask[i] = 0;
4911 nb_net_clients = 0;
4912 nb_numa_nodes = 0;
4913 nb_nics = 0;
4915 tb_size = 0;
4916 autostart= 1;
4918 register_watchdogs();
4920 optind = 1;
4921 for(;;) {
4922 if (optind >= argc)
4923 break;
4924 r = argv[optind];
4925 if (r[0] != '-') {
4926 hda_opt = drive_add(argv[optind++], HD_ALIAS, 0);
4927 } else {
4928 const QEMUOption *popt;
4930 optind++;
4931 /* Treat --foo the same as -foo. */
4932 if (r[1] == '-')
4933 r++;
4934 popt = qemu_options;
4935 for(;;) {
4936 if (!popt->name) {
4937 fprintf(stderr, "%s: invalid option -- '%s'\n",
4938 argv[0], r);
4939 exit(1);
4941 if (!strcmp(popt->name, r + 1))
4942 break;
4943 popt++;
4945 if (popt->flags & HAS_ARG) {
4946 if (optind >= argc) {
4947 fprintf(stderr, "%s: option '%s' requires an argument\n",
4948 argv[0], r);
4949 exit(1);
4951 optarg = argv[optind++];
4952 } else {
4953 optarg = NULL;
4956 switch(popt->index) {
4957 case QEMU_OPTION_M:
4958 machine = find_machine(optarg);
4959 if (!machine) {
4960 QEMUMachine *m;
4961 printf("Supported machines are:\n");
4962 for(m = first_machine; m != NULL; m = m->next) {
4963 if (m->alias)
4964 printf("%-10s %s (alias of %s)\n",
4965 m->alias, m->desc, m->name);
4966 printf("%-10s %s%s\n",
4967 m->name, m->desc,
4968 m->is_default ? " (default)" : "");
4970 exit(*optarg != '?');
4972 break;
4973 case QEMU_OPTION_cpu:
4974 /* hw initialization will check this */
4975 if (*optarg == '?') {
4976 /* XXX: implement xxx_cpu_list for targets that still miss it */
4977 #if defined(cpu_list)
4978 cpu_list(stdout, &fprintf);
4979 #endif
4980 exit(0);
4981 } else {
4982 cpu_model = optarg;
4984 break;
4985 case QEMU_OPTION_initrd:
4986 initrd_filename = optarg;
4987 break;
4988 case QEMU_OPTION_hda:
4989 if (cyls == 0)
4990 hda_opt = drive_add(optarg, HD_ALIAS, 0);
4991 else
4992 hda_opt = drive_add(optarg, HD_ALIAS
4993 ",cyls=%d,heads=%d,secs=%d%s",
4994 0, cyls, heads, secs,
4995 translation == BIOS_ATA_TRANSLATION_LBA ?
4996 ",trans=lba" :
4997 translation == BIOS_ATA_TRANSLATION_NONE ?
4998 ",trans=none" : "");
4999 break;
5000 case QEMU_OPTION_hdb:
5001 case QEMU_OPTION_hdc:
5002 case QEMU_OPTION_hdd:
5003 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5004 break;
5005 case QEMU_OPTION_drive:
5006 drive_add(NULL, "%s", optarg);
5007 break;
5008 case QEMU_OPTION_mtdblock:
5009 drive_add(optarg, MTD_ALIAS);
5010 break;
5011 case QEMU_OPTION_sd:
5012 drive_add(optarg, SD_ALIAS);
5013 break;
5014 case QEMU_OPTION_pflash:
5015 drive_add(optarg, PFLASH_ALIAS);
5016 break;
5017 case QEMU_OPTION_snapshot:
5018 snapshot = 1;
5019 break;
5020 case QEMU_OPTION_hdachs:
5022 const char *p;
5023 p = optarg;
5024 cyls = strtol(p, (char **)&p, 0);
5025 if (cyls < 1 || cyls > 16383)
5026 goto chs_fail;
5027 if (*p != ',')
5028 goto chs_fail;
5029 p++;
5030 heads = strtol(p, (char **)&p, 0);
5031 if (heads < 1 || heads > 16)
5032 goto chs_fail;
5033 if (*p != ',')
5034 goto chs_fail;
5035 p++;
5036 secs = strtol(p, (char **)&p, 0);
5037 if (secs < 1 || secs > 63)
5038 goto chs_fail;
5039 if (*p == ',') {
5040 p++;
5041 if (!strcmp(p, "none"))
5042 translation = BIOS_ATA_TRANSLATION_NONE;
5043 else if (!strcmp(p, "lba"))
5044 translation = BIOS_ATA_TRANSLATION_LBA;
5045 else if (!strcmp(p, "auto"))
5046 translation = BIOS_ATA_TRANSLATION_AUTO;
5047 else
5048 goto chs_fail;
5049 } else if (*p != '\0') {
5050 chs_fail:
5051 fprintf(stderr, "qemu: invalid physical CHS format\n");
5052 exit(1);
5054 if (hda_opt != NULL)
5055 snprintf(hda_opt->opt,
5056 sizeof(hda_opt->opt),
5057 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5058 0, cyls, heads, secs,
5059 translation == BIOS_ATA_TRANSLATION_LBA ?
5060 ",trans=lba" :
5061 translation == BIOS_ATA_TRANSLATION_NONE ?
5062 ",trans=none" : "");
5064 break;
5065 case QEMU_OPTION_numa:
5066 if (nb_numa_nodes >= MAX_NODES) {
5067 fprintf(stderr, "qemu: too many NUMA nodes\n");
5068 exit(1);
5070 numa_add(optarg);
5071 break;
5072 case QEMU_OPTION_nographic:
5073 display_type = DT_NOGRAPHIC;
5074 break;
5075 #ifdef CONFIG_CURSES
5076 case QEMU_OPTION_curses:
5077 display_type = DT_CURSES;
5078 break;
5079 #endif
5080 case QEMU_OPTION_portrait:
5081 graphic_rotate = 1;
5082 break;
5083 case QEMU_OPTION_kernel:
5084 kernel_filename = optarg;
5085 break;
5086 case QEMU_OPTION_append:
5087 kernel_cmdline = optarg;
5088 break;
5089 case QEMU_OPTION_cdrom:
5090 drive_add(optarg, CDROM_ALIAS);
5091 break;
5092 case QEMU_OPTION_boot:
5094 static const char * const params[] = {
5095 "order", "once", "menu", NULL
5097 char buf[sizeof(boot_devices)];
5098 char *standard_boot_devices;
5099 int legacy = 0;
5101 if (!strchr(optarg, '=')) {
5102 legacy = 1;
5103 pstrcpy(buf, sizeof(buf), optarg);
5104 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5105 fprintf(stderr,
5106 "qemu: unknown boot parameter '%s' in '%s'\n",
5107 buf, optarg);
5108 exit(1);
5111 if (legacy ||
5112 get_param_value(buf, sizeof(buf), "order", optarg)) {
5113 boot_devices_bitmap = parse_bootdevices(buf);
5114 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5116 if (!legacy) {
5117 if (get_param_value(buf, sizeof(buf),
5118 "once", optarg)) {
5119 boot_devices_bitmap |= parse_bootdevices(buf);
5120 standard_boot_devices = qemu_strdup(boot_devices);
5121 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5122 qemu_register_reset(restore_boot_devices,
5123 standard_boot_devices);
5125 if (get_param_value(buf, sizeof(buf),
5126 "menu", optarg)) {
5127 if (!strcmp(buf, "on")) {
5128 boot_menu = 1;
5129 } else if (!strcmp(buf, "off")) {
5130 boot_menu = 0;
5131 } else {
5132 fprintf(stderr,
5133 "qemu: invalid option value '%s'\n",
5134 buf);
5135 exit(1);
5140 break;
5141 case QEMU_OPTION_fda:
5142 case QEMU_OPTION_fdb:
5143 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5144 break;
5145 #ifdef TARGET_I386
5146 case QEMU_OPTION_no_fd_bootchk:
5147 fd_bootchk = 0;
5148 break;
5149 #endif
5150 case QEMU_OPTION_net:
5151 if (nb_net_clients >= MAX_NET_CLIENTS) {
5152 fprintf(stderr, "qemu: too many network clients\n");
5153 exit(1);
5155 net_clients[nb_net_clients] = optarg;
5156 nb_net_clients++;
5157 break;
5158 #ifdef CONFIG_SLIRP
5159 case QEMU_OPTION_tftp:
5160 legacy_tftp_prefix = optarg;
5161 break;
5162 case QEMU_OPTION_bootp:
5163 legacy_bootp_filename = optarg;
5164 break;
5165 #ifndef _WIN32
5166 case QEMU_OPTION_smb:
5167 net_slirp_smb(optarg);
5168 break;
5169 #endif
5170 case QEMU_OPTION_redir:
5171 net_slirp_redir(optarg);
5172 break;
5173 #endif
5174 case QEMU_OPTION_bt:
5175 add_device_config(DEV_BT, optarg);
5176 break;
5177 #ifdef HAS_AUDIO
5178 case QEMU_OPTION_audio_help:
5179 AUD_help ();
5180 exit (0);
5181 break;
5182 case QEMU_OPTION_soundhw:
5183 select_soundhw (optarg);
5184 break;
5185 #endif
5186 case QEMU_OPTION_h:
5187 help(0);
5188 break;
5189 case QEMU_OPTION_version:
5190 version();
5191 exit(0);
5192 break;
5193 case QEMU_OPTION_m: {
5194 uint64_t value;
5195 char *ptr;
5197 value = strtoul(optarg, &ptr, 10);
5198 switch (*ptr) {
5199 case 0: case 'M': case 'm':
5200 value <<= 20;
5201 break;
5202 case 'G': case 'g':
5203 value <<= 30;
5204 break;
5205 default:
5206 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5207 exit(1);
5210 /* On 32-bit hosts, QEMU is limited by virtual address space */
5211 if (value > (2047 << 20)
5212 #ifndef CONFIG_KQEMU
5213 && HOST_LONG_BITS == 32
5214 #endif
5216 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5217 exit(1);
5219 if (value != (uint64_t)(ram_addr_t)value) {
5220 fprintf(stderr, "qemu: ram size too large\n");
5221 exit(1);
5223 ram_size = value;
5224 break;
5226 case QEMU_OPTION_d:
5228 int mask;
5229 const CPULogItem *item;
5231 mask = cpu_str_to_log_mask(optarg);
5232 if (!mask) {
5233 printf("Log items (comma separated):\n");
5234 for(item = cpu_log_items; item->mask != 0; item++) {
5235 printf("%-10s %s\n", item->name, item->help);
5237 exit(1);
5239 cpu_set_log(mask);
5241 break;
5242 case QEMU_OPTION_s:
5243 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5244 break;
5245 case QEMU_OPTION_gdb:
5246 gdbstub_dev = optarg;
5247 break;
5248 case QEMU_OPTION_L:
5249 data_dir = optarg;
5250 break;
5251 case QEMU_OPTION_bios:
5252 bios_name = optarg;
5253 break;
5254 case QEMU_OPTION_singlestep:
5255 singlestep = 1;
5256 break;
5257 case QEMU_OPTION_S:
5258 autostart = 0;
5259 break;
5260 #ifndef _WIN32
5261 case QEMU_OPTION_k:
5262 keyboard_layout = optarg;
5263 break;
5264 #endif
5265 case QEMU_OPTION_localtime:
5266 rtc_utc = 0;
5267 break;
5268 case QEMU_OPTION_vga:
5269 select_vgahw (optarg);
5270 break;
5271 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5272 case QEMU_OPTION_g:
5274 const char *p;
5275 int w, h, depth;
5276 p = optarg;
5277 w = strtol(p, (char **)&p, 10);
5278 if (w <= 0) {
5279 graphic_error:
5280 fprintf(stderr, "qemu: invalid resolution or depth\n");
5281 exit(1);
5283 if (*p != 'x')
5284 goto graphic_error;
5285 p++;
5286 h = strtol(p, (char **)&p, 10);
5287 if (h <= 0)
5288 goto graphic_error;
5289 if (*p == 'x') {
5290 p++;
5291 depth = strtol(p, (char **)&p, 10);
5292 if (depth != 8 && depth != 15 && depth != 16 &&
5293 depth != 24 && depth != 32)
5294 goto graphic_error;
5295 } else if (*p == '\0') {
5296 depth = graphic_depth;
5297 } else {
5298 goto graphic_error;
5301 graphic_width = w;
5302 graphic_height = h;
5303 graphic_depth = depth;
5305 break;
5306 #endif
5307 case QEMU_OPTION_echr:
5309 char *r;
5310 term_escape_char = strtol(optarg, &r, 0);
5311 if (r == optarg)
5312 printf("Bad argument to echr\n");
5313 break;
5315 case QEMU_OPTION_monitor:
5316 monitor_device = optarg;
5317 break;
5318 case QEMU_OPTION_serial:
5319 if (serial_device_index >= MAX_SERIAL_PORTS) {
5320 fprintf(stderr, "qemu: too many serial ports\n");
5321 exit(1);
5323 serial_devices[serial_device_index] = optarg;
5324 serial_device_index++;
5325 break;
5326 case QEMU_OPTION_watchdog:
5327 i = select_watchdog(optarg);
5328 if (i > 0)
5329 exit (i == 1 ? 1 : 0);
5330 break;
5331 case QEMU_OPTION_watchdog_action:
5332 if (select_watchdog_action(optarg) == -1) {
5333 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5334 exit(1);
5336 break;
5337 case QEMU_OPTION_virtiocon:
5338 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5339 fprintf(stderr, "qemu: too many virtio consoles\n");
5340 exit(1);
5342 virtio_consoles[virtio_console_index] = optarg;
5343 virtio_console_index++;
5344 break;
5345 case QEMU_OPTION_parallel:
5346 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5347 fprintf(stderr, "qemu: too many parallel ports\n");
5348 exit(1);
5350 parallel_devices[parallel_device_index] = optarg;
5351 parallel_device_index++;
5352 break;
5353 case QEMU_OPTION_loadvm:
5354 loadvm = optarg;
5355 break;
5356 case QEMU_OPTION_full_screen:
5357 full_screen = 1;
5358 break;
5359 #ifdef CONFIG_SDL
5360 case QEMU_OPTION_no_frame:
5361 no_frame = 1;
5362 break;
5363 case QEMU_OPTION_alt_grab:
5364 alt_grab = 1;
5365 break;
5366 case QEMU_OPTION_no_quit:
5367 no_quit = 1;
5368 break;
5369 case QEMU_OPTION_sdl:
5370 display_type = DT_SDL;
5371 break;
5372 #endif
5373 case QEMU_OPTION_pidfile:
5374 pid_file = optarg;
5375 break;
5376 #ifdef TARGET_I386
5377 case QEMU_OPTION_win2k_hack:
5378 win2k_install_hack = 1;
5379 break;
5380 case QEMU_OPTION_rtc_td_hack:
5381 rtc_td_hack = 1;
5382 break;
5383 case QEMU_OPTION_acpitable:
5384 if(acpi_table_add(optarg) < 0) {
5385 fprintf(stderr, "Wrong acpi table provided\n");
5386 exit(1);
5388 break;
5389 case QEMU_OPTION_smbios:
5390 if(smbios_entry_add(optarg) < 0) {
5391 fprintf(stderr, "Wrong smbios provided\n");
5392 exit(1);
5394 break;
5395 #endif
5396 #ifdef CONFIG_KQEMU
5397 case QEMU_OPTION_enable_kqemu:
5398 kqemu_allowed = 1;
5399 break;
5400 case QEMU_OPTION_kernel_kqemu:
5401 kqemu_allowed = 2;
5402 break;
5403 #endif
5404 #ifdef CONFIG_KVM
5405 case QEMU_OPTION_enable_kvm:
5406 kvm_allowed = 1;
5407 #ifdef CONFIG_KQEMU
5408 kqemu_allowed = 0;
5409 #endif
5410 break;
5411 #endif
5412 case QEMU_OPTION_usb:
5413 usb_enabled = 1;
5414 break;
5415 case QEMU_OPTION_usbdevice:
5416 usb_enabled = 1;
5417 add_device_config(DEV_USB, optarg);
5418 break;
5419 case QEMU_OPTION_device:
5420 add_device_config(DEV_GENERIC, optarg);
5421 break;
5422 case QEMU_OPTION_smp:
5423 smp_cpus = atoi(optarg);
5424 if (smp_cpus < 1) {
5425 fprintf(stderr, "Invalid number of CPUs\n");
5426 exit(1);
5428 break;
5429 case QEMU_OPTION_vnc:
5430 display_type = DT_VNC;
5431 vnc_display = optarg;
5432 break;
5433 #ifdef TARGET_I386
5434 case QEMU_OPTION_no_acpi:
5435 acpi_enabled = 0;
5436 break;
5437 case QEMU_OPTION_no_hpet:
5438 no_hpet = 1;
5439 break;
5440 case QEMU_OPTION_balloon:
5441 if (balloon_parse(optarg) < 0) {
5442 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5443 exit(1);
5445 break;
5446 #endif
5447 case QEMU_OPTION_no_reboot:
5448 no_reboot = 1;
5449 break;
5450 case QEMU_OPTION_no_shutdown:
5451 no_shutdown = 1;
5452 break;
5453 case QEMU_OPTION_show_cursor:
5454 cursor_hide = 0;
5455 break;
5456 case QEMU_OPTION_uuid:
5457 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5458 fprintf(stderr, "Fail to parse UUID string."
5459 " Wrong format.\n");
5460 exit(1);
5462 break;
5463 #ifndef _WIN32
5464 case QEMU_OPTION_daemonize:
5465 daemonize = 1;
5466 break;
5467 #endif
5468 case QEMU_OPTION_option_rom:
5469 if (nb_option_roms >= MAX_OPTION_ROMS) {
5470 fprintf(stderr, "Too many option ROMs\n");
5471 exit(1);
5473 option_rom[nb_option_roms] = optarg;
5474 nb_option_roms++;
5475 break;
5476 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5477 case QEMU_OPTION_semihosting:
5478 semihosting_enabled = 1;
5479 break;
5480 #endif
5481 case QEMU_OPTION_name:
5482 qemu_name = qemu_strdup(optarg);
5484 char *p = strchr(qemu_name, ',');
5485 if (p != NULL) {
5486 *p++ = 0;
5487 if (strncmp(p, "process=", 8)) {
5488 fprintf(stderr, "Unknown subargument %s to -name", p);
5489 exit(1);
5491 p += 8;
5492 set_proc_name(p);
5495 break;
5496 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5497 case QEMU_OPTION_prom_env:
5498 if (nb_prom_envs >= MAX_PROM_ENVS) {
5499 fprintf(stderr, "Too many prom variables\n");
5500 exit(1);
5502 prom_envs[nb_prom_envs] = optarg;
5503 nb_prom_envs++;
5504 break;
5505 #endif
5506 #ifdef TARGET_ARM
5507 case QEMU_OPTION_old_param:
5508 old_param = 1;
5509 break;
5510 #endif
5511 case QEMU_OPTION_clock:
5512 configure_alarms(optarg);
5513 break;
5514 case QEMU_OPTION_startdate:
5516 struct tm tm;
5517 time_t rtc_start_date;
5518 if (!strcmp(optarg, "now")) {
5519 rtc_date_offset = -1;
5520 } else {
5521 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5522 &tm.tm_year,
5523 &tm.tm_mon,
5524 &tm.tm_mday,
5525 &tm.tm_hour,
5526 &tm.tm_min,
5527 &tm.tm_sec) == 6) {
5528 /* OK */
5529 } else if (sscanf(optarg, "%d-%d-%d",
5530 &tm.tm_year,
5531 &tm.tm_mon,
5532 &tm.tm_mday) == 3) {
5533 tm.tm_hour = 0;
5534 tm.tm_min = 0;
5535 tm.tm_sec = 0;
5536 } else {
5537 goto date_fail;
5539 tm.tm_year -= 1900;
5540 tm.tm_mon--;
5541 rtc_start_date = mktimegm(&tm);
5542 if (rtc_start_date == -1) {
5543 date_fail:
5544 fprintf(stderr, "Invalid date format. Valid format are:\n"
5545 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5546 exit(1);
5548 rtc_date_offset = time(NULL) - rtc_start_date;
5551 break;
5552 case QEMU_OPTION_tb_size:
5553 tb_size = strtol(optarg, NULL, 0);
5554 if (tb_size < 0)
5555 tb_size = 0;
5556 break;
5557 case QEMU_OPTION_icount:
5558 use_icount = 1;
5559 if (strcmp(optarg, "auto") == 0) {
5560 icount_time_shift = -1;
5561 } else {
5562 icount_time_shift = strtol(optarg, NULL, 0);
5564 break;
5565 case QEMU_OPTION_incoming:
5566 incoming = optarg;
5567 break;
5568 #ifndef _WIN32
5569 case QEMU_OPTION_chroot:
5570 chroot_dir = optarg;
5571 break;
5572 case QEMU_OPTION_runas:
5573 run_as = optarg;
5574 break;
5575 #endif
5576 #ifdef CONFIG_XEN
5577 case QEMU_OPTION_xen_domid:
5578 xen_domid = atoi(optarg);
5579 break;
5580 case QEMU_OPTION_xen_create:
5581 xen_mode = XEN_CREATE;
5582 break;
5583 case QEMU_OPTION_xen_attach:
5584 xen_mode = XEN_ATTACH;
5585 break;
5586 #endif
5591 /* If no data_dir is specified then try to find it relative to the
5592 executable path. */
5593 if (!data_dir) {
5594 data_dir = find_datadir(argv[0]);
5596 /* If all else fails use the install patch specified when building. */
5597 if (!data_dir) {
5598 data_dir = CONFIG_QEMU_SHAREDIR;
5601 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5602 if (kvm_allowed && kqemu_allowed) {
5603 fprintf(stderr,
5604 "You can not enable both KVM and kqemu at the same time\n");
5605 exit(1);
5607 #endif
5609 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5610 if (smp_cpus > machine->max_cpus) {
5611 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5612 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5613 machine->max_cpus);
5614 exit(1);
5617 if (display_type == DT_NOGRAPHIC) {
5618 if (serial_device_index == 0)
5619 serial_devices[0] = "stdio";
5620 if (parallel_device_index == 0)
5621 parallel_devices[0] = "null";
5622 if (strncmp(monitor_device, "vc", 2) == 0)
5623 monitor_device = "stdio";
5626 #ifndef _WIN32
5627 if (daemonize) {
5628 pid_t pid;
5630 if (pipe(fds) == -1)
5631 exit(1);
5633 pid = fork();
5634 if (pid > 0) {
5635 uint8_t status;
5636 ssize_t len;
5638 close(fds[1]);
5640 again:
5641 len = read(fds[0], &status, 1);
5642 if (len == -1 && (errno == EINTR))
5643 goto again;
5645 if (len != 1)
5646 exit(1);
5647 else if (status == 1) {
5648 fprintf(stderr, "Could not acquire pidfile\n");
5649 exit(1);
5650 } else
5651 exit(0);
5652 } else if (pid < 0)
5653 exit(1);
5655 setsid();
5657 pid = fork();
5658 if (pid > 0)
5659 exit(0);
5660 else if (pid < 0)
5661 exit(1);
5663 umask(027);
5665 signal(SIGTSTP, SIG_IGN);
5666 signal(SIGTTOU, SIG_IGN);
5667 signal(SIGTTIN, SIG_IGN);
5670 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5671 if (daemonize) {
5672 uint8_t status = 1;
5673 write(fds[1], &status, 1);
5674 } else
5675 fprintf(stderr, "Could not acquire pid file\n");
5676 exit(1);
5678 #endif
5680 #ifdef CONFIG_KQEMU
5681 if (smp_cpus > 1)
5682 kqemu_allowed = 0;
5683 #endif
5684 if (qemu_init_main_loop()) {
5685 fprintf(stderr, "qemu_init_main_loop failed\n");
5686 exit(1);
5688 linux_boot = (kernel_filename != NULL);
5690 if (!linux_boot && *kernel_cmdline != '\0') {
5691 fprintf(stderr, "-append only allowed with -kernel option\n");
5692 exit(1);
5695 if (!linux_boot && initrd_filename != NULL) {
5696 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5697 exit(1);
5700 setvbuf(stdout, NULL, _IOLBF, 0);
5702 init_timers();
5703 if (init_timer_alarm() < 0) {
5704 fprintf(stderr, "could not initialize alarm timer\n");
5705 exit(1);
5707 if (use_icount && icount_time_shift < 0) {
5708 use_icount = 2;
5709 /* 125MIPS seems a reasonable initial guess at the guest speed.
5710 It will be corrected fairly quickly anyway. */
5711 icount_time_shift = 3;
5712 init_icount_adjust();
5715 #ifdef _WIN32
5716 socket_init();
5717 #endif
5719 /* init network clients */
5720 if (nb_net_clients == 0) {
5721 /* if no clients, we use a default config */
5722 net_clients[nb_net_clients++] = "nic";
5723 #ifdef CONFIG_SLIRP
5724 net_clients[nb_net_clients++] = "user";
5725 #endif
5728 for(i = 0;i < nb_net_clients; i++) {
5729 if (net_client_parse(net_clients[i]) < 0)
5730 exit(1);
5733 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5734 net_set_boot_mask(net_boot);
5736 net_client_check();
5738 /* init the bluetooth world */
5739 if (foreach_device_config(DEV_BT, bt_parse))
5740 exit(1);
5742 /* init the memory */
5743 if (ram_size == 0)
5744 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5746 #ifdef CONFIG_KQEMU
5747 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5748 guest ram allocation. It needs to go away. */
5749 if (kqemu_allowed) {
5750 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5751 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5752 if (!kqemu_phys_ram_base) {
5753 fprintf(stderr, "Could not allocate physical memory\n");
5754 exit(1);
5757 #endif
5759 /* init the dynamic translator */
5760 cpu_exec_init_all(tb_size * 1024 * 1024);
5762 bdrv_init();
5764 /* we always create the cdrom drive, even if no disk is there */
5765 drive_add(NULL, CDROM_ALIAS);
5767 /* we always create at least one floppy */
5768 drive_add(NULL, FD_ALIAS, 0);
5770 /* we always create one sd slot, even if no card is in it */
5771 drive_add(NULL, SD_ALIAS);
5773 /* open the virtual block devices */
5775 TAILQ_FOREACH(dopt, &driveopts, next) {
5776 int fatal_error;
5777 if (drive_init(dopt, snapshot, machine, &fatal_error) == NULL)
5778 if (fatal_error)
5779 exit(1);
5782 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5783 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5785 #ifndef _WIN32
5786 /* must be after terminal init, SDL library changes signal handlers */
5787 sighandler_setup();
5788 #endif
5790 /* Maintain compatibility with multiple stdio monitors */
5791 if (!strcmp(monitor_device,"stdio")) {
5792 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5793 const char *devname = serial_devices[i];
5794 if (devname && !strcmp(devname,"mon:stdio")) {
5795 monitor_device = NULL;
5796 break;
5797 } else if (devname && !strcmp(devname,"stdio")) {
5798 monitor_device = NULL;
5799 serial_devices[i] = "mon:stdio";
5800 break;
5805 if (nb_numa_nodes > 0) {
5806 int i;
5808 if (nb_numa_nodes > smp_cpus) {
5809 nb_numa_nodes = smp_cpus;
5812 /* If no memory size if given for any node, assume the default case
5813 * and distribute the available memory equally across all nodes
5815 for (i = 0; i < nb_numa_nodes; i++) {
5816 if (node_mem[i] != 0)
5817 break;
5819 if (i == nb_numa_nodes) {
5820 uint64_t usedmem = 0;
5822 /* On Linux, the each node's border has to be 8MB aligned,
5823 * the final node gets the rest.
5825 for (i = 0; i < nb_numa_nodes - 1; i++) {
5826 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5827 usedmem += node_mem[i];
5829 node_mem[i] = ram_size - usedmem;
5832 for (i = 0; i < nb_numa_nodes; i++) {
5833 if (node_cpumask[i] != 0)
5834 break;
5836 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5837 * must cope with this anyway, because there are BIOSes out there in
5838 * real machines which also use this scheme.
5840 if (i == nb_numa_nodes) {
5841 for (i = 0; i < smp_cpus; i++) {
5842 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5847 if (kvm_enabled()) {
5848 int ret;
5850 ret = kvm_init(smp_cpus);
5851 if (ret < 0) {
5852 fprintf(stderr, "failed to initialize KVM\n");
5853 exit(1);
5857 if (monitor_device) {
5858 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5859 if (!monitor_hd) {
5860 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5861 exit(1);
5865 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5866 const char *devname = serial_devices[i];
5867 if (devname && strcmp(devname, "none")) {
5868 char label[32];
5869 snprintf(label, sizeof(label), "serial%d", i);
5870 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5871 if (!serial_hds[i]) {
5872 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5873 devname);
5874 exit(1);
5879 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5880 const char *devname = parallel_devices[i];
5881 if (devname && strcmp(devname, "none")) {
5882 char label[32];
5883 snprintf(label, sizeof(label), "parallel%d", i);
5884 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5885 if (!parallel_hds[i]) {
5886 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5887 devname);
5888 exit(1);
5893 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5894 const char *devname = virtio_consoles[i];
5895 if (devname && strcmp(devname, "none")) {
5896 char label[32];
5897 snprintf(label, sizeof(label), "virtcon%d", i);
5898 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5899 if (!virtcon_hds[i]) {
5900 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5901 devname);
5902 exit(1);
5907 module_call_init(MODULE_INIT_DEVICE);
5909 if (machine->compat_props) {
5910 qdev_prop_register_compat(machine->compat_props);
5912 machine->init(ram_size, boot_devices,
5913 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5916 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5917 for (i = 0; i < nb_numa_nodes; i++) {
5918 if (node_cpumask[i] & (1 << env->cpu_index)) {
5919 env->numa_node = i;
5924 current_machine = machine;
5926 /* init USB devices */
5927 if (usb_enabled) {
5928 foreach_device_config(DEV_USB, usb_parse);
5931 /* init generic devices */
5932 if (foreach_device_config(DEV_GENERIC, generic_parse))
5933 exit(1);
5935 if (!display_state)
5936 dumb_display_init();
5937 /* just use the first displaystate for the moment */
5938 ds = display_state;
5940 if (display_type == DT_DEFAULT) {
5941 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5942 display_type = DT_SDL;
5943 #else
5944 display_type = DT_VNC;
5945 vnc_display = "localhost:0,to=99";
5946 show_vnc_port = 1;
5947 #endif
5951 switch (display_type) {
5952 case DT_NOGRAPHIC:
5953 break;
5954 #if defined(CONFIG_CURSES)
5955 case DT_CURSES:
5956 curses_display_init(ds, full_screen);
5957 break;
5958 #endif
5959 #if defined(CONFIG_SDL)
5960 case DT_SDL:
5961 sdl_display_init(ds, full_screen, no_frame);
5962 break;
5963 #elif defined(CONFIG_COCOA)
5964 case DT_SDL:
5965 cocoa_display_init(ds, full_screen);
5966 break;
5967 #endif
5968 case DT_VNC:
5969 vnc_display_init(ds);
5970 if (vnc_display_open(ds, vnc_display) < 0)
5971 exit(1);
5973 if (show_vnc_port) {
5974 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5976 break;
5977 default:
5978 break;
5980 dpy_resize(ds);
5982 dcl = ds->listeners;
5983 while (dcl != NULL) {
5984 if (dcl->dpy_refresh != NULL) {
5985 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5986 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5988 dcl = dcl->next;
5991 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5992 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5993 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5996 text_consoles_set_display(display_state);
5997 qemu_chr_initial_reset();
5999 if (monitor_device && monitor_hd)
6000 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6002 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6003 const char *devname = serial_devices[i];
6004 if (devname && strcmp(devname, "none")) {
6005 if (strstart(devname, "vc", 0))
6006 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6010 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6011 const char *devname = parallel_devices[i];
6012 if (devname && strcmp(devname, "none")) {
6013 if (strstart(devname, "vc", 0))
6014 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6018 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6019 const char *devname = virtio_consoles[i];
6020 if (virtcon_hds[i] && devname) {
6021 if (strstart(devname, "vc", 0))
6022 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6026 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6027 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6028 gdbstub_dev);
6029 exit(1);
6032 if (loadvm)
6033 do_loadvm(cur_mon, loadvm);
6035 if (incoming)
6036 qemu_start_incoming_migration(incoming);
6038 if (autostart)
6039 vm_start();
6041 #ifndef _WIN32
6042 if (daemonize) {
6043 uint8_t status = 0;
6044 ssize_t len;
6046 again1:
6047 len = write(fds[1], &status, 1);
6048 if (len == -1 && (errno == EINTR))
6049 goto again1;
6051 if (len != 1)
6052 exit(1);
6054 chdir("/");
6055 TFR(fd = open("/dev/null", O_RDWR));
6056 if (fd == -1)
6057 exit(1);
6060 if (run_as) {
6061 pwd = getpwnam(run_as);
6062 if (!pwd) {
6063 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6064 exit(1);
6068 if (chroot_dir) {
6069 if (chroot(chroot_dir) < 0) {
6070 fprintf(stderr, "chroot failed\n");
6071 exit(1);
6073 chdir("/");
6076 if (run_as) {
6077 if (setgid(pwd->pw_gid) < 0) {
6078 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6079 exit(1);
6081 if (setuid(pwd->pw_uid) < 0) {
6082 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6083 exit(1);
6085 if (setuid(0) != -1) {
6086 fprintf(stderr, "Dropping privileges failed\n");
6087 exit(1);
6091 if (daemonize) {
6092 dup2(fd, 0);
6093 dup2(fd, 1);
6094 dup2(fd, 2);
6096 close(fd);
6098 #endif
6100 main_loop();
6101 quit_timers();
6102 net_cleanup();
6104 return 0;