timers: Createt TimersState and put all timers state there
[qemu.git] / vl.c
blob86cba18e7787c5cedbc5576f646bf0f022e4efe9
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
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 CONFIG_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 <mmsystem.h>
112 #endif
114 #ifdef CONFIG_SDL
115 #if defined(__APPLE__) || defined(main)
116 #include <SDL.h>
117 int qemu_main(int argc, char **argv, char **envp);
118 int main(int argc, char **argv)
120 return qemu_main(argc, argv, NULL);
122 #undef main
123 #define main qemu_main
124 #endif
125 #endif /* CONFIG_SDL */
127 #ifdef CONFIG_COCOA
128 #undef main
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
132 #include "hw/hw.h"
133 #include "hw/boards.h"
134 #include "hw/usb.h"
135 #include "hw/pcmcia.h"
136 #include "hw/pc.h"
137 #include "hw/audiodev.h"
138 #include "hw/isa.h"
139 #include "hw/baum.h"
140 #include "hw/bt.h"
141 #include "hw/watchdog.h"
142 #include "hw/smbios.h"
143 #include "hw/xen.h"
144 #include "hw/qdev.h"
145 #include "bt-host.h"
146 #include "net.h"
147 #include "monitor.h"
148 #include "console.h"
149 #include "sysemu.h"
150 #include "gdbstub.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
154 #include "block.h"
155 #include "dma.h"
156 #include "audio/audio.h"
157 #include "migration.h"
158 #include "kvm.h"
159 #include "balloon.h"
160 #include "qemu-option.h"
161 #include "qemu-config.h"
163 #include "disas.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #include "slirp/libslirp.h"
171 //#define DEBUG_NET
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 /* Maximum number of monitor devices */
177 #define MAX_MONITOR_DEVICES 10
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 ram_addr_t ram_size;
190 int nb_nics;
191 NICInfo nd_table[MAX_NICS];
192 int vm_running;
193 int autostart;
194 static int rtc_utc = 1;
195 static int rtc_date_offset = -1; /* -1 means no change */
196 int vga_interface_type = VGA_CIRRUS;
197 #ifdef TARGET_SPARC
198 int graphic_width = 1024;
199 int graphic_height = 768;
200 int graphic_depth = 8;
201 #else
202 int graphic_width = 800;
203 int graphic_height = 600;
204 int graphic_depth = 15;
205 #endif
206 static int full_screen = 0;
207 #ifdef CONFIG_SDL
208 static int no_frame = 0;
209 #endif
210 int no_quit = 0;
211 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
212 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
213 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
214 #ifdef TARGET_I386
215 int win2k_install_hack = 0;
216 int rtc_td_hack = 0;
217 #endif
218 int usb_enabled = 0;
219 int singlestep = 0;
220 int smp_cpus = 1;
221 int max_cpus = 0;
222 int smp_cores = 1;
223 int smp_threads = 1;
224 const char *vnc_display;
225 int acpi_enabled = 1;
226 int no_hpet = 0;
227 int fd_bootchk = 1;
228 int no_reboot = 0;
229 int no_shutdown = 0;
230 int cursor_hide = 1;
231 int graphic_rotate = 0;
232 uint8_t irq0override = 1;
233 #ifndef _WIN32
234 int daemonize = 0;
235 #endif
236 const char *watchdog;
237 const char *option_rom[MAX_OPTION_ROMS];
238 int nb_option_roms;
239 int semihosting_enabled = 0;
240 #ifdef TARGET_ARM
241 int old_param = 0;
242 #endif
243 const char *qemu_name;
244 int alt_grab = 0;
245 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
246 unsigned int nb_prom_envs = 0;
247 const char *prom_envs[MAX_PROM_ENVS];
248 #endif
249 int boot_menu;
251 int nb_numa_nodes;
252 uint64_t node_mem[MAX_NODES];
253 uint64_t node_cpumask[MAX_NODES];
255 static CPUState *cur_cpu;
256 static CPUState *next_cpu;
257 static int timer_alarm_pending = 1;
258 /* Conversion factor from emulated instructions to virtual clock ticks. */
259 static int icount_time_shift;
260 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
261 #define MAX_ICOUNT_SHIFT 10
262 /* Compensate for varying guest execution speed. */
263 static int64_t qemu_icount_bias;
264 static QEMUTimer *icount_rt_timer;
265 static QEMUTimer *icount_vm_timer;
266 static QEMUTimer *nographic_timer;
268 uint8_t qemu_uuid[16];
270 static QEMUBootSetHandler *boot_set_handler;
271 static void *boot_set_opaque;
273 /***********************************************************/
274 /* x86 ISA bus support */
276 target_phys_addr_t isa_mem_base = 0;
277 PicState2 *isa_pic;
279 /***********************************************************/
280 void hw_error(const char *fmt, ...)
282 va_list ap;
283 CPUState *env;
285 va_start(ap, fmt);
286 fprintf(stderr, "qemu: hardware error: ");
287 vfprintf(stderr, fmt, ap);
288 fprintf(stderr, "\n");
289 for(env = first_cpu; env != NULL; env = env->next_cpu) {
290 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
291 #ifdef TARGET_I386
292 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
293 #else
294 cpu_dump_state(env, stderr, fprintf, 0);
295 #endif
297 va_end(ap);
298 abort();
301 static void set_proc_name(const char *s)
303 #if defined(__linux__) && defined(PR_SET_NAME)
304 char name[16];
305 if (!s)
306 return;
307 name[sizeof(name) - 1] = 0;
308 strncpy(name, s, sizeof(name));
309 /* Could rewrite argv[0] too, but that's a bit more complicated.
310 This simple way is enough for `top'. */
311 prctl(PR_SET_NAME, name);
312 #endif
315 /***************/
316 /* ballooning */
318 static QEMUBalloonEvent *qemu_balloon_event;
319 void *qemu_balloon_event_opaque;
321 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
323 qemu_balloon_event = func;
324 qemu_balloon_event_opaque = opaque;
327 void qemu_balloon(ram_addr_t target)
329 if (qemu_balloon_event)
330 qemu_balloon_event(qemu_balloon_event_opaque, target);
333 ram_addr_t qemu_balloon_status(void)
335 if (qemu_balloon_event)
336 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
337 return 0;
340 /***********************************************************/
341 /* keyboard/mouse */
343 static QEMUPutKBDEvent *qemu_put_kbd_event;
344 static void *qemu_put_kbd_event_opaque;
345 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
346 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
348 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
350 qemu_put_kbd_event_opaque = opaque;
351 qemu_put_kbd_event = func;
354 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
355 void *opaque, int absolute,
356 const char *name)
358 QEMUPutMouseEntry *s, *cursor;
360 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
362 s->qemu_put_mouse_event = func;
363 s->qemu_put_mouse_event_opaque = opaque;
364 s->qemu_put_mouse_event_absolute = absolute;
365 s->qemu_put_mouse_event_name = qemu_strdup(name);
366 s->next = NULL;
368 if (!qemu_put_mouse_event_head) {
369 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
370 return s;
373 cursor = qemu_put_mouse_event_head;
374 while (cursor->next != NULL)
375 cursor = cursor->next;
377 cursor->next = s;
378 qemu_put_mouse_event_current = s;
380 return s;
383 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
385 QEMUPutMouseEntry *prev = NULL, *cursor;
387 if (!qemu_put_mouse_event_head || entry == NULL)
388 return;
390 cursor = qemu_put_mouse_event_head;
391 while (cursor != NULL && cursor != entry) {
392 prev = cursor;
393 cursor = cursor->next;
396 if (cursor == NULL) // does not exist or list empty
397 return;
398 else if (prev == NULL) { // entry is head
399 qemu_put_mouse_event_head = cursor->next;
400 if (qemu_put_mouse_event_current == entry)
401 qemu_put_mouse_event_current = cursor->next;
402 qemu_free(entry->qemu_put_mouse_event_name);
403 qemu_free(entry);
404 return;
407 prev->next = entry->next;
409 if (qemu_put_mouse_event_current == entry)
410 qemu_put_mouse_event_current = prev;
412 qemu_free(entry->qemu_put_mouse_event_name);
413 qemu_free(entry);
416 void kbd_put_keycode(int keycode)
418 if (qemu_put_kbd_event) {
419 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
423 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
425 QEMUPutMouseEvent *mouse_event;
426 void *mouse_event_opaque;
427 int width;
429 if (!qemu_put_mouse_event_current) {
430 return;
433 mouse_event =
434 qemu_put_mouse_event_current->qemu_put_mouse_event;
435 mouse_event_opaque =
436 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
438 if (mouse_event) {
439 if (graphic_rotate) {
440 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
441 width = 0x7fff;
442 else
443 width = graphic_width - 1;
444 mouse_event(mouse_event_opaque,
445 width - dy, dx, dz, buttons_state);
446 } else
447 mouse_event(mouse_event_opaque,
448 dx, dy, dz, buttons_state);
452 int kbd_mouse_is_absolute(void)
454 if (!qemu_put_mouse_event_current)
455 return 0;
457 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
460 void do_info_mice(Monitor *mon)
462 QEMUPutMouseEntry *cursor;
463 int index = 0;
465 if (!qemu_put_mouse_event_head) {
466 monitor_printf(mon, "No mouse devices connected\n");
467 return;
470 monitor_printf(mon, "Mouse devices available:\n");
471 cursor = qemu_put_mouse_event_head;
472 while (cursor != NULL) {
473 monitor_printf(mon, "%c Mouse #%d: %s\n",
474 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
475 index, cursor->qemu_put_mouse_event_name);
476 index++;
477 cursor = cursor->next;
481 void do_mouse_set(Monitor *mon, const QDict *qdict)
483 QEMUPutMouseEntry *cursor;
484 int i = 0;
485 int index = qdict_get_int(qdict, "index");
487 if (!qemu_put_mouse_event_head) {
488 monitor_printf(mon, "No mouse devices connected\n");
489 return;
492 cursor = qemu_put_mouse_event_head;
493 while (cursor != NULL && index != i) {
494 i++;
495 cursor = cursor->next;
498 if (cursor != NULL)
499 qemu_put_mouse_event_current = cursor;
500 else
501 monitor_printf(mon, "Mouse at given index not found\n");
504 /* compute with 96 bit intermediate result: (a*b)/c */
505 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
507 union {
508 uint64_t ll;
509 struct {
510 #ifdef HOST_WORDS_BIGENDIAN
511 uint32_t high, low;
512 #else
513 uint32_t low, high;
514 #endif
515 } l;
516 } u, res;
517 uint64_t rl, rh;
519 u.ll = a;
520 rl = (uint64_t)u.l.low * (uint64_t)b;
521 rh = (uint64_t)u.l.high * (uint64_t)b;
522 rh += (rl >> 32);
523 res.l.high = rh / c;
524 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
525 return res.ll;
528 /***********************************************************/
529 /* real time host monotonic timer */
531 #define QEMU_TIMER_BASE 1000000000LL
533 #ifdef WIN32
535 static int64_t clock_freq;
537 static void init_get_clock(void)
539 LARGE_INTEGER freq;
540 int ret;
541 ret = QueryPerformanceFrequency(&freq);
542 if (ret == 0) {
543 fprintf(stderr, "Could not calibrate ticks\n");
544 exit(1);
546 clock_freq = freq.QuadPart;
549 static int64_t get_clock(void)
551 LARGE_INTEGER ti;
552 QueryPerformanceCounter(&ti);
553 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
556 #else
558 static int use_rt_clock;
560 static void init_get_clock(void)
562 use_rt_clock = 0;
563 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
564 || defined(__DragonFly__)
566 struct timespec ts;
567 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
568 use_rt_clock = 1;
571 #endif
574 static int64_t get_clock(void)
576 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
577 || defined(__DragonFly__)
578 if (use_rt_clock) {
579 struct timespec ts;
580 clock_gettime(CLOCK_MONOTONIC, &ts);
581 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
582 } else
583 #endif
585 /* XXX: using gettimeofday leads to problems if the date
586 changes, so it should be avoided. */
587 struct timeval tv;
588 gettimeofday(&tv, NULL);
589 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
592 #endif
594 /* Return the virtual CPU time, based on the instruction counter. */
595 static int64_t cpu_get_icount(void)
597 int64_t icount;
598 CPUState *env = cpu_single_env;;
599 icount = qemu_icount;
600 if (env) {
601 if (!can_do_io(env))
602 fprintf(stderr, "Bad clock read\n");
603 icount -= (env->icount_decr.u16.low + env->icount_extra);
605 return qemu_icount_bias + (icount << icount_time_shift);
608 /***********************************************************/
609 /* guest cycle counter */
611 typedef struct TimersState {
612 int64_t cpu_ticks_prev;
613 int64_t cpu_ticks_offset;
614 int64_t cpu_clock_offset;
615 int32_t cpu_ticks_enabled;
616 int64_t ticks_per_sec;
617 } TimersState;
619 TimersState timers_state;
621 /* return the host CPU cycle counter and handle stop/restart */
622 int64_t cpu_get_ticks(void)
624 if (use_icount) {
625 return cpu_get_icount();
627 if (!timers_state.cpu_ticks_enabled) {
628 return timers_state.cpu_ticks_offset;
629 } else {
630 int64_t ticks;
631 ticks = cpu_get_real_ticks();
632 if (timers_state.cpu_ticks_prev > ticks) {
633 /* Note: non increasing ticks may happen if the host uses
634 software suspend */
635 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
637 timers_state.cpu_ticks_prev = ticks;
638 return ticks + timers_state.cpu_ticks_offset;
642 /* return the host CPU monotonic timer and handle stop/restart */
643 static int64_t cpu_get_clock(void)
645 int64_t ti;
646 if (!timers_state.cpu_ticks_enabled) {
647 return timers_state.cpu_clock_offset;
648 } else {
649 ti = get_clock();
650 return ti + timers_state.cpu_clock_offset;
654 /* enable cpu_get_ticks() */
655 void cpu_enable_ticks(void)
657 if (!timers_state.cpu_ticks_enabled) {
658 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
659 timers_state.cpu_clock_offset -= get_clock();
660 timers_state.cpu_ticks_enabled = 1;
664 /* disable cpu_get_ticks() : the clock is stopped. You must not call
665 cpu_get_ticks() after that. */
666 void cpu_disable_ticks(void)
668 if (timers_state.cpu_ticks_enabled) {
669 timers_state.cpu_ticks_offset = cpu_get_ticks();
670 timers_state.cpu_clock_offset = cpu_get_clock();
671 timers_state.cpu_ticks_enabled = 0;
675 /***********************************************************/
676 /* timers */
678 #define QEMU_TIMER_REALTIME 0
679 #define QEMU_TIMER_VIRTUAL 1
681 struct QEMUClock {
682 int type;
683 /* XXX: add frequency */
686 struct QEMUTimer {
687 QEMUClock *clock;
688 int64_t expire_time;
689 QEMUTimerCB *cb;
690 void *opaque;
691 struct QEMUTimer *next;
694 struct qemu_alarm_timer {
695 char const *name;
696 unsigned int flags;
698 int (*start)(struct qemu_alarm_timer *t);
699 void (*stop)(struct qemu_alarm_timer *t);
700 void (*rearm)(struct qemu_alarm_timer *t);
701 void *priv;
704 #define ALARM_FLAG_DYNTICKS 0x1
705 #define ALARM_FLAG_EXPIRED 0x2
707 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
709 return t && (t->flags & ALARM_FLAG_DYNTICKS);
712 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
714 if (!alarm_has_dynticks(t))
715 return;
717 t->rearm(t);
720 /* TODO: MIN_TIMER_REARM_US should be optimized */
721 #define MIN_TIMER_REARM_US 250
723 static struct qemu_alarm_timer *alarm_timer;
725 #ifdef _WIN32
727 struct qemu_alarm_win32 {
728 MMRESULT timerId;
729 unsigned int period;
730 } alarm_win32_data = {0, -1};
732 static int win32_start_timer(struct qemu_alarm_timer *t);
733 static void win32_stop_timer(struct qemu_alarm_timer *t);
734 static void win32_rearm_timer(struct qemu_alarm_timer *t);
736 #else
738 static int unix_start_timer(struct qemu_alarm_timer *t);
739 static void unix_stop_timer(struct qemu_alarm_timer *t);
741 #ifdef __linux__
743 static int dynticks_start_timer(struct qemu_alarm_timer *t);
744 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
745 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
747 static int hpet_start_timer(struct qemu_alarm_timer *t);
748 static void hpet_stop_timer(struct qemu_alarm_timer *t);
750 static int rtc_start_timer(struct qemu_alarm_timer *t);
751 static void rtc_stop_timer(struct qemu_alarm_timer *t);
753 #endif /* __linux__ */
755 #endif /* _WIN32 */
757 /* Correlation between real and virtual time is always going to be
758 fairly approximate, so ignore small variation.
759 When the guest is idle real and virtual time will be aligned in
760 the IO wait loop. */
761 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
763 static void icount_adjust(void)
765 int64_t cur_time;
766 int64_t cur_icount;
767 int64_t delta;
768 static int64_t last_delta;
769 /* If the VM is not running, then do nothing. */
770 if (!vm_running)
771 return;
773 cur_time = cpu_get_clock();
774 cur_icount = qemu_get_clock(vm_clock);
775 delta = cur_icount - cur_time;
776 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
777 if (delta > 0
778 && last_delta + ICOUNT_WOBBLE < delta * 2
779 && icount_time_shift > 0) {
780 /* The guest is getting too far ahead. Slow time down. */
781 icount_time_shift--;
783 if (delta < 0
784 && last_delta - ICOUNT_WOBBLE > delta * 2
785 && icount_time_shift < MAX_ICOUNT_SHIFT) {
786 /* The guest is getting too far behind. Speed time up. */
787 icount_time_shift++;
789 last_delta = delta;
790 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
793 static void icount_adjust_rt(void * opaque)
795 qemu_mod_timer(icount_rt_timer,
796 qemu_get_clock(rt_clock) + 1000);
797 icount_adjust();
800 static void icount_adjust_vm(void * opaque)
802 qemu_mod_timer(icount_vm_timer,
803 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
804 icount_adjust();
807 static void init_icount_adjust(void)
809 /* Have both realtime and virtual time triggers for speed adjustment.
810 The realtime trigger catches emulated time passing too slowly,
811 the virtual time trigger catches emulated time passing too fast.
812 Realtime triggers occur even when idle, so use them less frequently
813 than VM triggers. */
814 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
815 qemu_mod_timer(icount_rt_timer,
816 qemu_get_clock(rt_clock) + 1000);
817 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
818 qemu_mod_timer(icount_vm_timer,
819 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
822 static struct qemu_alarm_timer alarm_timers[] = {
823 #ifndef _WIN32
824 #ifdef __linux__
825 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
826 dynticks_stop_timer, dynticks_rearm_timer, NULL},
827 /* HPET - if available - is preferred */
828 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
829 /* ...otherwise try RTC */
830 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
831 #endif
832 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
833 #else
834 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
835 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
836 {"win32", 0, win32_start_timer,
837 win32_stop_timer, NULL, &alarm_win32_data},
838 #endif
839 {NULL, }
842 static void show_available_alarms(void)
844 int i;
846 printf("Available alarm timers, in order of precedence:\n");
847 for (i = 0; alarm_timers[i].name; i++)
848 printf("%s\n", alarm_timers[i].name);
851 static void configure_alarms(char const *opt)
853 int i;
854 int cur = 0;
855 int count = ARRAY_SIZE(alarm_timers) - 1;
856 char *arg;
857 char *name;
858 struct qemu_alarm_timer tmp;
860 if (!strcmp(opt, "?")) {
861 show_available_alarms();
862 exit(0);
865 arg = qemu_strdup(opt);
867 /* Reorder the array */
868 name = strtok(arg, ",");
869 while (name) {
870 for (i = 0; i < count && alarm_timers[i].name; i++) {
871 if (!strcmp(alarm_timers[i].name, name))
872 break;
875 if (i == count) {
876 fprintf(stderr, "Unknown clock %s\n", name);
877 goto next;
880 if (i < cur)
881 /* Ignore */
882 goto next;
884 /* Swap */
885 tmp = alarm_timers[i];
886 alarm_timers[i] = alarm_timers[cur];
887 alarm_timers[cur] = tmp;
889 cur++;
890 next:
891 name = strtok(NULL, ",");
894 qemu_free(arg);
896 if (cur) {
897 /* Disable remaining timers */
898 for (i = cur; i < count; i++)
899 alarm_timers[i].name = NULL;
900 } else {
901 show_available_alarms();
902 exit(1);
906 QEMUClock *rt_clock;
907 QEMUClock *vm_clock;
909 static QEMUTimer *active_timers[2];
911 static QEMUClock *qemu_new_clock(int type)
913 QEMUClock *clock;
914 clock = qemu_mallocz(sizeof(QEMUClock));
915 clock->type = type;
916 return clock;
919 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
921 QEMUTimer *ts;
923 ts = qemu_mallocz(sizeof(QEMUTimer));
924 ts->clock = clock;
925 ts->cb = cb;
926 ts->opaque = opaque;
927 return ts;
930 void qemu_free_timer(QEMUTimer *ts)
932 qemu_free(ts);
935 /* stop a timer, but do not dealloc it */
936 void qemu_del_timer(QEMUTimer *ts)
938 QEMUTimer **pt, *t;
940 /* NOTE: this code must be signal safe because
941 qemu_timer_expired() can be called from a signal. */
942 pt = &active_timers[ts->clock->type];
943 for(;;) {
944 t = *pt;
945 if (!t)
946 break;
947 if (t == ts) {
948 *pt = t->next;
949 break;
951 pt = &t->next;
955 /* modify the current timer so that it will be fired when current_time
956 >= expire_time. The corresponding callback will be called. */
957 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
959 QEMUTimer **pt, *t;
961 qemu_del_timer(ts);
963 /* add the timer in the sorted list */
964 /* NOTE: this code must be signal safe because
965 qemu_timer_expired() can be called from a signal. */
966 pt = &active_timers[ts->clock->type];
967 for(;;) {
968 t = *pt;
969 if (!t)
970 break;
971 if (t->expire_time > expire_time)
972 break;
973 pt = &t->next;
975 ts->expire_time = expire_time;
976 ts->next = *pt;
977 *pt = ts;
979 /* Rearm if necessary */
980 if (pt == &active_timers[ts->clock->type]) {
981 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
982 qemu_rearm_alarm_timer(alarm_timer);
984 /* Interrupt execution to force deadline recalculation. */
985 if (use_icount)
986 qemu_notify_event();
990 int qemu_timer_pending(QEMUTimer *ts)
992 QEMUTimer *t;
993 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
994 if (t == ts)
995 return 1;
997 return 0;
1000 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1002 if (!timer_head)
1003 return 0;
1004 return (timer_head->expire_time <= current_time);
1007 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1009 QEMUTimer *ts;
1011 for(;;) {
1012 ts = *ptimer_head;
1013 if (!ts || ts->expire_time > current_time)
1014 break;
1015 /* remove timer from the list before calling the callback */
1016 *ptimer_head = ts->next;
1017 ts->next = NULL;
1019 /* run the callback (the timer list can be modified) */
1020 ts->cb(ts->opaque);
1024 int64_t qemu_get_clock(QEMUClock *clock)
1026 switch(clock->type) {
1027 case QEMU_TIMER_REALTIME:
1028 return get_clock() / 1000000;
1029 default:
1030 case QEMU_TIMER_VIRTUAL:
1031 if (use_icount) {
1032 return cpu_get_icount();
1033 } else {
1034 return cpu_get_clock();
1039 int64_t get_ticks_per_sec(void)
1041 return timers_state.ticks_per_sec;
1044 static void init_timers(void)
1046 init_get_clock();
1047 timers_state.ticks_per_sec = QEMU_TIMER_BASE;
1048 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1049 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1052 /* save a timer */
1053 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1055 uint64_t expire_time;
1057 if (qemu_timer_pending(ts)) {
1058 expire_time = ts->expire_time;
1059 } else {
1060 expire_time = -1;
1062 qemu_put_be64(f, expire_time);
1065 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1067 uint64_t expire_time;
1069 expire_time = qemu_get_be64(f);
1070 if (expire_time != -1) {
1071 qemu_mod_timer(ts, expire_time);
1072 } else {
1073 qemu_del_timer(ts);
1077 static void timer_save(QEMUFile *f, void *opaque)
1079 struct TimersState *s = opaque;
1081 qemu_put_be64(f, s->cpu_ticks_offset);
1082 qemu_put_be64(f, s->ticks_per_sec);
1083 qemu_put_be64(f, s->cpu_clock_offset);
1086 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1088 struct TimersState *s = opaque;
1090 if (version_id != 1 && version_id != 2)
1091 return -EINVAL;
1092 s->cpu_ticks_offset = qemu_get_be64(f);
1093 s->ticks_per_sec = qemu_get_be64(f);
1094 if (version_id == 2) {
1095 s->cpu_clock_offset = qemu_get_be64(f);
1097 return 0;
1100 static void qemu_event_increment(void);
1102 #ifdef _WIN32
1103 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1104 DWORD_PTR dwUser, DWORD_PTR dw1,
1105 DWORD_PTR dw2)
1106 #else
1107 static void host_alarm_handler(int host_signum)
1108 #endif
1110 #if 0
1111 #define DISP_FREQ 1000
1113 static int64_t delta_min = INT64_MAX;
1114 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1115 static int count;
1116 ti = qemu_get_clock(vm_clock);
1117 if (last_clock != 0) {
1118 delta = ti - last_clock;
1119 if (delta < delta_min)
1120 delta_min = delta;
1121 if (delta > delta_max)
1122 delta_max = delta;
1123 delta_cum += delta;
1124 if (++count == DISP_FREQ) {
1125 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1126 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1127 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1128 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1129 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1130 count = 0;
1131 delta_min = INT64_MAX;
1132 delta_max = 0;
1133 delta_cum = 0;
1136 last_clock = ti;
1138 #endif
1139 if (alarm_has_dynticks(alarm_timer) ||
1140 (!use_icount &&
1141 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1142 qemu_get_clock(vm_clock))) ||
1143 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1144 qemu_get_clock(rt_clock))) {
1145 qemu_event_increment();
1146 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1148 #ifndef CONFIG_IOTHREAD
1149 if (next_cpu) {
1150 /* stop the currently executing cpu because a timer occured */
1151 cpu_exit(next_cpu);
1153 #endif
1154 timer_alarm_pending = 1;
1155 qemu_notify_event();
1159 static int64_t qemu_next_deadline(void)
1161 int64_t delta;
1163 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1164 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1165 qemu_get_clock(vm_clock);
1166 } else {
1167 /* To avoid problems with overflow limit this to 2^32. */
1168 delta = INT32_MAX;
1171 if (delta < 0)
1172 delta = 0;
1174 return delta;
1177 #if defined(__linux__) || defined(_WIN32)
1178 static uint64_t qemu_next_deadline_dyntick(void)
1180 int64_t delta;
1181 int64_t rtdelta;
1183 if (use_icount)
1184 delta = INT32_MAX;
1185 else
1186 delta = (qemu_next_deadline() + 999) / 1000;
1188 if (active_timers[QEMU_TIMER_REALTIME]) {
1189 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1190 qemu_get_clock(rt_clock))*1000;
1191 if (rtdelta < delta)
1192 delta = rtdelta;
1195 if (delta < MIN_TIMER_REARM_US)
1196 delta = MIN_TIMER_REARM_US;
1198 return delta;
1200 #endif
1202 #ifndef _WIN32
1204 /* Sets a specific flag */
1205 static int fcntl_setfl(int fd, int flag)
1207 int flags;
1209 flags = fcntl(fd, F_GETFL);
1210 if (flags == -1)
1211 return -errno;
1213 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1214 return -errno;
1216 return 0;
1219 #if defined(__linux__)
1221 #define RTC_FREQ 1024
1223 static void enable_sigio_timer(int fd)
1225 struct sigaction act;
1227 /* timer signal */
1228 sigfillset(&act.sa_mask);
1229 act.sa_flags = 0;
1230 act.sa_handler = host_alarm_handler;
1232 sigaction(SIGIO, &act, NULL);
1233 fcntl_setfl(fd, O_ASYNC);
1234 fcntl(fd, F_SETOWN, getpid());
1237 static int hpet_start_timer(struct qemu_alarm_timer *t)
1239 struct hpet_info info;
1240 int r, fd;
1242 fd = open("/dev/hpet", O_RDONLY);
1243 if (fd < 0)
1244 return -1;
1246 /* Set frequency */
1247 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1248 if (r < 0) {
1249 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1250 "error, but for better emulation accuracy type:\n"
1251 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1252 goto fail;
1255 /* Check capabilities */
1256 r = ioctl(fd, HPET_INFO, &info);
1257 if (r < 0)
1258 goto fail;
1260 /* Enable periodic mode */
1261 r = ioctl(fd, HPET_EPI, 0);
1262 if (info.hi_flags && (r < 0))
1263 goto fail;
1265 /* Enable interrupt */
1266 r = ioctl(fd, HPET_IE_ON, 0);
1267 if (r < 0)
1268 goto fail;
1270 enable_sigio_timer(fd);
1271 t->priv = (void *)(long)fd;
1273 return 0;
1274 fail:
1275 close(fd);
1276 return -1;
1279 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1281 int fd = (long)t->priv;
1283 close(fd);
1286 static int rtc_start_timer(struct qemu_alarm_timer *t)
1288 int rtc_fd;
1289 unsigned long current_rtc_freq = 0;
1291 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1292 if (rtc_fd < 0)
1293 return -1;
1294 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1295 if (current_rtc_freq != RTC_FREQ &&
1296 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1297 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1298 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1299 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1300 goto fail;
1302 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1303 fail:
1304 close(rtc_fd);
1305 return -1;
1308 enable_sigio_timer(rtc_fd);
1310 t->priv = (void *)(long)rtc_fd;
1312 return 0;
1315 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1317 int rtc_fd = (long)t->priv;
1319 close(rtc_fd);
1322 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1324 struct sigevent ev;
1325 timer_t host_timer;
1326 struct sigaction act;
1328 sigfillset(&act.sa_mask);
1329 act.sa_flags = 0;
1330 act.sa_handler = host_alarm_handler;
1332 sigaction(SIGALRM, &act, NULL);
1335 * Initialize ev struct to 0 to avoid valgrind complaining
1336 * about uninitialized data in timer_create call
1338 memset(&ev, 0, sizeof(ev));
1339 ev.sigev_value.sival_int = 0;
1340 ev.sigev_notify = SIGEV_SIGNAL;
1341 ev.sigev_signo = SIGALRM;
1343 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1344 perror("timer_create");
1346 /* disable dynticks */
1347 fprintf(stderr, "Dynamic Ticks disabled\n");
1349 return -1;
1352 t->priv = (void *)(long)host_timer;
1354 return 0;
1357 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1359 timer_t host_timer = (timer_t)(long)t->priv;
1361 timer_delete(host_timer);
1364 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1366 timer_t host_timer = (timer_t)(long)t->priv;
1367 struct itimerspec timeout;
1368 int64_t nearest_delta_us = INT64_MAX;
1369 int64_t current_us;
1371 if (!active_timers[QEMU_TIMER_REALTIME] &&
1372 !active_timers[QEMU_TIMER_VIRTUAL])
1373 return;
1375 nearest_delta_us = qemu_next_deadline_dyntick();
1377 /* check whether a timer is already running */
1378 if (timer_gettime(host_timer, &timeout)) {
1379 perror("gettime");
1380 fprintf(stderr, "Internal timer error: aborting\n");
1381 exit(1);
1383 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1384 if (current_us && current_us <= nearest_delta_us)
1385 return;
1387 timeout.it_interval.tv_sec = 0;
1388 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1389 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1390 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1391 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1392 perror("settime");
1393 fprintf(stderr, "Internal timer error: aborting\n");
1394 exit(1);
1398 #endif /* defined(__linux__) */
1400 static int unix_start_timer(struct qemu_alarm_timer *t)
1402 struct sigaction act;
1403 struct itimerval itv;
1404 int err;
1406 /* timer signal */
1407 sigfillset(&act.sa_mask);
1408 act.sa_flags = 0;
1409 act.sa_handler = host_alarm_handler;
1411 sigaction(SIGALRM, &act, NULL);
1413 itv.it_interval.tv_sec = 0;
1414 /* for i386 kernel 2.6 to get 1 ms */
1415 itv.it_interval.tv_usec = 999;
1416 itv.it_value.tv_sec = 0;
1417 itv.it_value.tv_usec = 10 * 1000;
1419 err = setitimer(ITIMER_REAL, &itv, NULL);
1420 if (err)
1421 return -1;
1423 return 0;
1426 static void unix_stop_timer(struct qemu_alarm_timer *t)
1428 struct itimerval itv;
1430 memset(&itv, 0, sizeof(itv));
1431 setitimer(ITIMER_REAL, &itv, NULL);
1434 #endif /* !defined(_WIN32) */
1437 #ifdef _WIN32
1439 static int win32_start_timer(struct qemu_alarm_timer *t)
1441 TIMECAPS tc;
1442 struct qemu_alarm_win32 *data = t->priv;
1443 UINT flags;
1445 memset(&tc, 0, sizeof(tc));
1446 timeGetDevCaps(&tc, sizeof(tc));
1448 if (data->period < tc.wPeriodMin)
1449 data->period = tc.wPeriodMin;
1451 timeBeginPeriod(data->period);
1453 flags = TIME_CALLBACK_FUNCTION;
1454 if (alarm_has_dynticks(t))
1455 flags |= TIME_ONESHOT;
1456 else
1457 flags |= TIME_PERIODIC;
1459 data->timerId = timeSetEvent(1, // interval (ms)
1460 data->period, // resolution
1461 host_alarm_handler, // function
1462 (DWORD)t, // parameter
1463 flags);
1465 if (!data->timerId) {
1466 perror("Failed to initialize win32 alarm timer");
1467 timeEndPeriod(data->period);
1468 return -1;
1471 return 0;
1474 static void win32_stop_timer(struct qemu_alarm_timer *t)
1476 struct qemu_alarm_win32 *data = t->priv;
1478 timeKillEvent(data->timerId);
1479 timeEndPeriod(data->period);
1482 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1484 struct qemu_alarm_win32 *data = t->priv;
1485 uint64_t nearest_delta_us;
1487 if (!active_timers[QEMU_TIMER_REALTIME] &&
1488 !active_timers[QEMU_TIMER_VIRTUAL])
1489 return;
1491 nearest_delta_us = qemu_next_deadline_dyntick();
1492 nearest_delta_us /= 1000;
1494 timeKillEvent(data->timerId);
1496 data->timerId = timeSetEvent(1,
1497 data->period,
1498 host_alarm_handler,
1499 (DWORD)t,
1500 TIME_ONESHOT | TIME_PERIODIC);
1502 if (!data->timerId) {
1503 perror("Failed to re-arm win32 alarm timer");
1505 timeEndPeriod(data->period);
1506 exit(1);
1510 #endif /* _WIN32 */
1512 static int init_timer_alarm(void)
1514 struct qemu_alarm_timer *t = NULL;
1515 int i, err = -1;
1517 for (i = 0; alarm_timers[i].name; i++) {
1518 t = &alarm_timers[i];
1520 err = t->start(t);
1521 if (!err)
1522 break;
1525 if (err) {
1526 err = -ENOENT;
1527 goto fail;
1530 alarm_timer = t;
1532 return 0;
1534 fail:
1535 return err;
1538 static void quit_timers(void)
1540 alarm_timer->stop(alarm_timer);
1541 alarm_timer = NULL;
1544 /***********************************************************/
1545 /* host time/date access */
1546 void qemu_get_timedate(struct tm *tm, int offset)
1548 time_t ti;
1549 struct tm *ret;
1551 time(&ti);
1552 ti += offset;
1553 if (rtc_date_offset == -1) {
1554 if (rtc_utc)
1555 ret = gmtime(&ti);
1556 else
1557 ret = localtime(&ti);
1558 } else {
1559 ti -= rtc_date_offset;
1560 ret = gmtime(&ti);
1563 memcpy(tm, ret, sizeof(struct tm));
1566 int qemu_timedate_diff(struct tm *tm)
1568 time_t seconds;
1570 if (rtc_date_offset == -1)
1571 if (rtc_utc)
1572 seconds = mktimegm(tm);
1573 else
1574 seconds = mktime(tm);
1575 else
1576 seconds = mktimegm(tm) + rtc_date_offset;
1578 return seconds - time(NULL);
1581 #ifdef _WIN32
1582 static void socket_cleanup(void)
1584 WSACleanup();
1587 static int socket_init(void)
1589 WSADATA Data;
1590 int ret, err;
1592 ret = WSAStartup(MAKEWORD(2,2), &Data);
1593 if (ret != 0) {
1594 err = WSAGetLastError();
1595 fprintf(stderr, "WSAStartup: %d\n", err);
1596 return -1;
1598 atexit(socket_cleanup);
1599 return 0;
1601 #endif
1603 /***********************************************************/
1604 /* Bluetooth support */
1605 static int nb_hcis;
1606 static int cur_hci;
1607 static struct HCIInfo *hci_table[MAX_NICS];
1609 static struct bt_vlan_s {
1610 struct bt_scatternet_s net;
1611 int id;
1612 struct bt_vlan_s *next;
1613 } *first_bt_vlan;
1615 /* find or alloc a new bluetooth "VLAN" */
1616 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1618 struct bt_vlan_s **pvlan, *vlan;
1619 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1620 if (vlan->id == id)
1621 return &vlan->net;
1623 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1624 vlan->id = id;
1625 pvlan = &first_bt_vlan;
1626 while (*pvlan != NULL)
1627 pvlan = &(*pvlan)->next;
1628 *pvlan = vlan;
1629 return &vlan->net;
1632 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1636 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1638 return -ENOTSUP;
1641 static struct HCIInfo null_hci = {
1642 .cmd_send = null_hci_send,
1643 .sco_send = null_hci_send,
1644 .acl_send = null_hci_send,
1645 .bdaddr_set = null_hci_addr_set,
1648 struct HCIInfo *qemu_next_hci(void)
1650 if (cur_hci == nb_hcis)
1651 return &null_hci;
1653 return hci_table[cur_hci++];
1656 static struct HCIInfo *hci_init(const char *str)
1658 char *endp;
1659 struct bt_scatternet_s *vlan = 0;
1661 if (!strcmp(str, "null"))
1662 /* null */
1663 return &null_hci;
1664 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1665 /* host[:hciN] */
1666 return bt_host_hci(str[4] ? str + 5 : "hci0");
1667 else if (!strncmp(str, "hci", 3)) {
1668 /* hci[,vlan=n] */
1669 if (str[3]) {
1670 if (!strncmp(str + 3, ",vlan=", 6)) {
1671 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1672 if (*endp)
1673 vlan = 0;
1675 } else
1676 vlan = qemu_find_bt_vlan(0);
1677 if (vlan)
1678 return bt_new_hci(vlan);
1681 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1683 return 0;
1686 static int bt_hci_parse(const char *str)
1688 struct HCIInfo *hci;
1689 bdaddr_t bdaddr;
1691 if (nb_hcis >= MAX_NICS) {
1692 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1693 return -1;
1696 hci = hci_init(str);
1697 if (!hci)
1698 return -1;
1700 bdaddr.b[0] = 0x52;
1701 bdaddr.b[1] = 0x54;
1702 bdaddr.b[2] = 0x00;
1703 bdaddr.b[3] = 0x12;
1704 bdaddr.b[4] = 0x34;
1705 bdaddr.b[5] = 0x56 + nb_hcis;
1706 hci->bdaddr_set(hci, bdaddr.b);
1708 hci_table[nb_hcis++] = hci;
1710 return 0;
1713 static void bt_vhci_add(int vlan_id)
1715 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1717 if (!vlan->slave)
1718 fprintf(stderr, "qemu: warning: adding a VHCI to "
1719 "an empty scatternet %i\n", vlan_id);
1721 bt_vhci_init(bt_new_hci(vlan));
1724 static struct bt_device_s *bt_device_add(const char *opt)
1726 struct bt_scatternet_s *vlan;
1727 int vlan_id = 0;
1728 char *endp = strstr(opt, ",vlan=");
1729 int len = (endp ? endp - opt : strlen(opt)) + 1;
1730 char devname[10];
1732 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1734 if (endp) {
1735 vlan_id = strtol(endp + 6, &endp, 0);
1736 if (*endp) {
1737 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1738 return 0;
1742 vlan = qemu_find_bt_vlan(vlan_id);
1744 if (!vlan->slave)
1745 fprintf(stderr, "qemu: warning: adding a slave device to "
1746 "an empty scatternet %i\n", vlan_id);
1748 if (!strcmp(devname, "keyboard"))
1749 return bt_keyboard_init(vlan);
1751 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1752 return 0;
1755 static int bt_parse(const char *opt)
1757 const char *endp, *p;
1758 int vlan;
1760 if (strstart(opt, "hci", &endp)) {
1761 if (!*endp || *endp == ',') {
1762 if (*endp)
1763 if (!strstart(endp, ",vlan=", 0))
1764 opt = endp + 1;
1766 return bt_hci_parse(opt);
1768 } else if (strstart(opt, "vhci", &endp)) {
1769 if (!*endp || *endp == ',') {
1770 if (*endp) {
1771 if (strstart(endp, ",vlan=", &p)) {
1772 vlan = strtol(p, (char **) &endp, 0);
1773 if (*endp) {
1774 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1775 return 1;
1777 } else {
1778 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1779 return 1;
1781 } else
1782 vlan = 0;
1784 bt_vhci_add(vlan);
1785 return 0;
1787 } else if (strstart(opt, "device:", &endp))
1788 return !bt_device_add(endp);
1790 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1791 return 1;
1794 /***********************************************************/
1795 /* QEMU Block devices */
1797 #define HD_ALIAS "index=%d,media=disk"
1798 #define CDROM_ALIAS "index=2,media=cdrom"
1799 #define FD_ALIAS "index=%d,if=floppy"
1800 #define PFLASH_ALIAS "if=pflash"
1801 #define MTD_ALIAS "if=mtd"
1802 #define SD_ALIAS "index=0,if=sd"
1804 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1806 va_list ap;
1807 char optstr[1024];
1808 QemuOpts *opts;
1810 va_start(ap, fmt);
1811 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1812 va_end(ap);
1814 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1815 if (!opts) {
1816 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1817 __FUNCTION__, optstr);
1818 return NULL;
1820 if (file)
1821 qemu_opt_set(opts, "file", file);
1822 return opts;
1825 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1827 DriveInfo *dinfo;
1829 /* seek interface, bus and unit */
1831 TAILQ_FOREACH(dinfo, &drives, next) {
1832 if (dinfo->type == type &&
1833 dinfo->bus == bus &&
1834 dinfo->unit == unit)
1835 return dinfo;
1838 return NULL;
1841 DriveInfo *drive_get_by_id(const char *id)
1843 DriveInfo *dinfo;
1845 TAILQ_FOREACH(dinfo, &drives, next) {
1846 if (strcmp(id, dinfo->id))
1847 continue;
1848 return dinfo;
1850 return NULL;
1853 int drive_get_max_bus(BlockInterfaceType type)
1855 int max_bus;
1856 DriveInfo *dinfo;
1858 max_bus = -1;
1859 TAILQ_FOREACH(dinfo, &drives, next) {
1860 if(dinfo->type == type &&
1861 dinfo->bus > max_bus)
1862 max_bus = dinfo->bus;
1864 return max_bus;
1867 const char *drive_get_serial(BlockDriverState *bdrv)
1869 DriveInfo *dinfo;
1871 TAILQ_FOREACH(dinfo, &drives, next) {
1872 if (dinfo->bdrv == bdrv)
1873 return dinfo->serial;
1876 return "\0";
1879 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1881 DriveInfo *dinfo;
1883 TAILQ_FOREACH(dinfo, &drives, next) {
1884 if (dinfo->bdrv == bdrv)
1885 return dinfo->onerror;
1888 return BLOCK_ERR_STOP_ENOSPC;
1891 static void bdrv_format_print(void *opaque, const char *name)
1893 fprintf(stderr, " %s", name);
1896 void drive_uninit(BlockDriverState *bdrv)
1898 DriveInfo *dinfo;
1900 TAILQ_FOREACH(dinfo, &drives, next) {
1901 if (dinfo->bdrv != bdrv)
1902 continue;
1903 qemu_opts_del(dinfo->opts);
1904 TAILQ_REMOVE(&drives, dinfo, next);
1905 qemu_free(dinfo);
1906 break;
1910 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1911 int *fatal_error)
1913 const char *buf;
1914 const char *file = NULL;
1915 char devname[128];
1916 const char *serial;
1917 const char *mediastr = "";
1918 BlockInterfaceType type;
1919 enum { MEDIA_DISK, MEDIA_CDROM } media;
1920 int bus_id, unit_id;
1921 int cyls, heads, secs, translation;
1922 BlockDriver *drv = NULL;
1923 QEMUMachine *machine = opaque;
1924 int max_devs;
1925 int index;
1926 int cache;
1927 int aio = 0;
1928 int bdrv_flags, onerror;
1929 const char *devaddr;
1930 DriveInfo *dinfo;
1931 int snapshot = 0;
1933 *fatal_error = 1;
1935 translation = BIOS_ATA_TRANSLATION_AUTO;
1936 cache = 1;
1938 if (machine && machine->use_scsi) {
1939 type = IF_SCSI;
1940 max_devs = MAX_SCSI_DEVS;
1941 pstrcpy(devname, sizeof(devname), "scsi");
1942 } else {
1943 type = IF_IDE;
1944 max_devs = MAX_IDE_DEVS;
1945 pstrcpy(devname, sizeof(devname), "ide");
1947 media = MEDIA_DISK;
1949 /* extract parameters */
1950 bus_id = qemu_opt_get_number(opts, "bus", 0);
1951 unit_id = qemu_opt_get_number(opts, "unit", -1);
1952 index = qemu_opt_get_number(opts, "index", -1);
1954 cyls = qemu_opt_get_number(opts, "cyls", 0);
1955 heads = qemu_opt_get_number(opts, "heads", 0);
1956 secs = qemu_opt_get_number(opts, "secs", 0);
1958 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1960 file = qemu_opt_get(opts, "file");
1961 serial = qemu_opt_get(opts, "serial");
1963 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1964 pstrcpy(devname, sizeof(devname), buf);
1965 if (!strcmp(buf, "ide")) {
1966 type = IF_IDE;
1967 max_devs = MAX_IDE_DEVS;
1968 } else if (!strcmp(buf, "scsi")) {
1969 type = IF_SCSI;
1970 max_devs = MAX_SCSI_DEVS;
1971 } else if (!strcmp(buf, "floppy")) {
1972 type = IF_FLOPPY;
1973 max_devs = 0;
1974 } else if (!strcmp(buf, "pflash")) {
1975 type = IF_PFLASH;
1976 max_devs = 0;
1977 } else if (!strcmp(buf, "mtd")) {
1978 type = IF_MTD;
1979 max_devs = 0;
1980 } else if (!strcmp(buf, "sd")) {
1981 type = IF_SD;
1982 max_devs = 0;
1983 } else if (!strcmp(buf, "virtio")) {
1984 type = IF_VIRTIO;
1985 max_devs = 0;
1986 } else if (!strcmp(buf, "xen")) {
1987 type = IF_XEN;
1988 max_devs = 0;
1989 } else if (!strcmp(buf, "none")) {
1990 type = IF_NONE;
1991 max_devs = 0;
1992 } else {
1993 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1994 return NULL;
1998 if (cyls || heads || secs) {
1999 if (cyls < 1 || cyls > 16383) {
2000 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2001 return NULL;
2003 if (heads < 1 || heads > 16) {
2004 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2005 return NULL;
2007 if (secs < 1 || secs > 63) {
2008 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2009 return NULL;
2013 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2014 if (!cyls) {
2015 fprintf(stderr,
2016 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2017 buf);
2018 return NULL;
2020 if (!strcmp(buf, "none"))
2021 translation = BIOS_ATA_TRANSLATION_NONE;
2022 else if (!strcmp(buf, "lba"))
2023 translation = BIOS_ATA_TRANSLATION_LBA;
2024 else if (!strcmp(buf, "auto"))
2025 translation = BIOS_ATA_TRANSLATION_AUTO;
2026 else {
2027 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2028 return NULL;
2032 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2033 if (!strcmp(buf, "disk")) {
2034 media = MEDIA_DISK;
2035 } else if (!strcmp(buf, "cdrom")) {
2036 if (cyls || secs || heads) {
2037 fprintf(stderr,
2038 "qemu: '%s' invalid physical CHS format\n", buf);
2039 return NULL;
2041 media = MEDIA_CDROM;
2042 } else {
2043 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2044 return NULL;
2048 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2049 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2050 cache = 0;
2051 else if (!strcmp(buf, "writethrough"))
2052 cache = 1;
2053 else if (!strcmp(buf, "writeback"))
2054 cache = 2;
2055 else {
2056 fprintf(stderr, "qemu: invalid cache option\n");
2057 return NULL;
2061 #ifdef CONFIG_LINUX_AIO
2062 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2063 if (!strcmp(buf, "threads"))
2064 aio = 0;
2065 else if (!strcmp(buf, "native"))
2066 aio = 1;
2067 else {
2068 fprintf(stderr, "qemu: invalid aio option\n");
2069 return NULL;
2072 #endif
2074 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2075 if (strcmp(buf, "?") == 0) {
2076 fprintf(stderr, "qemu: Supported formats:");
2077 bdrv_iterate_format(bdrv_format_print, NULL);
2078 fprintf(stderr, "\n");
2079 return NULL;
2081 drv = bdrv_find_format(buf);
2082 if (!drv) {
2083 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2084 return NULL;
2088 onerror = BLOCK_ERR_STOP_ENOSPC;
2089 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2090 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2091 fprintf(stderr, "werror is no supported by this format\n");
2092 return NULL;
2094 if (!strcmp(buf, "ignore"))
2095 onerror = BLOCK_ERR_IGNORE;
2096 else if (!strcmp(buf, "enospc"))
2097 onerror = BLOCK_ERR_STOP_ENOSPC;
2098 else if (!strcmp(buf, "stop"))
2099 onerror = BLOCK_ERR_STOP_ANY;
2100 else if (!strcmp(buf, "report"))
2101 onerror = BLOCK_ERR_REPORT;
2102 else {
2103 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2104 return NULL;
2108 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2109 if (type != IF_VIRTIO) {
2110 fprintf(stderr, "addr is not supported\n");
2111 return NULL;
2115 /* compute bus and unit according index */
2117 if (index != -1) {
2118 if (bus_id != 0 || unit_id != -1) {
2119 fprintf(stderr,
2120 "qemu: index cannot be used with bus and unit\n");
2121 return NULL;
2123 if (max_devs == 0)
2125 unit_id = index;
2126 bus_id = 0;
2127 } else {
2128 unit_id = index % max_devs;
2129 bus_id = index / max_devs;
2133 /* if user doesn't specify a unit_id,
2134 * try to find the first free
2137 if (unit_id == -1) {
2138 unit_id = 0;
2139 while (drive_get(type, bus_id, unit_id) != NULL) {
2140 unit_id++;
2141 if (max_devs && unit_id >= max_devs) {
2142 unit_id -= max_devs;
2143 bus_id++;
2148 /* check unit id */
2150 if (max_devs && unit_id >= max_devs) {
2151 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2152 unit_id, max_devs - 1);
2153 return NULL;
2157 * ignore multiple definitions
2160 if (drive_get(type, bus_id, unit_id) != NULL) {
2161 *fatal_error = 0;
2162 return NULL;
2165 /* init */
2167 dinfo = qemu_mallocz(sizeof(*dinfo));
2168 if ((buf = qemu_opts_id(opts)) != NULL) {
2169 dinfo->id = qemu_strdup(buf);
2170 } else {
2171 /* no id supplied -> create one */
2172 dinfo->id = qemu_mallocz(32);
2173 if (type == IF_IDE || type == IF_SCSI)
2174 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2175 if (max_devs)
2176 snprintf(dinfo->id, 32, "%s%i%s%i",
2177 devname, bus_id, mediastr, unit_id);
2178 else
2179 snprintf(dinfo->id, 32, "%s%s%i",
2180 devname, mediastr, unit_id);
2182 dinfo->bdrv = bdrv_new(dinfo->id);
2183 dinfo->devaddr = devaddr;
2184 dinfo->type = type;
2185 dinfo->bus = bus_id;
2186 dinfo->unit = unit_id;
2187 dinfo->onerror = onerror;
2188 dinfo->opts = opts;
2189 if (serial)
2190 strncpy(dinfo->serial, serial, sizeof(serial));
2191 TAILQ_INSERT_TAIL(&drives, dinfo, next);
2193 switch(type) {
2194 case IF_IDE:
2195 case IF_SCSI:
2196 case IF_XEN:
2197 switch(media) {
2198 case MEDIA_DISK:
2199 if (cyls != 0) {
2200 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2201 bdrv_set_translation_hint(dinfo->bdrv, translation);
2203 break;
2204 case MEDIA_CDROM:
2205 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2206 break;
2208 break;
2209 case IF_SD:
2210 /* FIXME: This isn't really a floppy, but it's a reasonable
2211 approximation. */
2212 case IF_FLOPPY:
2213 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2214 break;
2215 case IF_PFLASH:
2216 case IF_MTD:
2217 case IF_NONE:
2218 break;
2219 case IF_VIRTIO:
2220 /* add virtio block device */
2221 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2222 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2223 qemu_opt_set(opts, "drive", dinfo->id);
2224 if (devaddr)
2225 qemu_opt_set(opts, "addr", devaddr);
2226 break;
2227 case IF_COUNT:
2228 abort();
2230 if (!file) {
2231 *fatal_error = 0;
2232 return NULL;
2234 bdrv_flags = 0;
2235 if (snapshot) {
2236 bdrv_flags |= BDRV_O_SNAPSHOT;
2237 cache = 2; /* always use write-back with snapshot */
2239 if (cache == 0) /* no caching */
2240 bdrv_flags |= BDRV_O_NOCACHE;
2241 else if (cache == 2) /* write-back */
2242 bdrv_flags |= BDRV_O_CACHE_WB;
2244 if (aio == 1) {
2245 bdrv_flags |= BDRV_O_NATIVE_AIO;
2246 } else {
2247 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2250 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2251 fprintf(stderr, "qemu: could not open disk image %s\n",
2252 file);
2253 return NULL;
2256 if (bdrv_key_required(dinfo->bdrv))
2257 autostart = 0;
2258 *fatal_error = 0;
2259 return dinfo;
2262 static int drive_init_func(QemuOpts *opts, void *opaque)
2264 QEMUMachine *machine = opaque;
2265 int fatal_error = 0;
2267 if (drive_init(opts, machine, &fatal_error) == NULL) {
2268 if (fatal_error)
2269 return 1;
2271 return 0;
2274 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2276 if (NULL == qemu_opt_get(opts, "snapshot")) {
2277 qemu_opt_set(opts, "snapshot", "on");
2279 return 0;
2282 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2284 boot_set_handler = func;
2285 boot_set_opaque = opaque;
2288 int qemu_boot_set(const char *boot_devices)
2290 if (!boot_set_handler) {
2291 return -EINVAL;
2293 return boot_set_handler(boot_set_opaque, boot_devices);
2296 static int parse_bootdevices(char *devices)
2298 /* We just do some generic consistency checks */
2299 const char *p;
2300 int bitmap = 0;
2302 for (p = devices; *p != '\0'; p++) {
2303 /* Allowed boot devices are:
2304 * a-b: floppy disk drives
2305 * c-f: IDE disk drives
2306 * g-m: machine implementation dependant drives
2307 * n-p: network devices
2308 * It's up to each machine implementation to check if the given boot
2309 * devices match the actual hardware implementation and firmware
2310 * features.
2312 if (*p < 'a' || *p > 'p') {
2313 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2314 exit(1);
2316 if (bitmap & (1 << (*p - 'a'))) {
2317 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2318 exit(1);
2320 bitmap |= 1 << (*p - 'a');
2322 return bitmap;
2325 static void restore_boot_devices(void *opaque)
2327 char *standard_boot_devices = opaque;
2329 qemu_boot_set(standard_boot_devices);
2331 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2332 qemu_free(standard_boot_devices);
2335 static void numa_add(const char *optarg)
2337 char option[128];
2338 char *endptr;
2339 unsigned long long value, endvalue;
2340 int nodenr;
2342 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2343 if (!strcmp(option, "node")) {
2344 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2345 nodenr = nb_numa_nodes;
2346 } else {
2347 nodenr = strtoull(option, NULL, 10);
2350 if (get_param_value(option, 128, "mem", optarg) == 0) {
2351 node_mem[nodenr] = 0;
2352 } else {
2353 value = strtoull(option, &endptr, 0);
2354 switch (*endptr) {
2355 case 0: case 'M': case 'm':
2356 value <<= 20;
2357 break;
2358 case 'G': case 'g':
2359 value <<= 30;
2360 break;
2362 node_mem[nodenr] = value;
2364 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2365 node_cpumask[nodenr] = 0;
2366 } else {
2367 value = strtoull(option, &endptr, 10);
2368 if (value >= 64) {
2369 value = 63;
2370 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2371 } else {
2372 if (*endptr == '-') {
2373 endvalue = strtoull(endptr+1, &endptr, 10);
2374 if (endvalue >= 63) {
2375 endvalue = 62;
2376 fprintf(stderr,
2377 "only 63 CPUs in NUMA mode supported.\n");
2379 value = (1 << (endvalue + 1)) - (1 << value);
2380 } else {
2381 value = 1 << value;
2384 node_cpumask[nodenr] = value;
2386 nb_numa_nodes++;
2388 return;
2391 static void smp_parse(const char *optarg)
2393 int smp, sockets = 0, threads = 0, cores = 0;
2394 char *endptr;
2395 char option[128];
2397 smp = strtoul(optarg, &endptr, 10);
2398 if (endptr != optarg) {
2399 if (*endptr == ',') {
2400 endptr++;
2403 if (get_param_value(option, 128, "sockets", endptr) != 0)
2404 sockets = strtoull(option, NULL, 10);
2405 if (get_param_value(option, 128, "cores", endptr) != 0)
2406 cores = strtoull(option, NULL, 10);
2407 if (get_param_value(option, 128, "threads", endptr) != 0)
2408 threads = strtoull(option, NULL, 10);
2409 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2410 max_cpus = strtoull(option, NULL, 10);
2412 /* compute missing values, prefer sockets over cores over threads */
2413 if (smp == 0 || sockets == 0) {
2414 sockets = sockets > 0 ? sockets : 1;
2415 cores = cores > 0 ? cores : 1;
2416 threads = threads > 0 ? threads : 1;
2417 if (smp == 0) {
2418 smp = cores * threads * sockets;
2419 } else {
2420 sockets = smp / (cores * threads);
2422 } else {
2423 if (cores == 0) {
2424 threads = threads > 0 ? threads : 1;
2425 cores = smp / (sockets * threads);
2426 } else {
2427 if (sockets == 0) {
2428 sockets = smp / (cores * threads);
2429 } else {
2430 threads = smp / (cores * sockets);
2434 smp_cpus = smp;
2435 smp_cores = cores > 0 ? cores : 1;
2436 smp_threads = threads > 0 ? threads : 1;
2437 if (max_cpus == 0)
2438 max_cpus = smp_cpus;
2441 /***********************************************************/
2442 /* USB devices */
2444 static void usb_msd_password_cb(void *opaque, int err)
2446 USBDevice *dev = opaque;
2448 if (!err)
2449 usb_device_attach(dev);
2450 else
2451 dev->info->handle_destroy(dev);
2454 static struct {
2455 const char *name;
2456 const char *qdev;
2457 } usbdevs[] = {
2459 .name = "mouse",
2460 .qdev = "QEMU USB Mouse",
2462 .name = "tablet",
2463 .qdev = "QEMU USB Tablet",
2465 .name = "keyboard",
2466 .qdev = "QEMU USB Keyboard",
2468 .name = "wacom-tablet",
2469 .qdev = "QEMU PenPartner Tablet",
2473 static int usb_device_add(const char *devname, int is_hotplug)
2475 const char *p;
2476 USBBus *bus = usb_bus_find(-1 /* any */);
2477 USBDevice *dev = NULL;
2478 int i;
2480 if (!usb_enabled)
2481 return -1;
2483 /* simple devices which don't need extra care */
2484 for (i = 0; i < ARRAY_SIZE(usbdevs); i++) {
2485 if (strcmp(devname, usbdevs[i].name) != 0)
2486 continue;
2487 dev = usb_create_simple(bus, usbdevs[i].qdev);
2488 goto done;
2491 /* the other ones */
2492 if (strstart(devname, "host:", &p)) {
2493 dev = usb_host_device_open(p);
2494 } else if (strstart(devname, "disk:", &p)) {
2495 BlockDriverState *bs;
2497 dev = usb_msd_init(p);
2498 if (!dev)
2499 return -1;
2500 bs = usb_msd_get_bdrv(dev);
2501 if (bdrv_key_required(bs)) {
2502 autostart = 0;
2503 if (is_hotplug) {
2504 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2505 dev);
2506 return 0;
2509 } else if (strstart(devname, "serial:", &p)) {
2510 dev = usb_serial_init(p);
2511 #ifdef CONFIG_BRLAPI
2512 } else if (!strcmp(devname, "braille")) {
2513 dev = usb_baum_init();
2514 #endif
2515 } else if (strstart(devname, "net:", &p)) {
2516 int nic = nb_nics;
2518 if (net_client_init(NULL, "nic", p) < 0)
2519 return -1;
2520 nd_table[nic].model = "usb";
2521 dev = usb_net_init(&nd_table[nic]);
2522 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2523 dev = usb_bt_init(devname[2] ? hci_init(p) :
2524 bt_new_hci(qemu_find_bt_vlan(0)));
2525 } else {
2526 return -1;
2528 if (!dev)
2529 return -1;
2531 done:
2532 return 0;
2535 static int usb_device_del(const char *devname)
2537 int bus_num, addr;
2538 const char *p;
2540 if (strstart(devname, "host:", &p))
2541 return usb_host_device_close(p);
2543 if (!usb_enabled)
2544 return -1;
2546 p = strchr(devname, '.');
2547 if (!p)
2548 return -1;
2549 bus_num = strtoul(devname, NULL, 0);
2550 addr = strtoul(p + 1, NULL, 0);
2552 return usb_device_delete_addr(bus_num, addr);
2555 static int usb_parse(const char *cmdline)
2557 return usb_device_add(cmdline, 0);
2560 void do_usb_add(Monitor *mon, const QDict *qdict)
2562 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2565 void do_usb_del(Monitor *mon, const QDict *qdict)
2567 usb_device_del(qdict_get_str(qdict, "devname"));
2570 /***********************************************************/
2571 /* PCMCIA/Cardbus */
2573 static struct pcmcia_socket_entry_s {
2574 PCMCIASocket *socket;
2575 struct pcmcia_socket_entry_s *next;
2576 } *pcmcia_sockets = 0;
2578 void pcmcia_socket_register(PCMCIASocket *socket)
2580 struct pcmcia_socket_entry_s *entry;
2582 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2583 entry->socket = socket;
2584 entry->next = pcmcia_sockets;
2585 pcmcia_sockets = entry;
2588 void pcmcia_socket_unregister(PCMCIASocket *socket)
2590 struct pcmcia_socket_entry_s *entry, **ptr;
2592 ptr = &pcmcia_sockets;
2593 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2594 if (entry->socket == socket) {
2595 *ptr = entry->next;
2596 qemu_free(entry);
2600 void pcmcia_info(Monitor *mon)
2602 struct pcmcia_socket_entry_s *iter;
2604 if (!pcmcia_sockets)
2605 monitor_printf(mon, "No PCMCIA sockets\n");
2607 for (iter = pcmcia_sockets; iter; iter = iter->next)
2608 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2609 iter->socket->attached ? iter->socket->card_string :
2610 "Empty");
2613 /***********************************************************/
2614 /* register display */
2616 struct DisplayAllocator default_allocator = {
2617 defaultallocator_create_displaysurface,
2618 defaultallocator_resize_displaysurface,
2619 defaultallocator_free_displaysurface
2622 void register_displaystate(DisplayState *ds)
2624 DisplayState **s;
2625 s = &display_state;
2626 while (*s != NULL)
2627 s = &(*s)->next;
2628 ds->next = NULL;
2629 *s = ds;
2632 DisplayState *get_displaystate(void)
2634 return display_state;
2637 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2639 if(ds->allocator == &default_allocator) ds->allocator = da;
2640 return ds->allocator;
2643 /* dumb display */
2645 static void dumb_display_init(void)
2647 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2648 ds->allocator = &default_allocator;
2649 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2650 register_displaystate(ds);
2653 /***********************************************************/
2654 /* I/O handling */
2656 typedef struct IOHandlerRecord {
2657 int fd;
2658 IOCanRWHandler *fd_read_poll;
2659 IOHandler *fd_read;
2660 IOHandler *fd_write;
2661 int deleted;
2662 void *opaque;
2663 /* temporary data */
2664 struct pollfd *ufd;
2665 struct IOHandlerRecord *next;
2666 } IOHandlerRecord;
2668 static IOHandlerRecord *first_io_handler;
2670 /* XXX: fd_read_poll should be suppressed, but an API change is
2671 necessary in the character devices to suppress fd_can_read(). */
2672 int qemu_set_fd_handler2(int fd,
2673 IOCanRWHandler *fd_read_poll,
2674 IOHandler *fd_read,
2675 IOHandler *fd_write,
2676 void *opaque)
2678 IOHandlerRecord **pioh, *ioh;
2680 if (!fd_read && !fd_write) {
2681 pioh = &first_io_handler;
2682 for(;;) {
2683 ioh = *pioh;
2684 if (ioh == NULL)
2685 break;
2686 if (ioh->fd == fd) {
2687 ioh->deleted = 1;
2688 break;
2690 pioh = &ioh->next;
2692 } else {
2693 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2694 if (ioh->fd == fd)
2695 goto found;
2697 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2698 ioh->next = first_io_handler;
2699 first_io_handler = ioh;
2700 found:
2701 ioh->fd = fd;
2702 ioh->fd_read_poll = fd_read_poll;
2703 ioh->fd_read = fd_read;
2704 ioh->fd_write = fd_write;
2705 ioh->opaque = opaque;
2706 ioh->deleted = 0;
2708 return 0;
2711 int qemu_set_fd_handler(int fd,
2712 IOHandler *fd_read,
2713 IOHandler *fd_write,
2714 void *opaque)
2716 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2719 #ifdef _WIN32
2720 /***********************************************************/
2721 /* Polling handling */
2723 typedef struct PollingEntry {
2724 PollingFunc *func;
2725 void *opaque;
2726 struct PollingEntry *next;
2727 } PollingEntry;
2729 static PollingEntry *first_polling_entry;
2731 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2733 PollingEntry **ppe, *pe;
2734 pe = qemu_mallocz(sizeof(PollingEntry));
2735 pe->func = func;
2736 pe->opaque = opaque;
2737 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2738 *ppe = pe;
2739 return 0;
2742 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2744 PollingEntry **ppe, *pe;
2745 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2746 pe = *ppe;
2747 if (pe->func == func && pe->opaque == opaque) {
2748 *ppe = pe->next;
2749 qemu_free(pe);
2750 break;
2755 /***********************************************************/
2756 /* Wait objects support */
2757 typedef struct WaitObjects {
2758 int num;
2759 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2760 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2761 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2762 } WaitObjects;
2764 static WaitObjects wait_objects = {0};
2766 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2768 WaitObjects *w = &wait_objects;
2770 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2771 return -1;
2772 w->events[w->num] = handle;
2773 w->func[w->num] = func;
2774 w->opaque[w->num] = opaque;
2775 w->num++;
2776 return 0;
2779 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2781 int i, found;
2782 WaitObjects *w = &wait_objects;
2784 found = 0;
2785 for (i = 0; i < w->num; i++) {
2786 if (w->events[i] == handle)
2787 found = 1;
2788 if (found) {
2789 w->events[i] = w->events[i + 1];
2790 w->func[i] = w->func[i + 1];
2791 w->opaque[i] = w->opaque[i + 1];
2794 if (found)
2795 w->num--;
2797 #endif
2799 /***********************************************************/
2800 /* ram save/restore */
2802 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2803 #define RAM_SAVE_FLAG_COMPRESS 0x02
2804 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2805 #define RAM_SAVE_FLAG_PAGE 0x08
2806 #define RAM_SAVE_FLAG_EOS 0x10
2808 static int is_dup_page(uint8_t *page, uint8_t ch)
2810 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2811 uint32_t *array = (uint32_t *)page;
2812 int i;
2814 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2815 if (array[i] != val)
2816 return 0;
2819 return 1;
2822 static int ram_save_block(QEMUFile *f)
2824 static ram_addr_t current_addr = 0;
2825 ram_addr_t saved_addr = current_addr;
2826 ram_addr_t addr = 0;
2827 int found = 0;
2829 while (addr < last_ram_offset) {
2830 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2831 uint8_t *p;
2833 cpu_physical_memory_reset_dirty(current_addr,
2834 current_addr + TARGET_PAGE_SIZE,
2835 MIGRATION_DIRTY_FLAG);
2837 p = qemu_get_ram_ptr(current_addr);
2839 if (is_dup_page(p, *p)) {
2840 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2841 qemu_put_byte(f, *p);
2842 } else {
2843 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2844 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2847 found = 1;
2848 break;
2850 addr += TARGET_PAGE_SIZE;
2851 current_addr = (saved_addr + addr) % last_ram_offset;
2854 return found;
2857 static uint64_t bytes_transferred = 0;
2859 static ram_addr_t ram_save_remaining(void)
2861 ram_addr_t addr;
2862 ram_addr_t count = 0;
2864 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2865 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2866 count++;
2869 return count;
2872 uint64_t ram_bytes_remaining(void)
2874 return ram_save_remaining() * TARGET_PAGE_SIZE;
2877 uint64_t ram_bytes_transferred(void)
2879 return bytes_transferred;
2882 uint64_t ram_bytes_total(void)
2884 return last_ram_offset;
2887 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
2889 ram_addr_t addr;
2890 uint64_t bytes_transferred_last;
2891 double bwidth = 0;
2892 uint64_t expected_time = 0;
2894 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2895 qemu_file_set_error(f);
2896 return 0;
2899 if (stage == 1) {
2900 /* Make sure all dirty bits are set */
2901 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2902 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2903 cpu_physical_memory_set_dirty(addr);
2906 /* Enable dirty memory tracking */
2907 cpu_physical_memory_set_dirty_tracking(1);
2909 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2912 bytes_transferred_last = bytes_transferred;
2913 bwidth = get_clock();
2915 while (!qemu_file_rate_limit(f)) {
2916 int ret;
2918 ret = ram_save_block(f);
2919 bytes_transferred += ret * TARGET_PAGE_SIZE;
2920 if (ret == 0) /* no more blocks */
2921 break;
2924 bwidth = get_clock() - bwidth;
2925 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2927 /* if we haven't transferred anything this round, force expected_time to a
2928 * a very high value, but without crashing */
2929 if (bwidth == 0)
2930 bwidth = 0.000001;
2932 /* try transferring iterative blocks of memory */
2934 if (stage == 3) {
2936 /* flush all remaining blocks regardless of rate limiting */
2937 while (ram_save_block(f) != 0) {
2938 bytes_transferred += TARGET_PAGE_SIZE;
2940 cpu_physical_memory_set_dirty_tracking(0);
2943 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2945 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2947 return (stage == 2) && (expected_time <= migrate_max_downtime());
2950 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2952 ram_addr_t addr;
2953 int flags;
2955 if (version_id != 3)
2956 return -EINVAL;
2958 do {
2959 addr = qemu_get_be64(f);
2961 flags = addr & ~TARGET_PAGE_MASK;
2962 addr &= TARGET_PAGE_MASK;
2964 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2965 if (addr != last_ram_offset)
2966 return -EINVAL;
2969 if (flags & RAM_SAVE_FLAG_COMPRESS) {
2970 uint8_t ch = qemu_get_byte(f);
2971 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2972 #ifndef _WIN32
2973 if (ch == 0 &&
2974 (!kvm_enabled() || kvm_has_sync_mmu())) {
2975 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2977 #endif
2978 } else if (flags & RAM_SAVE_FLAG_PAGE)
2979 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2980 } while (!(flags & RAM_SAVE_FLAG_EOS));
2982 return 0;
2985 void qemu_service_io(void)
2987 qemu_notify_event();
2990 /***********************************************************/
2991 /* bottom halves (can be seen as timers which expire ASAP) */
2993 struct QEMUBH {
2994 QEMUBHFunc *cb;
2995 void *opaque;
2996 int scheduled;
2997 int idle;
2998 int deleted;
2999 QEMUBH *next;
3002 static QEMUBH *first_bh = NULL;
3004 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3006 QEMUBH *bh;
3007 bh = qemu_mallocz(sizeof(QEMUBH));
3008 bh->cb = cb;
3009 bh->opaque = opaque;
3010 bh->next = first_bh;
3011 first_bh = bh;
3012 return bh;
3015 int qemu_bh_poll(void)
3017 QEMUBH *bh, **bhp;
3018 int ret;
3020 ret = 0;
3021 for (bh = first_bh; bh; bh = bh->next) {
3022 if (!bh->deleted && bh->scheduled) {
3023 bh->scheduled = 0;
3024 if (!bh->idle)
3025 ret = 1;
3026 bh->idle = 0;
3027 bh->cb(bh->opaque);
3031 /* remove deleted bhs */
3032 bhp = &first_bh;
3033 while (*bhp) {
3034 bh = *bhp;
3035 if (bh->deleted) {
3036 *bhp = bh->next;
3037 qemu_free(bh);
3038 } else
3039 bhp = &bh->next;
3042 return ret;
3045 void qemu_bh_schedule_idle(QEMUBH *bh)
3047 if (bh->scheduled)
3048 return;
3049 bh->scheduled = 1;
3050 bh->idle = 1;
3053 void qemu_bh_schedule(QEMUBH *bh)
3055 if (bh->scheduled)
3056 return;
3057 bh->scheduled = 1;
3058 bh->idle = 0;
3059 /* stop the currently executing CPU to execute the BH ASAP */
3060 qemu_notify_event();
3063 void qemu_bh_cancel(QEMUBH *bh)
3065 bh->scheduled = 0;
3068 void qemu_bh_delete(QEMUBH *bh)
3070 bh->scheduled = 0;
3071 bh->deleted = 1;
3074 static void qemu_bh_update_timeout(int *timeout)
3076 QEMUBH *bh;
3078 for (bh = first_bh; bh; bh = bh->next) {
3079 if (!bh->deleted && bh->scheduled) {
3080 if (bh->idle) {
3081 /* idle bottom halves will be polled at least
3082 * every 10ms */
3083 *timeout = MIN(10, *timeout);
3084 } else {
3085 /* non-idle bottom halves will be executed
3086 * immediately */
3087 *timeout = 0;
3088 break;
3094 /***********************************************************/
3095 /* machine registration */
3097 static QEMUMachine *first_machine = NULL;
3098 QEMUMachine *current_machine = NULL;
3100 int qemu_register_machine(QEMUMachine *m)
3102 QEMUMachine **pm;
3103 pm = &first_machine;
3104 while (*pm != NULL)
3105 pm = &(*pm)->next;
3106 m->next = NULL;
3107 *pm = m;
3108 return 0;
3111 static QEMUMachine *find_machine(const char *name)
3113 QEMUMachine *m;
3115 for(m = first_machine; m != NULL; m = m->next) {
3116 if (!strcmp(m->name, name))
3117 return m;
3118 if (m->alias && !strcmp(m->alias, name))
3119 return m;
3121 return NULL;
3124 static QEMUMachine *find_default_machine(void)
3126 QEMUMachine *m;
3128 for(m = first_machine; m != NULL; m = m->next) {
3129 if (m->is_default) {
3130 return m;
3133 return NULL;
3136 /***********************************************************/
3137 /* main execution loop */
3139 static void gui_update(void *opaque)
3141 uint64_t interval = GUI_REFRESH_INTERVAL;
3142 DisplayState *ds = opaque;
3143 DisplayChangeListener *dcl = ds->listeners;
3145 dpy_refresh(ds);
3147 while (dcl != NULL) {
3148 if (dcl->gui_timer_interval &&
3149 dcl->gui_timer_interval < interval)
3150 interval = dcl->gui_timer_interval;
3151 dcl = dcl->next;
3153 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3156 static void nographic_update(void *opaque)
3158 uint64_t interval = GUI_REFRESH_INTERVAL;
3160 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3163 struct vm_change_state_entry {
3164 VMChangeStateHandler *cb;
3165 void *opaque;
3166 LIST_ENTRY (vm_change_state_entry) entries;
3169 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3171 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3172 void *opaque)
3174 VMChangeStateEntry *e;
3176 e = qemu_mallocz(sizeof (*e));
3178 e->cb = cb;
3179 e->opaque = opaque;
3180 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3181 return e;
3184 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3186 LIST_REMOVE (e, entries);
3187 qemu_free (e);
3190 static void vm_state_notify(int running, int reason)
3192 VMChangeStateEntry *e;
3194 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3195 e->cb(e->opaque, running, reason);
3199 static void resume_all_vcpus(void);
3200 static void pause_all_vcpus(void);
3202 void vm_start(void)
3204 if (!vm_running) {
3205 cpu_enable_ticks();
3206 vm_running = 1;
3207 vm_state_notify(1, 0);
3208 qemu_rearm_alarm_timer(alarm_timer);
3209 resume_all_vcpus();
3213 /* reset/shutdown handler */
3215 typedef struct QEMUResetEntry {
3216 TAILQ_ENTRY(QEMUResetEntry) entry;
3217 QEMUResetHandler *func;
3218 void *opaque;
3219 } QEMUResetEntry;
3221 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3222 TAILQ_HEAD_INITIALIZER(reset_handlers);
3223 static int reset_requested;
3224 static int shutdown_requested;
3225 static int powerdown_requested;
3226 static int debug_requested;
3227 static int vmstop_requested;
3229 int qemu_shutdown_requested(void)
3231 int r = shutdown_requested;
3232 shutdown_requested = 0;
3233 return r;
3236 int qemu_reset_requested(void)
3238 int r = reset_requested;
3239 reset_requested = 0;
3240 return r;
3243 int qemu_powerdown_requested(void)
3245 int r = powerdown_requested;
3246 powerdown_requested = 0;
3247 return r;
3250 static int qemu_debug_requested(void)
3252 int r = debug_requested;
3253 debug_requested = 0;
3254 return r;
3257 static int qemu_vmstop_requested(void)
3259 int r = vmstop_requested;
3260 vmstop_requested = 0;
3261 return r;
3264 static void do_vm_stop(int reason)
3266 if (vm_running) {
3267 cpu_disable_ticks();
3268 vm_running = 0;
3269 pause_all_vcpus();
3270 vm_state_notify(0, reason);
3274 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3276 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3278 re->func = func;
3279 re->opaque = opaque;
3280 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3283 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3285 QEMUResetEntry *re;
3287 TAILQ_FOREACH(re, &reset_handlers, entry) {
3288 if (re->func == func && re->opaque == opaque) {
3289 TAILQ_REMOVE(&reset_handlers, re, entry);
3290 qemu_free(re);
3291 return;
3296 void qemu_system_reset(void)
3298 QEMUResetEntry *re, *nre;
3300 /* reset all devices */
3301 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3302 re->func(re->opaque);
3306 void qemu_system_reset_request(void)
3308 if (no_reboot) {
3309 shutdown_requested = 1;
3310 } else {
3311 reset_requested = 1;
3313 qemu_notify_event();
3316 void qemu_system_shutdown_request(void)
3318 shutdown_requested = 1;
3319 qemu_notify_event();
3322 void qemu_system_powerdown_request(void)
3324 powerdown_requested = 1;
3325 qemu_notify_event();
3328 #ifdef CONFIG_IOTHREAD
3329 static void qemu_system_vmstop_request(int reason)
3331 vmstop_requested = reason;
3332 qemu_notify_event();
3334 #endif
3336 #ifndef _WIN32
3337 static int io_thread_fd = -1;
3339 static void qemu_event_increment(void)
3341 static const char byte = 0;
3343 if (io_thread_fd == -1)
3344 return;
3346 write(io_thread_fd, &byte, sizeof(byte));
3349 static void qemu_event_read(void *opaque)
3351 int fd = (unsigned long)opaque;
3352 ssize_t len;
3354 /* Drain the notify pipe */
3355 do {
3356 char buffer[512];
3357 len = read(fd, buffer, sizeof(buffer));
3358 } while ((len == -1 && errno == EINTR) || len > 0);
3361 static int qemu_event_init(void)
3363 int err;
3364 int fds[2];
3366 err = pipe(fds);
3367 if (err == -1)
3368 return -errno;
3370 err = fcntl_setfl(fds[0], O_NONBLOCK);
3371 if (err < 0)
3372 goto fail;
3374 err = fcntl_setfl(fds[1], O_NONBLOCK);
3375 if (err < 0)
3376 goto fail;
3378 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3379 (void *)(unsigned long)fds[0]);
3381 io_thread_fd = fds[1];
3382 return 0;
3384 fail:
3385 close(fds[0]);
3386 close(fds[1]);
3387 return err;
3389 #else
3390 HANDLE qemu_event_handle;
3392 static void dummy_event_handler(void *opaque)
3396 static int qemu_event_init(void)
3398 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3399 if (!qemu_event_handle) {
3400 perror("Failed CreateEvent");
3401 return -1;
3403 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3404 return 0;
3407 static void qemu_event_increment(void)
3409 SetEvent(qemu_event_handle);
3411 #endif
3413 static int cpu_can_run(CPUState *env)
3415 if (env->stop)
3416 return 0;
3417 if (env->stopped)
3418 return 0;
3419 return 1;
3422 #ifndef CONFIG_IOTHREAD
3423 static int qemu_init_main_loop(void)
3425 return qemu_event_init();
3428 void qemu_init_vcpu(void *_env)
3430 CPUState *env = _env;
3432 if (kvm_enabled())
3433 kvm_init_vcpu(env);
3434 env->nr_cores = smp_cores;
3435 env->nr_threads = smp_threads;
3436 return;
3439 int qemu_cpu_self(void *env)
3441 return 1;
3444 static void resume_all_vcpus(void)
3448 static void pause_all_vcpus(void)
3452 void qemu_cpu_kick(void *env)
3454 return;
3457 void qemu_notify_event(void)
3459 CPUState *env = cpu_single_env;
3461 if (env) {
3462 cpu_exit(env);
3466 #define qemu_mutex_lock_iothread() do { } while (0)
3467 #define qemu_mutex_unlock_iothread() do { } while (0)
3469 void vm_stop(int reason)
3471 do_vm_stop(reason);
3474 #else /* CONFIG_IOTHREAD */
3476 #include "qemu-thread.h"
3478 QemuMutex qemu_global_mutex;
3479 static QemuMutex qemu_fair_mutex;
3481 static QemuThread io_thread;
3483 static QemuThread *tcg_cpu_thread;
3484 static QemuCond *tcg_halt_cond;
3486 static int qemu_system_ready;
3487 /* cpu creation */
3488 static QemuCond qemu_cpu_cond;
3489 /* system init */
3490 static QemuCond qemu_system_cond;
3491 static QemuCond qemu_pause_cond;
3493 static void block_io_signals(void);
3494 static void unblock_io_signals(void);
3495 static int tcg_has_work(void);
3497 static int qemu_init_main_loop(void)
3499 int ret;
3501 ret = qemu_event_init();
3502 if (ret)
3503 return ret;
3505 qemu_cond_init(&qemu_pause_cond);
3506 qemu_mutex_init(&qemu_fair_mutex);
3507 qemu_mutex_init(&qemu_global_mutex);
3508 qemu_mutex_lock(&qemu_global_mutex);
3510 unblock_io_signals();
3511 qemu_thread_self(&io_thread);
3513 return 0;
3516 static void qemu_wait_io_event(CPUState *env)
3518 while (!tcg_has_work())
3519 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3521 qemu_mutex_unlock(&qemu_global_mutex);
3524 * Users of qemu_global_mutex can be starved, having no chance
3525 * to acquire it since this path will get to it first.
3526 * So use another lock to provide fairness.
3528 qemu_mutex_lock(&qemu_fair_mutex);
3529 qemu_mutex_unlock(&qemu_fair_mutex);
3531 qemu_mutex_lock(&qemu_global_mutex);
3532 if (env->stop) {
3533 env->stop = 0;
3534 env->stopped = 1;
3535 qemu_cond_signal(&qemu_pause_cond);
3539 static int qemu_cpu_exec(CPUState *env);
3541 static void *kvm_cpu_thread_fn(void *arg)
3543 CPUState *env = arg;
3545 block_io_signals();
3546 qemu_thread_self(env->thread);
3547 if (kvm_enabled())
3548 kvm_init_vcpu(env);
3550 /* signal CPU creation */
3551 qemu_mutex_lock(&qemu_global_mutex);
3552 env->created = 1;
3553 qemu_cond_signal(&qemu_cpu_cond);
3555 /* and wait for machine initialization */
3556 while (!qemu_system_ready)
3557 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3559 while (1) {
3560 if (cpu_can_run(env))
3561 qemu_cpu_exec(env);
3562 qemu_wait_io_event(env);
3565 return NULL;
3568 static void tcg_cpu_exec(void);
3570 static void *tcg_cpu_thread_fn(void *arg)
3572 CPUState *env = arg;
3574 block_io_signals();
3575 qemu_thread_self(env->thread);
3577 /* signal CPU creation */
3578 qemu_mutex_lock(&qemu_global_mutex);
3579 for (env = first_cpu; env != NULL; env = env->next_cpu)
3580 env->created = 1;
3581 qemu_cond_signal(&qemu_cpu_cond);
3583 /* and wait for machine initialization */
3584 while (!qemu_system_ready)
3585 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3587 while (1) {
3588 tcg_cpu_exec();
3589 qemu_wait_io_event(cur_cpu);
3592 return NULL;
3595 void qemu_cpu_kick(void *_env)
3597 CPUState *env = _env;
3598 qemu_cond_broadcast(env->halt_cond);
3599 if (kvm_enabled())
3600 qemu_thread_signal(env->thread, SIGUSR1);
3603 int qemu_cpu_self(void *env)
3605 return (cpu_single_env != NULL);
3608 static void cpu_signal(int sig)
3610 if (cpu_single_env)
3611 cpu_exit(cpu_single_env);
3614 static void block_io_signals(void)
3616 sigset_t set;
3617 struct sigaction sigact;
3619 sigemptyset(&set);
3620 sigaddset(&set, SIGUSR2);
3621 sigaddset(&set, SIGIO);
3622 sigaddset(&set, SIGALRM);
3623 pthread_sigmask(SIG_BLOCK, &set, NULL);
3625 sigemptyset(&set);
3626 sigaddset(&set, SIGUSR1);
3627 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3629 memset(&sigact, 0, sizeof(sigact));
3630 sigact.sa_handler = cpu_signal;
3631 sigaction(SIGUSR1, &sigact, NULL);
3634 static void unblock_io_signals(void)
3636 sigset_t set;
3638 sigemptyset(&set);
3639 sigaddset(&set, SIGUSR2);
3640 sigaddset(&set, SIGIO);
3641 sigaddset(&set, SIGALRM);
3642 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3644 sigemptyset(&set);
3645 sigaddset(&set, SIGUSR1);
3646 pthread_sigmask(SIG_BLOCK, &set, NULL);
3649 static void qemu_signal_lock(unsigned int msecs)
3651 qemu_mutex_lock(&qemu_fair_mutex);
3653 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3654 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3655 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3656 break;
3658 qemu_mutex_unlock(&qemu_fair_mutex);
3661 static void qemu_mutex_lock_iothread(void)
3663 if (kvm_enabled()) {
3664 qemu_mutex_lock(&qemu_fair_mutex);
3665 qemu_mutex_lock(&qemu_global_mutex);
3666 qemu_mutex_unlock(&qemu_fair_mutex);
3667 } else
3668 qemu_signal_lock(100);
3671 static void qemu_mutex_unlock_iothread(void)
3673 qemu_mutex_unlock(&qemu_global_mutex);
3676 static int all_vcpus_paused(void)
3678 CPUState *penv = first_cpu;
3680 while (penv) {
3681 if (!penv->stopped)
3682 return 0;
3683 penv = (CPUState *)penv->next_cpu;
3686 return 1;
3689 static void pause_all_vcpus(void)
3691 CPUState *penv = first_cpu;
3693 while (penv) {
3694 penv->stop = 1;
3695 qemu_thread_signal(penv->thread, SIGUSR1);
3696 qemu_cpu_kick(penv);
3697 penv = (CPUState *)penv->next_cpu;
3700 while (!all_vcpus_paused()) {
3701 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3702 penv = first_cpu;
3703 while (penv) {
3704 qemu_thread_signal(penv->thread, SIGUSR1);
3705 penv = (CPUState *)penv->next_cpu;
3710 static void resume_all_vcpus(void)
3712 CPUState *penv = first_cpu;
3714 while (penv) {
3715 penv->stop = 0;
3716 penv->stopped = 0;
3717 qemu_thread_signal(penv->thread, SIGUSR1);
3718 qemu_cpu_kick(penv);
3719 penv = (CPUState *)penv->next_cpu;
3723 static void tcg_init_vcpu(void *_env)
3725 CPUState *env = _env;
3726 /* share a single thread for all cpus with TCG */
3727 if (!tcg_cpu_thread) {
3728 env->thread = qemu_mallocz(sizeof(QemuThread));
3729 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3730 qemu_cond_init(env->halt_cond);
3731 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3732 while (env->created == 0)
3733 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3734 tcg_cpu_thread = env->thread;
3735 tcg_halt_cond = env->halt_cond;
3736 } else {
3737 env->thread = tcg_cpu_thread;
3738 env->halt_cond = tcg_halt_cond;
3742 static void kvm_start_vcpu(CPUState *env)
3744 env->thread = qemu_mallocz(sizeof(QemuThread));
3745 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3746 qemu_cond_init(env->halt_cond);
3747 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3748 while (env->created == 0)
3749 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3752 void qemu_init_vcpu(void *_env)
3754 CPUState *env = _env;
3756 if (kvm_enabled())
3757 kvm_start_vcpu(env);
3758 else
3759 tcg_init_vcpu(env);
3760 env->nr_cores = smp_cores;
3761 env->nr_threads = smp_threads;
3764 void qemu_notify_event(void)
3766 qemu_event_increment();
3769 void vm_stop(int reason)
3771 QemuThread me;
3772 qemu_thread_self(&me);
3774 if (!qemu_thread_equal(&me, &io_thread)) {
3775 qemu_system_vmstop_request(reason);
3777 * FIXME: should not return to device code in case
3778 * vm_stop() has been requested.
3780 if (cpu_single_env) {
3781 cpu_exit(cpu_single_env);
3782 cpu_single_env->stop = 1;
3784 return;
3786 do_vm_stop(reason);
3789 #endif
3792 #ifdef _WIN32
3793 static void host_main_loop_wait(int *timeout)
3795 int ret, ret2, i;
3796 PollingEntry *pe;
3799 /* XXX: need to suppress polling by better using win32 events */
3800 ret = 0;
3801 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3802 ret |= pe->func(pe->opaque);
3804 if (ret == 0) {
3805 int err;
3806 WaitObjects *w = &wait_objects;
3808 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3809 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3810 if (w->func[ret - WAIT_OBJECT_0])
3811 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3813 /* Check for additional signaled events */
3814 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3816 /* Check if event is signaled */
3817 ret2 = WaitForSingleObject(w->events[i], 0);
3818 if(ret2 == WAIT_OBJECT_0) {
3819 if (w->func[i])
3820 w->func[i](w->opaque[i]);
3821 } else if (ret2 == WAIT_TIMEOUT) {
3822 } else {
3823 err = GetLastError();
3824 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3827 } else if (ret == WAIT_TIMEOUT) {
3828 } else {
3829 err = GetLastError();
3830 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3834 *timeout = 0;
3836 #else
3837 static void host_main_loop_wait(int *timeout)
3840 #endif
3842 void main_loop_wait(int timeout)
3844 IOHandlerRecord *ioh;
3845 fd_set rfds, wfds, xfds;
3846 int ret, nfds;
3847 struct timeval tv;
3849 qemu_bh_update_timeout(&timeout);
3851 host_main_loop_wait(&timeout);
3853 /* poll any events */
3854 /* XXX: separate device handlers from system ones */
3855 nfds = -1;
3856 FD_ZERO(&rfds);
3857 FD_ZERO(&wfds);
3858 FD_ZERO(&xfds);
3859 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3860 if (ioh->deleted)
3861 continue;
3862 if (ioh->fd_read &&
3863 (!ioh->fd_read_poll ||
3864 ioh->fd_read_poll(ioh->opaque) != 0)) {
3865 FD_SET(ioh->fd, &rfds);
3866 if (ioh->fd > nfds)
3867 nfds = ioh->fd;
3869 if (ioh->fd_write) {
3870 FD_SET(ioh->fd, &wfds);
3871 if (ioh->fd > nfds)
3872 nfds = ioh->fd;
3876 tv.tv_sec = timeout / 1000;
3877 tv.tv_usec = (timeout % 1000) * 1000;
3879 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3881 qemu_mutex_unlock_iothread();
3882 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3883 qemu_mutex_lock_iothread();
3884 if (ret > 0) {
3885 IOHandlerRecord **pioh;
3887 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3888 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3889 ioh->fd_read(ioh->opaque);
3891 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3892 ioh->fd_write(ioh->opaque);
3896 /* remove deleted IO handlers */
3897 pioh = &first_io_handler;
3898 while (*pioh) {
3899 ioh = *pioh;
3900 if (ioh->deleted) {
3901 *pioh = ioh->next;
3902 qemu_free(ioh);
3903 } else
3904 pioh = &ioh->next;
3908 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3910 /* rearm timer, if not periodic */
3911 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3912 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3913 qemu_rearm_alarm_timer(alarm_timer);
3916 /* vm time timers */
3917 if (vm_running) {
3918 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3919 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3920 qemu_get_clock(vm_clock));
3923 /* real time timers */
3924 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3925 qemu_get_clock(rt_clock));
3927 /* Check bottom-halves last in case any of the earlier events triggered
3928 them. */
3929 qemu_bh_poll();
3933 static int qemu_cpu_exec(CPUState *env)
3935 int ret;
3936 #ifdef CONFIG_PROFILER
3937 int64_t ti;
3938 #endif
3940 #ifdef CONFIG_PROFILER
3941 ti = profile_getclock();
3942 #endif
3943 if (use_icount) {
3944 int64_t count;
3945 int decr;
3946 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3947 env->icount_decr.u16.low = 0;
3948 env->icount_extra = 0;
3949 count = qemu_next_deadline();
3950 count = (count + (1 << icount_time_shift) - 1)
3951 >> icount_time_shift;
3952 qemu_icount += count;
3953 decr = (count > 0xffff) ? 0xffff : count;
3954 count -= decr;
3955 env->icount_decr.u16.low = decr;
3956 env->icount_extra = count;
3958 ret = cpu_exec(env);
3959 #ifdef CONFIG_PROFILER
3960 qemu_time += profile_getclock() - ti;
3961 #endif
3962 if (use_icount) {
3963 /* Fold pending instructions back into the
3964 instruction counter, and clear the interrupt flag. */
3965 qemu_icount -= (env->icount_decr.u16.low
3966 + env->icount_extra);
3967 env->icount_decr.u32 = 0;
3968 env->icount_extra = 0;
3970 return ret;
3973 static void tcg_cpu_exec(void)
3975 int ret = 0;
3977 if (next_cpu == NULL)
3978 next_cpu = first_cpu;
3979 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3980 CPUState *env = cur_cpu = next_cpu;
3982 if (!vm_running)
3983 break;
3984 if (timer_alarm_pending) {
3985 timer_alarm_pending = 0;
3986 break;
3988 if (cpu_can_run(env))
3989 ret = qemu_cpu_exec(env);
3990 if (ret == EXCP_DEBUG) {
3991 gdb_set_stop_cpu(env);
3992 debug_requested = 1;
3993 break;
3998 static int cpu_has_work(CPUState *env)
4000 if (env->stop)
4001 return 1;
4002 if (env->stopped)
4003 return 0;
4004 if (!env->halted)
4005 return 1;
4006 if (qemu_cpu_has_work(env))
4007 return 1;
4008 return 0;
4011 static int tcg_has_work(void)
4013 CPUState *env;
4015 for (env = first_cpu; env != NULL; env = env->next_cpu)
4016 if (cpu_has_work(env))
4017 return 1;
4018 return 0;
4021 static int qemu_calculate_timeout(void)
4023 #ifndef CONFIG_IOTHREAD
4024 int timeout;
4026 if (!vm_running)
4027 timeout = 5000;
4028 else if (tcg_has_work())
4029 timeout = 0;
4030 else if (!use_icount)
4031 timeout = 5000;
4032 else {
4033 /* XXX: use timeout computed from timers */
4034 int64_t add;
4035 int64_t delta;
4036 /* Advance virtual time to the next event. */
4037 if (use_icount == 1) {
4038 /* When not using an adaptive execution frequency
4039 we tend to get badly out of sync with real time,
4040 so just delay for a reasonable amount of time. */
4041 delta = 0;
4042 } else {
4043 delta = cpu_get_icount() - cpu_get_clock();
4045 if (delta > 0) {
4046 /* If virtual time is ahead of real time then just
4047 wait for IO. */
4048 timeout = (delta / 1000000) + 1;
4049 } else {
4050 /* Wait for either IO to occur or the next
4051 timer event. */
4052 add = qemu_next_deadline();
4053 /* We advance the timer before checking for IO.
4054 Limit the amount we advance so that early IO
4055 activity won't get the guest too far ahead. */
4056 if (add > 10000000)
4057 add = 10000000;
4058 delta += add;
4059 add = (add + (1 << icount_time_shift) - 1)
4060 >> icount_time_shift;
4061 qemu_icount += add;
4062 timeout = delta / 1000000;
4063 if (timeout < 0)
4064 timeout = 0;
4068 return timeout;
4069 #else /* CONFIG_IOTHREAD */
4070 return 1000;
4071 #endif
4074 static int vm_can_run(void)
4076 if (powerdown_requested)
4077 return 0;
4078 if (reset_requested)
4079 return 0;
4080 if (shutdown_requested)
4081 return 0;
4082 if (debug_requested)
4083 return 0;
4084 return 1;
4087 qemu_irq qemu_system_powerdown;
4089 static void main_loop(void)
4091 int r;
4093 #ifdef CONFIG_IOTHREAD
4094 qemu_system_ready = 1;
4095 qemu_cond_broadcast(&qemu_system_cond);
4096 #endif
4098 for (;;) {
4099 do {
4100 #ifdef CONFIG_PROFILER
4101 int64_t ti;
4102 #endif
4103 #ifndef CONFIG_IOTHREAD
4104 tcg_cpu_exec();
4105 #endif
4106 #ifdef CONFIG_PROFILER
4107 ti = profile_getclock();
4108 #endif
4109 main_loop_wait(qemu_calculate_timeout());
4110 #ifdef CONFIG_PROFILER
4111 dev_time += profile_getclock() - ti;
4112 #endif
4113 } while (vm_can_run());
4115 if (qemu_debug_requested())
4116 vm_stop(EXCP_DEBUG);
4117 if (qemu_shutdown_requested()) {
4118 if (no_shutdown) {
4119 vm_stop(0);
4120 no_shutdown = 0;
4121 } else
4122 break;
4124 if (qemu_reset_requested()) {
4125 pause_all_vcpus();
4126 qemu_system_reset();
4127 resume_all_vcpus();
4129 if (qemu_powerdown_requested()) {
4130 qemu_irq_raise(qemu_system_powerdown);
4132 if ((r = qemu_vmstop_requested()))
4133 vm_stop(r);
4135 pause_all_vcpus();
4138 static void version(void)
4140 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4143 static void help(int exitcode)
4145 version();
4146 printf("usage: %s [options] [disk_image]\n"
4147 "\n"
4148 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4149 "\n"
4150 #define DEF(option, opt_arg, opt_enum, opt_help) \
4151 opt_help
4152 #define DEFHEADING(text) stringify(text) "\n"
4153 #include "qemu-options.h"
4154 #undef DEF
4155 #undef DEFHEADING
4156 #undef GEN_DOCS
4157 "\n"
4158 "During emulation, the following keys are useful:\n"
4159 "ctrl-alt-f toggle full screen\n"
4160 "ctrl-alt-n switch to virtual console 'n'\n"
4161 "ctrl-alt toggle mouse and keyboard grab\n"
4162 "\n"
4163 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4165 "qemu",
4166 DEFAULT_RAM_SIZE,
4167 #ifndef _WIN32
4168 DEFAULT_NETWORK_SCRIPT,
4169 DEFAULT_NETWORK_DOWN_SCRIPT,
4170 #endif
4171 DEFAULT_GDBSTUB_PORT,
4172 "/tmp/qemu.log");
4173 exit(exitcode);
4176 #define HAS_ARG 0x0001
4178 enum {
4179 #define DEF(option, opt_arg, opt_enum, opt_help) \
4180 opt_enum,
4181 #define DEFHEADING(text)
4182 #include "qemu-options.h"
4183 #undef DEF
4184 #undef DEFHEADING
4185 #undef GEN_DOCS
4188 typedef struct QEMUOption {
4189 const char *name;
4190 int flags;
4191 int index;
4192 } QEMUOption;
4194 static const QEMUOption qemu_options[] = {
4195 { "h", 0, QEMU_OPTION_h },
4196 #define DEF(option, opt_arg, opt_enum, opt_help) \
4197 { option, opt_arg, opt_enum },
4198 #define DEFHEADING(text)
4199 #include "qemu-options.h"
4200 #undef DEF
4201 #undef DEFHEADING
4202 #undef GEN_DOCS
4203 { NULL },
4206 #ifdef HAS_AUDIO
4207 struct soundhw soundhw[] = {
4208 #ifdef HAS_AUDIO_CHOICE
4209 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4211 "pcspk",
4212 "PC speaker",
4215 { .init_isa = pcspk_audio_init }
4217 #endif
4219 #ifdef CONFIG_SB16
4221 "sb16",
4222 "Creative Sound Blaster 16",
4225 { .init_isa = SB16_init }
4227 #endif
4229 #ifdef CONFIG_CS4231A
4231 "cs4231a",
4232 "CS4231A",
4235 { .init_isa = cs4231a_init }
4237 #endif
4239 #ifdef CONFIG_ADLIB
4241 "adlib",
4242 #ifdef HAS_YMF262
4243 "Yamaha YMF262 (OPL3)",
4244 #else
4245 "Yamaha YM3812 (OPL2)",
4246 #endif
4249 { .init_isa = Adlib_init }
4251 #endif
4253 #ifdef CONFIG_GUS
4255 "gus",
4256 "Gravis Ultrasound GF1",
4259 { .init_isa = GUS_init }
4261 #endif
4263 #ifdef CONFIG_AC97
4265 "ac97",
4266 "Intel 82801AA AC97 Audio",
4269 { .init_pci = ac97_init }
4271 #endif
4273 #ifdef CONFIG_ES1370
4275 "es1370",
4276 "ENSONIQ AudioPCI ES1370",
4279 { .init_pci = es1370_init }
4281 #endif
4283 #endif /* HAS_AUDIO_CHOICE */
4285 { NULL, NULL, 0, 0, { NULL } }
4288 static void select_soundhw (const char *optarg)
4290 struct soundhw *c;
4292 if (*optarg == '?') {
4293 show_valid_cards:
4295 printf ("Valid sound card names (comma separated):\n");
4296 for (c = soundhw; c->name; ++c) {
4297 printf ("%-11s %s\n", c->name, c->descr);
4299 printf ("\n-soundhw all will enable all of the above\n");
4300 exit (*optarg != '?');
4302 else {
4303 size_t l;
4304 const char *p;
4305 char *e;
4306 int bad_card = 0;
4308 if (!strcmp (optarg, "all")) {
4309 for (c = soundhw; c->name; ++c) {
4310 c->enabled = 1;
4312 return;
4315 p = optarg;
4316 while (*p) {
4317 e = strchr (p, ',');
4318 l = !e ? strlen (p) : (size_t) (e - p);
4320 for (c = soundhw; c->name; ++c) {
4321 if (!strncmp (c->name, p, l) && !c->name[l]) {
4322 c->enabled = 1;
4323 break;
4327 if (!c->name) {
4328 if (l > 80) {
4329 fprintf (stderr,
4330 "Unknown sound card name (too big to show)\n");
4332 else {
4333 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4334 (int) l, p);
4336 bad_card = 1;
4338 p += l + (e != NULL);
4341 if (bad_card)
4342 goto show_valid_cards;
4345 #endif
4347 static void select_vgahw (const char *p)
4349 const char *opts;
4351 vga_interface_type = VGA_NONE;
4352 if (strstart(p, "std", &opts)) {
4353 vga_interface_type = VGA_STD;
4354 } else if (strstart(p, "cirrus", &opts)) {
4355 vga_interface_type = VGA_CIRRUS;
4356 } else if (strstart(p, "vmware", &opts)) {
4357 vga_interface_type = VGA_VMWARE;
4358 } else if (strstart(p, "xenfb", &opts)) {
4359 vga_interface_type = VGA_XENFB;
4360 } else if (!strstart(p, "none", &opts)) {
4361 invalid_vga:
4362 fprintf(stderr, "Unknown vga type: %s\n", p);
4363 exit(1);
4365 while (*opts) {
4366 const char *nextopt;
4368 if (strstart(opts, ",retrace=", &nextopt)) {
4369 opts = nextopt;
4370 if (strstart(opts, "dumb", &nextopt))
4371 vga_retrace_method = VGA_RETRACE_DUMB;
4372 else if (strstart(opts, "precise", &nextopt))
4373 vga_retrace_method = VGA_RETRACE_PRECISE;
4374 else goto invalid_vga;
4375 } else goto invalid_vga;
4376 opts = nextopt;
4380 #ifdef TARGET_I386
4381 static int balloon_parse(const char *arg)
4383 QemuOpts *opts;
4385 if (strcmp(arg, "none") == 0) {
4386 return 0;
4389 if (!strncmp(arg, "virtio", 6)) {
4390 if (arg[6] == ',') {
4391 /* have params -> parse them */
4392 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4393 if (!opts)
4394 return -1;
4395 } else {
4396 /* create empty opts */
4397 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4399 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4400 return 0;
4403 return -1;
4405 #endif
4407 #ifdef _WIN32
4408 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4410 exit(STATUS_CONTROL_C_EXIT);
4411 return TRUE;
4413 #endif
4415 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4417 int ret;
4419 if(strlen(str) != 36)
4420 return -1;
4422 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4423 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4424 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4426 if(ret != 16)
4427 return -1;
4429 #ifdef TARGET_I386
4430 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4431 #endif
4433 return 0;
4436 #define MAX_NET_CLIENTS 32
4438 #ifndef _WIN32
4440 static void termsig_handler(int signal)
4442 qemu_system_shutdown_request();
4445 static void sigchld_handler(int signal)
4447 waitpid(-1, NULL, WNOHANG);
4450 static void sighandler_setup(void)
4452 struct sigaction act;
4454 memset(&act, 0, sizeof(act));
4455 act.sa_handler = termsig_handler;
4456 sigaction(SIGINT, &act, NULL);
4457 sigaction(SIGHUP, &act, NULL);
4458 sigaction(SIGTERM, &act, NULL);
4460 act.sa_handler = sigchld_handler;
4461 act.sa_flags = SA_NOCLDSTOP;
4462 sigaction(SIGCHLD, &act, NULL);
4465 #endif
4467 #ifdef _WIN32
4468 /* Look for support files in the same directory as the executable. */
4469 static char *find_datadir(const char *argv0)
4471 char *p;
4472 char buf[MAX_PATH];
4473 DWORD len;
4475 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4476 if (len == 0) {
4477 return NULL;
4480 buf[len] = 0;
4481 p = buf + len - 1;
4482 while (p != buf && *p != '\\')
4483 p--;
4484 *p = 0;
4485 if (access(buf, R_OK) == 0) {
4486 return qemu_strdup(buf);
4488 return NULL;
4490 #else /* !_WIN32 */
4492 /* Find a likely location for support files using the location of the binary.
4493 For installed binaries this will be "$bindir/../share/qemu". When
4494 running from the build tree this will be "$bindir/../pc-bios". */
4495 #define SHARE_SUFFIX "/share/qemu"
4496 #define BUILD_SUFFIX "/pc-bios"
4497 static char *find_datadir(const char *argv0)
4499 char *dir;
4500 char *p = NULL;
4501 char *res;
4502 char buf[PATH_MAX];
4503 size_t max_len;
4505 #if defined(__linux__)
4507 int len;
4508 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4509 if (len > 0) {
4510 buf[len] = 0;
4511 p = buf;
4514 #elif defined(__FreeBSD__)
4516 int len;
4517 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4518 if (len > 0) {
4519 buf[len] = 0;
4520 p = buf;
4523 #endif
4524 /* If we don't have any way of figuring out the actual executable
4525 location then try argv[0]. */
4526 if (!p) {
4527 p = realpath(argv0, buf);
4528 if (!p) {
4529 return NULL;
4532 dir = dirname(p);
4533 dir = dirname(dir);
4535 max_len = strlen(dir) +
4536 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4537 res = qemu_mallocz(max_len);
4538 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4539 if (access(res, R_OK)) {
4540 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4541 if (access(res, R_OK)) {
4542 qemu_free(res);
4543 res = NULL;
4547 return res;
4549 #undef SHARE_SUFFIX
4550 #undef BUILD_SUFFIX
4551 #endif
4553 char *qemu_find_file(int type, const char *name)
4555 int len;
4556 const char *subdir;
4557 char *buf;
4559 /* If name contains path separators then try it as a straight path. */
4560 if ((strchr(name, '/') || strchr(name, '\\'))
4561 && access(name, R_OK) == 0) {
4562 return qemu_strdup(name);
4564 switch (type) {
4565 case QEMU_FILE_TYPE_BIOS:
4566 subdir = "";
4567 break;
4568 case QEMU_FILE_TYPE_KEYMAP:
4569 subdir = "keymaps/";
4570 break;
4571 default:
4572 abort();
4574 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4575 buf = qemu_mallocz(len);
4576 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4577 if (access(buf, R_OK)) {
4578 qemu_free(buf);
4579 return NULL;
4581 return buf;
4584 static int device_init_func(QemuOpts *opts, void *opaque)
4586 DeviceState *dev;
4588 dev = qdev_device_add(opts);
4589 if (!dev)
4590 return -1;
4591 return 0;
4594 struct device_config {
4595 enum {
4596 DEV_USB, /* -usbdevice */
4597 DEV_BT, /* -bt */
4598 } type;
4599 const char *cmdline;
4600 TAILQ_ENTRY(device_config) next;
4602 TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4604 static void add_device_config(int type, const char *cmdline)
4606 struct device_config *conf;
4608 conf = qemu_mallocz(sizeof(*conf));
4609 conf->type = type;
4610 conf->cmdline = cmdline;
4611 TAILQ_INSERT_TAIL(&device_configs, conf, next);
4614 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4616 struct device_config *conf;
4617 int rc;
4619 TAILQ_FOREACH(conf, &device_configs, next) {
4620 if (conf->type != type)
4621 continue;
4622 rc = func(conf->cmdline);
4623 if (0 != rc)
4624 return rc;
4626 return 0;
4629 int main(int argc, char **argv, char **envp)
4631 const char *gdbstub_dev = NULL;
4632 uint32_t boot_devices_bitmap = 0;
4633 int i;
4634 int snapshot, linux_boot, net_boot;
4635 const char *initrd_filename;
4636 const char *kernel_filename, *kernel_cmdline;
4637 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4638 DisplayState *ds;
4639 DisplayChangeListener *dcl;
4640 int cyls, heads, secs, translation;
4641 const char *net_clients[MAX_NET_CLIENTS];
4642 int nb_net_clients;
4643 QemuOpts *hda_opts = NULL, *opts;
4644 int optind;
4645 const char *r, *optarg;
4646 CharDriverState *monitor_hds[MAX_MONITOR_DEVICES];
4647 const char *monitor_devices[MAX_MONITOR_DEVICES];
4648 int monitor_device_index;
4649 const char *serial_devices[MAX_SERIAL_PORTS];
4650 int serial_device_index;
4651 const char *parallel_devices[MAX_PARALLEL_PORTS];
4652 int parallel_device_index;
4653 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4654 int virtio_console_index;
4655 const char *loadvm = NULL;
4656 QEMUMachine *machine;
4657 const char *cpu_model;
4658 #ifndef _WIN32
4659 int fds[2];
4660 #endif
4661 int tb_size;
4662 const char *pid_file = NULL;
4663 const char *incoming = NULL;
4664 #ifndef _WIN32
4665 int fd = 0;
4666 struct passwd *pwd = NULL;
4667 const char *chroot_dir = NULL;
4668 const char *run_as = NULL;
4669 #endif
4670 CPUState *env;
4671 int show_vnc_port = 0;
4673 qemu_errors_to_file(stderr);
4674 qemu_cache_utils_init(envp);
4676 LIST_INIT (&vm_change_state_head);
4677 #ifndef _WIN32
4679 struct sigaction act;
4680 sigfillset(&act.sa_mask);
4681 act.sa_flags = 0;
4682 act.sa_handler = SIG_IGN;
4683 sigaction(SIGPIPE, &act, NULL);
4685 #else
4686 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4687 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4688 QEMU to run on a single CPU */
4690 HANDLE h;
4691 DWORD mask, smask;
4692 int i;
4693 h = GetCurrentProcess();
4694 if (GetProcessAffinityMask(h, &mask, &smask)) {
4695 for(i = 0; i < 32; i++) {
4696 if (mask & (1 << i))
4697 break;
4699 if (i != 32) {
4700 mask = 1 << i;
4701 SetProcessAffinityMask(h, mask);
4705 #endif
4707 module_call_init(MODULE_INIT_MACHINE);
4708 machine = find_default_machine();
4709 cpu_model = NULL;
4710 initrd_filename = NULL;
4711 ram_size = 0;
4712 snapshot = 0;
4713 kernel_filename = NULL;
4714 kernel_cmdline = "";
4715 cyls = heads = secs = 0;
4716 translation = BIOS_ATA_TRANSLATION_AUTO;
4718 serial_devices[0] = "vc:80Cx24C";
4719 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4720 serial_devices[i] = NULL;
4721 serial_device_index = 0;
4723 parallel_devices[0] = "vc:80Cx24C";
4724 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4725 parallel_devices[i] = NULL;
4726 parallel_device_index = 0;
4728 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4729 virtio_consoles[i] = NULL;
4730 virtio_console_index = 0;
4732 monitor_devices[0] = "vc:80Cx24C";
4733 for (i = 1; i < MAX_MONITOR_DEVICES; i++) {
4734 monitor_devices[i] = NULL;
4736 monitor_device_index = 0;
4738 for (i = 0; i < MAX_NODES; i++) {
4739 node_mem[i] = 0;
4740 node_cpumask[i] = 0;
4743 nb_net_clients = 0;
4744 nb_numa_nodes = 0;
4745 nb_nics = 0;
4747 tb_size = 0;
4748 autostart= 1;
4750 optind = 1;
4751 for(;;) {
4752 if (optind >= argc)
4753 break;
4754 r = argv[optind];
4755 if (r[0] != '-') {
4756 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4757 } else {
4758 const QEMUOption *popt;
4760 optind++;
4761 /* Treat --foo the same as -foo. */
4762 if (r[1] == '-')
4763 r++;
4764 popt = qemu_options;
4765 for(;;) {
4766 if (!popt->name) {
4767 fprintf(stderr, "%s: invalid option -- '%s'\n",
4768 argv[0], r);
4769 exit(1);
4771 if (!strcmp(popt->name, r + 1))
4772 break;
4773 popt++;
4775 if (popt->flags & HAS_ARG) {
4776 if (optind >= argc) {
4777 fprintf(stderr, "%s: option '%s' requires an argument\n",
4778 argv[0], r);
4779 exit(1);
4781 optarg = argv[optind++];
4782 } else {
4783 optarg = NULL;
4786 switch(popt->index) {
4787 case QEMU_OPTION_M:
4788 machine = find_machine(optarg);
4789 if (!machine) {
4790 QEMUMachine *m;
4791 printf("Supported machines are:\n");
4792 for(m = first_machine; m != NULL; m = m->next) {
4793 if (m->alias)
4794 printf("%-10s %s (alias of %s)\n",
4795 m->alias, m->desc, m->name);
4796 printf("%-10s %s%s\n",
4797 m->name, m->desc,
4798 m->is_default ? " (default)" : "");
4800 exit(*optarg != '?');
4802 break;
4803 case QEMU_OPTION_cpu:
4804 /* hw initialization will check this */
4805 if (*optarg == '?') {
4806 /* XXX: implement xxx_cpu_list for targets that still miss it */
4807 #if defined(cpu_list)
4808 cpu_list(stdout, &fprintf);
4809 #endif
4810 exit(0);
4811 } else {
4812 cpu_model = optarg;
4814 break;
4815 case QEMU_OPTION_initrd:
4816 initrd_filename = optarg;
4817 break;
4818 case QEMU_OPTION_hda:
4819 if (cyls == 0)
4820 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4821 else
4822 hda_opts = drive_add(optarg, HD_ALIAS
4823 ",cyls=%d,heads=%d,secs=%d%s",
4824 0, cyls, heads, secs,
4825 translation == BIOS_ATA_TRANSLATION_LBA ?
4826 ",trans=lba" :
4827 translation == BIOS_ATA_TRANSLATION_NONE ?
4828 ",trans=none" : "");
4829 break;
4830 case QEMU_OPTION_hdb:
4831 case QEMU_OPTION_hdc:
4832 case QEMU_OPTION_hdd:
4833 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4834 break;
4835 case QEMU_OPTION_drive:
4836 drive_add(NULL, "%s", optarg);
4837 break;
4838 case QEMU_OPTION_set:
4839 if (qemu_set_option(optarg) != 0)
4840 exit(1);
4841 break;
4842 case QEMU_OPTION_mtdblock:
4843 drive_add(optarg, MTD_ALIAS);
4844 break;
4845 case QEMU_OPTION_sd:
4846 drive_add(optarg, SD_ALIAS);
4847 break;
4848 case QEMU_OPTION_pflash:
4849 drive_add(optarg, PFLASH_ALIAS);
4850 break;
4851 case QEMU_OPTION_snapshot:
4852 snapshot = 1;
4853 break;
4854 case QEMU_OPTION_hdachs:
4856 const char *p;
4857 p = optarg;
4858 cyls = strtol(p, (char **)&p, 0);
4859 if (cyls < 1 || cyls > 16383)
4860 goto chs_fail;
4861 if (*p != ',')
4862 goto chs_fail;
4863 p++;
4864 heads = strtol(p, (char **)&p, 0);
4865 if (heads < 1 || heads > 16)
4866 goto chs_fail;
4867 if (*p != ',')
4868 goto chs_fail;
4869 p++;
4870 secs = strtol(p, (char **)&p, 0);
4871 if (secs < 1 || secs > 63)
4872 goto chs_fail;
4873 if (*p == ',') {
4874 p++;
4875 if (!strcmp(p, "none"))
4876 translation = BIOS_ATA_TRANSLATION_NONE;
4877 else if (!strcmp(p, "lba"))
4878 translation = BIOS_ATA_TRANSLATION_LBA;
4879 else if (!strcmp(p, "auto"))
4880 translation = BIOS_ATA_TRANSLATION_AUTO;
4881 else
4882 goto chs_fail;
4883 } else if (*p != '\0') {
4884 chs_fail:
4885 fprintf(stderr, "qemu: invalid physical CHS format\n");
4886 exit(1);
4888 if (hda_opts != NULL) {
4889 char num[16];
4890 snprintf(num, sizeof(num), "%d", cyls);
4891 qemu_opt_set(hda_opts, "cyls", num);
4892 snprintf(num, sizeof(num), "%d", heads);
4893 qemu_opt_set(hda_opts, "heads", num);
4894 snprintf(num, sizeof(num), "%d", secs);
4895 qemu_opt_set(hda_opts, "secs", num);
4896 if (translation == BIOS_ATA_TRANSLATION_LBA)
4897 qemu_opt_set(hda_opts, "trans", "lba");
4898 if (translation == BIOS_ATA_TRANSLATION_NONE)
4899 qemu_opt_set(hda_opts, "trans", "none");
4902 break;
4903 case QEMU_OPTION_numa:
4904 if (nb_numa_nodes >= MAX_NODES) {
4905 fprintf(stderr, "qemu: too many NUMA nodes\n");
4906 exit(1);
4908 numa_add(optarg);
4909 break;
4910 case QEMU_OPTION_nographic:
4911 display_type = DT_NOGRAPHIC;
4912 break;
4913 #ifdef CONFIG_CURSES
4914 case QEMU_OPTION_curses:
4915 display_type = DT_CURSES;
4916 break;
4917 #endif
4918 case QEMU_OPTION_portrait:
4919 graphic_rotate = 1;
4920 break;
4921 case QEMU_OPTION_kernel:
4922 kernel_filename = optarg;
4923 break;
4924 case QEMU_OPTION_append:
4925 kernel_cmdline = optarg;
4926 break;
4927 case QEMU_OPTION_cdrom:
4928 drive_add(optarg, CDROM_ALIAS);
4929 break;
4930 case QEMU_OPTION_boot:
4932 static const char * const params[] = {
4933 "order", "once", "menu", NULL
4935 char buf[sizeof(boot_devices)];
4936 char *standard_boot_devices;
4937 int legacy = 0;
4939 if (!strchr(optarg, '=')) {
4940 legacy = 1;
4941 pstrcpy(buf, sizeof(buf), optarg);
4942 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4943 fprintf(stderr,
4944 "qemu: unknown boot parameter '%s' in '%s'\n",
4945 buf, optarg);
4946 exit(1);
4949 if (legacy ||
4950 get_param_value(buf, sizeof(buf), "order", optarg)) {
4951 boot_devices_bitmap = parse_bootdevices(buf);
4952 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4954 if (!legacy) {
4955 if (get_param_value(buf, sizeof(buf),
4956 "once", optarg)) {
4957 boot_devices_bitmap |= parse_bootdevices(buf);
4958 standard_boot_devices = qemu_strdup(boot_devices);
4959 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4960 qemu_register_reset(restore_boot_devices,
4961 standard_boot_devices);
4963 if (get_param_value(buf, sizeof(buf),
4964 "menu", optarg)) {
4965 if (!strcmp(buf, "on")) {
4966 boot_menu = 1;
4967 } else if (!strcmp(buf, "off")) {
4968 boot_menu = 0;
4969 } else {
4970 fprintf(stderr,
4971 "qemu: invalid option value '%s'\n",
4972 buf);
4973 exit(1);
4978 break;
4979 case QEMU_OPTION_fda:
4980 case QEMU_OPTION_fdb:
4981 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4982 break;
4983 #ifdef TARGET_I386
4984 case QEMU_OPTION_no_fd_bootchk:
4985 fd_bootchk = 0;
4986 break;
4987 #endif
4988 case QEMU_OPTION_net:
4989 if (nb_net_clients >= MAX_NET_CLIENTS) {
4990 fprintf(stderr, "qemu: too many network clients\n");
4991 exit(1);
4993 net_clients[nb_net_clients] = optarg;
4994 nb_net_clients++;
4995 break;
4996 #ifdef CONFIG_SLIRP
4997 case QEMU_OPTION_tftp:
4998 legacy_tftp_prefix = optarg;
4999 break;
5000 case QEMU_OPTION_bootp:
5001 legacy_bootp_filename = optarg;
5002 break;
5003 #ifndef _WIN32
5004 case QEMU_OPTION_smb:
5005 net_slirp_smb(optarg);
5006 break;
5007 #endif
5008 case QEMU_OPTION_redir:
5009 net_slirp_redir(optarg);
5010 break;
5011 #endif
5012 case QEMU_OPTION_bt:
5013 add_device_config(DEV_BT, optarg);
5014 break;
5015 #ifdef HAS_AUDIO
5016 case QEMU_OPTION_audio_help:
5017 AUD_help ();
5018 exit (0);
5019 break;
5020 case QEMU_OPTION_soundhw:
5021 select_soundhw (optarg);
5022 break;
5023 #endif
5024 case QEMU_OPTION_h:
5025 help(0);
5026 break;
5027 case QEMU_OPTION_version:
5028 version();
5029 exit(0);
5030 break;
5031 case QEMU_OPTION_m: {
5032 uint64_t value;
5033 char *ptr;
5035 value = strtoul(optarg, &ptr, 10);
5036 switch (*ptr) {
5037 case 0: case 'M': case 'm':
5038 value <<= 20;
5039 break;
5040 case 'G': case 'g':
5041 value <<= 30;
5042 break;
5043 default:
5044 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5045 exit(1);
5048 /* On 32-bit hosts, QEMU is limited by virtual address space */
5049 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5050 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5051 exit(1);
5053 if (value != (uint64_t)(ram_addr_t)value) {
5054 fprintf(stderr, "qemu: ram size too large\n");
5055 exit(1);
5057 ram_size = value;
5058 break;
5060 case QEMU_OPTION_d:
5062 int mask;
5063 const CPULogItem *item;
5065 mask = cpu_str_to_log_mask(optarg);
5066 if (!mask) {
5067 printf("Log items (comma separated):\n");
5068 for(item = cpu_log_items; item->mask != 0; item++) {
5069 printf("%-10s %s\n", item->name, item->help);
5071 exit(1);
5073 cpu_set_log(mask);
5075 break;
5076 case QEMU_OPTION_s:
5077 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5078 break;
5079 case QEMU_OPTION_gdb:
5080 gdbstub_dev = optarg;
5081 break;
5082 case QEMU_OPTION_L:
5083 data_dir = optarg;
5084 break;
5085 case QEMU_OPTION_bios:
5086 bios_name = optarg;
5087 break;
5088 case QEMU_OPTION_singlestep:
5089 singlestep = 1;
5090 break;
5091 case QEMU_OPTION_S:
5092 autostart = 0;
5093 break;
5094 #ifndef _WIN32
5095 case QEMU_OPTION_k:
5096 keyboard_layout = optarg;
5097 break;
5098 #endif
5099 case QEMU_OPTION_localtime:
5100 rtc_utc = 0;
5101 break;
5102 case QEMU_OPTION_vga:
5103 select_vgahw (optarg);
5104 break;
5105 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5106 case QEMU_OPTION_g:
5108 const char *p;
5109 int w, h, depth;
5110 p = optarg;
5111 w = strtol(p, (char **)&p, 10);
5112 if (w <= 0) {
5113 graphic_error:
5114 fprintf(stderr, "qemu: invalid resolution or depth\n");
5115 exit(1);
5117 if (*p != 'x')
5118 goto graphic_error;
5119 p++;
5120 h = strtol(p, (char **)&p, 10);
5121 if (h <= 0)
5122 goto graphic_error;
5123 if (*p == 'x') {
5124 p++;
5125 depth = strtol(p, (char **)&p, 10);
5126 if (depth != 8 && depth != 15 && depth != 16 &&
5127 depth != 24 && depth != 32)
5128 goto graphic_error;
5129 } else if (*p == '\0') {
5130 depth = graphic_depth;
5131 } else {
5132 goto graphic_error;
5135 graphic_width = w;
5136 graphic_height = h;
5137 graphic_depth = depth;
5139 break;
5140 #endif
5141 case QEMU_OPTION_echr:
5143 char *r;
5144 term_escape_char = strtol(optarg, &r, 0);
5145 if (r == optarg)
5146 printf("Bad argument to echr\n");
5147 break;
5149 case QEMU_OPTION_monitor:
5150 if (monitor_device_index >= MAX_MONITOR_DEVICES) {
5151 fprintf(stderr, "qemu: too many monitor devices\n");
5152 exit(1);
5154 monitor_devices[monitor_device_index] = optarg;
5155 monitor_device_index++;
5156 break;
5157 case QEMU_OPTION_chardev:
5158 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5159 if (!opts) {
5160 fprintf(stderr, "parse error: %s\n", optarg);
5161 exit(1);
5163 if (NULL == qemu_chr_open_opts(opts, NULL)) {
5164 exit(1);
5166 break;
5167 case QEMU_OPTION_serial:
5168 if (serial_device_index >= MAX_SERIAL_PORTS) {
5169 fprintf(stderr, "qemu: too many serial ports\n");
5170 exit(1);
5172 serial_devices[serial_device_index] = optarg;
5173 serial_device_index++;
5174 break;
5175 case QEMU_OPTION_watchdog:
5176 if (watchdog) {
5177 fprintf(stderr,
5178 "qemu: only one watchdog option may be given\n");
5179 return 1;
5181 watchdog = optarg;
5182 break;
5183 case QEMU_OPTION_watchdog_action:
5184 if (select_watchdog_action(optarg) == -1) {
5185 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5186 exit(1);
5188 break;
5189 case QEMU_OPTION_virtiocon:
5190 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5191 fprintf(stderr, "qemu: too many virtio consoles\n");
5192 exit(1);
5194 virtio_consoles[virtio_console_index] = optarg;
5195 virtio_console_index++;
5196 break;
5197 case QEMU_OPTION_parallel:
5198 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5199 fprintf(stderr, "qemu: too many parallel ports\n");
5200 exit(1);
5202 parallel_devices[parallel_device_index] = optarg;
5203 parallel_device_index++;
5204 break;
5205 case QEMU_OPTION_loadvm:
5206 loadvm = optarg;
5207 break;
5208 case QEMU_OPTION_full_screen:
5209 full_screen = 1;
5210 break;
5211 #ifdef CONFIG_SDL
5212 case QEMU_OPTION_no_frame:
5213 no_frame = 1;
5214 break;
5215 case QEMU_OPTION_alt_grab:
5216 alt_grab = 1;
5217 break;
5218 case QEMU_OPTION_no_quit:
5219 no_quit = 1;
5220 break;
5221 case QEMU_OPTION_sdl:
5222 display_type = DT_SDL;
5223 break;
5224 #endif
5225 case QEMU_OPTION_pidfile:
5226 pid_file = optarg;
5227 break;
5228 #ifdef TARGET_I386
5229 case QEMU_OPTION_win2k_hack:
5230 win2k_install_hack = 1;
5231 break;
5232 case QEMU_OPTION_rtc_td_hack:
5233 rtc_td_hack = 1;
5234 break;
5235 case QEMU_OPTION_acpitable:
5236 if(acpi_table_add(optarg) < 0) {
5237 fprintf(stderr, "Wrong acpi table provided\n");
5238 exit(1);
5240 break;
5241 case QEMU_OPTION_smbios:
5242 if(smbios_entry_add(optarg) < 0) {
5243 fprintf(stderr, "Wrong smbios provided\n");
5244 exit(1);
5246 break;
5247 #endif
5248 #ifdef CONFIG_KVM
5249 case QEMU_OPTION_enable_kvm:
5250 kvm_allowed = 1;
5251 break;
5252 #endif
5253 case QEMU_OPTION_usb:
5254 usb_enabled = 1;
5255 break;
5256 case QEMU_OPTION_usbdevice:
5257 usb_enabled = 1;
5258 add_device_config(DEV_USB, optarg);
5259 break;
5260 case QEMU_OPTION_device:
5261 opts = qemu_opts_parse(&qemu_device_opts, optarg, "driver");
5262 if (!opts) {
5263 fprintf(stderr, "parse error: %s\n", optarg);
5264 exit(1);
5266 break;
5267 case QEMU_OPTION_smp:
5268 smp_parse(optarg);
5269 if (smp_cpus < 1) {
5270 fprintf(stderr, "Invalid number of CPUs\n");
5271 exit(1);
5273 if (max_cpus < smp_cpus) {
5274 fprintf(stderr, "maxcpus must be equal to or greater than "
5275 "smp\n");
5276 exit(1);
5278 if (max_cpus > 255) {
5279 fprintf(stderr, "Unsupported number of maxcpus\n");
5280 exit(1);
5282 break;
5283 case QEMU_OPTION_vnc:
5284 display_type = DT_VNC;
5285 vnc_display = optarg;
5286 break;
5287 #ifdef TARGET_I386
5288 case QEMU_OPTION_no_acpi:
5289 acpi_enabled = 0;
5290 break;
5291 case QEMU_OPTION_no_hpet:
5292 no_hpet = 1;
5293 break;
5294 case QEMU_OPTION_balloon:
5295 if (balloon_parse(optarg) < 0) {
5296 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5297 exit(1);
5299 break;
5300 #endif
5301 case QEMU_OPTION_no_reboot:
5302 no_reboot = 1;
5303 break;
5304 case QEMU_OPTION_no_shutdown:
5305 no_shutdown = 1;
5306 break;
5307 case QEMU_OPTION_show_cursor:
5308 cursor_hide = 0;
5309 break;
5310 case QEMU_OPTION_uuid:
5311 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5312 fprintf(stderr, "Fail to parse UUID string."
5313 " Wrong format.\n");
5314 exit(1);
5316 break;
5317 #ifndef _WIN32
5318 case QEMU_OPTION_daemonize:
5319 daemonize = 1;
5320 break;
5321 #endif
5322 case QEMU_OPTION_option_rom:
5323 if (nb_option_roms >= MAX_OPTION_ROMS) {
5324 fprintf(stderr, "Too many option ROMs\n");
5325 exit(1);
5327 option_rom[nb_option_roms] = optarg;
5328 nb_option_roms++;
5329 break;
5330 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5331 case QEMU_OPTION_semihosting:
5332 semihosting_enabled = 1;
5333 break;
5334 #endif
5335 case QEMU_OPTION_name:
5336 qemu_name = qemu_strdup(optarg);
5338 char *p = strchr(qemu_name, ',');
5339 if (p != NULL) {
5340 *p++ = 0;
5341 if (strncmp(p, "process=", 8)) {
5342 fprintf(stderr, "Unknown subargument %s to -name", p);
5343 exit(1);
5345 p += 8;
5346 set_proc_name(p);
5349 break;
5350 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5351 case QEMU_OPTION_prom_env:
5352 if (nb_prom_envs >= MAX_PROM_ENVS) {
5353 fprintf(stderr, "Too many prom variables\n");
5354 exit(1);
5356 prom_envs[nb_prom_envs] = optarg;
5357 nb_prom_envs++;
5358 break;
5359 #endif
5360 #ifdef TARGET_ARM
5361 case QEMU_OPTION_old_param:
5362 old_param = 1;
5363 break;
5364 #endif
5365 case QEMU_OPTION_clock:
5366 configure_alarms(optarg);
5367 break;
5368 case QEMU_OPTION_startdate:
5370 struct tm tm;
5371 time_t rtc_start_date;
5372 if (!strcmp(optarg, "now")) {
5373 rtc_date_offset = -1;
5374 } else {
5375 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5376 &tm.tm_year,
5377 &tm.tm_mon,
5378 &tm.tm_mday,
5379 &tm.tm_hour,
5380 &tm.tm_min,
5381 &tm.tm_sec) == 6) {
5382 /* OK */
5383 } else if (sscanf(optarg, "%d-%d-%d",
5384 &tm.tm_year,
5385 &tm.tm_mon,
5386 &tm.tm_mday) == 3) {
5387 tm.tm_hour = 0;
5388 tm.tm_min = 0;
5389 tm.tm_sec = 0;
5390 } else {
5391 goto date_fail;
5393 tm.tm_year -= 1900;
5394 tm.tm_mon--;
5395 rtc_start_date = mktimegm(&tm);
5396 if (rtc_start_date == -1) {
5397 date_fail:
5398 fprintf(stderr, "Invalid date format. Valid format are:\n"
5399 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5400 exit(1);
5402 rtc_date_offset = time(NULL) - rtc_start_date;
5405 break;
5406 case QEMU_OPTION_tb_size:
5407 tb_size = strtol(optarg, NULL, 0);
5408 if (tb_size < 0)
5409 tb_size = 0;
5410 break;
5411 case QEMU_OPTION_icount:
5412 use_icount = 1;
5413 if (strcmp(optarg, "auto") == 0) {
5414 icount_time_shift = -1;
5415 } else {
5416 icount_time_shift = strtol(optarg, NULL, 0);
5418 break;
5419 case QEMU_OPTION_incoming:
5420 incoming = optarg;
5421 break;
5422 #ifndef _WIN32
5423 case QEMU_OPTION_chroot:
5424 chroot_dir = optarg;
5425 break;
5426 case QEMU_OPTION_runas:
5427 run_as = optarg;
5428 break;
5429 #endif
5430 #ifdef CONFIG_XEN
5431 case QEMU_OPTION_xen_domid:
5432 xen_domid = atoi(optarg);
5433 break;
5434 case QEMU_OPTION_xen_create:
5435 xen_mode = XEN_CREATE;
5436 break;
5437 case QEMU_OPTION_xen_attach:
5438 xen_mode = XEN_ATTACH;
5439 break;
5440 #endif
5445 if (kvm_enabled()) {
5446 int ret;
5448 ret = kvm_init(smp_cpus);
5449 if (ret < 0) {
5450 fprintf(stderr, "failed to initialize KVM\n");
5451 exit(1);
5455 /* If no data_dir is specified then try to find it relative to the
5456 executable path. */
5457 if (!data_dir) {
5458 data_dir = find_datadir(argv[0]);
5460 /* If all else fails use the install patch specified when building. */
5461 if (!data_dir) {
5462 data_dir = CONFIG_QEMU_SHAREDIR;
5466 * Default to max_cpus = smp_cpus, in case the user doesn't
5467 * specify a max_cpus value.
5469 if (!max_cpus)
5470 max_cpus = smp_cpus;
5472 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5473 if (smp_cpus > machine->max_cpus) {
5474 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5475 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5476 machine->max_cpus);
5477 exit(1);
5480 if (display_type == DT_NOGRAPHIC) {
5481 if (serial_device_index == 0)
5482 serial_devices[0] = "stdio";
5483 if (parallel_device_index == 0)
5484 parallel_devices[0] = "null";
5485 if (strncmp(monitor_devices[0], "vc", 2) == 0) {
5486 monitor_devices[0] = "stdio";
5490 #ifndef _WIN32
5491 if (daemonize) {
5492 pid_t pid;
5494 if (pipe(fds) == -1)
5495 exit(1);
5497 pid = fork();
5498 if (pid > 0) {
5499 uint8_t status;
5500 ssize_t len;
5502 close(fds[1]);
5504 again:
5505 len = read(fds[0], &status, 1);
5506 if (len == -1 && (errno == EINTR))
5507 goto again;
5509 if (len != 1)
5510 exit(1);
5511 else if (status == 1) {
5512 fprintf(stderr, "Could not acquire pidfile\n");
5513 exit(1);
5514 } else
5515 exit(0);
5516 } else if (pid < 0)
5517 exit(1);
5519 setsid();
5521 pid = fork();
5522 if (pid > 0)
5523 exit(0);
5524 else if (pid < 0)
5525 exit(1);
5527 umask(027);
5529 signal(SIGTSTP, SIG_IGN);
5530 signal(SIGTTOU, SIG_IGN);
5531 signal(SIGTTIN, SIG_IGN);
5534 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5535 if (daemonize) {
5536 uint8_t status = 1;
5537 write(fds[1], &status, 1);
5538 } else
5539 fprintf(stderr, "Could not acquire pid file\n");
5540 exit(1);
5542 #endif
5544 if (qemu_init_main_loop()) {
5545 fprintf(stderr, "qemu_init_main_loop failed\n");
5546 exit(1);
5548 linux_boot = (kernel_filename != NULL);
5550 if (!linux_boot && *kernel_cmdline != '\0') {
5551 fprintf(stderr, "-append only allowed with -kernel option\n");
5552 exit(1);
5555 if (!linux_boot && initrd_filename != NULL) {
5556 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5557 exit(1);
5560 #ifndef _WIN32
5561 /* Win32 doesn't support line-buffering and requires size >= 2 */
5562 setvbuf(stdout, NULL, _IOLBF, 0);
5563 #endif
5565 init_timers();
5566 if (init_timer_alarm() < 0) {
5567 fprintf(stderr, "could not initialize alarm timer\n");
5568 exit(1);
5570 if (use_icount && icount_time_shift < 0) {
5571 use_icount = 2;
5572 /* 125MIPS seems a reasonable initial guess at the guest speed.
5573 It will be corrected fairly quickly anyway. */
5574 icount_time_shift = 3;
5575 init_icount_adjust();
5578 #ifdef _WIN32
5579 socket_init();
5580 #endif
5582 /* init network clients */
5583 if (nb_net_clients == 0) {
5584 /* if no clients, we use a default config */
5585 net_clients[nb_net_clients++] = "nic";
5586 #ifdef CONFIG_SLIRP
5587 net_clients[nb_net_clients++] = "user";
5588 #endif
5591 for(i = 0;i < nb_net_clients; i++) {
5592 if (net_client_parse(net_clients[i]) < 0)
5593 exit(1);
5596 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5597 net_set_boot_mask(net_boot);
5599 net_client_check();
5601 /* init the bluetooth world */
5602 if (foreach_device_config(DEV_BT, bt_parse))
5603 exit(1);
5605 /* init the memory */
5606 if (ram_size == 0)
5607 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5609 /* init the dynamic translator */
5610 cpu_exec_init_all(tb_size * 1024 * 1024);
5612 bdrv_init();
5614 /* we always create the cdrom drive, even if no disk is there */
5615 drive_add(NULL, CDROM_ALIAS);
5617 /* we always create at least one floppy */
5618 drive_add(NULL, FD_ALIAS, 0);
5620 /* we always create one sd slot, even if no card is in it */
5621 drive_add(NULL, SD_ALIAS);
5623 /* open the virtual block devices */
5624 if (snapshot)
5625 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5626 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5627 exit(1);
5629 register_savevm("timer", 0, 2, timer_save, timer_load, &timers_state);
5630 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5632 /* Maintain compatibility with multiple stdio monitors */
5633 if (!strcmp(monitor_devices[0],"stdio")) {
5634 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5635 const char *devname = serial_devices[i];
5636 if (devname && !strcmp(devname,"mon:stdio")) {
5637 monitor_devices[0] = NULL;
5638 break;
5639 } else if (devname && !strcmp(devname,"stdio")) {
5640 monitor_devices[0] = NULL;
5641 serial_devices[i] = "mon:stdio";
5642 break;
5647 if (nb_numa_nodes > 0) {
5648 int i;
5650 if (nb_numa_nodes > smp_cpus) {
5651 nb_numa_nodes = smp_cpus;
5654 /* If no memory size if given for any node, assume the default case
5655 * and distribute the available memory equally across all nodes
5657 for (i = 0; i < nb_numa_nodes; i++) {
5658 if (node_mem[i] != 0)
5659 break;
5661 if (i == nb_numa_nodes) {
5662 uint64_t usedmem = 0;
5664 /* On Linux, the each node's border has to be 8MB aligned,
5665 * the final node gets the rest.
5667 for (i = 0; i < nb_numa_nodes - 1; i++) {
5668 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5669 usedmem += node_mem[i];
5671 node_mem[i] = ram_size - usedmem;
5674 for (i = 0; i < nb_numa_nodes; i++) {
5675 if (node_cpumask[i] != 0)
5676 break;
5678 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5679 * must cope with this anyway, because there are BIOSes out there in
5680 * real machines which also use this scheme.
5682 if (i == nb_numa_nodes) {
5683 for (i = 0; i < smp_cpus; i++) {
5684 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5689 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5690 const char *devname = monitor_devices[i];
5691 if (devname && strcmp(devname, "none")) {
5692 char label[32];
5693 if (i == 0) {
5694 snprintf(label, sizeof(label), "monitor");
5695 } else {
5696 snprintf(label, sizeof(label), "monitor%d", i);
5698 monitor_hds[i] = qemu_chr_open(label, devname, NULL);
5699 if (!monitor_hds[i]) {
5700 fprintf(stderr, "qemu: could not open monitor device '%s'\n",
5701 devname);
5702 exit(1);
5707 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5708 const char *devname = serial_devices[i];
5709 if (devname && strcmp(devname, "none")) {
5710 char label[32];
5711 snprintf(label, sizeof(label), "serial%d", i);
5712 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5713 if (!serial_hds[i]) {
5714 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5715 devname);
5716 exit(1);
5721 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5722 const char *devname = parallel_devices[i];
5723 if (devname && strcmp(devname, "none")) {
5724 char label[32];
5725 snprintf(label, sizeof(label), "parallel%d", i);
5726 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5727 if (!parallel_hds[i]) {
5728 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5729 devname);
5730 exit(1);
5735 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5736 const char *devname = virtio_consoles[i];
5737 if (devname && strcmp(devname, "none")) {
5738 char label[32];
5739 snprintf(label, sizeof(label), "virtcon%d", i);
5740 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5741 if (!virtcon_hds[i]) {
5742 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5743 devname);
5744 exit(1);
5749 module_call_init(MODULE_INIT_DEVICE);
5751 if (watchdog) {
5752 i = select_watchdog(watchdog);
5753 if (i > 0)
5754 exit (i == 1 ? 1 : 0);
5757 if (machine->compat_props) {
5758 qdev_prop_register_compat(machine->compat_props);
5760 machine->init(ram_size, boot_devices,
5761 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5764 #ifndef _WIN32
5765 /* must be after terminal init, SDL library changes signal handlers */
5766 sighandler_setup();
5767 #endif
5769 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5770 for (i = 0; i < nb_numa_nodes; i++) {
5771 if (node_cpumask[i] & (1 << env->cpu_index)) {
5772 env->numa_node = i;
5777 current_machine = machine;
5779 /* init USB devices */
5780 if (usb_enabled) {
5781 foreach_device_config(DEV_USB, usb_parse);
5784 /* init generic devices */
5785 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5786 exit(1);
5788 if (!display_state)
5789 dumb_display_init();
5790 /* just use the first displaystate for the moment */
5791 ds = display_state;
5793 if (display_type == DT_DEFAULT) {
5794 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5795 display_type = DT_SDL;
5796 #else
5797 display_type = DT_VNC;
5798 vnc_display = "localhost:0,to=99";
5799 show_vnc_port = 1;
5800 #endif
5804 switch (display_type) {
5805 case DT_NOGRAPHIC:
5806 break;
5807 #if defined(CONFIG_CURSES)
5808 case DT_CURSES:
5809 curses_display_init(ds, full_screen);
5810 break;
5811 #endif
5812 #if defined(CONFIG_SDL)
5813 case DT_SDL:
5814 sdl_display_init(ds, full_screen, no_frame);
5815 break;
5816 #elif defined(CONFIG_COCOA)
5817 case DT_SDL:
5818 cocoa_display_init(ds, full_screen);
5819 break;
5820 #endif
5821 case DT_VNC:
5822 vnc_display_init(ds);
5823 if (vnc_display_open(ds, vnc_display) < 0)
5824 exit(1);
5826 if (show_vnc_port) {
5827 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5829 break;
5830 default:
5831 break;
5833 dpy_resize(ds);
5835 dcl = ds->listeners;
5836 while (dcl != NULL) {
5837 if (dcl->dpy_refresh != NULL) {
5838 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5839 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5841 dcl = dcl->next;
5844 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5845 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5846 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5849 text_consoles_set_display(display_state);
5850 qemu_chr_initial_reset();
5852 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5853 if (monitor_devices[i] && monitor_hds[i]) {
5854 monitor_init(monitor_hds[i],
5855 MONITOR_USE_READLINE |
5856 ((i == 0) ? MONITOR_IS_DEFAULT : 0));
5860 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5861 const char *devname = serial_devices[i];
5862 if (devname && strcmp(devname, "none")) {
5863 if (strstart(devname, "vc", 0))
5864 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5868 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5869 const char *devname = parallel_devices[i];
5870 if (devname && strcmp(devname, "none")) {
5871 if (strstart(devname, "vc", 0))
5872 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5876 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5877 const char *devname = virtio_consoles[i];
5878 if (virtcon_hds[i] && devname) {
5879 if (strstart(devname, "vc", 0))
5880 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5884 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5885 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5886 gdbstub_dev);
5887 exit(1);
5890 if (loadvm) {
5891 if (load_vmstate(cur_mon, loadvm) < 0) {
5892 autostart = 0;
5896 if (incoming) {
5897 qemu_start_incoming_migration(incoming);
5898 } else if (autostart) {
5899 vm_start();
5902 #ifndef _WIN32
5903 if (daemonize) {
5904 uint8_t status = 0;
5905 ssize_t len;
5907 again1:
5908 len = write(fds[1], &status, 1);
5909 if (len == -1 && (errno == EINTR))
5910 goto again1;
5912 if (len != 1)
5913 exit(1);
5915 chdir("/");
5916 TFR(fd = open("/dev/null", O_RDWR));
5917 if (fd == -1)
5918 exit(1);
5921 if (run_as) {
5922 pwd = getpwnam(run_as);
5923 if (!pwd) {
5924 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5925 exit(1);
5929 if (chroot_dir) {
5930 if (chroot(chroot_dir) < 0) {
5931 fprintf(stderr, "chroot failed\n");
5932 exit(1);
5934 chdir("/");
5937 if (run_as) {
5938 if (setgid(pwd->pw_gid) < 0) {
5939 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5940 exit(1);
5942 if (setuid(pwd->pw_uid) < 0) {
5943 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5944 exit(1);
5946 if (setuid(0) != -1) {
5947 fprintf(stderr, "Dropping privileges failed\n");
5948 exit(1);
5952 if (daemonize) {
5953 dup2(fd, 0);
5954 dup2(fd, 1);
5955 dup2(fd, 2);
5957 close(fd);
5959 #endif
5961 main_loop();
5962 quit_timers();
5963 net_cleanup();
5965 return 0;