net: fix coding style nit
[qemu/aliguori-queue.git] / vl.c
blob7bfd41593158060b09f61293d0136d5705ebe8a1
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <libgen.h>
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
49 #endif
50 #ifdef __linux__
51 #include <linux/if_tun.h>
52 #endif
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef CONFIG_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
60 #include <libutil.h>
61 #else
62 #include <util.h>
63 #endif
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
66 #else
67 #ifdef __linux__
68 #include <pty.h>
69 #include <malloc.h>
70 #include <linux/rtc.h>
71 #include <sys/prctl.h>
73 /* For the benefit of older linux systems which don't supply it,
74 we use a local copy of hpet.h. */
75 /* #include <linux/hpet.h> */
76 #include "hpet.h"
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
80 #endif
81 #ifdef __sun__
82 #include <sys/stat.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
92 #include <net/if.h>
93 #include <syslog.h>
94 #include <stropts.h>
95 #endif
96 #endif
97 #endif
99 #if defined(__OpenBSD__)
100 #include <util.h>
101 #endif
103 #if defined(CONFIG_VDE)
104 #include <libvdeplug.h>
105 #endif
107 #ifdef _WIN32
108 #include <windows.h>
109 #include <mmsystem.h>
110 #endif
112 #ifdef CONFIG_SDL
113 #if defined(__APPLE__) || defined(main)
114 #include <SDL.h>
115 int qemu_main(int argc, char **argv, char **envp);
116 int main(int argc, char **argv)
118 return qemu_main(argc, argv, NULL);
120 #undef main
121 #define main qemu_main
122 #endif
123 #endif /* CONFIG_SDL */
125 #ifdef CONFIG_COCOA
126 #undef main
127 #define main qemu_main
128 #endif /* CONFIG_COCOA */
130 #include "hw/hw.h"
131 #include "hw/boards.h"
132 #include "hw/usb.h"
133 #include "hw/pcmcia.h"
134 #include "hw/pc.h"
135 #include "hw/audiodev.h"
136 #include "hw/isa.h"
137 #include "hw/baum.h"
138 #include "hw/bt.h"
139 #include "hw/watchdog.h"
140 #include "hw/smbios.h"
141 #include "hw/xen.h"
142 #include "hw/qdev.h"
143 #include "bt-host.h"
144 #include "net.h"
145 #include "monitor.h"
146 #include "console.h"
147 #include "sysemu.h"
148 #include "gdbstub.h"
149 #include "qemu-timer.h"
150 #include "qemu-char.h"
151 #include "cache-utils.h"
152 #include "block.h"
153 #include "dma.h"
154 #include "audio/audio.h"
155 #include "migration.h"
156 #include "kvm.h"
157 #include "balloon.h"
158 #include "qemu-option.h"
159 #include "qemu-config.h"
161 #include "disas.h"
163 #include "exec-all.h"
165 #include "qemu_socket.h"
167 #include "slirp/libslirp.h"
169 #include "qemu-queue.h"
171 //#define DEBUG_NET
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 /* 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 = QTAILQ_HEAD_INITIALIZER(drives);
184 struct driveoptlist driveopts = QTAILQ_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 #ifdef WIN32
533 static int64_t clock_freq;
535 static void init_get_clock(void)
537 LARGE_INTEGER freq;
538 int ret;
539 ret = QueryPerformanceFrequency(&freq);
540 if (ret == 0) {
541 fprintf(stderr, "Could not calibrate ticks\n");
542 exit(1);
544 clock_freq = freq.QuadPart;
547 static int64_t get_clock(void)
549 LARGE_INTEGER ti;
550 QueryPerformanceCounter(&ti);
551 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
554 #else
556 static int use_rt_clock;
558 static void init_get_clock(void)
560 use_rt_clock = 0;
561 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
562 || defined(__DragonFly__)
564 struct timespec ts;
565 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
566 use_rt_clock = 1;
569 #endif
572 static int64_t get_clock(void)
574 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
575 || defined(__DragonFly__)
576 if (use_rt_clock) {
577 struct timespec ts;
578 clock_gettime(CLOCK_MONOTONIC, &ts);
579 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
580 } else
581 #endif
583 /* XXX: using gettimeofday leads to problems if the date
584 changes, so it should be avoided. */
585 struct timeval tv;
586 gettimeofday(&tv, NULL);
587 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
590 #endif
592 /* Return the virtual CPU time, based on the instruction counter. */
593 static int64_t cpu_get_icount(void)
595 int64_t icount;
596 CPUState *env = cpu_single_env;;
597 icount = qemu_icount;
598 if (env) {
599 if (!can_do_io(env))
600 fprintf(stderr, "Bad clock read\n");
601 icount -= (env->icount_decr.u16.low + env->icount_extra);
603 return qemu_icount_bias + (icount << icount_time_shift);
606 /***********************************************************/
607 /* guest cycle counter */
609 typedef struct TimersState {
610 int64_t cpu_ticks_prev;
611 int64_t cpu_ticks_offset;
612 int64_t cpu_clock_offset;
613 int32_t cpu_ticks_enabled;
614 int64_t dummy;
615 } TimersState;
617 TimersState timers_state;
619 /* return the host CPU cycle counter and handle stop/restart */
620 int64_t cpu_get_ticks(void)
622 if (use_icount) {
623 return cpu_get_icount();
625 if (!timers_state.cpu_ticks_enabled) {
626 return timers_state.cpu_ticks_offset;
627 } else {
628 int64_t ticks;
629 ticks = cpu_get_real_ticks();
630 if (timers_state.cpu_ticks_prev > ticks) {
631 /* Note: non increasing ticks may happen if the host uses
632 software suspend */
633 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
635 timers_state.cpu_ticks_prev = ticks;
636 return ticks + timers_state.cpu_ticks_offset;
640 /* return the host CPU monotonic timer and handle stop/restart */
641 static int64_t cpu_get_clock(void)
643 int64_t ti;
644 if (!timers_state.cpu_ticks_enabled) {
645 return timers_state.cpu_clock_offset;
646 } else {
647 ti = get_clock();
648 return ti + timers_state.cpu_clock_offset;
652 /* enable cpu_get_ticks() */
653 void cpu_enable_ticks(void)
655 if (!timers_state.cpu_ticks_enabled) {
656 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
657 timers_state.cpu_clock_offset -= get_clock();
658 timers_state.cpu_ticks_enabled = 1;
662 /* disable cpu_get_ticks() : the clock is stopped. You must not call
663 cpu_get_ticks() after that. */
664 void cpu_disable_ticks(void)
666 if (timers_state.cpu_ticks_enabled) {
667 timers_state.cpu_ticks_offset = cpu_get_ticks();
668 timers_state.cpu_clock_offset = cpu_get_clock();
669 timers_state.cpu_ticks_enabled = 0;
673 /***********************************************************/
674 /* timers */
676 #define QEMU_TIMER_REALTIME 0
677 #define QEMU_TIMER_VIRTUAL 1
679 struct QEMUClock {
680 int type;
681 /* XXX: add frequency */
684 struct QEMUTimer {
685 QEMUClock *clock;
686 int64_t expire_time;
687 QEMUTimerCB *cb;
688 void *opaque;
689 struct QEMUTimer *next;
692 struct qemu_alarm_timer {
693 char const *name;
694 unsigned int flags;
696 int (*start)(struct qemu_alarm_timer *t);
697 void (*stop)(struct qemu_alarm_timer *t);
698 void (*rearm)(struct qemu_alarm_timer *t);
699 void *priv;
702 #define ALARM_FLAG_DYNTICKS 0x1
703 #define ALARM_FLAG_EXPIRED 0x2
705 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
707 return t && (t->flags & ALARM_FLAG_DYNTICKS);
710 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
712 if (!alarm_has_dynticks(t))
713 return;
715 t->rearm(t);
718 /* TODO: MIN_TIMER_REARM_US should be optimized */
719 #define MIN_TIMER_REARM_US 250
721 static struct qemu_alarm_timer *alarm_timer;
723 #ifdef _WIN32
725 struct qemu_alarm_win32 {
726 MMRESULT timerId;
727 unsigned int period;
728 } alarm_win32_data = {0, -1};
730 static int win32_start_timer(struct qemu_alarm_timer *t);
731 static void win32_stop_timer(struct qemu_alarm_timer *t);
732 static void win32_rearm_timer(struct qemu_alarm_timer *t);
734 #else
736 static int unix_start_timer(struct qemu_alarm_timer *t);
737 static void unix_stop_timer(struct qemu_alarm_timer *t);
739 #ifdef __linux__
741 static int dynticks_start_timer(struct qemu_alarm_timer *t);
742 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
743 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
745 static int hpet_start_timer(struct qemu_alarm_timer *t);
746 static void hpet_stop_timer(struct qemu_alarm_timer *t);
748 static int rtc_start_timer(struct qemu_alarm_timer *t);
749 static void rtc_stop_timer(struct qemu_alarm_timer *t);
751 #endif /* __linux__ */
753 #endif /* _WIN32 */
755 /* Correlation between real and virtual time is always going to be
756 fairly approximate, so ignore small variation.
757 When the guest is idle real and virtual time will be aligned in
758 the IO wait loop. */
759 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
761 static void icount_adjust(void)
763 int64_t cur_time;
764 int64_t cur_icount;
765 int64_t delta;
766 static int64_t last_delta;
767 /* If the VM is not running, then do nothing. */
768 if (!vm_running)
769 return;
771 cur_time = cpu_get_clock();
772 cur_icount = qemu_get_clock(vm_clock);
773 delta = cur_icount - cur_time;
774 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
775 if (delta > 0
776 && last_delta + ICOUNT_WOBBLE < delta * 2
777 && icount_time_shift > 0) {
778 /* The guest is getting too far ahead. Slow time down. */
779 icount_time_shift--;
781 if (delta < 0
782 && last_delta - ICOUNT_WOBBLE > delta * 2
783 && icount_time_shift < MAX_ICOUNT_SHIFT) {
784 /* The guest is getting too far behind. Speed time up. */
785 icount_time_shift++;
787 last_delta = delta;
788 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
791 static void icount_adjust_rt(void * opaque)
793 qemu_mod_timer(icount_rt_timer,
794 qemu_get_clock(rt_clock) + 1000);
795 icount_adjust();
798 static void icount_adjust_vm(void * opaque)
800 qemu_mod_timer(icount_vm_timer,
801 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
802 icount_adjust();
805 static void init_icount_adjust(void)
807 /* Have both realtime and virtual time triggers for speed adjustment.
808 The realtime trigger catches emulated time passing too slowly,
809 the virtual time trigger catches emulated time passing too fast.
810 Realtime triggers occur even when idle, so use them less frequently
811 than VM triggers. */
812 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
813 qemu_mod_timer(icount_rt_timer,
814 qemu_get_clock(rt_clock) + 1000);
815 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
816 qemu_mod_timer(icount_vm_timer,
817 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
820 static struct qemu_alarm_timer alarm_timers[] = {
821 #ifndef _WIN32
822 #ifdef __linux__
823 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
824 dynticks_stop_timer, dynticks_rearm_timer, NULL},
825 /* HPET - if available - is preferred */
826 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
827 /* ...otherwise try RTC */
828 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
829 #endif
830 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
831 #else
832 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
833 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
834 {"win32", 0, win32_start_timer,
835 win32_stop_timer, NULL, &alarm_win32_data},
836 #endif
837 {NULL, }
840 static void show_available_alarms(void)
842 int i;
844 printf("Available alarm timers, in order of precedence:\n");
845 for (i = 0; alarm_timers[i].name; i++)
846 printf("%s\n", alarm_timers[i].name);
849 static void configure_alarms(char const *opt)
851 int i;
852 int cur = 0;
853 int count = ARRAY_SIZE(alarm_timers) - 1;
854 char *arg;
855 char *name;
856 struct qemu_alarm_timer tmp;
858 if (!strcmp(opt, "?")) {
859 show_available_alarms();
860 exit(0);
863 arg = qemu_strdup(opt);
865 /* Reorder the array */
866 name = strtok(arg, ",");
867 while (name) {
868 for (i = 0; i < count && alarm_timers[i].name; i++) {
869 if (!strcmp(alarm_timers[i].name, name))
870 break;
873 if (i == count) {
874 fprintf(stderr, "Unknown clock %s\n", name);
875 goto next;
878 if (i < cur)
879 /* Ignore */
880 goto next;
882 /* Swap */
883 tmp = alarm_timers[i];
884 alarm_timers[i] = alarm_timers[cur];
885 alarm_timers[cur] = tmp;
887 cur++;
888 next:
889 name = strtok(NULL, ",");
892 qemu_free(arg);
894 if (cur) {
895 /* Disable remaining timers */
896 for (i = cur; i < count; i++)
897 alarm_timers[i].name = NULL;
898 } else {
899 show_available_alarms();
900 exit(1);
904 QEMUClock *rt_clock;
905 QEMUClock *vm_clock;
907 static QEMUTimer *active_timers[2];
909 static QEMUClock *qemu_new_clock(int type)
911 QEMUClock *clock;
912 clock = qemu_mallocz(sizeof(QEMUClock));
913 clock->type = type;
914 return clock;
917 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
919 QEMUTimer *ts;
921 ts = qemu_mallocz(sizeof(QEMUTimer));
922 ts->clock = clock;
923 ts->cb = cb;
924 ts->opaque = opaque;
925 return ts;
928 void qemu_free_timer(QEMUTimer *ts)
930 qemu_free(ts);
933 /* stop a timer, but do not dealloc it */
934 void qemu_del_timer(QEMUTimer *ts)
936 QEMUTimer **pt, *t;
938 /* NOTE: this code must be signal safe because
939 qemu_timer_expired() can be called from a signal. */
940 pt = &active_timers[ts->clock->type];
941 for(;;) {
942 t = *pt;
943 if (!t)
944 break;
945 if (t == ts) {
946 *pt = t->next;
947 break;
949 pt = &t->next;
953 /* modify the current timer so that it will be fired when current_time
954 >= expire_time. The corresponding callback will be called. */
955 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
957 QEMUTimer **pt, *t;
959 qemu_del_timer(ts);
961 /* add the timer in the sorted list */
962 /* NOTE: this code must be signal safe because
963 qemu_timer_expired() can be called from a signal. */
964 pt = &active_timers[ts->clock->type];
965 for(;;) {
966 t = *pt;
967 if (!t)
968 break;
969 if (t->expire_time > expire_time)
970 break;
971 pt = &t->next;
973 ts->expire_time = expire_time;
974 ts->next = *pt;
975 *pt = ts;
977 /* Rearm if necessary */
978 if (pt == &active_timers[ts->clock->type]) {
979 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
980 qemu_rearm_alarm_timer(alarm_timer);
982 /* Interrupt execution to force deadline recalculation. */
983 if (use_icount)
984 qemu_notify_event();
988 int qemu_timer_pending(QEMUTimer *ts)
990 QEMUTimer *t;
991 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
992 if (t == ts)
993 return 1;
995 return 0;
998 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1000 if (!timer_head)
1001 return 0;
1002 return (timer_head->expire_time <= current_time);
1005 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1007 QEMUTimer *ts;
1009 for(;;) {
1010 ts = *ptimer_head;
1011 if (!ts || ts->expire_time > current_time)
1012 break;
1013 /* remove timer from the list before calling the callback */
1014 *ptimer_head = ts->next;
1015 ts->next = NULL;
1017 /* run the callback (the timer list can be modified) */
1018 ts->cb(ts->opaque);
1022 int64_t qemu_get_clock(QEMUClock *clock)
1024 switch(clock->type) {
1025 case QEMU_TIMER_REALTIME:
1026 return get_clock() / 1000000;
1027 default:
1028 case QEMU_TIMER_VIRTUAL:
1029 if (use_icount) {
1030 return cpu_get_icount();
1031 } else {
1032 return cpu_get_clock();
1037 static void init_timers(void)
1039 init_get_clock();
1040 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1041 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1044 /* save a timer */
1045 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1047 uint64_t expire_time;
1049 if (qemu_timer_pending(ts)) {
1050 expire_time = ts->expire_time;
1051 } else {
1052 expire_time = -1;
1054 qemu_put_be64(f, expire_time);
1057 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1059 uint64_t expire_time;
1061 expire_time = qemu_get_be64(f);
1062 if (expire_time != -1) {
1063 qemu_mod_timer(ts, expire_time);
1064 } else {
1065 qemu_del_timer(ts);
1069 static const VMStateDescription vmstate_timers = {
1070 .name = "timer",
1071 .version_id = 2,
1072 .minimum_version_id = 1,
1073 .minimum_version_id_old = 1,
1074 .fields = (VMStateField []) {
1075 VMSTATE_INT64(cpu_ticks_offset, TimersState),
1076 VMSTATE_INT64(dummy, TimersState),
1077 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1078 VMSTATE_END_OF_LIST()
1082 static void qemu_event_increment(void);
1084 #ifdef _WIN32
1085 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1086 DWORD_PTR dwUser, DWORD_PTR dw1,
1087 DWORD_PTR dw2)
1088 #else
1089 static void host_alarm_handler(int host_signum)
1090 #endif
1092 #if 0
1093 #define DISP_FREQ 1000
1095 static int64_t delta_min = INT64_MAX;
1096 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1097 static int count;
1098 ti = qemu_get_clock(vm_clock);
1099 if (last_clock != 0) {
1100 delta = ti - last_clock;
1101 if (delta < delta_min)
1102 delta_min = delta;
1103 if (delta > delta_max)
1104 delta_max = delta;
1105 delta_cum += delta;
1106 if (++count == DISP_FREQ) {
1107 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1108 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1109 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1110 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1111 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1112 count = 0;
1113 delta_min = INT64_MAX;
1114 delta_max = 0;
1115 delta_cum = 0;
1118 last_clock = ti;
1120 #endif
1121 if (alarm_has_dynticks(alarm_timer) ||
1122 (!use_icount &&
1123 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1124 qemu_get_clock(vm_clock))) ||
1125 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1126 qemu_get_clock(rt_clock))) {
1127 qemu_event_increment();
1128 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1130 #ifndef CONFIG_IOTHREAD
1131 if (next_cpu) {
1132 /* stop the currently executing cpu because a timer occured */
1133 cpu_exit(next_cpu);
1135 #endif
1136 timer_alarm_pending = 1;
1137 qemu_notify_event();
1141 static int64_t qemu_next_deadline(void)
1143 int64_t delta;
1145 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1146 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1147 qemu_get_clock(vm_clock);
1148 } else {
1149 /* To avoid problems with overflow limit this to 2^32. */
1150 delta = INT32_MAX;
1153 if (delta < 0)
1154 delta = 0;
1156 return delta;
1159 #if defined(__linux__) || defined(_WIN32)
1160 static uint64_t qemu_next_deadline_dyntick(void)
1162 int64_t delta;
1163 int64_t rtdelta;
1165 if (use_icount)
1166 delta = INT32_MAX;
1167 else
1168 delta = (qemu_next_deadline() + 999) / 1000;
1170 if (active_timers[QEMU_TIMER_REALTIME]) {
1171 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1172 qemu_get_clock(rt_clock))*1000;
1173 if (rtdelta < delta)
1174 delta = rtdelta;
1177 if (delta < MIN_TIMER_REARM_US)
1178 delta = MIN_TIMER_REARM_US;
1180 return delta;
1182 #endif
1184 #ifndef _WIN32
1186 /* Sets a specific flag */
1187 static int fcntl_setfl(int fd, int flag)
1189 int flags;
1191 flags = fcntl(fd, F_GETFL);
1192 if (flags == -1)
1193 return -errno;
1195 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1196 return -errno;
1198 return 0;
1201 #if defined(__linux__)
1203 #define RTC_FREQ 1024
1205 static void enable_sigio_timer(int fd)
1207 struct sigaction act;
1209 /* timer signal */
1210 sigfillset(&act.sa_mask);
1211 act.sa_flags = 0;
1212 act.sa_handler = host_alarm_handler;
1214 sigaction(SIGIO, &act, NULL);
1215 fcntl_setfl(fd, O_ASYNC);
1216 fcntl(fd, F_SETOWN, getpid());
1219 static int hpet_start_timer(struct qemu_alarm_timer *t)
1221 struct hpet_info info;
1222 int r, fd;
1224 fd = open("/dev/hpet", O_RDONLY);
1225 if (fd < 0)
1226 return -1;
1228 /* Set frequency */
1229 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1230 if (r < 0) {
1231 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1232 "error, but for better emulation accuracy type:\n"
1233 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1234 goto fail;
1237 /* Check capabilities */
1238 r = ioctl(fd, HPET_INFO, &info);
1239 if (r < 0)
1240 goto fail;
1242 /* Enable periodic mode */
1243 r = ioctl(fd, HPET_EPI, 0);
1244 if (info.hi_flags && (r < 0))
1245 goto fail;
1247 /* Enable interrupt */
1248 r = ioctl(fd, HPET_IE_ON, 0);
1249 if (r < 0)
1250 goto fail;
1252 enable_sigio_timer(fd);
1253 t->priv = (void *)(long)fd;
1255 return 0;
1256 fail:
1257 close(fd);
1258 return -1;
1261 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1263 int fd = (long)t->priv;
1265 close(fd);
1268 static int rtc_start_timer(struct qemu_alarm_timer *t)
1270 int rtc_fd;
1271 unsigned long current_rtc_freq = 0;
1273 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1274 if (rtc_fd < 0)
1275 return -1;
1276 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1277 if (current_rtc_freq != RTC_FREQ &&
1278 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1279 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1280 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1281 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1282 goto fail;
1284 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1285 fail:
1286 close(rtc_fd);
1287 return -1;
1290 enable_sigio_timer(rtc_fd);
1292 t->priv = (void *)(long)rtc_fd;
1294 return 0;
1297 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1299 int rtc_fd = (long)t->priv;
1301 close(rtc_fd);
1304 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1306 struct sigevent ev;
1307 timer_t host_timer;
1308 struct sigaction act;
1310 sigfillset(&act.sa_mask);
1311 act.sa_flags = 0;
1312 act.sa_handler = host_alarm_handler;
1314 sigaction(SIGALRM, &act, NULL);
1317 * Initialize ev struct to 0 to avoid valgrind complaining
1318 * about uninitialized data in timer_create call
1320 memset(&ev, 0, sizeof(ev));
1321 ev.sigev_value.sival_int = 0;
1322 ev.sigev_notify = SIGEV_SIGNAL;
1323 ev.sigev_signo = SIGALRM;
1325 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1326 perror("timer_create");
1328 /* disable dynticks */
1329 fprintf(stderr, "Dynamic Ticks disabled\n");
1331 return -1;
1334 t->priv = (void *)(long)host_timer;
1336 return 0;
1339 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1341 timer_t host_timer = (timer_t)(long)t->priv;
1343 timer_delete(host_timer);
1346 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1348 timer_t host_timer = (timer_t)(long)t->priv;
1349 struct itimerspec timeout;
1350 int64_t nearest_delta_us = INT64_MAX;
1351 int64_t current_us;
1353 if (!active_timers[QEMU_TIMER_REALTIME] &&
1354 !active_timers[QEMU_TIMER_VIRTUAL])
1355 return;
1357 nearest_delta_us = qemu_next_deadline_dyntick();
1359 /* check whether a timer is already running */
1360 if (timer_gettime(host_timer, &timeout)) {
1361 perror("gettime");
1362 fprintf(stderr, "Internal timer error: aborting\n");
1363 exit(1);
1365 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1366 if (current_us && current_us <= nearest_delta_us)
1367 return;
1369 timeout.it_interval.tv_sec = 0;
1370 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1371 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1372 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1373 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1374 perror("settime");
1375 fprintf(stderr, "Internal timer error: aborting\n");
1376 exit(1);
1380 #endif /* defined(__linux__) */
1382 static int unix_start_timer(struct qemu_alarm_timer *t)
1384 struct sigaction act;
1385 struct itimerval itv;
1386 int err;
1388 /* timer signal */
1389 sigfillset(&act.sa_mask);
1390 act.sa_flags = 0;
1391 act.sa_handler = host_alarm_handler;
1393 sigaction(SIGALRM, &act, NULL);
1395 itv.it_interval.tv_sec = 0;
1396 /* for i386 kernel 2.6 to get 1 ms */
1397 itv.it_interval.tv_usec = 999;
1398 itv.it_value.tv_sec = 0;
1399 itv.it_value.tv_usec = 10 * 1000;
1401 err = setitimer(ITIMER_REAL, &itv, NULL);
1402 if (err)
1403 return -1;
1405 return 0;
1408 static void unix_stop_timer(struct qemu_alarm_timer *t)
1410 struct itimerval itv;
1412 memset(&itv, 0, sizeof(itv));
1413 setitimer(ITIMER_REAL, &itv, NULL);
1416 #endif /* !defined(_WIN32) */
1419 #ifdef _WIN32
1421 static int win32_start_timer(struct qemu_alarm_timer *t)
1423 TIMECAPS tc;
1424 struct qemu_alarm_win32 *data = t->priv;
1425 UINT flags;
1427 memset(&tc, 0, sizeof(tc));
1428 timeGetDevCaps(&tc, sizeof(tc));
1430 if (data->period < tc.wPeriodMin)
1431 data->period = tc.wPeriodMin;
1433 timeBeginPeriod(data->period);
1435 flags = TIME_CALLBACK_FUNCTION;
1436 if (alarm_has_dynticks(t))
1437 flags |= TIME_ONESHOT;
1438 else
1439 flags |= TIME_PERIODIC;
1441 data->timerId = timeSetEvent(1, // interval (ms)
1442 data->period, // resolution
1443 host_alarm_handler, // function
1444 (DWORD)t, // parameter
1445 flags);
1447 if (!data->timerId) {
1448 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1449 GetLastError());
1450 timeEndPeriod(data->period);
1451 return -1;
1454 return 0;
1457 static void win32_stop_timer(struct qemu_alarm_timer *t)
1459 struct qemu_alarm_win32 *data = t->priv;
1461 timeKillEvent(data->timerId);
1462 timeEndPeriod(data->period);
1465 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1467 struct qemu_alarm_win32 *data = t->priv;
1468 uint64_t nearest_delta_us;
1470 if (!active_timers[QEMU_TIMER_REALTIME] &&
1471 !active_timers[QEMU_TIMER_VIRTUAL])
1472 return;
1474 nearest_delta_us = qemu_next_deadline_dyntick();
1475 nearest_delta_us /= 1000;
1477 timeKillEvent(data->timerId);
1479 data->timerId = timeSetEvent(1,
1480 data->period,
1481 host_alarm_handler,
1482 (DWORD)t,
1483 TIME_ONESHOT | TIME_PERIODIC);
1485 if (!data->timerId) {
1486 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1487 GetLastError());
1489 timeEndPeriod(data->period);
1490 exit(1);
1494 #endif /* _WIN32 */
1496 static int init_timer_alarm(void)
1498 struct qemu_alarm_timer *t = NULL;
1499 int i, err = -1;
1501 for (i = 0; alarm_timers[i].name; i++) {
1502 t = &alarm_timers[i];
1504 err = t->start(t);
1505 if (!err)
1506 break;
1509 if (err) {
1510 err = -ENOENT;
1511 goto fail;
1514 alarm_timer = t;
1516 return 0;
1518 fail:
1519 return err;
1522 static void quit_timers(void)
1524 alarm_timer->stop(alarm_timer);
1525 alarm_timer = NULL;
1528 /***********************************************************/
1529 /* host time/date access */
1530 void qemu_get_timedate(struct tm *tm, int offset)
1532 time_t ti;
1533 struct tm *ret;
1535 time(&ti);
1536 ti += offset;
1537 if (rtc_date_offset == -1) {
1538 if (rtc_utc)
1539 ret = gmtime(&ti);
1540 else
1541 ret = localtime(&ti);
1542 } else {
1543 ti -= rtc_date_offset;
1544 ret = gmtime(&ti);
1547 memcpy(tm, ret, sizeof(struct tm));
1550 int qemu_timedate_diff(struct tm *tm)
1552 time_t seconds;
1554 if (rtc_date_offset == -1)
1555 if (rtc_utc)
1556 seconds = mktimegm(tm);
1557 else
1558 seconds = mktime(tm);
1559 else
1560 seconds = mktimegm(tm) + rtc_date_offset;
1562 return seconds - time(NULL);
1565 #ifdef _WIN32
1566 static void socket_cleanup(void)
1568 WSACleanup();
1571 static int socket_init(void)
1573 WSADATA Data;
1574 int ret, err;
1576 ret = WSAStartup(MAKEWORD(2,2), &Data);
1577 if (ret != 0) {
1578 err = WSAGetLastError();
1579 fprintf(stderr, "WSAStartup: %d\n", err);
1580 return -1;
1582 atexit(socket_cleanup);
1583 return 0;
1585 #endif
1587 /***********************************************************/
1588 /* Bluetooth support */
1589 static int nb_hcis;
1590 static int cur_hci;
1591 static struct HCIInfo *hci_table[MAX_NICS];
1593 static struct bt_vlan_s {
1594 struct bt_scatternet_s net;
1595 int id;
1596 struct bt_vlan_s *next;
1597 } *first_bt_vlan;
1599 /* find or alloc a new bluetooth "VLAN" */
1600 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1602 struct bt_vlan_s **pvlan, *vlan;
1603 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1604 if (vlan->id == id)
1605 return &vlan->net;
1607 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1608 vlan->id = id;
1609 pvlan = &first_bt_vlan;
1610 while (*pvlan != NULL)
1611 pvlan = &(*pvlan)->next;
1612 *pvlan = vlan;
1613 return &vlan->net;
1616 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1620 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1622 return -ENOTSUP;
1625 static struct HCIInfo null_hci = {
1626 .cmd_send = null_hci_send,
1627 .sco_send = null_hci_send,
1628 .acl_send = null_hci_send,
1629 .bdaddr_set = null_hci_addr_set,
1632 struct HCIInfo *qemu_next_hci(void)
1634 if (cur_hci == nb_hcis)
1635 return &null_hci;
1637 return hci_table[cur_hci++];
1640 static struct HCIInfo *hci_init(const char *str)
1642 char *endp;
1643 struct bt_scatternet_s *vlan = 0;
1645 if (!strcmp(str, "null"))
1646 /* null */
1647 return &null_hci;
1648 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1649 /* host[:hciN] */
1650 return bt_host_hci(str[4] ? str + 5 : "hci0");
1651 else if (!strncmp(str, "hci", 3)) {
1652 /* hci[,vlan=n] */
1653 if (str[3]) {
1654 if (!strncmp(str + 3, ",vlan=", 6)) {
1655 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1656 if (*endp)
1657 vlan = 0;
1659 } else
1660 vlan = qemu_find_bt_vlan(0);
1661 if (vlan)
1662 return bt_new_hci(vlan);
1665 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1667 return 0;
1670 static int bt_hci_parse(const char *str)
1672 struct HCIInfo *hci;
1673 bdaddr_t bdaddr;
1675 if (nb_hcis >= MAX_NICS) {
1676 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1677 return -1;
1680 hci = hci_init(str);
1681 if (!hci)
1682 return -1;
1684 bdaddr.b[0] = 0x52;
1685 bdaddr.b[1] = 0x54;
1686 bdaddr.b[2] = 0x00;
1687 bdaddr.b[3] = 0x12;
1688 bdaddr.b[4] = 0x34;
1689 bdaddr.b[5] = 0x56 + nb_hcis;
1690 hci->bdaddr_set(hci, bdaddr.b);
1692 hci_table[nb_hcis++] = hci;
1694 return 0;
1697 static void bt_vhci_add(int vlan_id)
1699 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1701 if (!vlan->slave)
1702 fprintf(stderr, "qemu: warning: adding a VHCI to "
1703 "an empty scatternet %i\n", vlan_id);
1705 bt_vhci_init(bt_new_hci(vlan));
1708 static struct bt_device_s *bt_device_add(const char *opt)
1710 struct bt_scatternet_s *vlan;
1711 int vlan_id = 0;
1712 char *endp = strstr(opt, ",vlan=");
1713 int len = (endp ? endp - opt : strlen(opt)) + 1;
1714 char devname[10];
1716 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1718 if (endp) {
1719 vlan_id = strtol(endp + 6, &endp, 0);
1720 if (*endp) {
1721 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1722 return 0;
1726 vlan = qemu_find_bt_vlan(vlan_id);
1728 if (!vlan->slave)
1729 fprintf(stderr, "qemu: warning: adding a slave device to "
1730 "an empty scatternet %i\n", vlan_id);
1732 if (!strcmp(devname, "keyboard"))
1733 return bt_keyboard_init(vlan);
1735 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1736 return 0;
1739 static int bt_parse(const char *opt)
1741 const char *endp, *p;
1742 int vlan;
1744 if (strstart(opt, "hci", &endp)) {
1745 if (!*endp || *endp == ',') {
1746 if (*endp)
1747 if (!strstart(endp, ",vlan=", 0))
1748 opt = endp + 1;
1750 return bt_hci_parse(opt);
1752 } else if (strstart(opt, "vhci", &endp)) {
1753 if (!*endp || *endp == ',') {
1754 if (*endp) {
1755 if (strstart(endp, ",vlan=", &p)) {
1756 vlan = strtol(p, (char **) &endp, 0);
1757 if (*endp) {
1758 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1759 return 1;
1761 } else {
1762 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1763 return 1;
1765 } else
1766 vlan = 0;
1768 bt_vhci_add(vlan);
1769 return 0;
1771 } else if (strstart(opt, "device:", &endp))
1772 return !bt_device_add(endp);
1774 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1775 return 1;
1778 /***********************************************************/
1779 /* QEMU Block devices */
1781 #define HD_ALIAS "index=%d,media=disk"
1782 #define CDROM_ALIAS "index=2,media=cdrom"
1783 #define FD_ALIAS "index=%d,if=floppy"
1784 #define PFLASH_ALIAS "if=pflash"
1785 #define MTD_ALIAS "if=mtd"
1786 #define SD_ALIAS "index=0,if=sd"
1788 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1790 va_list ap;
1791 char optstr[1024];
1792 QemuOpts *opts;
1794 va_start(ap, fmt);
1795 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1796 va_end(ap);
1798 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1799 if (!opts) {
1800 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1801 __FUNCTION__, optstr);
1802 return NULL;
1804 if (file)
1805 qemu_opt_set(opts, "file", file);
1806 return opts;
1809 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1811 DriveInfo *dinfo;
1813 /* seek interface, bus and unit */
1815 QTAILQ_FOREACH(dinfo, &drives, next) {
1816 if (dinfo->type == type &&
1817 dinfo->bus == bus &&
1818 dinfo->unit == unit)
1819 return dinfo;
1822 return NULL;
1825 DriveInfo *drive_get_by_id(const char *id)
1827 DriveInfo *dinfo;
1829 QTAILQ_FOREACH(dinfo, &drives, next) {
1830 if (strcmp(id, dinfo->id))
1831 continue;
1832 return dinfo;
1834 return NULL;
1837 int drive_get_max_bus(BlockInterfaceType type)
1839 int max_bus;
1840 DriveInfo *dinfo;
1842 max_bus = -1;
1843 QTAILQ_FOREACH(dinfo, &drives, next) {
1844 if(dinfo->type == type &&
1845 dinfo->bus > max_bus)
1846 max_bus = dinfo->bus;
1848 return max_bus;
1851 const char *drive_get_serial(BlockDriverState *bdrv)
1853 DriveInfo *dinfo;
1855 QTAILQ_FOREACH(dinfo, &drives, next) {
1856 if (dinfo->bdrv == bdrv)
1857 return dinfo->serial;
1860 return "\0";
1863 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1865 DriveInfo *dinfo;
1867 QTAILQ_FOREACH(dinfo, &drives, next) {
1868 if (dinfo->bdrv == bdrv)
1869 return dinfo->onerror;
1872 return BLOCK_ERR_STOP_ENOSPC;
1875 static void bdrv_format_print(void *opaque, const char *name)
1877 fprintf(stderr, " %s", name);
1880 void drive_uninit(BlockDriverState *bdrv)
1882 DriveInfo *dinfo;
1884 QTAILQ_FOREACH(dinfo, &drives, next) {
1885 if (dinfo->bdrv != bdrv)
1886 continue;
1887 qemu_opts_del(dinfo->opts);
1888 QTAILQ_REMOVE(&drives, dinfo, next);
1889 qemu_free(dinfo);
1890 break;
1894 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1895 int *fatal_error)
1897 const char *buf;
1898 const char *file = NULL;
1899 char devname[128];
1900 const char *serial;
1901 const char *mediastr = "";
1902 BlockInterfaceType type;
1903 enum { MEDIA_DISK, MEDIA_CDROM } media;
1904 int bus_id, unit_id;
1905 int cyls, heads, secs, translation;
1906 BlockDriver *drv = NULL;
1907 QEMUMachine *machine = opaque;
1908 int max_devs;
1909 int index;
1910 int cache;
1911 int aio = 0;
1912 int bdrv_flags, onerror;
1913 const char *devaddr;
1914 DriveInfo *dinfo;
1915 int snapshot = 0;
1917 *fatal_error = 1;
1919 translation = BIOS_ATA_TRANSLATION_AUTO;
1920 cache = 1;
1922 if (machine && machine->use_scsi) {
1923 type = IF_SCSI;
1924 max_devs = MAX_SCSI_DEVS;
1925 pstrcpy(devname, sizeof(devname), "scsi");
1926 } else {
1927 type = IF_IDE;
1928 max_devs = MAX_IDE_DEVS;
1929 pstrcpy(devname, sizeof(devname), "ide");
1931 media = MEDIA_DISK;
1933 /* extract parameters */
1934 bus_id = qemu_opt_get_number(opts, "bus", 0);
1935 unit_id = qemu_opt_get_number(opts, "unit", -1);
1936 index = qemu_opt_get_number(opts, "index", -1);
1938 cyls = qemu_opt_get_number(opts, "cyls", 0);
1939 heads = qemu_opt_get_number(opts, "heads", 0);
1940 secs = qemu_opt_get_number(opts, "secs", 0);
1942 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1944 file = qemu_opt_get(opts, "file");
1945 serial = qemu_opt_get(opts, "serial");
1947 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1948 pstrcpy(devname, sizeof(devname), buf);
1949 if (!strcmp(buf, "ide")) {
1950 type = IF_IDE;
1951 max_devs = MAX_IDE_DEVS;
1952 } else if (!strcmp(buf, "scsi")) {
1953 type = IF_SCSI;
1954 max_devs = MAX_SCSI_DEVS;
1955 } else if (!strcmp(buf, "floppy")) {
1956 type = IF_FLOPPY;
1957 max_devs = 0;
1958 } else if (!strcmp(buf, "pflash")) {
1959 type = IF_PFLASH;
1960 max_devs = 0;
1961 } else if (!strcmp(buf, "mtd")) {
1962 type = IF_MTD;
1963 max_devs = 0;
1964 } else if (!strcmp(buf, "sd")) {
1965 type = IF_SD;
1966 max_devs = 0;
1967 } else if (!strcmp(buf, "virtio")) {
1968 type = IF_VIRTIO;
1969 max_devs = 0;
1970 } else if (!strcmp(buf, "xen")) {
1971 type = IF_XEN;
1972 max_devs = 0;
1973 } else if (!strcmp(buf, "none")) {
1974 type = IF_NONE;
1975 max_devs = 0;
1976 } else {
1977 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1978 return NULL;
1982 if (cyls || heads || secs) {
1983 if (cyls < 1 || cyls > 16383) {
1984 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1985 return NULL;
1987 if (heads < 1 || heads > 16) {
1988 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1989 return NULL;
1991 if (secs < 1 || secs > 63) {
1992 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
1993 return NULL;
1997 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
1998 if (!cyls) {
1999 fprintf(stderr,
2000 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2001 buf);
2002 return NULL;
2004 if (!strcmp(buf, "none"))
2005 translation = BIOS_ATA_TRANSLATION_NONE;
2006 else if (!strcmp(buf, "lba"))
2007 translation = BIOS_ATA_TRANSLATION_LBA;
2008 else if (!strcmp(buf, "auto"))
2009 translation = BIOS_ATA_TRANSLATION_AUTO;
2010 else {
2011 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2012 return NULL;
2016 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2017 if (!strcmp(buf, "disk")) {
2018 media = MEDIA_DISK;
2019 } else if (!strcmp(buf, "cdrom")) {
2020 if (cyls || secs || heads) {
2021 fprintf(stderr,
2022 "qemu: '%s' invalid physical CHS format\n", buf);
2023 return NULL;
2025 media = MEDIA_CDROM;
2026 } else {
2027 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2028 return NULL;
2032 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2033 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2034 cache = 0;
2035 else if (!strcmp(buf, "writethrough"))
2036 cache = 1;
2037 else if (!strcmp(buf, "writeback"))
2038 cache = 2;
2039 else {
2040 fprintf(stderr, "qemu: invalid cache option\n");
2041 return NULL;
2045 #ifdef CONFIG_LINUX_AIO
2046 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2047 if (!strcmp(buf, "threads"))
2048 aio = 0;
2049 else if (!strcmp(buf, "native"))
2050 aio = 1;
2051 else {
2052 fprintf(stderr, "qemu: invalid aio option\n");
2053 return NULL;
2056 #endif
2058 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2059 if (strcmp(buf, "?") == 0) {
2060 fprintf(stderr, "qemu: Supported formats:");
2061 bdrv_iterate_format(bdrv_format_print, NULL);
2062 fprintf(stderr, "\n");
2063 return NULL;
2065 drv = bdrv_find_format(buf);
2066 if (!drv) {
2067 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2068 return NULL;
2072 onerror = BLOCK_ERR_STOP_ENOSPC;
2073 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2074 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2075 fprintf(stderr, "werror is no supported by this format\n");
2076 return NULL;
2078 if (!strcmp(buf, "ignore"))
2079 onerror = BLOCK_ERR_IGNORE;
2080 else if (!strcmp(buf, "enospc"))
2081 onerror = BLOCK_ERR_STOP_ENOSPC;
2082 else if (!strcmp(buf, "stop"))
2083 onerror = BLOCK_ERR_STOP_ANY;
2084 else if (!strcmp(buf, "report"))
2085 onerror = BLOCK_ERR_REPORT;
2086 else {
2087 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2088 return NULL;
2092 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2093 if (type != IF_VIRTIO) {
2094 fprintf(stderr, "addr is not supported\n");
2095 return NULL;
2099 /* compute bus and unit according index */
2101 if (index != -1) {
2102 if (bus_id != 0 || unit_id != -1) {
2103 fprintf(stderr,
2104 "qemu: index cannot be used with bus and unit\n");
2105 return NULL;
2107 if (max_devs == 0)
2109 unit_id = index;
2110 bus_id = 0;
2111 } else {
2112 unit_id = index % max_devs;
2113 bus_id = index / max_devs;
2117 /* if user doesn't specify a unit_id,
2118 * try to find the first free
2121 if (unit_id == -1) {
2122 unit_id = 0;
2123 while (drive_get(type, bus_id, unit_id) != NULL) {
2124 unit_id++;
2125 if (max_devs && unit_id >= max_devs) {
2126 unit_id -= max_devs;
2127 bus_id++;
2132 /* check unit id */
2134 if (max_devs && unit_id >= max_devs) {
2135 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2136 unit_id, max_devs - 1);
2137 return NULL;
2141 * ignore multiple definitions
2144 if (drive_get(type, bus_id, unit_id) != NULL) {
2145 *fatal_error = 0;
2146 return NULL;
2149 /* init */
2151 dinfo = qemu_mallocz(sizeof(*dinfo));
2152 if ((buf = qemu_opts_id(opts)) != NULL) {
2153 dinfo->id = qemu_strdup(buf);
2154 } else {
2155 /* no id supplied -> create one */
2156 dinfo->id = qemu_mallocz(32);
2157 if (type == IF_IDE || type == IF_SCSI)
2158 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2159 if (max_devs)
2160 snprintf(dinfo->id, 32, "%s%i%s%i",
2161 devname, bus_id, mediastr, unit_id);
2162 else
2163 snprintf(dinfo->id, 32, "%s%s%i",
2164 devname, mediastr, unit_id);
2166 dinfo->bdrv = bdrv_new(dinfo->id);
2167 dinfo->devaddr = devaddr;
2168 dinfo->type = type;
2169 dinfo->bus = bus_id;
2170 dinfo->unit = unit_id;
2171 dinfo->onerror = onerror;
2172 dinfo->opts = opts;
2173 if (serial)
2174 strncpy(dinfo->serial, serial, sizeof(serial));
2175 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2177 switch(type) {
2178 case IF_IDE:
2179 case IF_SCSI:
2180 case IF_XEN:
2181 case IF_NONE:
2182 switch(media) {
2183 case MEDIA_DISK:
2184 if (cyls != 0) {
2185 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2186 bdrv_set_translation_hint(dinfo->bdrv, translation);
2188 break;
2189 case MEDIA_CDROM:
2190 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2191 break;
2193 break;
2194 case IF_SD:
2195 /* FIXME: This isn't really a floppy, but it's a reasonable
2196 approximation. */
2197 case IF_FLOPPY:
2198 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2199 break;
2200 case IF_PFLASH:
2201 case IF_MTD:
2202 break;
2203 case IF_VIRTIO:
2204 /* add virtio block device */
2205 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2206 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2207 qemu_opt_set(opts, "drive", dinfo->id);
2208 if (devaddr)
2209 qemu_opt_set(opts, "addr", devaddr);
2210 break;
2211 case IF_COUNT:
2212 abort();
2214 if (!file) {
2215 *fatal_error = 0;
2216 return NULL;
2218 bdrv_flags = 0;
2219 if (snapshot) {
2220 bdrv_flags |= BDRV_O_SNAPSHOT;
2221 cache = 2; /* always use write-back with snapshot */
2223 if (cache == 0) /* no caching */
2224 bdrv_flags |= BDRV_O_NOCACHE;
2225 else if (cache == 2) /* write-back */
2226 bdrv_flags |= BDRV_O_CACHE_WB;
2228 if (aio == 1) {
2229 bdrv_flags |= BDRV_O_NATIVE_AIO;
2230 } else {
2231 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2234 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2235 fprintf(stderr, "qemu: could not open disk image %s\n",
2236 file);
2237 return NULL;
2240 if (bdrv_key_required(dinfo->bdrv))
2241 autostart = 0;
2242 *fatal_error = 0;
2243 return dinfo;
2246 static int drive_init_func(QemuOpts *opts, void *opaque)
2248 QEMUMachine *machine = opaque;
2249 int fatal_error = 0;
2251 if (drive_init(opts, machine, &fatal_error) == NULL) {
2252 if (fatal_error)
2253 return 1;
2255 return 0;
2258 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2260 if (NULL == qemu_opt_get(opts, "snapshot")) {
2261 qemu_opt_set(opts, "snapshot", "on");
2263 return 0;
2266 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2268 boot_set_handler = func;
2269 boot_set_opaque = opaque;
2272 int qemu_boot_set(const char *boot_devices)
2274 if (!boot_set_handler) {
2275 return -EINVAL;
2277 return boot_set_handler(boot_set_opaque, boot_devices);
2280 static int parse_bootdevices(char *devices)
2282 /* We just do some generic consistency checks */
2283 const char *p;
2284 int bitmap = 0;
2286 for (p = devices; *p != '\0'; p++) {
2287 /* Allowed boot devices are:
2288 * a-b: floppy disk drives
2289 * c-f: IDE disk drives
2290 * g-m: machine implementation dependant drives
2291 * n-p: network devices
2292 * It's up to each machine implementation to check if the given boot
2293 * devices match the actual hardware implementation and firmware
2294 * features.
2296 if (*p < 'a' || *p > 'p') {
2297 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2298 exit(1);
2300 if (bitmap & (1 << (*p - 'a'))) {
2301 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2302 exit(1);
2304 bitmap |= 1 << (*p - 'a');
2306 return bitmap;
2309 static void restore_boot_devices(void *opaque)
2311 char *standard_boot_devices = opaque;
2313 qemu_boot_set(standard_boot_devices);
2315 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2316 qemu_free(standard_boot_devices);
2319 static void numa_add(const char *optarg)
2321 char option[128];
2322 char *endptr;
2323 unsigned long long value, endvalue;
2324 int nodenr;
2326 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2327 if (!strcmp(option, "node")) {
2328 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2329 nodenr = nb_numa_nodes;
2330 } else {
2331 nodenr = strtoull(option, NULL, 10);
2334 if (get_param_value(option, 128, "mem", optarg) == 0) {
2335 node_mem[nodenr] = 0;
2336 } else {
2337 value = strtoull(option, &endptr, 0);
2338 switch (*endptr) {
2339 case 0: case 'M': case 'm':
2340 value <<= 20;
2341 break;
2342 case 'G': case 'g':
2343 value <<= 30;
2344 break;
2346 node_mem[nodenr] = value;
2348 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2349 node_cpumask[nodenr] = 0;
2350 } else {
2351 value = strtoull(option, &endptr, 10);
2352 if (value >= 64) {
2353 value = 63;
2354 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2355 } else {
2356 if (*endptr == '-') {
2357 endvalue = strtoull(endptr+1, &endptr, 10);
2358 if (endvalue >= 63) {
2359 endvalue = 62;
2360 fprintf(stderr,
2361 "only 63 CPUs in NUMA mode supported.\n");
2363 value = (1 << (endvalue + 1)) - (1 << value);
2364 } else {
2365 value = 1 << value;
2368 node_cpumask[nodenr] = value;
2370 nb_numa_nodes++;
2372 return;
2375 static void smp_parse(const char *optarg)
2377 int smp, sockets = 0, threads = 0, cores = 0;
2378 char *endptr;
2379 char option[128];
2381 smp = strtoul(optarg, &endptr, 10);
2382 if (endptr != optarg) {
2383 if (*endptr == ',') {
2384 endptr++;
2387 if (get_param_value(option, 128, "sockets", endptr) != 0)
2388 sockets = strtoull(option, NULL, 10);
2389 if (get_param_value(option, 128, "cores", endptr) != 0)
2390 cores = strtoull(option, NULL, 10);
2391 if (get_param_value(option, 128, "threads", endptr) != 0)
2392 threads = strtoull(option, NULL, 10);
2393 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2394 max_cpus = strtoull(option, NULL, 10);
2396 /* compute missing values, prefer sockets over cores over threads */
2397 if (smp == 0 || sockets == 0) {
2398 sockets = sockets > 0 ? sockets : 1;
2399 cores = cores > 0 ? cores : 1;
2400 threads = threads > 0 ? threads : 1;
2401 if (smp == 0) {
2402 smp = cores * threads * sockets;
2403 } else {
2404 sockets = smp / (cores * threads);
2406 } else {
2407 if (cores == 0) {
2408 threads = threads > 0 ? threads : 1;
2409 cores = smp / (sockets * threads);
2410 } else {
2411 if (sockets == 0) {
2412 sockets = smp / (cores * threads);
2413 } else {
2414 threads = smp / (cores * sockets);
2418 smp_cpus = smp;
2419 smp_cores = cores > 0 ? cores : 1;
2420 smp_threads = threads > 0 ? threads : 1;
2421 if (max_cpus == 0)
2422 max_cpus = smp_cpus;
2425 /***********************************************************/
2426 /* USB devices */
2428 static void usb_msd_password_cb(void *opaque, int err)
2430 USBDevice *dev = opaque;
2432 if (!err)
2433 usb_device_attach(dev);
2434 else
2435 dev->info->handle_destroy(dev);
2438 static struct {
2439 const char *name;
2440 const char *qdev;
2441 } usbdevs[] = {
2443 .name = "mouse",
2444 .qdev = "QEMU USB Mouse",
2446 .name = "tablet",
2447 .qdev = "QEMU USB Tablet",
2449 .name = "keyboard",
2450 .qdev = "QEMU USB Keyboard",
2452 .name = "wacom-tablet",
2453 .qdev = "QEMU PenPartner Tablet",
2457 static int usb_device_add(const char *devname, int is_hotplug)
2459 const char *p;
2460 USBBus *bus = usb_bus_find(-1 /* any */);
2461 USBDevice *dev = NULL;
2462 int i;
2464 if (!usb_enabled)
2465 return -1;
2467 /* simple devices which don't need extra care */
2468 for (i = 0; i < ARRAY_SIZE(usbdevs); i++) {
2469 if (strcmp(devname, usbdevs[i].name) != 0)
2470 continue;
2471 dev = usb_create_simple(bus, usbdevs[i].qdev);
2472 goto done;
2475 /* the other ones */
2476 if (strstart(devname, "host:", &p)) {
2477 dev = usb_host_device_open(p);
2478 } else if (strstart(devname, "disk:", &p)) {
2479 BlockDriverState *bs;
2481 dev = usb_msd_init(p);
2482 if (!dev)
2483 return -1;
2484 bs = usb_msd_get_bdrv(dev);
2485 if (bdrv_key_required(bs)) {
2486 autostart = 0;
2487 if (is_hotplug) {
2488 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2489 dev);
2490 return 0;
2493 } else if (strstart(devname, "serial:", &p)) {
2494 dev = usb_serial_init(p);
2495 #ifdef CONFIG_BRLAPI
2496 } else if (!strcmp(devname, "braille")) {
2497 dev = usb_baum_init();
2498 #endif
2499 } else if (strstart(devname, "net:", &p)) {
2500 int nic = nb_nics;
2502 if (net_client_init(NULL, "nic", p) < 0)
2503 return -1;
2504 nd_table[nic].model = "usb";
2505 dev = usb_net_init(&nd_table[nic]);
2506 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2507 dev = usb_bt_init(devname[2] ? hci_init(p) :
2508 bt_new_hci(qemu_find_bt_vlan(0)));
2509 } else {
2510 return -1;
2512 if (!dev)
2513 return -1;
2515 done:
2516 return 0;
2519 static int usb_device_del(const char *devname)
2521 int bus_num, addr;
2522 const char *p;
2524 if (strstart(devname, "host:", &p))
2525 return usb_host_device_close(p);
2527 if (!usb_enabled)
2528 return -1;
2530 p = strchr(devname, '.');
2531 if (!p)
2532 return -1;
2533 bus_num = strtoul(devname, NULL, 0);
2534 addr = strtoul(p + 1, NULL, 0);
2536 return usb_device_delete_addr(bus_num, addr);
2539 static int usb_parse(const char *cmdline)
2541 return usb_device_add(cmdline, 0);
2544 void do_usb_add(Monitor *mon, const QDict *qdict)
2546 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2549 void do_usb_del(Monitor *mon, const QDict *qdict)
2551 usb_device_del(qdict_get_str(qdict, "devname"));
2554 /***********************************************************/
2555 /* PCMCIA/Cardbus */
2557 static struct pcmcia_socket_entry_s {
2558 PCMCIASocket *socket;
2559 struct pcmcia_socket_entry_s *next;
2560 } *pcmcia_sockets = 0;
2562 void pcmcia_socket_register(PCMCIASocket *socket)
2564 struct pcmcia_socket_entry_s *entry;
2566 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2567 entry->socket = socket;
2568 entry->next = pcmcia_sockets;
2569 pcmcia_sockets = entry;
2572 void pcmcia_socket_unregister(PCMCIASocket *socket)
2574 struct pcmcia_socket_entry_s *entry, **ptr;
2576 ptr = &pcmcia_sockets;
2577 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2578 if (entry->socket == socket) {
2579 *ptr = entry->next;
2580 qemu_free(entry);
2584 void pcmcia_info(Monitor *mon)
2586 struct pcmcia_socket_entry_s *iter;
2588 if (!pcmcia_sockets)
2589 monitor_printf(mon, "No PCMCIA sockets\n");
2591 for (iter = pcmcia_sockets; iter; iter = iter->next)
2592 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2593 iter->socket->attached ? iter->socket->card_string :
2594 "Empty");
2597 /***********************************************************/
2598 /* register display */
2600 struct DisplayAllocator default_allocator = {
2601 defaultallocator_create_displaysurface,
2602 defaultallocator_resize_displaysurface,
2603 defaultallocator_free_displaysurface
2606 void register_displaystate(DisplayState *ds)
2608 DisplayState **s;
2609 s = &display_state;
2610 while (*s != NULL)
2611 s = &(*s)->next;
2612 ds->next = NULL;
2613 *s = ds;
2616 DisplayState *get_displaystate(void)
2618 return display_state;
2621 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2623 if(ds->allocator == &default_allocator) ds->allocator = da;
2624 return ds->allocator;
2627 /* dumb display */
2629 static void dumb_display_init(void)
2631 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2632 ds->allocator = &default_allocator;
2633 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2634 register_displaystate(ds);
2637 /***********************************************************/
2638 /* I/O handling */
2640 typedef struct IOHandlerRecord {
2641 int fd;
2642 IOCanRWHandler *fd_read_poll;
2643 IOHandler *fd_read;
2644 IOHandler *fd_write;
2645 int deleted;
2646 void *opaque;
2647 /* temporary data */
2648 struct pollfd *ufd;
2649 struct IOHandlerRecord *next;
2650 } IOHandlerRecord;
2652 static IOHandlerRecord *first_io_handler;
2654 /* XXX: fd_read_poll should be suppressed, but an API change is
2655 necessary in the character devices to suppress fd_can_read(). */
2656 int qemu_set_fd_handler2(int fd,
2657 IOCanRWHandler *fd_read_poll,
2658 IOHandler *fd_read,
2659 IOHandler *fd_write,
2660 void *opaque)
2662 IOHandlerRecord **pioh, *ioh;
2664 if (!fd_read && !fd_write) {
2665 pioh = &first_io_handler;
2666 for(;;) {
2667 ioh = *pioh;
2668 if (ioh == NULL)
2669 break;
2670 if (ioh->fd == fd) {
2671 ioh->deleted = 1;
2672 break;
2674 pioh = &ioh->next;
2676 } else {
2677 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2678 if (ioh->fd == fd)
2679 goto found;
2681 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2682 ioh->next = first_io_handler;
2683 first_io_handler = ioh;
2684 found:
2685 ioh->fd = fd;
2686 ioh->fd_read_poll = fd_read_poll;
2687 ioh->fd_read = fd_read;
2688 ioh->fd_write = fd_write;
2689 ioh->opaque = opaque;
2690 ioh->deleted = 0;
2692 return 0;
2695 int qemu_set_fd_handler(int fd,
2696 IOHandler *fd_read,
2697 IOHandler *fd_write,
2698 void *opaque)
2700 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2703 #ifdef _WIN32
2704 /***********************************************************/
2705 /* Polling handling */
2707 typedef struct PollingEntry {
2708 PollingFunc *func;
2709 void *opaque;
2710 struct PollingEntry *next;
2711 } PollingEntry;
2713 static PollingEntry *first_polling_entry;
2715 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2717 PollingEntry **ppe, *pe;
2718 pe = qemu_mallocz(sizeof(PollingEntry));
2719 pe->func = func;
2720 pe->opaque = opaque;
2721 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2722 *ppe = pe;
2723 return 0;
2726 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2728 PollingEntry **ppe, *pe;
2729 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2730 pe = *ppe;
2731 if (pe->func == func && pe->opaque == opaque) {
2732 *ppe = pe->next;
2733 qemu_free(pe);
2734 break;
2739 /***********************************************************/
2740 /* Wait objects support */
2741 typedef struct WaitObjects {
2742 int num;
2743 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2744 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2745 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2746 } WaitObjects;
2748 static WaitObjects wait_objects = {0};
2750 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2752 WaitObjects *w = &wait_objects;
2754 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2755 return -1;
2756 w->events[w->num] = handle;
2757 w->func[w->num] = func;
2758 w->opaque[w->num] = opaque;
2759 w->num++;
2760 return 0;
2763 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2765 int i, found;
2766 WaitObjects *w = &wait_objects;
2768 found = 0;
2769 for (i = 0; i < w->num; i++) {
2770 if (w->events[i] == handle)
2771 found = 1;
2772 if (found) {
2773 w->events[i] = w->events[i + 1];
2774 w->func[i] = w->func[i + 1];
2775 w->opaque[i] = w->opaque[i + 1];
2778 if (found)
2779 w->num--;
2781 #endif
2783 /***********************************************************/
2784 /* ram save/restore */
2786 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2787 #define RAM_SAVE_FLAG_COMPRESS 0x02
2788 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2789 #define RAM_SAVE_FLAG_PAGE 0x08
2790 #define RAM_SAVE_FLAG_EOS 0x10
2792 static int is_dup_page(uint8_t *page, uint8_t ch)
2794 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2795 uint32_t *array = (uint32_t *)page;
2796 int i;
2798 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2799 if (array[i] != val)
2800 return 0;
2803 return 1;
2806 static int ram_save_block(QEMUFile *f)
2808 static ram_addr_t current_addr = 0;
2809 ram_addr_t saved_addr = current_addr;
2810 ram_addr_t addr = 0;
2811 int found = 0;
2813 while (addr < last_ram_offset) {
2814 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2815 uint8_t *p;
2817 cpu_physical_memory_reset_dirty(current_addr,
2818 current_addr + TARGET_PAGE_SIZE,
2819 MIGRATION_DIRTY_FLAG);
2821 p = qemu_get_ram_ptr(current_addr);
2823 if (is_dup_page(p, *p)) {
2824 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2825 qemu_put_byte(f, *p);
2826 } else {
2827 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2828 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2831 found = 1;
2832 break;
2834 addr += TARGET_PAGE_SIZE;
2835 current_addr = (saved_addr + addr) % last_ram_offset;
2838 return found;
2841 static uint64_t bytes_transferred = 0;
2843 static ram_addr_t ram_save_remaining(void)
2845 ram_addr_t addr;
2846 ram_addr_t count = 0;
2848 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2849 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2850 count++;
2853 return count;
2856 uint64_t ram_bytes_remaining(void)
2858 return ram_save_remaining() * TARGET_PAGE_SIZE;
2861 uint64_t ram_bytes_transferred(void)
2863 return bytes_transferred;
2866 uint64_t ram_bytes_total(void)
2868 return last_ram_offset;
2871 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
2873 ram_addr_t addr;
2874 uint64_t bytes_transferred_last;
2875 double bwidth = 0;
2876 uint64_t expected_time = 0;
2878 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2879 qemu_file_set_error(f);
2880 return 0;
2883 if (stage == 1) {
2884 /* Make sure all dirty bits are set */
2885 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2886 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2887 cpu_physical_memory_set_dirty(addr);
2890 /* Enable dirty memory tracking */
2891 cpu_physical_memory_set_dirty_tracking(1);
2893 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2896 bytes_transferred_last = bytes_transferred;
2897 bwidth = get_clock();
2899 while (!qemu_file_rate_limit(f)) {
2900 int ret;
2902 ret = ram_save_block(f);
2903 bytes_transferred += ret * TARGET_PAGE_SIZE;
2904 if (ret == 0) /* no more blocks */
2905 break;
2908 bwidth = get_clock() - bwidth;
2909 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2911 /* if we haven't transferred anything this round, force expected_time to a
2912 * a very high value, but without crashing */
2913 if (bwidth == 0)
2914 bwidth = 0.000001;
2916 /* try transferring iterative blocks of memory */
2918 if (stage == 3) {
2920 /* flush all remaining blocks regardless of rate limiting */
2921 while (ram_save_block(f) != 0) {
2922 bytes_transferred += TARGET_PAGE_SIZE;
2924 cpu_physical_memory_set_dirty_tracking(0);
2927 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2929 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2931 return (stage == 2) && (expected_time <= migrate_max_downtime());
2934 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2936 ram_addr_t addr;
2937 int flags;
2939 if (version_id != 3)
2940 return -EINVAL;
2942 do {
2943 addr = qemu_get_be64(f);
2945 flags = addr & ~TARGET_PAGE_MASK;
2946 addr &= TARGET_PAGE_MASK;
2948 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2949 if (addr != last_ram_offset)
2950 return -EINVAL;
2953 if (flags & RAM_SAVE_FLAG_COMPRESS) {
2954 uint8_t ch = qemu_get_byte(f);
2955 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2956 #ifndef _WIN32
2957 if (ch == 0 &&
2958 (!kvm_enabled() || kvm_has_sync_mmu())) {
2959 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2961 #endif
2962 } else if (flags & RAM_SAVE_FLAG_PAGE)
2963 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2964 } while (!(flags & RAM_SAVE_FLAG_EOS));
2966 return 0;
2969 void qemu_service_io(void)
2971 qemu_notify_event();
2974 /***********************************************************/
2975 /* bottom halves (can be seen as timers which expire ASAP) */
2977 struct QEMUBH {
2978 QEMUBHFunc *cb;
2979 void *opaque;
2980 int scheduled;
2981 int idle;
2982 int deleted;
2983 QEMUBH *next;
2986 static QEMUBH *first_bh = NULL;
2988 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
2990 QEMUBH *bh;
2991 bh = qemu_mallocz(sizeof(QEMUBH));
2992 bh->cb = cb;
2993 bh->opaque = opaque;
2994 bh->next = first_bh;
2995 first_bh = bh;
2996 return bh;
2999 int qemu_bh_poll(void)
3001 QEMUBH *bh, **bhp;
3002 int ret;
3004 ret = 0;
3005 for (bh = first_bh; bh; bh = bh->next) {
3006 if (!bh->deleted && bh->scheduled) {
3007 bh->scheduled = 0;
3008 if (!bh->idle)
3009 ret = 1;
3010 bh->idle = 0;
3011 bh->cb(bh->opaque);
3015 /* remove deleted bhs */
3016 bhp = &first_bh;
3017 while (*bhp) {
3018 bh = *bhp;
3019 if (bh->deleted) {
3020 *bhp = bh->next;
3021 qemu_free(bh);
3022 } else
3023 bhp = &bh->next;
3026 return ret;
3029 void qemu_bh_schedule_idle(QEMUBH *bh)
3031 if (bh->scheduled)
3032 return;
3033 bh->scheduled = 1;
3034 bh->idle = 1;
3037 void qemu_bh_schedule(QEMUBH *bh)
3039 if (bh->scheduled)
3040 return;
3041 bh->scheduled = 1;
3042 bh->idle = 0;
3043 /* stop the currently executing CPU to execute the BH ASAP */
3044 qemu_notify_event();
3047 void qemu_bh_cancel(QEMUBH *bh)
3049 bh->scheduled = 0;
3052 void qemu_bh_delete(QEMUBH *bh)
3054 bh->scheduled = 0;
3055 bh->deleted = 1;
3058 static void qemu_bh_update_timeout(int *timeout)
3060 QEMUBH *bh;
3062 for (bh = first_bh; bh; bh = bh->next) {
3063 if (!bh->deleted && bh->scheduled) {
3064 if (bh->idle) {
3065 /* idle bottom halves will be polled at least
3066 * every 10ms */
3067 *timeout = MIN(10, *timeout);
3068 } else {
3069 /* non-idle bottom halves will be executed
3070 * immediately */
3071 *timeout = 0;
3072 break;
3078 /***********************************************************/
3079 /* machine registration */
3081 static QEMUMachine *first_machine = NULL;
3082 QEMUMachine *current_machine = NULL;
3084 int qemu_register_machine(QEMUMachine *m)
3086 QEMUMachine **pm;
3087 pm = &first_machine;
3088 while (*pm != NULL)
3089 pm = &(*pm)->next;
3090 m->next = NULL;
3091 *pm = m;
3092 return 0;
3095 static QEMUMachine *find_machine(const char *name)
3097 QEMUMachine *m;
3099 for(m = first_machine; m != NULL; m = m->next) {
3100 if (!strcmp(m->name, name))
3101 return m;
3102 if (m->alias && !strcmp(m->alias, name))
3103 return m;
3105 return NULL;
3108 static QEMUMachine *find_default_machine(void)
3110 QEMUMachine *m;
3112 for(m = first_machine; m != NULL; m = m->next) {
3113 if (m->is_default) {
3114 return m;
3117 return NULL;
3120 /***********************************************************/
3121 /* main execution loop */
3123 static void gui_update(void *opaque)
3125 uint64_t interval = GUI_REFRESH_INTERVAL;
3126 DisplayState *ds = opaque;
3127 DisplayChangeListener *dcl = ds->listeners;
3129 dpy_refresh(ds);
3131 while (dcl != NULL) {
3132 if (dcl->gui_timer_interval &&
3133 dcl->gui_timer_interval < interval)
3134 interval = dcl->gui_timer_interval;
3135 dcl = dcl->next;
3137 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3140 static void nographic_update(void *opaque)
3142 uint64_t interval = GUI_REFRESH_INTERVAL;
3144 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3147 struct vm_change_state_entry {
3148 VMChangeStateHandler *cb;
3149 void *opaque;
3150 QLIST_ENTRY (vm_change_state_entry) entries;
3153 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3155 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3156 void *opaque)
3158 VMChangeStateEntry *e;
3160 e = qemu_mallocz(sizeof (*e));
3162 e->cb = cb;
3163 e->opaque = opaque;
3164 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3165 return e;
3168 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3170 QLIST_REMOVE (e, entries);
3171 qemu_free (e);
3174 static void vm_state_notify(int running, int reason)
3176 VMChangeStateEntry *e;
3178 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3179 e->cb(e->opaque, running, reason);
3183 static void resume_all_vcpus(void);
3184 static void pause_all_vcpus(void);
3186 void vm_start(void)
3188 if (!vm_running) {
3189 cpu_enable_ticks();
3190 vm_running = 1;
3191 vm_state_notify(1, 0);
3192 qemu_rearm_alarm_timer(alarm_timer);
3193 resume_all_vcpus();
3197 /* reset/shutdown handler */
3199 typedef struct QEMUResetEntry {
3200 QTAILQ_ENTRY(QEMUResetEntry) entry;
3201 QEMUResetHandler *func;
3202 void *opaque;
3203 } QEMUResetEntry;
3205 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3206 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3207 static int reset_requested;
3208 static int shutdown_requested;
3209 static int powerdown_requested;
3210 static int debug_requested;
3211 static int vmstop_requested;
3213 int qemu_shutdown_requested(void)
3215 int r = shutdown_requested;
3216 shutdown_requested = 0;
3217 return r;
3220 int qemu_reset_requested(void)
3222 int r = reset_requested;
3223 reset_requested = 0;
3224 return r;
3227 int qemu_powerdown_requested(void)
3229 int r = powerdown_requested;
3230 powerdown_requested = 0;
3231 return r;
3234 static int qemu_debug_requested(void)
3236 int r = debug_requested;
3237 debug_requested = 0;
3238 return r;
3241 static int qemu_vmstop_requested(void)
3243 int r = vmstop_requested;
3244 vmstop_requested = 0;
3245 return r;
3248 static void do_vm_stop(int reason)
3250 if (vm_running) {
3251 cpu_disable_ticks();
3252 vm_running = 0;
3253 pause_all_vcpus();
3254 vm_state_notify(0, reason);
3258 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3260 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3262 re->func = func;
3263 re->opaque = opaque;
3264 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3267 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3269 QEMUResetEntry *re;
3271 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3272 if (re->func == func && re->opaque == opaque) {
3273 QTAILQ_REMOVE(&reset_handlers, re, entry);
3274 qemu_free(re);
3275 return;
3280 void qemu_system_reset(void)
3282 QEMUResetEntry *re, *nre;
3284 /* reset all devices */
3285 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3286 re->func(re->opaque);
3290 void qemu_system_reset_request(void)
3292 if (no_reboot) {
3293 shutdown_requested = 1;
3294 } else {
3295 reset_requested = 1;
3297 qemu_notify_event();
3300 void qemu_system_shutdown_request(void)
3302 shutdown_requested = 1;
3303 qemu_notify_event();
3306 void qemu_system_powerdown_request(void)
3308 powerdown_requested = 1;
3309 qemu_notify_event();
3312 #ifdef CONFIG_IOTHREAD
3313 static void qemu_system_vmstop_request(int reason)
3315 vmstop_requested = reason;
3316 qemu_notify_event();
3318 #endif
3320 #ifndef _WIN32
3321 static int io_thread_fd = -1;
3323 static void qemu_event_increment(void)
3325 static const char byte = 0;
3327 if (io_thread_fd == -1)
3328 return;
3330 write(io_thread_fd, &byte, sizeof(byte));
3333 static void qemu_event_read(void *opaque)
3335 int fd = (unsigned long)opaque;
3336 ssize_t len;
3338 /* Drain the notify pipe */
3339 do {
3340 char buffer[512];
3341 len = read(fd, buffer, sizeof(buffer));
3342 } while ((len == -1 && errno == EINTR) || len > 0);
3345 static int qemu_event_init(void)
3347 int err;
3348 int fds[2];
3350 err = pipe(fds);
3351 if (err == -1)
3352 return -errno;
3354 err = fcntl_setfl(fds[0], O_NONBLOCK);
3355 if (err < 0)
3356 goto fail;
3358 err = fcntl_setfl(fds[1], O_NONBLOCK);
3359 if (err < 0)
3360 goto fail;
3362 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3363 (void *)(unsigned long)fds[0]);
3365 io_thread_fd = fds[1];
3366 return 0;
3368 fail:
3369 close(fds[0]);
3370 close(fds[1]);
3371 return err;
3373 #else
3374 HANDLE qemu_event_handle;
3376 static void dummy_event_handler(void *opaque)
3380 static int qemu_event_init(void)
3382 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3383 if (!qemu_event_handle) {
3384 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3385 return -1;
3387 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3388 return 0;
3391 static void qemu_event_increment(void)
3393 if (!SetEvent(qemu_event_handle)) {
3394 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3395 GetLastError());
3396 exit (1);
3399 #endif
3401 static int cpu_can_run(CPUState *env)
3403 if (env->stop)
3404 return 0;
3405 if (env->stopped)
3406 return 0;
3407 return 1;
3410 #ifndef CONFIG_IOTHREAD
3411 static int qemu_init_main_loop(void)
3413 return qemu_event_init();
3416 void qemu_init_vcpu(void *_env)
3418 CPUState *env = _env;
3420 if (kvm_enabled())
3421 kvm_init_vcpu(env);
3422 env->nr_cores = smp_cores;
3423 env->nr_threads = smp_threads;
3424 return;
3427 int qemu_cpu_self(void *env)
3429 return 1;
3432 static void resume_all_vcpus(void)
3436 static void pause_all_vcpus(void)
3440 void qemu_cpu_kick(void *env)
3442 return;
3445 void qemu_notify_event(void)
3447 CPUState *env = cpu_single_env;
3449 if (env) {
3450 cpu_exit(env);
3454 #define qemu_mutex_lock_iothread() do { } while (0)
3455 #define qemu_mutex_unlock_iothread() do { } while (0)
3457 void vm_stop(int reason)
3459 do_vm_stop(reason);
3462 #else /* CONFIG_IOTHREAD */
3464 #include "qemu-thread.h"
3466 QemuMutex qemu_global_mutex;
3467 static QemuMutex qemu_fair_mutex;
3469 static QemuThread io_thread;
3471 static QemuThread *tcg_cpu_thread;
3472 static QemuCond *tcg_halt_cond;
3474 static int qemu_system_ready;
3475 /* cpu creation */
3476 static QemuCond qemu_cpu_cond;
3477 /* system init */
3478 static QemuCond qemu_system_cond;
3479 static QemuCond qemu_pause_cond;
3481 static void block_io_signals(void);
3482 static void unblock_io_signals(void);
3483 static int tcg_has_work(void);
3485 static int qemu_init_main_loop(void)
3487 int ret;
3489 ret = qemu_event_init();
3490 if (ret)
3491 return ret;
3493 qemu_cond_init(&qemu_pause_cond);
3494 qemu_mutex_init(&qemu_fair_mutex);
3495 qemu_mutex_init(&qemu_global_mutex);
3496 qemu_mutex_lock(&qemu_global_mutex);
3498 unblock_io_signals();
3499 qemu_thread_self(&io_thread);
3501 return 0;
3504 static void qemu_wait_io_event(CPUState *env)
3506 while (!tcg_has_work())
3507 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3509 qemu_mutex_unlock(&qemu_global_mutex);
3512 * Users of qemu_global_mutex can be starved, having no chance
3513 * to acquire it since this path will get to it first.
3514 * So use another lock to provide fairness.
3516 qemu_mutex_lock(&qemu_fair_mutex);
3517 qemu_mutex_unlock(&qemu_fair_mutex);
3519 qemu_mutex_lock(&qemu_global_mutex);
3520 if (env->stop) {
3521 env->stop = 0;
3522 env->stopped = 1;
3523 qemu_cond_signal(&qemu_pause_cond);
3527 static int qemu_cpu_exec(CPUState *env);
3529 static void *kvm_cpu_thread_fn(void *arg)
3531 CPUState *env = arg;
3533 block_io_signals();
3534 qemu_thread_self(env->thread);
3535 if (kvm_enabled())
3536 kvm_init_vcpu(env);
3538 /* signal CPU creation */
3539 qemu_mutex_lock(&qemu_global_mutex);
3540 env->created = 1;
3541 qemu_cond_signal(&qemu_cpu_cond);
3543 /* and wait for machine initialization */
3544 while (!qemu_system_ready)
3545 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3547 while (1) {
3548 if (cpu_can_run(env))
3549 qemu_cpu_exec(env);
3550 qemu_wait_io_event(env);
3553 return NULL;
3556 static void tcg_cpu_exec(void);
3558 static void *tcg_cpu_thread_fn(void *arg)
3560 CPUState *env = arg;
3562 block_io_signals();
3563 qemu_thread_self(env->thread);
3565 /* signal CPU creation */
3566 qemu_mutex_lock(&qemu_global_mutex);
3567 for (env = first_cpu; env != NULL; env = env->next_cpu)
3568 env->created = 1;
3569 qemu_cond_signal(&qemu_cpu_cond);
3571 /* and wait for machine initialization */
3572 while (!qemu_system_ready)
3573 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3575 while (1) {
3576 tcg_cpu_exec();
3577 qemu_wait_io_event(cur_cpu);
3580 return NULL;
3583 void qemu_cpu_kick(void *_env)
3585 CPUState *env = _env;
3586 qemu_cond_broadcast(env->halt_cond);
3587 if (kvm_enabled())
3588 qemu_thread_signal(env->thread, SIGUSR1);
3591 int qemu_cpu_self(void *env)
3593 return (cpu_single_env != NULL);
3596 static void cpu_signal(int sig)
3598 if (cpu_single_env)
3599 cpu_exit(cpu_single_env);
3602 static void block_io_signals(void)
3604 sigset_t set;
3605 struct sigaction sigact;
3607 sigemptyset(&set);
3608 sigaddset(&set, SIGUSR2);
3609 sigaddset(&set, SIGIO);
3610 sigaddset(&set, SIGALRM);
3611 pthread_sigmask(SIG_BLOCK, &set, NULL);
3613 sigemptyset(&set);
3614 sigaddset(&set, SIGUSR1);
3615 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3617 memset(&sigact, 0, sizeof(sigact));
3618 sigact.sa_handler = cpu_signal;
3619 sigaction(SIGUSR1, &sigact, NULL);
3622 static void unblock_io_signals(void)
3624 sigset_t set;
3626 sigemptyset(&set);
3627 sigaddset(&set, SIGUSR2);
3628 sigaddset(&set, SIGIO);
3629 sigaddset(&set, SIGALRM);
3630 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3632 sigemptyset(&set);
3633 sigaddset(&set, SIGUSR1);
3634 pthread_sigmask(SIG_BLOCK, &set, NULL);
3637 static void qemu_signal_lock(unsigned int msecs)
3639 qemu_mutex_lock(&qemu_fair_mutex);
3641 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3642 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3643 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3644 break;
3646 qemu_mutex_unlock(&qemu_fair_mutex);
3649 static void qemu_mutex_lock_iothread(void)
3651 if (kvm_enabled()) {
3652 qemu_mutex_lock(&qemu_fair_mutex);
3653 qemu_mutex_lock(&qemu_global_mutex);
3654 qemu_mutex_unlock(&qemu_fair_mutex);
3655 } else
3656 qemu_signal_lock(100);
3659 static void qemu_mutex_unlock_iothread(void)
3661 qemu_mutex_unlock(&qemu_global_mutex);
3664 static int all_vcpus_paused(void)
3666 CPUState *penv = first_cpu;
3668 while (penv) {
3669 if (!penv->stopped)
3670 return 0;
3671 penv = (CPUState *)penv->next_cpu;
3674 return 1;
3677 static void pause_all_vcpus(void)
3679 CPUState *penv = first_cpu;
3681 while (penv) {
3682 penv->stop = 1;
3683 qemu_thread_signal(penv->thread, SIGUSR1);
3684 qemu_cpu_kick(penv);
3685 penv = (CPUState *)penv->next_cpu;
3688 while (!all_vcpus_paused()) {
3689 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3690 penv = first_cpu;
3691 while (penv) {
3692 qemu_thread_signal(penv->thread, SIGUSR1);
3693 penv = (CPUState *)penv->next_cpu;
3698 static void resume_all_vcpus(void)
3700 CPUState *penv = first_cpu;
3702 while (penv) {
3703 penv->stop = 0;
3704 penv->stopped = 0;
3705 qemu_thread_signal(penv->thread, SIGUSR1);
3706 qemu_cpu_kick(penv);
3707 penv = (CPUState *)penv->next_cpu;
3711 static void tcg_init_vcpu(void *_env)
3713 CPUState *env = _env;
3714 /* share a single thread for all cpus with TCG */
3715 if (!tcg_cpu_thread) {
3716 env->thread = qemu_mallocz(sizeof(QemuThread));
3717 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3718 qemu_cond_init(env->halt_cond);
3719 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3720 while (env->created == 0)
3721 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3722 tcg_cpu_thread = env->thread;
3723 tcg_halt_cond = env->halt_cond;
3724 } else {
3725 env->thread = tcg_cpu_thread;
3726 env->halt_cond = tcg_halt_cond;
3730 static void kvm_start_vcpu(CPUState *env)
3732 env->thread = qemu_mallocz(sizeof(QemuThread));
3733 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3734 qemu_cond_init(env->halt_cond);
3735 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3736 while (env->created == 0)
3737 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3740 void qemu_init_vcpu(void *_env)
3742 CPUState *env = _env;
3744 if (kvm_enabled())
3745 kvm_start_vcpu(env);
3746 else
3747 tcg_init_vcpu(env);
3748 env->nr_cores = smp_cores;
3749 env->nr_threads = smp_threads;
3752 void qemu_notify_event(void)
3754 qemu_event_increment();
3757 void vm_stop(int reason)
3759 QemuThread me;
3760 qemu_thread_self(&me);
3762 if (!qemu_thread_equal(&me, &io_thread)) {
3763 qemu_system_vmstop_request(reason);
3765 * FIXME: should not return to device code in case
3766 * vm_stop() has been requested.
3768 if (cpu_single_env) {
3769 cpu_exit(cpu_single_env);
3770 cpu_single_env->stop = 1;
3772 return;
3774 do_vm_stop(reason);
3777 #endif
3780 #ifdef _WIN32
3781 static void host_main_loop_wait(int *timeout)
3783 int ret, ret2, i;
3784 PollingEntry *pe;
3787 /* XXX: need to suppress polling by better using win32 events */
3788 ret = 0;
3789 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3790 ret |= pe->func(pe->opaque);
3792 if (ret == 0) {
3793 int err;
3794 WaitObjects *w = &wait_objects;
3796 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3797 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3798 if (w->func[ret - WAIT_OBJECT_0])
3799 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3801 /* Check for additional signaled events */
3802 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3804 /* Check if event is signaled */
3805 ret2 = WaitForSingleObject(w->events[i], 0);
3806 if(ret2 == WAIT_OBJECT_0) {
3807 if (w->func[i])
3808 w->func[i](w->opaque[i]);
3809 } else if (ret2 == WAIT_TIMEOUT) {
3810 } else {
3811 err = GetLastError();
3812 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3815 } else if (ret == WAIT_TIMEOUT) {
3816 } else {
3817 err = GetLastError();
3818 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3822 *timeout = 0;
3824 #else
3825 static void host_main_loop_wait(int *timeout)
3828 #endif
3830 void main_loop_wait(int timeout)
3832 IOHandlerRecord *ioh;
3833 fd_set rfds, wfds, xfds;
3834 int ret, nfds;
3835 struct timeval tv;
3837 qemu_bh_update_timeout(&timeout);
3839 host_main_loop_wait(&timeout);
3841 /* poll any events */
3842 /* XXX: separate device handlers from system ones */
3843 nfds = -1;
3844 FD_ZERO(&rfds);
3845 FD_ZERO(&wfds);
3846 FD_ZERO(&xfds);
3847 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3848 if (ioh->deleted)
3849 continue;
3850 if (ioh->fd_read &&
3851 (!ioh->fd_read_poll ||
3852 ioh->fd_read_poll(ioh->opaque) != 0)) {
3853 FD_SET(ioh->fd, &rfds);
3854 if (ioh->fd > nfds)
3855 nfds = ioh->fd;
3857 if (ioh->fd_write) {
3858 FD_SET(ioh->fd, &wfds);
3859 if (ioh->fd > nfds)
3860 nfds = ioh->fd;
3864 tv.tv_sec = timeout / 1000;
3865 tv.tv_usec = (timeout % 1000) * 1000;
3867 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3869 qemu_mutex_unlock_iothread();
3870 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3871 qemu_mutex_lock_iothread();
3872 if (ret > 0) {
3873 IOHandlerRecord **pioh;
3875 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3876 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3877 ioh->fd_read(ioh->opaque);
3879 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3880 ioh->fd_write(ioh->opaque);
3884 /* remove deleted IO handlers */
3885 pioh = &first_io_handler;
3886 while (*pioh) {
3887 ioh = *pioh;
3888 if (ioh->deleted) {
3889 *pioh = ioh->next;
3890 qemu_free(ioh);
3891 } else
3892 pioh = &ioh->next;
3896 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3898 /* rearm timer, if not periodic */
3899 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3900 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3901 qemu_rearm_alarm_timer(alarm_timer);
3904 /* vm time timers */
3905 if (vm_running) {
3906 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3907 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3908 qemu_get_clock(vm_clock));
3911 /* real time timers */
3912 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3913 qemu_get_clock(rt_clock));
3915 /* Check bottom-halves last in case any of the earlier events triggered
3916 them. */
3917 qemu_bh_poll();
3921 static int qemu_cpu_exec(CPUState *env)
3923 int ret;
3924 #ifdef CONFIG_PROFILER
3925 int64_t ti;
3926 #endif
3928 #ifdef CONFIG_PROFILER
3929 ti = profile_getclock();
3930 #endif
3931 if (use_icount) {
3932 int64_t count;
3933 int decr;
3934 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3935 env->icount_decr.u16.low = 0;
3936 env->icount_extra = 0;
3937 count = qemu_next_deadline();
3938 count = (count + (1 << icount_time_shift) - 1)
3939 >> icount_time_shift;
3940 qemu_icount += count;
3941 decr = (count > 0xffff) ? 0xffff : count;
3942 count -= decr;
3943 env->icount_decr.u16.low = decr;
3944 env->icount_extra = count;
3946 ret = cpu_exec(env);
3947 #ifdef CONFIG_PROFILER
3948 qemu_time += profile_getclock() - ti;
3949 #endif
3950 if (use_icount) {
3951 /* Fold pending instructions back into the
3952 instruction counter, and clear the interrupt flag. */
3953 qemu_icount -= (env->icount_decr.u16.low
3954 + env->icount_extra);
3955 env->icount_decr.u32 = 0;
3956 env->icount_extra = 0;
3958 return ret;
3961 static void tcg_cpu_exec(void)
3963 int ret = 0;
3965 if (next_cpu == NULL)
3966 next_cpu = first_cpu;
3967 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3968 CPUState *env = cur_cpu = next_cpu;
3970 if (!vm_running)
3971 break;
3972 if (timer_alarm_pending) {
3973 timer_alarm_pending = 0;
3974 break;
3976 if (cpu_can_run(env))
3977 ret = qemu_cpu_exec(env);
3978 if (ret == EXCP_DEBUG) {
3979 gdb_set_stop_cpu(env);
3980 debug_requested = 1;
3981 break;
3986 static int cpu_has_work(CPUState *env)
3988 if (env->stop)
3989 return 1;
3990 if (env->stopped)
3991 return 0;
3992 if (!env->halted)
3993 return 1;
3994 if (qemu_cpu_has_work(env))
3995 return 1;
3996 return 0;
3999 static int tcg_has_work(void)
4001 CPUState *env;
4003 for (env = first_cpu; env != NULL; env = env->next_cpu)
4004 if (cpu_has_work(env))
4005 return 1;
4006 return 0;
4009 static int qemu_calculate_timeout(void)
4011 #ifndef CONFIG_IOTHREAD
4012 int timeout;
4014 if (!vm_running)
4015 timeout = 5000;
4016 else if (tcg_has_work())
4017 timeout = 0;
4018 else if (!use_icount)
4019 timeout = 5000;
4020 else {
4021 /* XXX: use timeout computed from timers */
4022 int64_t add;
4023 int64_t delta;
4024 /* Advance virtual time to the next event. */
4025 if (use_icount == 1) {
4026 /* When not using an adaptive execution frequency
4027 we tend to get badly out of sync with real time,
4028 so just delay for a reasonable amount of time. */
4029 delta = 0;
4030 } else {
4031 delta = cpu_get_icount() - cpu_get_clock();
4033 if (delta > 0) {
4034 /* If virtual time is ahead of real time then just
4035 wait for IO. */
4036 timeout = (delta / 1000000) + 1;
4037 } else {
4038 /* Wait for either IO to occur or the next
4039 timer event. */
4040 add = qemu_next_deadline();
4041 /* We advance the timer before checking for IO.
4042 Limit the amount we advance so that early IO
4043 activity won't get the guest too far ahead. */
4044 if (add > 10000000)
4045 add = 10000000;
4046 delta += add;
4047 add = (add + (1 << icount_time_shift) - 1)
4048 >> icount_time_shift;
4049 qemu_icount += add;
4050 timeout = delta / 1000000;
4051 if (timeout < 0)
4052 timeout = 0;
4056 return timeout;
4057 #else /* CONFIG_IOTHREAD */
4058 return 1000;
4059 #endif
4062 static int vm_can_run(void)
4064 if (powerdown_requested)
4065 return 0;
4066 if (reset_requested)
4067 return 0;
4068 if (shutdown_requested)
4069 return 0;
4070 if (debug_requested)
4071 return 0;
4072 return 1;
4075 qemu_irq qemu_system_powerdown;
4077 static void main_loop(void)
4079 int r;
4081 #ifdef CONFIG_IOTHREAD
4082 qemu_system_ready = 1;
4083 qemu_cond_broadcast(&qemu_system_cond);
4084 #endif
4086 for (;;) {
4087 do {
4088 #ifdef CONFIG_PROFILER
4089 int64_t ti;
4090 #endif
4091 #ifndef CONFIG_IOTHREAD
4092 tcg_cpu_exec();
4093 #endif
4094 #ifdef CONFIG_PROFILER
4095 ti = profile_getclock();
4096 #endif
4097 main_loop_wait(qemu_calculate_timeout());
4098 #ifdef CONFIG_PROFILER
4099 dev_time += profile_getclock() - ti;
4100 #endif
4101 } while (vm_can_run());
4103 if (qemu_debug_requested())
4104 vm_stop(EXCP_DEBUG);
4105 if (qemu_shutdown_requested()) {
4106 if (no_shutdown) {
4107 vm_stop(0);
4108 no_shutdown = 0;
4109 } else
4110 break;
4112 if (qemu_reset_requested()) {
4113 pause_all_vcpus();
4114 qemu_system_reset();
4115 resume_all_vcpus();
4117 if (qemu_powerdown_requested()) {
4118 qemu_irq_raise(qemu_system_powerdown);
4120 if ((r = qemu_vmstop_requested()))
4121 vm_stop(r);
4123 pause_all_vcpus();
4126 static void version(void)
4128 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4131 static void help(int exitcode)
4133 version();
4134 printf("usage: %s [options] [disk_image]\n"
4135 "\n"
4136 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4137 "\n"
4138 #define DEF(option, opt_arg, opt_enum, opt_help) \
4139 opt_help
4140 #define DEFHEADING(text) stringify(text) "\n"
4141 #include "qemu-options.h"
4142 #undef DEF
4143 #undef DEFHEADING
4144 #undef GEN_DOCS
4145 "\n"
4146 "During emulation, the following keys are useful:\n"
4147 "ctrl-alt-f toggle full screen\n"
4148 "ctrl-alt-n switch to virtual console 'n'\n"
4149 "ctrl-alt toggle mouse and keyboard grab\n"
4150 "\n"
4151 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4153 "qemu",
4154 DEFAULT_RAM_SIZE,
4155 #ifndef _WIN32
4156 DEFAULT_NETWORK_SCRIPT,
4157 DEFAULT_NETWORK_DOWN_SCRIPT,
4158 #endif
4159 DEFAULT_GDBSTUB_PORT,
4160 "/tmp/qemu.log");
4161 exit(exitcode);
4164 #define HAS_ARG 0x0001
4166 enum {
4167 #define DEF(option, opt_arg, opt_enum, opt_help) \
4168 opt_enum,
4169 #define DEFHEADING(text)
4170 #include "qemu-options.h"
4171 #undef DEF
4172 #undef DEFHEADING
4173 #undef GEN_DOCS
4176 typedef struct QEMUOption {
4177 const char *name;
4178 int flags;
4179 int index;
4180 } QEMUOption;
4182 static const QEMUOption qemu_options[] = {
4183 { "h", 0, QEMU_OPTION_h },
4184 #define DEF(option, opt_arg, opt_enum, opt_help) \
4185 { option, opt_arg, opt_enum },
4186 #define DEFHEADING(text)
4187 #include "qemu-options.h"
4188 #undef DEF
4189 #undef DEFHEADING
4190 #undef GEN_DOCS
4191 { NULL },
4194 #ifdef HAS_AUDIO
4195 struct soundhw soundhw[] = {
4196 #ifdef HAS_AUDIO_CHOICE
4197 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4199 "pcspk",
4200 "PC speaker",
4203 { .init_isa = pcspk_audio_init }
4205 #endif
4207 #ifdef CONFIG_SB16
4209 "sb16",
4210 "Creative Sound Blaster 16",
4213 { .init_isa = SB16_init }
4215 #endif
4217 #ifdef CONFIG_CS4231A
4219 "cs4231a",
4220 "CS4231A",
4223 { .init_isa = cs4231a_init }
4225 #endif
4227 #ifdef CONFIG_ADLIB
4229 "adlib",
4230 #ifdef HAS_YMF262
4231 "Yamaha YMF262 (OPL3)",
4232 #else
4233 "Yamaha YM3812 (OPL2)",
4234 #endif
4237 { .init_isa = Adlib_init }
4239 #endif
4241 #ifdef CONFIG_GUS
4243 "gus",
4244 "Gravis Ultrasound GF1",
4247 { .init_isa = GUS_init }
4249 #endif
4251 #ifdef CONFIG_AC97
4253 "ac97",
4254 "Intel 82801AA AC97 Audio",
4257 { .init_pci = ac97_init }
4259 #endif
4261 #ifdef CONFIG_ES1370
4263 "es1370",
4264 "ENSONIQ AudioPCI ES1370",
4267 { .init_pci = es1370_init }
4269 #endif
4271 #endif /* HAS_AUDIO_CHOICE */
4273 { NULL, NULL, 0, 0, { NULL } }
4276 static void select_soundhw (const char *optarg)
4278 struct soundhw *c;
4280 if (*optarg == '?') {
4281 show_valid_cards:
4283 printf ("Valid sound card names (comma separated):\n");
4284 for (c = soundhw; c->name; ++c) {
4285 printf ("%-11s %s\n", c->name, c->descr);
4287 printf ("\n-soundhw all will enable all of the above\n");
4288 exit (*optarg != '?');
4290 else {
4291 size_t l;
4292 const char *p;
4293 char *e;
4294 int bad_card = 0;
4296 if (!strcmp (optarg, "all")) {
4297 for (c = soundhw; c->name; ++c) {
4298 c->enabled = 1;
4300 return;
4303 p = optarg;
4304 while (*p) {
4305 e = strchr (p, ',');
4306 l = !e ? strlen (p) : (size_t) (e - p);
4308 for (c = soundhw; c->name; ++c) {
4309 if (!strncmp (c->name, p, l) && !c->name[l]) {
4310 c->enabled = 1;
4311 break;
4315 if (!c->name) {
4316 if (l > 80) {
4317 fprintf (stderr,
4318 "Unknown sound card name (too big to show)\n");
4320 else {
4321 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4322 (int) l, p);
4324 bad_card = 1;
4326 p += l + (e != NULL);
4329 if (bad_card)
4330 goto show_valid_cards;
4333 #endif
4335 static void select_vgahw (const char *p)
4337 const char *opts;
4339 vga_interface_type = VGA_NONE;
4340 if (strstart(p, "std", &opts)) {
4341 vga_interface_type = VGA_STD;
4342 } else if (strstart(p, "cirrus", &opts)) {
4343 vga_interface_type = VGA_CIRRUS;
4344 } else if (strstart(p, "vmware", &opts)) {
4345 vga_interface_type = VGA_VMWARE;
4346 } else if (strstart(p, "xenfb", &opts)) {
4347 vga_interface_type = VGA_XENFB;
4348 } else if (!strstart(p, "none", &opts)) {
4349 invalid_vga:
4350 fprintf(stderr, "Unknown vga type: %s\n", p);
4351 exit(1);
4353 while (*opts) {
4354 const char *nextopt;
4356 if (strstart(opts, ",retrace=", &nextopt)) {
4357 opts = nextopt;
4358 if (strstart(opts, "dumb", &nextopt))
4359 vga_retrace_method = VGA_RETRACE_DUMB;
4360 else if (strstart(opts, "precise", &nextopt))
4361 vga_retrace_method = VGA_RETRACE_PRECISE;
4362 else goto invalid_vga;
4363 } else goto invalid_vga;
4364 opts = nextopt;
4368 #ifdef TARGET_I386
4369 static int balloon_parse(const char *arg)
4371 QemuOpts *opts;
4373 if (strcmp(arg, "none") == 0) {
4374 return 0;
4377 if (!strncmp(arg, "virtio", 6)) {
4378 if (arg[6] == ',') {
4379 /* have params -> parse them */
4380 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4381 if (!opts)
4382 return -1;
4383 } else {
4384 /* create empty opts */
4385 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4387 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4388 return 0;
4391 return -1;
4393 #endif
4395 #ifdef _WIN32
4396 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4398 exit(STATUS_CONTROL_C_EXIT);
4399 return TRUE;
4401 #endif
4403 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4405 int ret;
4407 if(strlen(str) != 36)
4408 return -1;
4410 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4411 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4412 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4414 if(ret != 16)
4415 return -1;
4417 #ifdef TARGET_I386
4418 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4419 #endif
4421 return 0;
4424 #define MAX_NET_CLIENTS 32
4426 #ifndef _WIN32
4428 static void termsig_handler(int signal)
4430 qemu_system_shutdown_request();
4433 static void sigchld_handler(int signal)
4435 waitpid(-1, NULL, WNOHANG);
4438 static void sighandler_setup(void)
4440 struct sigaction act;
4442 memset(&act, 0, sizeof(act));
4443 act.sa_handler = termsig_handler;
4444 sigaction(SIGINT, &act, NULL);
4445 sigaction(SIGHUP, &act, NULL);
4446 sigaction(SIGTERM, &act, NULL);
4448 act.sa_handler = sigchld_handler;
4449 act.sa_flags = SA_NOCLDSTOP;
4450 sigaction(SIGCHLD, &act, NULL);
4453 #endif
4455 #ifdef _WIN32
4456 /* Look for support files in the same directory as the executable. */
4457 static char *find_datadir(const char *argv0)
4459 char *p;
4460 char buf[MAX_PATH];
4461 DWORD len;
4463 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4464 if (len == 0) {
4465 return NULL;
4468 buf[len] = 0;
4469 p = buf + len - 1;
4470 while (p != buf && *p != '\\')
4471 p--;
4472 *p = 0;
4473 if (access(buf, R_OK) == 0) {
4474 return qemu_strdup(buf);
4476 return NULL;
4478 #else /* !_WIN32 */
4480 /* Find a likely location for support files using the location of the binary.
4481 For installed binaries this will be "$bindir/../share/qemu". When
4482 running from the build tree this will be "$bindir/../pc-bios". */
4483 #define SHARE_SUFFIX "/share/qemu"
4484 #define BUILD_SUFFIX "/pc-bios"
4485 static char *find_datadir(const char *argv0)
4487 char *dir;
4488 char *p = NULL;
4489 char *res;
4490 char buf[PATH_MAX];
4491 size_t max_len;
4493 #if defined(__linux__)
4495 int len;
4496 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4497 if (len > 0) {
4498 buf[len] = 0;
4499 p = buf;
4502 #elif defined(__FreeBSD__)
4504 int len;
4505 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4506 if (len > 0) {
4507 buf[len] = 0;
4508 p = buf;
4511 #endif
4512 /* If we don't have any way of figuring out the actual executable
4513 location then try argv[0]. */
4514 if (!p) {
4515 p = realpath(argv0, buf);
4516 if (!p) {
4517 return NULL;
4520 dir = dirname(p);
4521 dir = dirname(dir);
4523 max_len = strlen(dir) +
4524 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4525 res = qemu_mallocz(max_len);
4526 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4527 if (access(res, R_OK)) {
4528 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4529 if (access(res, R_OK)) {
4530 qemu_free(res);
4531 res = NULL;
4535 return res;
4537 #undef SHARE_SUFFIX
4538 #undef BUILD_SUFFIX
4539 #endif
4541 char *qemu_find_file(int type, const char *name)
4543 int len;
4544 const char *subdir;
4545 char *buf;
4547 /* If name contains path separators then try it as a straight path. */
4548 if ((strchr(name, '/') || strchr(name, '\\'))
4549 && access(name, R_OK) == 0) {
4550 return qemu_strdup(name);
4552 switch (type) {
4553 case QEMU_FILE_TYPE_BIOS:
4554 subdir = "";
4555 break;
4556 case QEMU_FILE_TYPE_KEYMAP:
4557 subdir = "keymaps/";
4558 break;
4559 default:
4560 abort();
4562 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4563 buf = qemu_mallocz(len);
4564 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4565 if (access(buf, R_OK)) {
4566 qemu_free(buf);
4567 return NULL;
4569 return buf;
4572 static int device_init_func(QemuOpts *opts, void *opaque)
4574 DeviceState *dev;
4576 dev = qdev_device_add(opts);
4577 if (!dev)
4578 return -1;
4579 return 0;
4582 struct device_config {
4583 enum {
4584 DEV_USB, /* -usbdevice */
4585 DEV_BT, /* -bt */
4586 } type;
4587 const char *cmdline;
4588 QTAILQ_ENTRY(device_config) next;
4590 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4592 static void add_device_config(int type, const char *cmdline)
4594 struct device_config *conf;
4596 conf = qemu_mallocz(sizeof(*conf));
4597 conf->type = type;
4598 conf->cmdline = cmdline;
4599 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4602 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4604 struct device_config *conf;
4605 int rc;
4607 QTAILQ_FOREACH(conf, &device_configs, next) {
4608 if (conf->type != type)
4609 continue;
4610 rc = func(conf->cmdline);
4611 if (0 != rc)
4612 return rc;
4614 return 0;
4617 int main(int argc, char **argv, char **envp)
4619 const char *gdbstub_dev = NULL;
4620 uint32_t boot_devices_bitmap = 0;
4621 int i;
4622 int snapshot, linux_boot, net_boot;
4623 const char *initrd_filename;
4624 const char *kernel_filename, *kernel_cmdline;
4625 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4626 DisplayState *ds;
4627 DisplayChangeListener *dcl;
4628 int cyls, heads, secs, translation;
4629 const char *net_clients[MAX_NET_CLIENTS];
4630 int nb_net_clients;
4631 QemuOpts *hda_opts = NULL, *opts;
4632 int optind;
4633 const char *r, *optarg;
4634 CharDriverState *monitor_hds[MAX_MONITOR_DEVICES];
4635 const char *monitor_devices[MAX_MONITOR_DEVICES];
4636 int monitor_device_index;
4637 const char *serial_devices[MAX_SERIAL_PORTS];
4638 int serial_device_index;
4639 const char *parallel_devices[MAX_PARALLEL_PORTS];
4640 int parallel_device_index;
4641 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4642 int virtio_console_index;
4643 const char *loadvm = NULL;
4644 QEMUMachine *machine;
4645 const char *cpu_model;
4646 #ifndef _WIN32
4647 int fds[2];
4648 #endif
4649 int tb_size;
4650 const char *pid_file = NULL;
4651 const char *incoming = NULL;
4652 #ifndef _WIN32
4653 int fd = 0;
4654 struct passwd *pwd = NULL;
4655 const char *chroot_dir = NULL;
4656 const char *run_as = NULL;
4657 #endif
4658 CPUState *env;
4659 int show_vnc_port = 0;
4661 qemu_errors_to_file(stderr);
4662 qemu_cache_utils_init(envp);
4664 QLIST_INIT (&vm_change_state_head);
4665 #ifndef _WIN32
4667 struct sigaction act;
4668 sigfillset(&act.sa_mask);
4669 act.sa_flags = 0;
4670 act.sa_handler = SIG_IGN;
4671 sigaction(SIGPIPE, &act, NULL);
4673 #else
4674 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4675 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4676 QEMU to run on a single CPU */
4678 HANDLE h;
4679 DWORD mask, smask;
4680 int i;
4681 h = GetCurrentProcess();
4682 if (GetProcessAffinityMask(h, &mask, &smask)) {
4683 for(i = 0; i < 32; i++) {
4684 if (mask & (1 << i))
4685 break;
4687 if (i != 32) {
4688 mask = 1 << i;
4689 SetProcessAffinityMask(h, mask);
4693 #endif
4695 module_call_init(MODULE_INIT_MACHINE);
4696 machine = find_default_machine();
4697 cpu_model = NULL;
4698 initrd_filename = NULL;
4699 ram_size = 0;
4700 snapshot = 0;
4701 kernel_filename = NULL;
4702 kernel_cmdline = "";
4703 cyls = heads = secs = 0;
4704 translation = BIOS_ATA_TRANSLATION_AUTO;
4706 serial_devices[0] = "vc:80Cx24C";
4707 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4708 serial_devices[i] = NULL;
4709 serial_device_index = 0;
4711 parallel_devices[0] = "vc:80Cx24C";
4712 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4713 parallel_devices[i] = NULL;
4714 parallel_device_index = 0;
4716 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4717 virtio_consoles[i] = NULL;
4718 virtio_console_index = 0;
4720 monitor_devices[0] = "vc:80Cx24C";
4721 for (i = 1; i < MAX_MONITOR_DEVICES; i++) {
4722 monitor_devices[i] = NULL;
4724 monitor_device_index = 0;
4726 for (i = 0; i < MAX_NODES; i++) {
4727 node_mem[i] = 0;
4728 node_cpumask[i] = 0;
4731 nb_net_clients = 0;
4732 nb_numa_nodes = 0;
4733 nb_nics = 0;
4735 tb_size = 0;
4736 autostart= 1;
4738 optind = 1;
4739 for(;;) {
4740 if (optind >= argc)
4741 break;
4742 r = argv[optind];
4743 if (r[0] != '-') {
4744 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4745 } else {
4746 const QEMUOption *popt;
4748 optind++;
4749 /* Treat --foo the same as -foo. */
4750 if (r[1] == '-')
4751 r++;
4752 popt = qemu_options;
4753 for(;;) {
4754 if (!popt->name) {
4755 fprintf(stderr, "%s: invalid option -- '%s'\n",
4756 argv[0], r);
4757 exit(1);
4759 if (!strcmp(popt->name, r + 1))
4760 break;
4761 popt++;
4763 if (popt->flags & HAS_ARG) {
4764 if (optind >= argc) {
4765 fprintf(stderr, "%s: option '%s' requires an argument\n",
4766 argv[0], r);
4767 exit(1);
4769 optarg = argv[optind++];
4770 } else {
4771 optarg = NULL;
4774 switch(popt->index) {
4775 case QEMU_OPTION_M:
4776 machine = find_machine(optarg);
4777 if (!machine) {
4778 QEMUMachine *m;
4779 printf("Supported machines are:\n");
4780 for(m = first_machine; m != NULL; m = m->next) {
4781 if (m->alias)
4782 printf("%-10s %s (alias of %s)\n",
4783 m->alias, m->desc, m->name);
4784 printf("%-10s %s%s\n",
4785 m->name, m->desc,
4786 m->is_default ? " (default)" : "");
4788 exit(*optarg != '?');
4790 break;
4791 case QEMU_OPTION_cpu:
4792 /* hw initialization will check this */
4793 if (*optarg == '?') {
4794 /* XXX: implement xxx_cpu_list for targets that still miss it */
4795 #if defined(cpu_list)
4796 cpu_list(stdout, &fprintf);
4797 #endif
4798 exit(0);
4799 } else {
4800 cpu_model = optarg;
4802 break;
4803 case QEMU_OPTION_initrd:
4804 initrd_filename = optarg;
4805 break;
4806 case QEMU_OPTION_hda:
4807 if (cyls == 0)
4808 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4809 else
4810 hda_opts = drive_add(optarg, HD_ALIAS
4811 ",cyls=%d,heads=%d,secs=%d%s",
4812 0, cyls, heads, secs,
4813 translation == BIOS_ATA_TRANSLATION_LBA ?
4814 ",trans=lba" :
4815 translation == BIOS_ATA_TRANSLATION_NONE ?
4816 ",trans=none" : "");
4817 break;
4818 case QEMU_OPTION_hdb:
4819 case QEMU_OPTION_hdc:
4820 case QEMU_OPTION_hdd:
4821 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4822 break;
4823 case QEMU_OPTION_drive:
4824 drive_add(NULL, "%s", optarg);
4825 break;
4826 case QEMU_OPTION_set:
4827 if (qemu_set_option(optarg) != 0)
4828 exit(1);
4829 break;
4830 case QEMU_OPTION_mtdblock:
4831 drive_add(optarg, MTD_ALIAS);
4832 break;
4833 case QEMU_OPTION_sd:
4834 drive_add(optarg, SD_ALIAS);
4835 break;
4836 case QEMU_OPTION_pflash:
4837 drive_add(optarg, PFLASH_ALIAS);
4838 break;
4839 case QEMU_OPTION_snapshot:
4840 snapshot = 1;
4841 break;
4842 case QEMU_OPTION_hdachs:
4844 const char *p;
4845 p = optarg;
4846 cyls = strtol(p, (char **)&p, 0);
4847 if (cyls < 1 || cyls > 16383)
4848 goto chs_fail;
4849 if (*p != ',')
4850 goto chs_fail;
4851 p++;
4852 heads = strtol(p, (char **)&p, 0);
4853 if (heads < 1 || heads > 16)
4854 goto chs_fail;
4855 if (*p != ',')
4856 goto chs_fail;
4857 p++;
4858 secs = strtol(p, (char **)&p, 0);
4859 if (secs < 1 || secs > 63)
4860 goto chs_fail;
4861 if (*p == ',') {
4862 p++;
4863 if (!strcmp(p, "none"))
4864 translation = BIOS_ATA_TRANSLATION_NONE;
4865 else if (!strcmp(p, "lba"))
4866 translation = BIOS_ATA_TRANSLATION_LBA;
4867 else if (!strcmp(p, "auto"))
4868 translation = BIOS_ATA_TRANSLATION_AUTO;
4869 else
4870 goto chs_fail;
4871 } else if (*p != '\0') {
4872 chs_fail:
4873 fprintf(stderr, "qemu: invalid physical CHS format\n");
4874 exit(1);
4876 if (hda_opts != NULL) {
4877 char num[16];
4878 snprintf(num, sizeof(num), "%d", cyls);
4879 qemu_opt_set(hda_opts, "cyls", num);
4880 snprintf(num, sizeof(num), "%d", heads);
4881 qemu_opt_set(hda_opts, "heads", num);
4882 snprintf(num, sizeof(num), "%d", secs);
4883 qemu_opt_set(hda_opts, "secs", num);
4884 if (translation == BIOS_ATA_TRANSLATION_LBA)
4885 qemu_opt_set(hda_opts, "trans", "lba");
4886 if (translation == BIOS_ATA_TRANSLATION_NONE)
4887 qemu_opt_set(hda_opts, "trans", "none");
4890 break;
4891 case QEMU_OPTION_numa:
4892 if (nb_numa_nodes >= MAX_NODES) {
4893 fprintf(stderr, "qemu: too many NUMA nodes\n");
4894 exit(1);
4896 numa_add(optarg);
4897 break;
4898 case QEMU_OPTION_nographic:
4899 display_type = DT_NOGRAPHIC;
4900 break;
4901 #ifdef CONFIG_CURSES
4902 case QEMU_OPTION_curses:
4903 display_type = DT_CURSES;
4904 break;
4905 #endif
4906 case QEMU_OPTION_portrait:
4907 graphic_rotate = 1;
4908 break;
4909 case QEMU_OPTION_kernel:
4910 kernel_filename = optarg;
4911 break;
4912 case QEMU_OPTION_append:
4913 kernel_cmdline = optarg;
4914 break;
4915 case QEMU_OPTION_cdrom:
4916 drive_add(optarg, CDROM_ALIAS);
4917 break;
4918 case QEMU_OPTION_boot:
4920 static const char * const params[] = {
4921 "order", "once", "menu", NULL
4923 char buf[sizeof(boot_devices)];
4924 char *standard_boot_devices;
4925 int legacy = 0;
4927 if (!strchr(optarg, '=')) {
4928 legacy = 1;
4929 pstrcpy(buf, sizeof(buf), optarg);
4930 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4931 fprintf(stderr,
4932 "qemu: unknown boot parameter '%s' in '%s'\n",
4933 buf, optarg);
4934 exit(1);
4937 if (legacy ||
4938 get_param_value(buf, sizeof(buf), "order", optarg)) {
4939 boot_devices_bitmap = parse_bootdevices(buf);
4940 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4942 if (!legacy) {
4943 if (get_param_value(buf, sizeof(buf),
4944 "once", optarg)) {
4945 boot_devices_bitmap |= parse_bootdevices(buf);
4946 standard_boot_devices = qemu_strdup(boot_devices);
4947 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4948 qemu_register_reset(restore_boot_devices,
4949 standard_boot_devices);
4951 if (get_param_value(buf, sizeof(buf),
4952 "menu", optarg)) {
4953 if (!strcmp(buf, "on")) {
4954 boot_menu = 1;
4955 } else if (!strcmp(buf, "off")) {
4956 boot_menu = 0;
4957 } else {
4958 fprintf(stderr,
4959 "qemu: invalid option value '%s'\n",
4960 buf);
4961 exit(1);
4966 break;
4967 case QEMU_OPTION_fda:
4968 case QEMU_OPTION_fdb:
4969 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4970 break;
4971 #ifdef TARGET_I386
4972 case QEMU_OPTION_no_fd_bootchk:
4973 fd_bootchk = 0;
4974 break;
4975 #endif
4976 case QEMU_OPTION_net:
4977 if (nb_net_clients >= MAX_NET_CLIENTS) {
4978 fprintf(stderr, "qemu: too many network clients\n");
4979 exit(1);
4981 net_clients[nb_net_clients] = optarg;
4982 nb_net_clients++;
4983 break;
4984 #ifdef CONFIG_SLIRP
4985 case QEMU_OPTION_tftp:
4986 legacy_tftp_prefix = optarg;
4987 break;
4988 case QEMU_OPTION_bootp:
4989 legacy_bootp_filename = optarg;
4990 break;
4991 #ifndef _WIN32
4992 case QEMU_OPTION_smb:
4993 net_slirp_smb(optarg);
4994 break;
4995 #endif
4996 case QEMU_OPTION_redir:
4997 net_slirp_redir(optarg);
4998 break;
4999 #endif
5000 case QEMU_OPTION_bt:
5001 add_device_config(DEV_BT, optarg);
5002 break;
5003 #ifdef HAS_AUDIO
5004 case QEMU_OPTION_audio_help:
5005 AUD_help ();
5006 exit (0);
5007 break;
5008 case QEMU_OPTION_soundhw:
5009 select_soundhw (optarg);
5010 break;
5011 #endif
5012 case QEMU_OPTION_h:
5013 help(0);
5014 break;
5015 case QEMU_OPTION_version:
5016 version();
5017 exit(0);
5018 break;
5019 case QEMU_OPTION_m: {
5020 uint64_t value;
5021 char *ptr;
5023 value = strtoul(optarg, &ptr, 10);
5024 switch (*ptr) {
5025 case 0: case 'M': case 'm':
5026 value <<= 20;
5027 break;
5028 case 'G': case 'g':
5029 value <<= 30;
5030 break;
5031 default:
5032 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5033 exit(1);
5036 /* On 32-bit hosts, QEMU is limited by virtual address space */
5037 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5038 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5039 exit(1);
5041 if (value != (uint64_t)(ram_addr_t)value) {
5042 fprintf(stderr, "qemu: ram size too large\n");
5043 exit(1);
5045 ram_size = value;
5046 break;
5048 case QEMU_OPTION_d:
5050 int mask;
5051 const CPULogItem *item;
5053 mask = cpu_str_to_log_mask(optarg);
5054 if (!mask) {
5055 printf("Log items (comma separated):\n");
5056 for(item = cpu_log_items; item->mask != 0; item++) {
5057 printf("%-10s %s\n", item->name, item->help);
5059 exit(1);
5061 cpu_set_log(mask);
5063 break;
5064 case QEMU_OPTION_s:
5065 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5066 break;
5067 case QEMU_OPTION_gdb:
5068 gdbstub_dev = optarg;
5069 break;
5070 case QEMU_OPTION_L:
5071 data_dir = optarg;
5072 break;
5073 case QEMU_OPTION_bios:
5074 bios_name = optarg;
5075 break;
5076 case QEMU_OPTION_singlestep:
5077 singlestep = 1;
5078 break;
5079 case QEMU_OPTION_S:
5080 autostart = 0;
5081 break;
5082 #ifndef _WIN32
5083 case QEMU_OPTION_k:
5084 keyboard_layout = optarg;
5085 break;
5086 #endif
5087 case QEMU_OPTION_localtime:
5088 rtc_utc = 0;
5089 break;
5090 case QEMU_OPTION_vga:
5091 select_vgahw (optarg);
5092 break;
5093 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5094 case QEMU_OPTION_g:
5096 const char *p;
5097 int w, h, depth;
5098 p = optarg;
5099 w = strtol(p, (char **)&p, 10);
5100 if (w <= 0) {
5101 graphic_error:
5102 fprintf(stderr, "qemu: invalid resolution or depth\n");
5103 exit(1);
5105 if (*p != 'x')
5106 goto graphic_error;
5107 p++;
5108 h = strtol(p, (char **)&p, 10);
5109 if (h <= 0)
5110 goto graphic_error;
5111 if (*p == 'x') {
5112 p++;
5113 depth = strtol(p, (char **)&p, 10);
5114 if (depth != 8 && depth != 15 && depth != 16 &&
5115 depth != 24 && depth != 32)
5116 goto graphic_error;
5117 } else if (*p == '\0') {
5118 depth = graphic_depth;
5119 } else {
5120 goto graphic_error;
5123 graphic_width = w;
5124 graphic_height = h;
5125 graphic_depth = depth;
5127 break;
5128 #endif
5129 case QEMU_OPTION_echr:
5131 char *r;
5132 term_escape_char = strtol(optarg, &r, 0);
5133 if (r == optarg)
5134 printf("Bad argument to echr\n");
5135 break;
5137 case QEMU_OPTION_monitor:
5138 if (monitor_device_index >= MAX_MONITOR_DEVICES) {
5139 fprintf(stderr, "qemu: too many monitor devices\n");
5140 exit(1);
5142 monitor_devices[monitor_device_index] = optarg;
5143 monitor_device_index++;
5144 break;
5145 case QEMU_OPTION_chardev:
5146 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5147 if (!opts) {
5148 fprintf(stderr, "parse error: %s\n", optarg);
5149 exit(1);
5151 if (qemu_chr_open_opts(opts, NULL) == NULL) {
5152 exit(1);
5154 break;
5155 case QEMU_OPTION_serial:
5156 if (serial_device_index >= MAX_SERIAL_PORTS) {
5157 fprintf(stderr, "qemu: too many serial ports\n");
5158 exit(1);
5160 serial_devices[serial_device_index] = optarg;
5161 serial_device_index++;
5162 break;
5163 case QEMU_OPTION_watchdog:
5164 if (watchdog) {
5165 fprintf(stderr,
5166 "qemu: only one watchdog option may be given\n");
5167 return 1;
5169 watchdog = optarg;
5170 break;
5171 case QEMU_OPTION_watchdog_action:
5172 if (select_watchdog_action(optarg) == -1) {
5173 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5174 exit(1);
5176 break;
5177 case QEMU_OPTION_virtiocon:
5178 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5179 fprintf(stderr, "qemu: too many virtio consoles\n");
5180 exit(1);
5182 virtio_consoles[virtio_console_index] = optarg;
5183 virtio_console_index++;
5184 break;
5185 case QEMU_OPTION_parallel:
5186 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5187 fprintf(stderr, "qemu: too many parallel ports\n");
5188 exit(1);
5190 parallel_devices[parallel_device_index] = optarg;
5191 parallel_device_index++;
5192 break;
5193 case QEMU_OPTION_loadvm:
5194 loadvm = optarg;
5195 break;
5196 case QEMU_OPTION_full_screen:
5197 full_screen = 1;
5198 break;
5199 #ifdef CONFIG_SDL
5200 case QEMU_OPTION_no_frame:
5201 no_frame = 1;
5202 break;
5203 case QEMU_OPTION_alt_grab:
5204 alt_grab = 1;
5205 break;
5206 case QEMU_OPTION_no_quit:
5207 no_quit = 1;
5208 break;
5209 case QEMU_OPTION_sdl:
5210 display_type = DT_SDL;
5211 break;
5212 #endif
5213 case QEMU_OPTION_pidfile:
5214 pid_file = optarg;
5215 break;
5216 #ifdef TARGET_I386
5217 case QEMU_OPTION_win2k_hack:
5218 win2k_install_hack = 1;
5219 break;
5220 case QEMU_OPTION_rtc_td_hack:
5221 rtc_td_hack = 1;
5222 break;
5223 case QEMU_OPTION_acpitable:
5224 if(acpi_table_add(optarg) < 0) {
5225 fprintf(stderr, "Wrong acpi table provided\n");
5226 exit(1);
5228 break;
5229 case QEMU_OPTION_smbios:
5230 if(smbios_entry_add(optarg) < 0) {
5231 fprintf(stderr, "Wrong smbios provided\n");
5232 exit(1);
5234 break;
5235 #endif
5236 #ifdef CONFIG_KVM
5237 case QEMU_OPTION_enable_kvm:
5238 kvm_allowed = 1;
5239 break;
5240 #endif
5241 case QEMU_OPTION_usb:
5242 usb_enabled = 1;
5243 break;
5244 case QEMU_OPTION_usbdevice:
5245 usb_enabled = 1;
5246 add_device_config(DEV_USB, optarg);
5247 break;
5248 case QEMU_OPTION_device:
5249 opts = qemu_opts_parse(&qemu_device_opts, optarg, "driver");
5250 if (!opts) {
5251 fprintf(stderr, "parse error: %s\n", optarg);
5252 exit(1);
5254 break;
5255 case QEMU_OPTION_smp:
5256 smp_parse(optarg);
5257 if (smp_cpus < 1) {
5258 fprintf(stderr, "Invalid number of CPUs\n");
5259 exit(1);
5261 if (max_cpus < smp_cpus) {
5262 fprintf(stderr, "maxcpus must be equal to or greater than "
5263 "smp\n");
5264 exit(1);
5266 if (max_cpus > 255) {
5267 fprintf(stderr, "Unsupported number of maxcpus\n");
5268 exit(1);
5270 break;
5271 case QEMU_OPTION_vnc:
5272 display_type = DT_VNC;
5273 vnc_display = optarg;
5274 break;
5275 #ifdef TARGET_I386
5276 case QEMU_OPTION_no_acpi:
5277 acpi_enabled = 0;
5278 break;
5279 case QEMU_OPTION_no_hpet:
5280 no_hpet = 1;
5281 break;
5282 case QEMU_OPTION_balloon:
5283 if (balloon_parse(optarg) < 0) {
5284 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5285 exit(1);
5287 break;
5288 #endif
5289 case QEMU_OPTION_no_reboot:
5290 no_reboot = 1;
5291 break;
5292 case QEMU_OPTION_no_shutdown:
5293 no_shutdown = 1;
5294 break;
5295 case QEMU_OPTION_show_cursor:
5296 cursor_hide = 0;
5297 break;
5298 case QEMU_OPTION_uuid:
5299 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5300 fprintf(stderr, "Fail to parse UUID string."
5301 " Wrong format.\n");
5302 exit(1);
5304 break;
5305 #ifndef _WIN32
5306 case QEMU_OPTION_daemonize:
5307 daemonize = 1;
5308 break;
5309 #endif
5310 case QEMU_OPTION_option_rom:
5311 if (nb_option_roms >= MAX_OPTION_ROMS) {
5312 fprintf(stderr, "Too many option ROMs\n");
5313 exit(1);
5315 option_rom[nb_option_roms] = optarg;
5316 nb_option_roms++;
5317 break;
5318 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5319 case QEMU_OPTION_semihosting:
5320 semihosting_enabled = 1;
5321 break;
5322 #endif
5323 case QEMU_OPTION_name:
5324 qemu_name = qemu_strdup(optarg);
5326 char *p = strchr(qemu_name, ',');
5327 if (p != NULL) {
5328 *p++ = 0;
5329 if (strncmp(p, "process=", 8)) {
5330 fprintf(stderr, "Unknown subargument %s to -name", p);
5331 exit(1);
5333 p += 8;
5334 set_proc_name(p);
5337 break;
5338 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5339 case QEMU_OPTION_prom_env:
5340 if (nb_prom_envs >= MAX_PROM_ENVS) {
5341 fprintf(stderr, "Too many prom variables\n");
5342 exit(1);
5344 prom_envs[nb_prom_envs] = optarg;
5345 nb_prom_envs++;
5346 break;
5347 #endif
5348 #ifdef TARGET_ARM
5349 case QEMU_OPTION_old_param:
5350 old_param = 1;
5351 break;
5352 #endif
5353 case QEMU_OPTION_clock:
5354 configure_alarms(optarg);
5355 break;
5356 case QEMU_OPTION_startdate:
5358 struct tm tm;
5359 time_t rtc_start_date;
5360 if (!strcmp(optarg, "now")) {
5361 rtc_date_offset = -1;
5362 } else {
5363 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5364 &tm.tm_year,
5365 &tm.tm_mon,
5366 &tm.tm_mday,
5367 &tm.tm_hour,
5368 &tm.tm_min,
5369 &tm.tm_sec) == 6) {
5370 /* OK */
5371 } else if (sscanf(optarg, "%d-%d-%d",
5372 &tm.tm_year,
5373 &tm.tm_mon,
5374 &tm.tm_mday) == 3) {
5375 tm.tm_hour = 0;
5376 tm.tm_min = 0;
5377 tm.tm_sec = 0;
5378 } else {
5379 goto date_fail;
5381 tm.tm_year -= 1900;
5382 tm.tm_mon--;
5383 rtc_start_date = mktimegm(&tm);
5384 if (rtc_start_date == -1) {
5385 date_fail:
5386 fprintf(stderr, "Invalid date format. Valid format are:\n"
5387 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5388 exit(1);
5390 rtc_date_offset = time(NULL) - rtc_start_date;
5393 break;
5394 case QEMU_OPTION_tb_size:
5395 tb_size = strtol(optarg, NULL, 0);
5396 if (tb_size < 0)
5397 tb_size = 0;
5398 break;
5399 case QEMU_OPTION_icount:
5400 use_icount = 1;
5401 if (strcmp(optarg, "auto") == 0) {
5402 icount_time_shift = -1;
5403 } else {
5404 icount_time_shift = strtol(optarg, NULL, 0);
5406 break;
5407 case QEMU_OPTION_incoming:
5408 incoming = optarg;
5409 break;
5410 #ifndef _WIN32
5411 case QEMU_OPTION_chroot:
5412 chroot_dir = optarg;
5413 break;
5414 case QEMU_OPTION_runas:
5415 run_as = optarg;
5416 break;
5417 #endif
5418 #ifdef CONFIG_XEN
5419 case QEMU_OPTION_xen_domid:
5420 xen_domid = atoi(optarg);
5421 break;
5422 case QEMU_OPTION_xen_create:
5423 xen_mode = XEN_CREATE;
5424 break;
5425 case QEMU_OPTION_xen_attach:
5426 xen_mode = XEN_ATTACH;
5427 break;
5428 #endif
5433 /* If no data_dir is specified then try to find it relative to the
5434 executable path. */
5435 if (!data_dir) {
5436 data_dir = find_datadir(argv[0]);
5438 /* If all else fails use the install patch specified when building. */
5439 if (!data_dir) {
5440 data_dir = CONFIG_QEMU_SHAREDIR;
5444 * Default to max_cpus = smp_cpus, in case the user doesn't
5445 * specify a max_cpus value.
5447 if (!max_cpus)
5448 max_cpus = smp_cpus;
5450 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5451 if (smp_cpus > machine->max_cpus) {
5452 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5453 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5454 machine->max_cpus);
5455 exit(1);
5458 if (display_type == DT_NOGRAPHIC) {
5459 if (serial_device_index == 0)
5460 serial_devices[0] = "stdio";
5461 if (parallel_device_index == 0)
5462 parallel_devices[0] = "null";
5463 if (strncmp(monitor_devices[0], "vc", 2) == 0) {
5464 monitor_devices[0] = "stdio";
5468 #ifndef _WIN32
5469 if (daemonize) {
5470 pid_t pid;
5472 if (pipe(fds) == -1)
5473 exit(1);
5475 pid = fork();
5476 if (pid > 0) {
5477 uint8_t status;
5478 ssize_t len;
5480 close(fds[1]);
5482 again:
5483 len = read(fds[0], &status, 1);
5484 if (len == -1 && (errno == EINTR))
5485 goto again;
5487 if (len != 1)
5488 exit(1);
5489 else if (status == 1) {
5490 fprintf(stderr, "Could not acquire pidfile\n");
5491 exit(1);
5492 } else
5493 exit(0);
5494 } else if (pid < 0)
5495 exit(1);
5497 setsid();
5499 pid = fork();
5500 if (pid > 0)
5501 exit(0);
5502 else if (pid < 0)
5503 exit(1);
5505 umask(027);
5507 signal(SIGTSTP, SIG_IGN);
5508 signal(SIGTTOU, SIG_IGN);
5509 signal(SIGTTIN, SIG_IGN);
5512 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5513 if (daemonize) {
5514 uint8_t status = 1;
5515 write(fds[1], &status, 1);
5516 } else
5517 fprintf(stderr, "Could not acquire pid file\n");
5518 exit(1);
5520 #endif
5522 if (kvm_enabled()) {
5523 int ret;
5525 ret = kvm_init(smp_cpus);
5526 if (ret < 0) {
5527 fprintf(stderr, "failed to initialize KVM\n");
5528 exit(1);
5532 if (qemu_init_main_loop()) {
5533 fprintf(stderr, "qemu_init_main_loop failed\n");
5534 exit(1);
5536 linux_boot = (kernel_filename != NULL);
5538 if (!linux_boot && *kernel_cmdline != '\0') {
5539 fprintf(stderr, "-append only allowed with -kernel option\n");
5540 exit(1);
5543 if (!linux_boot && initrd_filename != NULL) {
5544 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5545 exit(1);
5548 #ifndef _WIN32
5549 /* Win32 doesn't support line-buffering and requires size >= 2 */
5550 setvbuf(stdout, NULL, _IOLBF, 0);
5551 #endif
5553 init_timers();
5554 if (init_timer_alarm() < 0) {
5555 fprintf(stderr, "could not initialize alarm timer\n");
5556 exit(1);
5558 if (use_icount && icount_time_shift < 0) {
5559 use_icount = 2;
5560 /* 125MIPS seems a reasonable initial guess at the guest speed.
5561 It will be corrected fairly quickly anyway. */
5562 icount_time_shift = 3;
5563 init_icount_adjust();
5566 #ifdef _WIN32
5567 socket_init();
5568 #endif
5570 /* init network clients */
5571 if (nb_net_clients == 0) {
5572 /* if no clients, we use a default config */
5573 net_clients[nb_net_clients++] = "nic";
5574 #ifdef CONFIG_SLIRP
5575 net_clients[nb_net_clients++] = "user";
5576 #endif
5579 for(i = 0;i < nb_net_clients; i++) {
5580 if (net_client_parse(net_clients[i]) < 0)
5581 exit(1);
5584 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5585 net_set_boot_mask(net_boot);
5587 net_client_check();
5589 /* init the bluetooth world */
5590 if (foreach_device_config(DEV_BT, bt_parse))
5591 exit(1);
5593 /* init the memory */
5594 if (ram_size == 0)
5595 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5597 /* init the dynamic translator */
5598 cpu_exec_init_all(tb_size * 1024 * 1024);
5600 bdrv_init();
5602 /* we always create the cdrom drive, even if no disk is there */
5603 drive_add(NULL, CDROM_ALIAS);
5605 /* we always create at least one floppy */
5606 drive_add(NULL, FD_ALIAS, 0);
5608 /* we always create one sd slot, even if no card is in it */
5609 drive_add(NULL, SD_ALIAS);
5611 /* open the virtual block devices */
5612 if (snapshot)
5613 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5614 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5615 exit(1);
5617 vmstate_register(0, &vmstate_timers ,&timers_state);
5618 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5620 /* Maintain compatibility with multiple stdio monitors */
5621 if (!strcmp(monitor_devices[0],"stdio")) {
5622 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5623 const char *devname = serial_devices[i];
5624 if (devname && !strcmp(devname,"mon:stdio")) {
5625 monitor_devices[0] = NULL;
5626 break;
5627 } else if (devname && !strcmp(devname,"stdio")) {
5628 monitor_devices[0] = NULL;
5629 serial_devices[i] = "mon:stdio";
5630 break;
5635 if (nb_numa_nodes > 0) {
5636 int i;
5638 if (nb_numa_nodes > smp_cpus) {
5639 nb_numa_nodes = smp_cpus;
5642 /* If no memory size if given for any node, assume the default case
5643 * and distribute the available memory equally across all nodes
5645 for (i = 0; i < nb_numa_nodes; i++) {
5646 if (node_mem[i] != 0)
5647 break;
5649 if (i == nb_numa_nodes) {
5650 uint64_t usedmem = 0;
5652 /* On Linux, the each node's border has to be 8MB aligned,
5653 * the final node gets the rest.
5655 for (i = 0; i < nb_numa_nodes - 1; i++) {
5656 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5657 usedmem += node_mem[i];
5659 node_mem[i] = ram_size - usedmem;
5662 for (i = 0; i < nb_numa_nodes; i++) {
5663 if (node_cpumask[i] != 0)
5664 break;
5666 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5667 * must cope with this anyway, because there are BIOSes out there in
5668 * real machines which also use this scheme.
5670 if (i == nb_numa_nodes) {
5671 for (i = 0; i < smp_cpus; i++) {
5672 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5677 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5678 const char *devname = monitor_devices[i];
5679 if (devname && strcmp(devname, "none")) {
5680 char label[32];
5681 if (i == 0) {
5682 snprintf(label, sizeof(label), "monitor");
5683 } else {
5684 snprintf(label, sizeof(label), "monitor%d", i);
5686 monitor_hds[i] = qemu_chr_open(label, devname, NULL);
5687 if (!monitor_hds[i]) {
5688 fprintf(stderr, "qemu: could not open monitor device '%s'\n",
5689 devname);
5690 exit(1);
5695 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5696 const char *devname = serial_devices[i];
5697 if (devname && strcmp(devname, "none")) {
5698 char label[32];
5699 snprintf(label, sizeof(label), "serial%d", i);
5700 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5701 if (!serial_hds[i]) {
5702 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5703 devname);
5704 exit(1);
5709 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5710 const char *devname = parallel_devices[i];
5711 if (devname && strcmp(devname, "none")) {
5712 char label[32];
5713 snprintf(label, sizeof(label), "parallel%d", i);
5714 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5715 if (!parallel_hds[i]) {
5716 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5717 devname);
5718 exit(1);
5723 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5724 const char *devname = virtio_consoles[i];
5725 if (devname && strcmp(devname, "none")) {
5726 char label[32];
5727 snprintf(label, sizeof(label), "virtcon%d", i);
5728 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5729 if (!virtcon_hds[i]) {
5730 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5731 devname);
5732 exit(1);
5737 module_call_init(MODULE_INIT_DEVICE);
5739 if (watchdog) {
5740 i = select_watchdog(watchdog);
5741 if (i > 0)
5742 exit (i == 1 ? 1 : 0);
5745 if (machine->compat_props) {
5746 qdev_prop_register_compat(machine->compat_props);
5748 machine->init(ram_size, boot_devices,
5749 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5752 #ifndef _WIN32
5753 /* must be after terminal init, SDL library changes signal handlers */
5754 sighandler_setup();
5755 #endif
5757 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5758 for (i = 0; i < nb_numa_nodes; i++) {
5759 if (node_cpumask[i] & (1 << env->cpu_index)) {
5760 env->numa_node = i;
5765 current_machine = machine;
5767 /* init USB devices */
5768 if (usb_enabled) {
5769 foreach_device_config(DEV_USB, usb_parse);
5772 /* init generic devices */
5773 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5774 exit(1);
5776 if (!display_state)
5777 dumb_display_init();
5778 /* just use the first displaystate for the moment */
5779 ds = display_state;
5781 if (display_type == DT_DEFAULT) {
5782 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5783 display_type = DT_SDL;
5784 #else
5785 display_type = DT_VNC;
5786 vnc_display = "localhost:0,to=99";
5787 show_vnc_port = 1;
5788 #endif
5792 switch (display_type) {
5793 case DT_NOGRAPHIC:
5794 break;
5795 #if defined(CONFIG_CURSES)
5796 case DT_CURSES:
5797 curses_display_init(ds, full_screen);
5798 break;
5799 #endif
5800 #if defined(CONFIG_SDL)
5801 case DT_SDL:
5802 sdl_display_init(ds, full_screen, no_frame);
5803 break;
5804 #elif defined(CONFIG_COCOA)
5805 case DT_SDL:
5806 cocoa_display_init(ds, full_screen);
5807 break;
5808 #endif
5809 case DT_VNC:
5810 vnc_display_init(ds);
5811 if (vnc_display_open(ds, vnc_display) < 0)
5812 exit(1);
5814 if (show_vnc_port) {
5815 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5817 break;
5818 default:
5819 break;
5821 dpy_resize(ds);
5823 dcl = ds->listeners;
5824 while (dcl != NULL) {
5825 if (dcl->dpy_refresh != NULL) {
5826 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5827 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5829 dcl = dcl->next;
5832 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5833 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5834 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5837 text_consoles_set_display(display_state);
5838 qemu_chr_initial_reset();
5840 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5841 if (monitor_devices[i] && monitor_hds[i]) {
5842 monitor_init(monitor_hds[i],
5843 MONITOR_USE_READLINE |
5844 ((i == 0) ? MONITOR_IS_DEFAULT : 0));
5848 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5849 const char *devname = serial_devices[i];
5850 if (devname && strcmp(devname, "none")) {
5851 if (strstart(devname, "vc", 0))
5852 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5856 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5857 const char *devname = parallel_devices[i];
5858 if (devname && strcmp(devname, "none")) {
5859 if (strstart(devname, "vc", 0))
5860 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5864 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5865 const char *devname = virtio_consoles[i];
5866 if (virtcon_hds[i] && devname) {
5867 if (strstart(devname, "vc", 0))
5868 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5872 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5873 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5874 gdbstub_dev);
5875 exit(1);
5878 if (loadvm) {
5879 if (load_vmstate(cur_mon, loadvm) < 0) {
5880 autostart = 0;
5884 if (incoming) {
5885 qemu_start_incoming_migration(incoming);
5886 } else if (autostart) {
5887 vm_start();
5890 #ifndef _WIN32
5891 if (daemonize) {
5892 uint8_t status = 0;
5893 ssize_t len;
5895 again1:
5896 len = write(fds[1], &status, 1);
5897 if (len == -1 && (errno == EINTR))
5898 goto again1;
5900 if (len != 1)
5901 exit(1);
5903 chdir("/");
5904 TFR(fd = open("/dev/null", O_RDWR));
5905 if (fd == -1)
5906 exit(1);
5909 if (run_as) {
5910 pwd = getpwnam(run_as);
5911 if (!pwd) {
5912 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5913 exit(1);
5917 if (chroot_dir) {
5918 if (chroot(chroot_dir) < 0) {
5919 fprintf(stderr, "chroot failed\n");
5920 exit(1);
5922 chdir("/");
5925 if (run_as) {
5926 if (setgid(pwd->pw_gid) < 0) {
5927 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5928 exit(1);
5930 if (setuid(pwd->pw_uid) < 0) {
5931 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5932 exit(1);
5934 if (setuid(0) != -1) {
5935 fprintf(stderr, "Dropping privileges failed\n");
5936 exit(1);
5940 if (daemonize) {
5941 dup2(fd, 0);
5942 dup2(fd, 1);
5943 dup2(fd, 2);
5945 close(fd);
5947 #endif
5949 main_loop();
5950 quit_timers();
5951 net_cleanup();
5953 return 0;