Fix the size of the property fields.
[qemu/navara.git] / vl.c
blob2e5b15ea83135394ce197a22e1241bea2e2906a8
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
34 /* Needed early to override system queue definitions on BSD */
35 #include "sys-queue.h"
37 #ifndef _WIN32
38 #include <libgen.h>
39 #include <pwd.h>
40 #include <sys/times.h>
41 #include <sys/wait.h>
42 #include <termios.h>
43 #include <sys/mman.h>
44 #include <sys/ioctl.h>
45 #include <sys/resource.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <net/if.h>
49 #if defined(__NetBSD__)
50 #include <net/if_tap.h>
51 #endif
52 #ifdef __linux__
53 #include <linux/if_tun.h>
54 #endif
55 #include <arpa/inet.h>
56 #include <dirent.h>
57 #include <netdb.h>
58 #include <sys/select.h>
59 #ifdef CONFIG_BSD
60 #include <sys/stat.h>
61 #if defined(__FreeBSD__) || defined(__DragonFly__)
62 #include <libutil.h>
63 #else
64 #include <util.h>
65 #endif
66 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
67 #include <freebsd/stdlib.h>
68 #else
69 #ifdef __linux__
70 #include <pty.h>
71 #include <malloc.h>
72 #include <linux/rtc.h>
73 #include <sys/prctl.h>
75 /* For the benefit of older linux systems which don't supply it,
76 we use a local copy of hpet.h. */
77 /* #include <linux/hpet.h> */
78 #include "hpet.h"
80 #include <linux/ppdev.h>
81 #include <linux/parport.h>
82 #endif
83 #ifdef __sun__
84 #include <sys/stat.h>
85 #include <sys/ethernet.h>
86 #include <sys/sockio.h>
87 #include <netinet/arp.h>
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/ip_icmp.h> // must come after ip.h
92 #include <netinet/udp.h>
93 #include <netinet/tcp.h>
94 #include <net/if.h>
95 #include <syslog.h>
96 #include <stropts.h>
97 #endif
98 #endif
99 #endif
101 #if defined(__OpenBSD__)
102 #include <util.h>
103 #endif
105 #if defined(CONFIG_VDE)
106 #include <libvdeplug.h>
107 #endif
109 #ifdef _WIN32
110 #include <windows.h>
111 #include <mmsystem.h>
112 #endif
114 #ifdef CONFIG_SDL
115 #if defined(__APPLE__) || defined(main)
116 #include <SDL.h>
117 int qemu_main(int argc, char **argv, char **envp);
118 int main(int argc, char **argv)
120 return qemu_main(argc, argv, NULL);
122 #undef main
123 #define main qemu_main
124 #endif
125 #endif /* CONFIG_SDL */
127 #ifdef CONFIG_COCOA
128 #undef main
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
132 #include "hw/hw.h"
133 #include "hw/boards.h"
134 #include "hw/usb.h"
135 #include "hw/pcmcia.h"
136 #include "hw/pc.h"
137 #include "hw/audiodev.h"
138 #include "hw/isa.h"
139 #include "hw/baum.h"
140 #include "hw/bt.h"
141 #include "hw/watchdog.h"
142 #include "hw/smbios.h"
143 #include "hw/xen.h"
144 #include "hw/qdev.h"
145 #include "bt-host.h"
146 #include "net.h"
147 #include "monitor.h"
148 #include "console.h"
149 #include "sysemu.h"
150 #include "gdbstub.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
154 #include "block.h"
155 #include "dma.h"
156 #include "audio/audio.h"
157 #include "migration.h"
158 #include "kvm.h"
159 #include "balloon.h"
160 #include "qemu-option.h"
162 #include "disas.h"
164 #include "exec-all.h"
166 #include "qemu_socket.h"
168 #include "slirp/libslirp.h"
170 //#define DEBUG_NET
171 //#define DEBUG_SLIRP
173 #define DEFAULT_RAM_SIZE 128
175 static const char *data_dir;
176 const char *bios_name = NULL;
177 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
178 to store the VM snapshots */
179 struct drivelist drives = TAILQ_HEAD_INITIALIZER(drives);
180 struct driveoptlist driveopts = TAILQ_HEAD_INITIALIZER(driveopts);
181 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
182 static DisplayState *display_state;
183 DisplayType display_type = DT_DEFAULT;
184 const char* keyboard_layout = NULL;
185 int64_t ticks_per_sec;
186 ram_addr_t ram_size;
187 int nb_nics;
188 NICInfo nd_table[MAX_NICS];
189 int vm_running;
190 int autostart;
191 static int rtc_utc = 1;
192 static int rtc_date_offset = -1; /* -1 means no change */
193 int cirrus_vga_enabled = 1;
194 int std_vga_enabled = 0;
195 int vmsvga_enabled = 0;
196 int xenfb_enabled = 0;
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 const char *vnc_display;
223 int acpi_enabled = 1;
224 int no_hpet = 0;
225 int virtio_balloon = 1;
226 const char *virtio_balloon_devaddr;
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 #ifndef _WIN32
233 int daemonize = 0;
234 #endif
235 WatchdogTimerModel *watchdog = NULL;
236 int watchdog_action = WDT_RESET;
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 #ifdef __linux__
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 QEMUPutKeyboardEntry *qemu_put_kbd_event_head;
344 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
345 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
347 QEMUPutKeyboardEntry *qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
349 QEMUPutKeyboardEntry *s, *cursor;
351 s = qemu_mallocz(sizeof(QEMUPutKeyboardEntry));
353 s->qemu_put_kbd_event = func;
354 s->qemu_put_kbd_event_opaque = opaque;
355 s->next = NULL;
357 if (!qemu_put_kbd_event_head) {
358 qemu_put_kbd_event_head = s;
359 return s;
362 cursor = qemu_put_kbd_event_head;
363 while (cursor->next != NULL)
364 cursor = cursor->next;
366 cursor->next = s;
368 return s;
371 void qemu_remove_kbd_event_handler(QEMUPutKeyboardEntry *entry)
373 QEMUPutKeyboardEntry *prev = NULL, *cursor;
375 if (!qemu_put_kbd_event_head || entry == NULL)
376 return;
378 cursor = qemu_put_kbd_event_head;
379 while (cursor != NULL && cursor != entry) {
380 prev = cursor;
381 cursor = cursor->next;
384 if (cursor == NULL) // does not exist or list empty
385 return;
386 else if (prev == NULL) { // entry is head
387 qemu_put_kbd_event_head = cursor->next;
388 qemu_free(entry);
389 return;
392 prev->next = entry->next;
393 qemu_free(entry);
396 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
397 void *opaque, int absolute,
398 const char *name)
400 QEMUPutMouseEntry *s, *cursor;
402 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
404 s->qemu_put_mouse_event = func;
405 s->qemu_put_mouse_event_opaque = opaque;
406 s->qemu_put_mouse_event_absolute = absolute;
407 s->qemu_put_mouse_event_name = qemu_strdup(name);
408 s->next = NULL;
410 if (!qemu_put_mouse_event_head) {
411 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
412 return s;
415 cursor = qemu_put_mouse_event_head;
416 while (cursor->next != NULL)
417 cursor = cursor->next;
419 cursor->next = s;
420 qemu_put_mouse_event_current = s;
422 return s;
425 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
427 QEMUPutMouseEntry *prev = NULL, *cursor;
429 if (!qemu_put_mouse_event_head || entry == NULL)
430 return;
432 cursor = qemu_put_mouse_event_head;
433 while (cursor != NULL && cursor != entry) {
434 prev = cursor;
435 cursor = cursor->next;
438 if (cursor == NULL) // does not exist or list empty
439 return;
440 else if (prev == NULL) { // entry is head
441 qemu_put_mouse_event_head = cursor->next;
442 if (qemu_put_mouse_event_current == entry)
443 qemu_put_mouse_event_current = cursor->next;
444 qemu_free(entry->qemu_put_mouse_event_name);
445 qemu_free(entry);
446 return;
449 prev->next = entry->next;
451 if (qemu_put_mouse_event_current == entry)
452 qemu_put_mouse_event_current = prev;
454 qemu_free(entry->qemu_put_mouse_event_name);
455 qemu_free(entry);
458 void kbd_put_keycode(int keycode)
460 QEMUPutKeyboardEntry *cursor;
462 cursor = qemu_put_kbd_event_head;
463 while (cursor != NULL) {
464 cursor->qemu_put_kbd_event(cursor->qemu_put_kbd_event_opaque, keycode);
465 cursor = cursor->next;
469 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
471 QEMUPutMouseEvent *mouse_event;
472 void *mouse_event_opaque;
473 int width;
475 if (!qemu_put_mouse_event_current) {
476 return;
479 mouse_event =
480 qemu_put_mouse_event_current->qemu_put_mouse_event;
481 mouse_event_opaque =
482 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
484 if (mouse_event) {
485 if (graphic_rotate) {
486 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
487 width = 0x7fff;
488 else
489 width = graphic_width - 1;
490 mouse_event(mouse_event_opaque,
491 width - dy, dx, dz, buttons_state);
492 } else
493 mouse_event(mouse_event_opaque,
494 dx, dy, dz, buttons_state);
498 int kbd_mouse_is_absolute(void)
500 if (!qemu_put_mouse_event_current)
501 return 0;
503 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
506 void do_info_mice(Monitor *mon)
508 QEMUPutMouseEntry *cursor;
509 int index = 0;
511 if (!qemu_put_mouse_event_head) {
512 monitor_printf(mon, "No mouse devices connected\n");
513 return;
516 monitor_printf(mon, "Mouse devices available:\n");
517 cursor = qemu_put_mouse_event_head;
518 while (cursor != NULL) {
519 monitor_printf(mon, "%c Mouse #%d: %s\n",
520 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
521 index, cursor->qemu_put_mouse_event_name);
522 index++;
523 cursor = cursor->next;
527 void do_mouse_set(Monitor *mon, int index)
529 QEMUPutMouseEntry *cursor;
530 int i = 0;
532 if (!qemu_put_mouse_event_head) {
533 monitor_printf(mon, "No mouse devices connected\n");
534 return;
537 cursor = qemu_put_mouse_event_head;
538 while (cursor != NULL && index != i) {
539 i++;
540 cursor = cursor->next;
543 if (cursor != NULL)
544 qemu_put_mouse_event_current = cursor;
545 else
546 monitor_printf(mon, "Mouse at given index not found\n");
549 /* compute with 96 bit intermediate result: (a*b)/c */
550 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
552 union {
553 uint64_t ll;
554 struct {
555 #ifdef HOST_WORDS_BIGENDIAN
556 uint32_t high, low;
557 #else
558 uint32_t low, high;
559 #endif
560 } l;
561 } u, res;
562 uint64_t rl, rh;
564 u.ll = a;
565 rl = (uint64_t)u.l.low * (uint64_t)b;
566 rh = (uint64_t)u.l.high * (uint64_t)b;
567 rh += (rl >> 32);
568 res.l.high = rh / c;
569 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
570 return res.ll;
573 /***********************************************************/
574 /* real time host monotonic timer */
576 #define QEMU_TIMER_BASE 1000000000LL
578 #ifdef WIN32
580 static int64_t clock_freq;
582 static void init_get_clock(void)
584 LARGE_INTEGER freq;
585 int ret;
586 ret = QueryPerformanceFrequency(&freq);
587 if (ret == 0) {
588 fprintf(stderr, "Could not calibrate ticks\n");
589 exit(1);
591 clock_freq = freq.QuadPart;
594 static int64_t get_clock(void)
596 LARGE_INTEGER ti;
597 QueryPerformanceCounter(&ti);
598 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
601 #else
603 static int use_rt_clock;
605 static void init_get_clock(void)
607 use_rt_clock = 0;
608 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
609 || defined(__DragonFly__)
611 struct timespec ts;
612 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
613 use_rt_clock = 1;
616 #endif
619 static int64_t get_clock(void)
621 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
622 || defined(__DragonFly__)
623 if (use_rt_clock) {
624 struct timespec ts;
625 clock_gettime(CLOCK_MONOTONIC, &ts);
626 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
627 } else
628 #endif
630 /* XXX: using gettimeofday leads to problems if the date
631 changes, so it should be avoided. */
632 struct timeval tv;
633 gettimeofday(&tv, NULL);
634 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
637 #endif
639 /* Return the virtual CPU time, based on the instruction counter. */
640 static int64_t cpu_get_icount(void)
642 int64_t icount;
643 CPUState *env = cpu_single_env;;
644 icount = qemu_icount;
645 if (env) {
646 if (!can_do_io(env))
647 fprintf(stderr, "Bad clock read\n");
648 icount -= (env->icount_decr.u16.low + env->icount_extra);
650 return qemu_icount_bias + (icount << icount_time_shift);
653 /***********************************************************/
654 /* guest cycle counter */
656 static int64_t cpu_ticks_prev;
657 static int64_t cpu_ticks_offset;
658 static int64_t cpu_clock_offset;
659 static int cpu_ticks_enabled;
661 /* return the host CPU cycle counter and handle stop/restart */
662 int64_t cpu_get_ticks(void)
664 if (use_icount) {
665 return cpu_get_icount();
667 if (!cpu_ticks_enabled) {
668 return cpu_ticks_offset;
669 } else {
670 int64_t ticks;
671 ticks = cpu_get_real_ticks();
672 if (cpu_ticks_prev > ticks) {
673 /* Note: non increasing ticks may happen if the host uses
674 software suspend */
675 cpu_ticks_offset += cpu_ticks_prev - ticks;
677 cpu_ticks_prev = ticks;
678 return ticks + cpu_ticks_offset;
682 /* return the host CPU monotonic timer and handle stop/restart */
683 static int64_t cpu_get_clock(void)
685 int64_t ti;
686 if (!cpu_ticks_enabled) {
687 return cpu_clock_offset;
688 } else {
689 ti = get_clock();
690 return ti + cpu_clock_offset;
694 /* enable cpu_get_ticks() */
695 void cpu_enable_ticks(void)
697 if (!cpu_ticks_enabled) {
698 cpu_ticks_offset -= cpu_get_real_ticks();
699 cpu_clock_offset -= get_clock();
700 cpu_ticks_enabled = 1;
704 /* disable cpu_get_ticks() : the clock is stopped. You must not call
705 cpu_get_ticks() after that. */
706 void cpu_disable_ticks(void)
708 if (cpu_ticks_enabled) {
709 cpu_ticks_offset = cpu_get_ticks();
710 cpu_clock_offset = cpu_get_clock();
711 cpu_ticks_enabled = 0;
715 /***********************************************************/
716 /* timers */
718 #define QEMU_TIMER_REALTIME 0
719 #define QEMU_TIMER_VIRTUAL 1
721 struct QEMUClock {
722 int type;
723 /* XXX: add frequency */
726 struct QEMUTimer {
727 QEMUClock *clock;
728 int64_t expire_time;
729 QEMUTimerCB *cb;
730 void *opaque;
731 struct QEMUTimer *next;
734 struct qemu_alarm_timer {
735 char const *name;
736 unsigned int flags;
738 int (*start)(struct qemu_alarm_timer *t);
739 void (*stop)(struct qemu_alarm_timer *t);
740 void (*rearm)(struct qemu_alarm_timer *t);
741 void *priv;
744 #define ALARM_FLAG_DYNTICKS 0x1
745 #define ALARM_FLAG_EXPIRED 0x2
747 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
749 return t && (t->flags & ALARM_FLAG_DYNTICKS);
752 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
754 if (!alarm_has_dynticks(t))
755 return;
757 t->rearm(t);
760 /* TODO: MIN_TIMER_REARM_US should be optimized */
761 #define MIN_TIMER_REARM_US 250
763 static struct qemu_alarm_timer *alarm_timer;
765 #ifdef _WIN32
767 struct qemu_alarm_win32 {
768 MMRESULT timerId;
769 unsigned int period;
770 } alarm_win32_data = {0, -1};
772 static int win32_start_timer(struct qemu_alarm_timer *t);
773 static void win32_stop_timer(struct qemu_alarm_timer *t);
774 static void win32_rearm_timer(struct qemu_alarm_timer *t);
776 #else
778 static int unix_start_timer(struct qemu_alarm_timer *t);
779 static void unix_stop_timer(struct qemu_alarm_timer *t);
781 #ifdef __linux__
783 static int dynticks_start_timer(struct qemu_alarm_timer *t);
784 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
785 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
787 static int hpet_start_timer(struct qemu_alarm_timer *t);
788 static void hpet_stop_timer(struct qemu_alarm_timer *t);
790 static int rtc_start_timer(struct qemu_alarm_timer *t);
791 static void rtc_stop_timer(struct qemu_alarm_timer *t);
793 #endif /* __linux__ */
795 #endif /* _WIN32 */
797 /* Correlation between real and virtual time is always going to be
798 fairly approximate, so ignore small variation.
799 When the guest is idle real and virtual time will be aligned in
800 the IO wait loop. */
801 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
803 static void icount_adjust(void)
805 int64_t cur_time;
806 int64_t cur_icount;
807 int64_t delta;
808 static int64_t last_delta;
809 /* If the VM is not running, then do nothing. */
810 if (!vm_running)
811 return;
813 cur_time = cpu_get_clock();
814 cur_icount = qemu_get_clock(vm_clock);
815 delta = cur_icount - cur_time;
816 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
817 if (delta > 0
818 && last_delta + ICOUNT_WOBBLE < delta * 2
819 && icount_time_shift > 0) {
820 /* The guest is getting too far ahead. Slow time down. */
821 icount_time_shift--;
823 if (delta < 0
824 && last_delta - ICOUNT_WOBBLE > delta * 2
825 && icount_time_shift < MAX_ICOUNT_SHIFT) {
826 /* The guest is getting too far behind. Speed time up. */
827 icount_time_shift++;
829 last_delta = delta;
830 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
833 static void icount_adjust_rt(void * opaque)
835 qemu_mod_timer(icount_rt_timer,
836 qemu_get_clock(rt_clock) + 1000);
837 icount_adjust();
840 static void icount_adjust_vm(void * opaque)
842 qemu_mod_timer(icount_vm_timer,
843 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
844 icount_adjust();
847 static void init_icount_adjust(void)
849 /* Have both realtime and virtual time triggers for speed adjustment.
850 The realtime trigger catches emulated time passing too slowly,
851 the virtual time trigger catches emulated time passing too fast.
852 Realtime triggers occur even when idle, so use them less frequently
853 than VM triggers. */
854 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
855 qemu_mod_timer(icount_rt_timer,
856 qemu_get_clock(rt_clock) + 1000);
857 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
858 qemu_mod_timer(icount_vm_timer,
859 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
862 static struct qemu_alarm_timer alarm_timers[] = {
863 #ifndef _WIN32
864 #ifdef __linux__
865 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
866 dynticks_stop_timer, dynticks_rearm_timer, NULL},
867 /* HPET - if available - is preferred */
868 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
869 /* ...otherwise try RTC */
870 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
871 #endif
872 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
873 #else
874 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
875 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
876 {"win32", 0, win32_start_timer,
877 win32_stop_timer, NULL, &alarm_win32_data},
878 #endif
879 {NULL, }
882 static void show_available_alarms(void)
884 int i;
886 printf("Available alarm timers, in order of precedence:\n");
887 for (i = 0; alarm_timers[i].name; i++)
888 printf("%s\n", alarm_timers[i].name);
891 static void configure_alarms(char const *opt)
893 int i;
894 int cur = 0;
895 int count = ARRAY_SIZE(alarm_timers) - 1;
896 char *arg;
897 char *name;
898 struct qemu_alarm_timer tmp;
900 if (!strcmp(opt, "?")) {
901 show_available_alarms();
902 exit(0);
905 arg = strdup(opt);
907 /* Reorder the array */
908 name = strtok(arg, ",");
909 while (name) {
910 for (i = 0; i < count && alarm_timers[i].name; i++) {
911 if (!strcmp(alarm_timers[i].name, name))
912 break;
915 if (i == count) {
916 fprintf(stderr, "Unknown clock %s\n", name);
917 goto next;
920 if (i < cur)
921 /* Ignore */
922 goto next;
924 /* Swap */
925 tmp = alarm_timers[i];
926 alarm_timers[i] = alarm_timers[cur];
927 alarm_timers[cur] = tmp;
929 cur++;
930 next:
931 name = strtok(NULL, ",");
934 free(arg);
936 if (cur) {
937 /* Disable remaining timers */
938 for (i = cur; i < count; i++)
939 alarm_timers[i].name = NULL;
940 } else {
941 show_available_alarms();
942 exit(1);
946 QEMUClock *rt_clock;
947 QEMUClock *vm_clock;
949 static QEMUTimer *active_timers[2];
951 static QEMUClock *qemu_new_clock(int type)
953 QEMUClock *clock;
954 clock = qemu_mallocz(sizeof(QEMUClock));
955 clock->type = type;
956 return clock;
959 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
961 QEMUTimer *ts;
963 ts = qemu_mallocz(sizeof(QEMUTimer));
964 ts->clock = clock;
965 ts->cb = cb;
966 ts->opaque = opaque;
967 return ts;
970 void qemu_free_timer(QEMUTimer *ts)
972 qemu_free(ts);
975 /* stop a timer, but do not dealloc it */
976 void qemu_del_timer(QEMUTimer *ts)
978 QEMUTimer **pt, *t;
980 /* NOTE: this code must be signal safe because
981 qemu_timer_expired() can be called from a signal. */
982 pt = &active_timers[ts->clock->type];
983 for(;;) {
984 t = *pt;
985 if (!t)
986 break;
987 if (t == ts) {
988 *pt = t->next;
989 break;
991 pt = &t->next;
995 /* modify the current timer so that it will be fired when current_time
996 >= expire_time. The corresponding callback will be called. */
997 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
999 QEMUTimer **pt, *t;
1001 qemu_del_timer(ts);
1003 /* add the timer in the sorted list */
1004 /* NOTE: this code must be signal safe because
1005 qemu_timer_expired() can be called from a signal. */
1006 pt = &active_timers[ts->clock->type];
1007 for(;;) {
1008 t = *pt;
1009 if (!t)
1010 break;
1011 if (t->expire_time > expire_time)
1012 break;
1013 pt = &t->next;
1015 ts->expire_time = expire_time;
1016 ts->next = *pt;
1017 *pt = ts;
1019 /* Rearm if necessary */
1020 if (pt == &active_timers[ts->clock->type]) {
1021 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1022 qemu_rearm_alarm_timer(alarm_timer);
1024 /* Interrupt execution to force deadline recalculation. */
1025 if (use_icount)
1026 qemu_notify_event();
1030 int qemu_timer_pending(QEMUTimer *ts)
1032 QEMUTimer *t;
1033 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1034 if (t == ts)
1035 return 1;
1037 return 0;
1040 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1042 if (!timer_head)
1043 return 0;
1044 return (timer_head->expire_time <= current_time);
1047 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1049 QEMUTimer *ts;
1051 for(;;) {
1052 ts = *ptimer_head;
1053 if (!ts || ts->expire_time > current_time)
1054 break;
1055 /* remove timer from the list before calling the callback */
1056 *ptimer_head = ts->next;
1057 ts->next = NULL;
1059 /* run the callback (the timer list can be modified) */
1060 ts->cb(ts->opaque);
1064 int64_t qemu_get_clock(QEMUClock *clock)
1066 switch(clock->type) {
1067 case QEMU_TIMER_REALTIME:
1068 return get_clock() / 1000000;
1069 default:
1070 case QEMU_TIMER_VIRTUAL:
1071 if (use_icount) {
1072 return cpu_get_icount();
1073 } else {
1074 return cpu_get_clock();
1079 static void init_timers(void)
1081 init_get_clock();
1082 ticks_per_sec = QEMU_TIMER_BASE;
1083 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1084 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1087 /* save a timer */
1088 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1090 uint64_t expire_time;
1092 if (qemu_timer_pending(ts)) {
1093 expire_time = ts->expire_time;
1094 } else {
1095 expire_time = -1;
1097 qemu_put_be64(f, expire_time);
1100 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1102 uint64_t expire_time;
1104 expire_time = qemu_get_be64(f);
1105 if (expire_time != -1) {
1106 qemu_mod_timer(ts, expire_time);
1107 } else {
1108 qemu_del_timer(ts);
1112 static void timer_save(QEMUFile *f, void *opaque)
1114 if (cpu_ticks_enabled) {
1115 hw_error("cannot save state if virtual timers are running");
1117 qemu_put_be64(f, cpu_ticks_offset);
1118 qemu_put_be64(f, ticks_per_sec);
1119 qemu_put_be64(f, cpu_clock_offset);
1122 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1124 if (version_id != 1 && version_id != 2)
1125 return -EINVAL;
1126 if (cpu_ticks_enabled) {
1127 return -EINVAL;
1129 cpu_ticks_offset=qemu_get_be64(f);
1130 ticks_per_sec=qemu_get_be64(f);
1131 if (version_id == 2) {
1132 cpu_clock_offset=qemu_get_be64(f);
1134 return 0;
1137 static void qemu_event_increment(void);
1139 #ifdef _WIN32
1140 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1141 DWORD_PTR dwUser, DWORD_PTR dw1,
1142 DWORD_PTR dw2)
1143 #else
1144 static void host_alarm_handler(int host_signum)
1145 #endif
1147 #if 0
1148 #define DISP_FREQ 1000
1150 static int64_t delta_min = INT64_MAX;
1151 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1152 static int count;
1153 ti = qemu_get_clock(vm_clock);
1154 if (last_clock != 0) {
1155 delta = ti - last_clock;
1156 if (delta < delta_min)
1157 delta_min = delta;
1158 if (delta > delta_max)
1159 delta_max = delta;
1160 delta_cum += delta;
1161 if (++count == DISP_FREQ) {
1162 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1163 muldiv64(delta_min, 1000000, ticks_per_sec),
1164 muldiv64(delta_max, 1000000, ticks_per_sec),
1165 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1166 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1167 count = 0;
1168 delta_min = INT64_MAX;
1169 delta_max = 0;
1170 delta_cum = 0;
1173 last_clock = ti;
1175 #endif
1176 if (alarm_has_dynticks(alarm_timer) ||
1177 (!use_icount &&
1178 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1179 qemu_get_clock(vm_clock))) ||
1180 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1181 qemu_get_clock(rt_clock))) {
1182 qemu_event_increment();
1183 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1185 #ifndef CONFIG_IOTHREAD
1186 if (next_cpu) {
1187 /* stop the currently executing cpu because a timer occured */
1188 cpu_exit(next_cpu);
1189 #ifdef CONFIG_KQEMU
1190 if (next_cpu->kqemu_enabled) {
1191 kqemu_cpu_interrupt(next_cpu);
1193 #endif
1195 #endif
1196 timer_alarm_pending = 1;
1197 qemu_notify_event();
1201 static int64_t qemu_next_deadline(void)
1203 int64_t delta;
1205 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1206 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1207 qemu_get_clock(vm_clock);
1208 } else {
1209 /* To avoid problems with overflow limit this to 2^32. */
1210 delta = INT32_MAX;
1213 if (delta < 0)
1214 delta = 0;
1216 return delta;
1219 #if defined(__linux__) || defined(_WIN32)
1220 static uint64_t qemu_next_deadline_dyntick(void)
1222 int64_t delta;
1223 int64_t rtdelta;
1225 if (use_icount)
1226 delta = INT32_MAX;
1227 else
1228 delta = (qemu_next_deadline() + 999) / 1000;
1230 if (active_timers[QEMU_TIMER_REALTIME]) {
1231 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1232 qemu_get_clock(rt_clock))*1000;
1233 if (rtdelta < delta)
1234 delta = rtdelta;
1237 if (delta < MIN_TIMER_REARM_US)
1238 delta = MIN_TIMER_REARM_US;
1240 return delta;
1242 #endif
1244 #ifndef _WIN32
1246 /* Sets a specific flag */
1247 static int fcntl_setfl(int fd, int flag)
1249 int flags;
1251 flags = fcntl(fd, F_GETFL);
1252 if (flags == -1)
1253 return -errno;
1255 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1256 return -errno;
1258 return 0;
1261 #if defined(__linux__)
1263 #define RTC_FREQ 1024
1265 static void enable_sigio_timer(int fd)
1267 struct sigaction act;
1269 /* timer signal */
1270 sigfillset(&act.sa_mask);
1271 act.sa_flags = 0;
1272 act.sa_handler = host_alarm_handler;
1274 sigaction(SIGIO, &act, NULL);
1275 fcntl_setfl(fd, O_ASYNC);
1276 fcntl(fd, F_SETOWN, getpid());
1279 static int hpet_start_timer(struct qemu_alarm_timer *t)
1281 struct hpet_info info;
1282 int r, fd;
1284 fd = open("/dev/hpet", O_RDONLY);
1285 if (fd < 0)
1286 return -1;
1288 /* Set frequency */
1289 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1290 if (r < 0) {
1291 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1292 "error, but for better emulation accuracy type:\n"
1293 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1294 goto fail;
1297 /* Check capabilities */
1298 r = ioctl(fd, HPET_INFO, &info);
1299 if (r < 0)
1300 goto fail;
1302 /* Enable periodic mode */
1303 r = ioctl(fd, HPET_EPI, 0);
1304 if (info.hi_flags && (r < 0))
1305 goto fail;
1307 /* Enable interrupt */
1308 r = ioctl(fd, HPET_IE_ON, 0);
1309 if (r < 0)
1310 goto fail;
1312 enable_sigio_timer(fd);
1313 t->priv = (void *)(long)fd;
1315 return 0;
1316 fail:
1317 close(fd);
1318 return -1;
1321 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1323 int fd = (long)t->priv;
1325 close(fd);
1328 static int rtc_start_timer(struct qemu_alarm_timer *t)
1330 int rtc_fd;
1331 unsigned long current_rtc_freq = 0;
1333 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1334 if (rtc_fd < 0)
1335 return -1;
1336 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1337 if (current_rtc_freq != RTC_FREQ &&
1338 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1339 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1340 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1341 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1342 goto fail;
1344 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1345 fail:
1346 close(rtc_fd);
1347 return -1;
1350 enable_sigio_timer(rtc_fd);
1352 t->priv = (void *)(long)rtc_fd;
1354 return 0;
1357 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1359 int rtc_fd = (long)t->priv;
1361 close(rtc_fd);
1364 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1366 struct sigevent ev;
1367 timer_t host_timer;
1368 struct sigaction act;
1370 sigfillset(&act.sa_mask);
1371 act.sa_flags = 0;
1372 act.sa_handler = host_alarm_handler;
1374 sigaction(SIGALRM, &act, NULL);
1377 * Initialize ev struct to 0 to avoid valgrind complaining
1378 * about uninitialized data in timer_create call
1380 memset(&ev, 0, sizeof(ev));
1381 ev.sigev_value.sival_int = 0;
1382 ev.sigev_notify = SIGEV_SIGNAL;
1383 ev.sigev_signo = SIGALRM;
1385 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1386 perror("timer_create");
1388 /* disable dynticks */
1389 fprintf(stderr, "Dynamic Ticks disabled\n");
1391 return -1;
1394 t->priv = (void *)(long)host_timer;
1396 return 0;
1399 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1401 timer_t host_timer = (timer_t)(long)t->priv;
1403 timer_delete(host_timer);
1406 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1408 timer_t host_timer = (timer_t)(long)t->priv;
1409 struct itimerspec timeout;
1410 int64_t nearest_delta_us = INT64_MAX;
1411 int64_t current_us;
1413 if (!active_timers[QEMU_TIMER_REALTIME] &&
1414 !active_timers[QEMU_TIMER_VIRTUAL])
1415 return;
1417 nearest_delta_us = qemu_next_deadline_dyntick();
1419 /* check whether a timer is already running */
1420 if (timer_gettime(host_timer, &timeout)) {
1421 perror("gettime");
1422 fprintf(stderr, "Internal timer error: aborting\n");
1423 exit(1);
1425 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1426 if (current_us && current_us <= nearest_delta_us)
1427 return;
1429 timeout.it_interval.tv_sec = 0;
1430 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1431 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1432 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1433 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1434 perror("settime");
1435 fprintf(stderr, "Internal timer error: aborting\n");
1436 exit(1);
1440 #endif /* defined(__linux__) */
1442 static int unix_start_timer(struct qemu_alarm_timer *t)
1444 struct sigaction act;
1445 struct itimerval itv;
1446 int err;
1448 /* timer signal */
1449 sigfillset(&act.sa_mask);
1450 act.sa_flags = 0;
1451 act.sa_handler = host_alarm_handler;
1453 sigaction(SIGALRM, &act, NULL);
1455 itv.it_interval.tv_sec = 0;
1456 /* for i386 kernel 2.6 to get 1 ms */
1457 itv.it_interval.tv_usec = 999;
1458 itv.it_value.tv_sec = 0;
1459 itv.it_value.tv_usec = 10 * 1000;
1461 err = setitimer(ITIMER_REAL, &itv, NULL);
1462 if (err)
1463 return -1;
1465 return 0;
1468 static void unix_stop_timer(struct qemu_alarm_timer *t)
1470 struct itimerval itv;
1472 memset(&itv, 0, sizeof(itv));
1473 setitimer(ITIMER_REAL, &itv, NULL);
1476 #endif /* !defined(_WIN32) */
1479 #ifdef _WIN32
1481 static int win32_start_timer(struct qemu_alarm_timer *t)
1483 TIMECAPS tc;
1484 struct qemu_alarm_win32 *data = t->priv;
1485 UINT flags;
1487 memset(&tc, 0, sizeof(tc));
1488 timeGetDevCaps(&tc, sizeof(tc));
1490 if (data->period < tc.wPeriodMin)
1491 data->period = tc.wPeriodMin;
1493 timeBeginPeriod(data->period);
1495 flags = TIME_CALLBACK_FUNCTION;
1496 if (alarm_has_dynticks(t))
1497 flags |= TIME_ONESHOT;
1498 else
1499 flags |= TIME_PERIODIC;
1501 data->timerId = timeSetEvent(1, // interval (ms)
1502 data->period, // resolution
1503 host_alarm_handler, // function
1504 (DWORD_PTR)t, // parameter
1505 flags);
1507 if (!data->timerId) {
1508 perror("Failed to initialize win32 alarm timer");
1509 timeEndPeriod(data->period);
1510 return -1;
1513 return 0;
1516 static void win32_stop_timer(struct qemu_alarm_timer *t)
1518 struct qemu_alarm_win32 *data = t->priv;
1520 timeKillEvent(data->timerId);
1521 timeEndPeriod(data->period);
1524 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1526 struct qemu_alarm_win32 *data = t->priv;
1527 uint64_t nearest_delta_us;
1529 if (!active_timers[QEMU_TIMER_REALTIME] &&
1530 !active_timers[QEMU_TIMER_VIRTUAL])
1531 return;
1533 nearest_delta_us = qemu_next_deadline_dyntick();
1534 nearest_delta_us /= 1000;
1536 timeKillEvent(data->timerId);
1538 data->timerId = timeSetEvent(1,
1539 data->period,
1540 host_alarm_handler,
1541 (DWORD_PTR)t,
1542 TIME_ONESHOT | TIME_PERIODIC);
1544 if (!data->timerId) {
1545 perror("Failed to re-arm win32 alarm timer");
1547 timeEndPeriod(data->period);
1548 exit(1);
1552 #endif /* _WIN32 */
1554 static int init_timer_alarm(void)
1556 struct qemu_alarm_timer *t = NULL;
1557 int i, err = -1;
1559 for (i = 0; alarm_timers[i].name; i++) {
1560 t = &alarm_timers[i];
1562 err = t->start(t);
1563 if (!err)
1564 break;
1567 if (err) {
1568 err = -ENOENT;
1569 goto fail;
1572 alarm_timer = t;
1574 return 0;
1576 fail:
1577 return err;
1580 static void quit_timers(void)
1582 alarm_timer->stop(alarm_timer);
1583 alarm_timer = NULL;
1586 /***********************************************************/
1587 /* host time/date access */
1588 void qemu_get_timedate(struct tm *tm, int offset)
1590 time_t ti;
1591 struct tm *ret;
1593 time(&ti);
1594 ti += offset;
1595 if (rtc_date_offset == -1) {
1596 if (rtc_utc)
1597 ret = gmtime(&ti);
1598 else
1599 ret = localtime(&ti);
1600 } else {
1601 ti -= rtc_date_offset;
1602 ret = gmtime(&ti);
1605 memcpy(tm, ret, sizeof(struct tm));
1608 int qemu_timedate_diff(struct tm *tm)
1610 time_t seconds;
1612 if (rtc_date_offset == -1)
1613 if (rtc_utc)
1614 seconds = mktimegm(tm);
1615 else
1616 seconds = mktime(tm);
1617 else
1618 seconds = mktimegm(tm) + rtc_date_offset;
1620 return seconds - time(NULL);
1623 #ifdef _WIN32
1624 static void socket_cleanup(void)
1626 WSACleanup();
1629 static int socket_init(void)
1631 WSADATA Data;
1632 int ret, err;
1634 ret = WSAStartup(MAKEWORD(2,2), &Data);
1635 if (ret != 0) {
1636 err = WSAGetLastError();
1637 fprintf(stderr, "WSAStartup: %d\n", err);
1638 return -1;
1640 atexit(socket_cleanup);
1641 return 0;
1643 #endif
1645 /***********************************************************/
1646 /* Bluetooth support */
1647 static int nb_hcis;
1648 static int cur_hci;
1649 static struct HCIInfo *hci_table[MAX_NICS];
1651 static struct bt_vlan_s {
1652 struct bt_scatternet_s net;
1653 int id;
1654 struct bt_vlan_s *next;
1655 } *first_bt_vlan;
1657 /* find or alloc a new bluetooth "VLAN" */
1658 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1660 struct bt_vlan_s **pvlan, *vlan;
1661 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1662 if (vlan->id == id)
1663 return &vlan->net;
1665 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1666 vlan->id = id;
1667 pvlan = &first_bt_vlan;
1668 while (*pvlan != NULL)
1669 pvlan = &(*pvlan)->next;
1670 *pvlan = vlan;
1671 return &vlan->net;
1674 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1678 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1680 return -ENOTSUP;
1683 static struct HCIInfo null_hci = {
1684 .cmd_send = null_hci_send,
1685 .sco_send = null_hci_send,
1686 .acl_send = null_hci_send,
1687 .bdaddr_set = null_hci_addr_set,
1690 struct HCIInfo *qemu_next_hci(void)
1692 if (cur_hci == nb_hcis)
1693 return &null_hci;
1695 return hci_table[cur_hci++];
1698 static struct HCIInfo *hci_init(const char *str)
1700 char *endp;
1701 struct bt_scatternet_s *vlan = 0;
1703 if (!strcmp(str, "null"))
1704 /* null */
1705 return &null_hci;
1706 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1707 /* host[:hciN] */
1708 return bt_host_hci(str[4] ? str + 5 : "hci0");
1709 else if (!strncmp(str, "hci", 3)) {
1710 /* hci[,vlan=n] */
1711 if (str[3]) {
1712 if (!strncmp(str + 3, ",vlan=", 6)) {
1713 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1714 if (*endp)
1715 vlan = 0;
1717 } else
1718 vlan = qemu_find_bt_vlan(0);
1719 if (vlan)
1720 return bt_new_hci(vlan);
1723 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1725 return 0;
1728 static int bt_hci_parse(const char *str)
1730 struct HCIInfo *hci;
1731 bdaddr_t bdaddr;
1733 if (nb_hcis >= MAX_NICS) {
1734 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1735 return -1;
1738 hci = hci_init(str);
1739 if (!hci)
1740 return -1;
1742 bdaddr.b[0] = 0x52;
1743 bdaddr.b[1] = 0x54;
1744 bdaddr.b[2] = 0x00;
1745 bdaddr.b[3] = 0x12;
1746 bdaddr.b[4] = 0x34;
1747 bdaddr.b[5] = 0x56 + nb_hcis;
1748 hci->bdaddr_set(hci, bdaddr.b);
1750 hci_table[nb_hcis++] = hci;
1752 return 0;
1755 static void bt_vhci_add(int vlan_id)
1757 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1759 if (!vlan->slave)
1760 fprintf(stderr, "qemu: warning: adding a VHCI to "
1761 "an empty scatternet %i\n", vlan_id);
1763 bt_vhci_init(bt_new_hci(vlan));
1766 static struct bt_device_s *bt_device_add(const char *opt)
1768 struct bt_scatternet_s *vlan;
1769 int vlan_id = 0;
1770 char *endp = strstr(opt, ",vlan=");
1771 int len = (endp ? endp - opt : strlen(opt)) + 1;
1772 char devname[10];
1774 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1776 if (endp) {
1777 vlan_id = strtol(endp + 6, &endp, 0);
1778 if (*endp) {
1779 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1780 return 0;
1784 vlan = qemu_find_bt_vlan(vlan_id);
1786 if (!vlan->slave)
1787 fprintf(stderr, "qemu: warning: adding a slave device to "
1788 "an empty scatternet %i\n", vlan_id);
1790 if (!strcmp(devname, "keyboard"))
1791 return bt_keyboard_init(vlan);
1793 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1794 return 0;
1797 static int bt_parse(const char *opt)
1799 const char *endp, *p;
1800 int vlan;
1802 if (strstart(opt, "hci", &endp)) {
1803 if (!*endp || *endp == ',') {
1804 if (*endp)
1805 if (!strstart(endp, ",vlan=", 0))
1806 opt = endp + 1;
1808 return bt_hci_parse(opt);
1810 } else if (strstart(opt, "vhci", &endp)) {
1811 if (!*endp || *endp == ',') {
1812 if (*endp) {
1813 if (strstart(endp, ",vlan=", &p)) {
1814 vlan = strtol(p, (char **) &endp, 0);
1815 if (*endp) {
1816 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1817 return 1;
1819 } else {
1820 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1821 return 1;
1823 } else
1824 vlan = 0;
1826 bt_vhci_add(vlan);
1827 return 0;
1829 } else if (strstart(opt, "device:", &endp))
1830 return !bt_device_add(endp);
1832 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1833 return 1;
1836 /***********************************************************/
1837 /* QEMU Block devices */
1839 #define HD_ALIAS "index=%d,media=disk"
1840 #define CDROM_ALIAS "index=2,media=cdrom"
1841 #define FD_ALIAS "index=%d,if=floppy"
1842 #define PFLASH_ALIAS "if=pflash"
1843 #define MTD_ALIAS "if=mtd"
1844 #define SD_ALIAS "index=0,if=sd"
1846 static QemuOptsList drive_opt_list = {
1847 .name = "drive",
1848 .head = TAILQ_HEAD_INITIALIZER(drive_opt_list.head),
1849 .desc = {
1851 .name = "bus",
1852 .type = QEMU_OPT_NUMBER,
1853 .help = "bus number",
1855 .name = "unit",
1856 .type = QEMU_OPT_NUMBER,
1857 .help = "unit number (i.e. lun for scsi)",
1859 .name = "if",
1860 .type = QEMU_OPT_STRING,
1861 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
1863 .name = "index",
1864 .type = QEMU_OPT_NUMBER,
1866 .name = "cyls",
1867 .type = QEMU_OPT_NUMBER,
1868 .help = "number of cylinders (ide disk geometry)",
1870 .name = "heads",
1871 .type = QEMU_OPT_NUMBER,
1872 .help = "number of heads (ide disk geometry)",
1874 .name = "secs",
1875 .type = QEMU_OPT_NUMBER,
1876 .help = "number of sectors (ide disk geometry)",
1878 .name = "trans",
1879 .type = QEMU_OPT_STRING,
1880 .help = "chs translation (auto, lba. none)",
1882 .name = "media",
1883 .type = QEMU_OPT_STRING,
1884 .help = "media type (disk, cdrom)",
1886 .name = "snapshot",
1887 .type = QEMU_OPT_BOOL,
1889 .name = "file",
1890 .type = QEMU_OPT_STRING,
1891 .help = "disk image",
1893 .name = "cache",
1894 .type = QEMU_OPT_STRING,
1895 .help = "host cache usage (none, writeback, writethrough)",
1897 .name = "format",
1898 .type = QEMU_OPT_STRING,
1899 .help = "disk format (raw, qcow2, ...)",
1901 .name = "serial",
1902 .type = QEMU_OPT_STRING,
1904 .name = "werror",
1905 .type = QEMU_OPT_STRING,
1907 .name = "addr",
1908 .type = QEMU_OPT_STRING,
1909 .help = "pci address (virtio only)",
1911 { /* end if list */ }
1915 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1917 va_list ap;
1918 char optstr[1024];
1919 QemuOpts *opts;
1921 va_start(ap, fmt);
1922 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1923 va_end(ap);
1925 opts = qemu_opts_parse(&drive_opt_list, optstr, NULL);
1926 if (!opts) {
1927 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1928 __FUNCTION__, optstr);
1929 return NULL;
1931 if (file)
1932 qemu_opt_set(opts, "file", file);
1933 return opts;
1936 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1938 DriveInfo *dinfo;
1940 /* seek interface, bus and unit */
1942 TAILQ_FOREACH(dinfo, &drives, next) {
1943 if (dinfo->type == type &&
1944 dinfo->bus == bus &&
1945 dinfo->unit == unit)
1946 return dinfo;
1949 return NULL;
1952 DriveInfo *drive_get_by_id(char *id)
1954 DriveInfo *dinfo;
1956 TAILQ_FOREACH(dinfo, &drives, next) {
1957 if (strcmp(id, dinfo->id))
1958 continue;
1959 return dinfo;
1961 return NULL;
1964 int drive_get_max_bus(BlockInterfaceType type)
1966 int max_bus;
1967 DriveInfo *dinfo;
1969 max_bus = -1;
1970 TAILQ_FOREACH(dinfo, &drives, next) {
1971 if(dinfo->type == type &&
1972 dinfo->bus > max_bus)
1973 max_bus = dinfo->bus;
1975 return max_bus;
1978 const char *drive_get_serial(BlockDriverState *bdrv)
1980 DriveInfo *dinfo;
1982 TAILQ_FOREACH(dinfo, &drives, next) {
1983 if (dinfo->bdrv == bdrv)
1984 return dinfo->serial;
1987 return "\0";
1990 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1992 DriveInfo *dinfo;
1994 TAILQ_FOREACH(dinfo, &drives, next) {
1995 if (dinfo->bdrv == bdrv)
1996 return dinfo->onerror;
1999 return BLOCK_ERR_STOP_ENOSPC;
2002 static void bdrv_format_print(void *opaque, const char *name)
2004 fprintf(stderr, " %s", name);
2007 void drive_uninit(BlockDriverState *bdrv)
2009 DriveInfo *dinfo;
2011 TAILQ_FOREACH(dinfo, &drives, next) {
2012 if (dinfo->bdrv != bdrv)
2013 continue;
2014 qemu_opts_del(dinfo->opts);
2015 TAILQ_REMOVE(&drives, dinfo, next);
2016 qemu_free(dinfo);
2017 break;
2021 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
2022 int *fatal_error)
2024 const char *buf;
2025 const char *file = NULL;
2026 char devname[128];
2027 const char *serial;
2028 const char *mediastr = "";
2029 BlockInterfaceType type;
2030 enum { MEDIA_DISK, MEDIA_CDROM } media;
2031 int bus_id, unit_id;
2032 int cyls, heads, secs, translation;
2033 BlockDriver *drv = NULL;
2034 QEMUMachine *machine = opaque;
2035 int max_devs;
2036 int index;
2037 int cache;
2038 int bdrv_flags, onerror;
2039 const char *devaddr;
2040 DriveInfo *dinfo;
2041 int snapshot = 0;
2043 *fatal_error = 1;
2045 translation = BIOS_ATA_TRANSLATION_AUTO;
2046 cache = 1;
2048 if (machine->use_scsi) {
2049 type = IF_SCSI;
2050 max_devs = MAX_SCSI_DEVS;
2051 pstrcpy(devname, sizeof(devname), "scsi");
2052 } else {
2053 type = IF_IDE;
2054 max_devs = MAX_IDE_DEVS;
2055 pstrcpy(devname, sizeof(devname), "ide");
2057 media = MEDIA_DISK;
2059 /* extract parameters */
2060 bus_id = qemu_opt_get_number(opts, "bus", 0);
2061 unit_id = qemu_opt_get_number(opts, "unit", -1);
2062 index = qemu_opt_get_number(opts, "index", -1);
2064 cyls = qemu_opt_get_number(opts, "cyls", 0);
2065 heads = qemu_opt_get_number(opts, "heads", 0);
2066 secs = qemu_opt_get_number(opts, "secs", 0);
2068 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2070 file = qemu_opt_get(opts, "file");
2071 serial = qemu_opt_get(opts, "serial");
2073 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2074 pstrcpy(devname, sizeof(devname), buf);
2075 if (!strcmp(buf, "ide")) {
2076 type = IF_IDE;
2077 max_devs = MAX_IDE_DEVS;
2078 } else if (!strcmp(buf, "scsi")) {
2079 type = IF_SCSI;
2080 max_devs = MAX_SCSI_DEVS;
2081 } else if (!strcmp(buf, "floppy")) {
2082 type = IF_FLOPPY;
2083 max_devs = 0;
2084 } else if (!strcmp(buf, "pflash")) {
2085 type = IF_PFLASH;
2086 max_devs = 0;
2087 } else if (!strcmp(buf, "mtd")) {
2088 type = IF_MTD;
2089 max_devs = 0;
2090 } else if (!strcmp(buf, "sd")) {
2091 type = IF_SD;
2092 max_devs = 0;
2093 } else if (!strcmp(buf, "virtio")) {
2094 type = IF_VIRTIO;
2095 max_devs = 0;
2096 } else if (!strcmp(buf, "xen")) {
2097 type = IF_XEN;
2098 max_devs = 0;
2099 } else {
2100 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2101 return NULL;
2105 if (cyls || heads || secs) {
2106 if (cyls < 1 || cyls > 16383) {
2107 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2108 return NULL;
2110 if (heads < 1 || heads > 16) {
2111 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2112 return NULL;
2114 if (secs < 1 || secs > 63) {
2115 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2116 return NULL;
2120 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2121 if (!cyls) {
2122 fprintf(stderr,
2123 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2124 buf);
2125 return NULL;
2127 if (!strcmp(buf, "none"))
2128 translation = BIOS_ATA_TRANSLATION_NONE;
2129 else if (!strcmp(buf, "lba"))
2130 translation = BIOS_ATA_TRANSLATION_LBA;
2131 else if (!strcmp(buf, "auto"))
2132 translation = BIOS_ATA_TRANSLATION_AUTO;
2133 else {
2134 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2135 return NULL;
2139 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2140 if (!strcmp(buf, "disk")) {
2141 media = MEDIA_DISK;
2142 } else if (!strcmp(buf, "cdrom")) {
2143 if (cyls || secs || heads) {
2144 fprintf(stderr,
2145 "qemu: '%s' invalid physical CHS format\n", buf);
2146 return NULL;
2148 media = MEDIA_CDROM;
2149 } else {
2150 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2151 return NULL;
2155 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2156 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2157 cache = 0;
2158 else if (!strcmp(buf, "writethrough"))
2159 cache = 1;
2160 else if (!strcmp(buf, "writeback"))
2161 cache = 2;
2162 else {
2163 fprintf(stderr, "qemu: invalid cache option\n");
2164 return NULL;
2168 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2169 if (strcmp(buf, "?") == 0) {
2170 fprintf(stderr, "qemu: Supported formats:");
2171 bdrv_iterate_format(bdrv_format_print, NULL);
2172 fprintf(stderr, "\n");
2173 return NULL;
2175 drv = bdrv_find_format(buf);
2176 if (!drv) {
2177 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2178 return NULL;
2182 onerror = BLOCK_ERR_STOP_ENOSPC;
2183 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2184 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2185 fprintf(stderr, "werror is no supported by this format\n");
2186 return NULL;
2188 if (!strcmp(buf, "ignore"))
2189 onerror = BLOCK_ERR_IGNORE;
2190 else if (!strcmp(buf, "enospc"))
2191 onerror = BLOCK_ERR_STOP_ENOSPC;
2192 else if (!strcmp(buf, "stop"))
2193 onerror = BLOCK_ERR_STOP_ANY;
2194 else if (!strcmp(buf, "report"))
2195 onerror = BLOCK_ERR_REPORT;
2196 else {
2197 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2198 return NULL;
2202 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2203 if (type != IF_VIRTIO) {
2204 fprintf(stderr, "addr is not supported\n");
2205 return NULL;
2209 /* compute bus and unit according index */
2211 if (index != -1) {
2212 if (bus_id != 0 || unit_id != -1) {
2213 fprintf(stderr,
2214 "qemu: index cannot be used with bus and unit\n");
2215 return NULL;
2217 if (max_devs == 0)
2219 unit_id = index;
2220 bus_id = 0;
2221 } else {
2222 unit_id = index % max_devs;
2223 bus_id = index / max_devs;
2227 /* if user doesn't specify a unit_id,
2228 * try to find the first free
2231 if (unit_id == -1) {
2232 unit_id = 0;
2233 while (drive_get(type, bus_id, unit_id) != NULL) {
2234 unit_id++;
2235 if (max_devs && unit_id >= max_devs) {
2236 unit_id -= max_devs;
2237 bus_id++;
2242 /* check unit id */
2244 if (max_devs && unit_id >= max_devs) {
2245 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2246 unit_id, max_devs - 1);
2247 return NULL;
2251 * ignore multiple definitions
2254 if (drive_get(type, bus_id, unit_id) != NULL) {
2255 *fatal_error = 0;
2256 return NULL;
2259 /* init */
2261 dinfo = qemu_mallocz(sizeof(*dinfo));
2262 if ((buf = qemu_opt_get(opts, "id")) != NULL) {
2263 dinfo->id = qemu_strdup(buf);
2264 } else {
2265 /* no id supplied -> create one */
2266 dinfo->id = qemu_mallocz(32);
2267 if (type == IF_IDE || type == IF_SCSI)
2268 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2269 if (max_devs)
2270 snprintf(dinfo->id, 32, "%s%i%s%i",
2271 devname, bus_id, mediastr, unit_id);
2272 else
2273 snprintf(dinfo->id, 32, "%s%s%i",
2274 devname, mediastr, unit_id);
2276 dinfo->bdrv = bdrv_new(dinfo->id);
2277 dinfo->devaddr = devaddr;
2278 dinfo->type = type;
2279 dinfo->bus = bus_id;
2280 dinfo->unit = unit_id;
2281 dinfo->onerror = onerror;
2282 dinfo->opts = opts;
2283 if (serial)
2284 strncpy(dinfo->serial, serial, sizeof(serial));
2285 TAILQ_INSERT_TAIL(&drives, dinfo, next);
2287 switch(type) {
2288 case IF_IDE:
2289 case IF_SCSI:
2290 case IF_XEN:
2291 switch(media) {
2292 case MEDIA_DISK:
2293 if (cyls != 0) {
2294 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2295 bdrv_set_translation_hint(dinfo->bdrv, translation);
2297 break;
2298 case MEDIA_CDROM:
2299 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2300 break;
2302 break;
2303 case IF_SD:
2304 /* FIXME: This isn't really a floppy, but it's a reasonable
2305 approximation. */
2306 case IF_FLOPPY:
2307 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2308 break;
2309 case IF_PFLASH:
2310 case IF_MTD:
2311 case IF_VIRTIO:
2312 break;
2313 case IF_COUNT:
2314 abort();
2316 if (!file) {
2317 *fatal_error = 0;
2318 return NULL;
2320 bdrv_flags = 0;
2321 if (snapshot) {
2322 bdrv_flags |= BDRV_O_SNAPSHOT;
2323 cache = 2; /* always use write-back with snapshot */
2325 if (cache == 0) /* no caching */
2326 bdrv_flags |= BDRV_O_NOCACHE;
2327 else if (cache == 2) /* write-back */
2328 bdrv_flags |= BDRV_O_CACHE_WB;
2329 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2330 fprintf(stderr, "qemu: could not open disk image %s\n",
2331 file);
2332 return NULL;
2334 if (bdrv_key_required(dinfo->bdrv))
2335 autostart = 0;
2336 *fatal_error = 0;
2337 return dinfo;
2340 static int drive_init_func(QemuOpts *opts, void *opaque)
2342 QEMUMachine *machine = opaque;
2343 int fatal_error = 0;
2345 if (drive_init(opts, machine, &fatal_error) == NULL) {
2346 if (fatal_error)
2347 return 1;
2349 return 0;
2352 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2354 if (NULL == qemu_opt_get(opts, "snapshot")) {
2355 qemu_opt_set(opts, "snapshot", "on");
2357 return 0;
2360 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2362 boot_set_handler = func;
2363 boot_set_opaque = opaque;
2366 int qemu_boot_set(const char *boot_devices)
2368 if (!boot_set_handler) {
2369 return -EINVAL;
2371 return boot_set_handler(boot_set_opaque, boot_devices);
2374 static int parse_bootdevices(char *devices)
2376 /* We just do some generic consistency checks */
2377 const char *p;
2378 int bitmap = 0;
2380 for (p = devices; *p != '\0'; p++) {
2381 /* Allowed boot devices are:
2382 * a-b: floppy disk drives
2383 * c-f: IDE disk drives
2384 * g-m: machine implementation dependant drives
2385 * n-p: network devices
2386 * It's up to each machine implementation to check if the given boot
2387 * devices match the actual hardware implementation and firmware
2388 * features.
2390 if (*p < 'a' || *p > 'p') {
2391 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2392 exit(1);
2394 if (bitmap & (1 << (*p - 'a'))) {
2395 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2396 exit(1);
2398 bitmap |= 1 << (*p - 'a');
2400 return bitmap;
2403 static void restore_boot_devices(void *opaque)
2405 char *standard_boot_devices = opaque;
2407 qemu_boot_set(standard_boot_devices);
2409 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2410 qemu_free(standard_boot_devices);
2413 static void numa_add(const char *optarg)
2415 char option[128];
2416 char *endptr;
2417 unsigned long long value, endvalue;
2418 int nodenr;
2420 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2421 if (!strcmp(option, "node")) {
2422 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2423 nodenr = nb_numa_nodes;
2424 } else {
2425 nodenr = strtoull(option, NULL, 10);
2428 if (get_param_value(option, 128, "mem", optarg) == 0) {
2429 node_mem[nodenr] = 0;
2430 } else {
2431 value = strtoull(option, &endptr, 0);
2432 switch (*endptr) {
2433 case 0: case 'M': case 'm':
2434 value <<= 20;
2435 break;
2436 case 'G': case 'g':
2437 value <<= 30;
2438 break;
2440 node_mem[nodenr] = value;
2442 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2443 node_cpumask[nodenr] = 0;
2444 } else {
2445 value = strtoull(option, &endptr, 10);
2446 if (value >= 64) {
2447 value = 63;
2448 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2449 } else {
2450 if (*endptr == '-') {
2451 endvalue = strtoull(endptr+1, &endptr, 10);
2452 if (endvalue >= 63) {
2453 endvalue = 62;
2454 fprintf(stderr,
2455 "only 63 CPUs in NUMA mode supported.\n");
2457 value = (1 << (endvalue + 1)) - (1 << value);
2458 } else {
2459 value = 1 << value;
2462 node_cpumask[nodenr] = value;
2464 nb_numa_nodes++;
2466 return;
2469 /***********************************************************/
2470 /* USB devices */
2472 static USBPort *used_usb_ports;
2473 static USBPort *free_usb_ports;
2475 /* ??? Maybe change this to register a hub to keep track of the topology. */
2476 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2477 usb_attachfn attach)
2479 port->opaque = opaque;
2480 port->index = index;
2481 port->attach = attach;
2482 port->next = free_usb_ports;
2483 free_usb_ports = port;
2486 int usb_device_add_dev(USBDevice *dev)
2488 USBPort *port;
2490 /* Find a USB port to add the device to. */
2491 port = free_usb_ports;
2492 if (!port->next) {
2493 USBDevice *hub;
2495 /* Create a new hub and chain it on. */
2496 free_usb_ports = NULL;
2497 port->next = used_usb_ports;
2498 used_usb_ports = port;
2500 hub = usb_hub_init(VM_USB_HUB_SIZE);
2501 usb_attach(port, hub);
2502 port = free_usb_ports;
2505 free_usb_ports = port->next;
2506 port->next = used_usb_ports;
2507 used_usb_ports = port;
2508 usb_attach(port, dev);
2509 return 0;
2512 static void usb_msd_password_cb(void *opaque, int err)
2514 USBDevice *dev = opaque;
2516 if (!err)
2517 usb_device_add_dev(dev);
2518 else
2519 dev->handle_destroy(dev);
2522 static int usb_device_add(const char *devname, int is_hotplug)
2524 const char *p;
2525 USBDevice *dev;
2527 if (!free_usb_ports)
2528 return -1;
2530 if (strstart(devname, "host:", &p)) {
2531 dev = usb_host_device_open(p);
2532 } else if (!strcmp(devname, "mouse")) {
2533 dev = usb_mouse_init();
2534 } else if (!strcmp(devname, "tablet")) {
2535 dev = usb_tablet_init();
2536 } else if (!strcmp(devname, "keyboard")) {
2537 dev = usb_keyboard_init();
2538 } else if (strstart(devname, "disk:", &p)) {
2539 BlockDriverState *bs;
2541 dev = usb_msd_init(p);
2542 if (!dev)
2543 return -1;
2544 bs = usb_msd_get_bdrv(dev);
2545 if (bdrv_key_required(bs)) {
2546 autostart = 0;
2547 if (is_hotplug) {
2548 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2549 dev);
2550 return 0;
2553 } else if (!strcmp(devname, "wacom-tablet")) {
2554 dev = usb_wacom_init();
2555 } else if (strstart(devname, "serial:", &p)) {
2556 dev = usb_serial_init(p);
2557 #ifdef CONFIG_BRLAPI
2558 } else if (!strcmp(devname, "braille")) {
2559 dev = usb_baum_init();
2560 #endif
2561 } else if (strstart(devname, "net:", &p)) {
2562 int nic = nb_nics;
2564 if (net_client_init(NULL, "nic", p) < 0)
2565 return -1;
2566 nd_table[nic].model = "usb";
2567 dev = usb_net_init(&nd_table[nic]);
2568 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2569 dev = usb_bt_init(devname[2] ? hci_init(p) :
2570 bt_new_hci(qemu_find_bt_vlan(0)));
2571 } else {
2572 return -1;
2574 if (!dev)
2575 return -1;
2577 return usb_device_add_dev(dev);
2580 int usb_device_del_addr(int bus_num, int addr)
2582 USBPort *port;
2583 USBPort **lastp;
2584 USBDevice *dev;
2586 if (!used_usb_ports)
2587 return -1;
2589 if (bus_num != 0)
2590 return -1;
2592 lastp = &used_usb_ports;
2593 port = used_usb_ports;
2594 while (port && port->dev->addr != addr) {
2595 lastp = &port->next;
2596 port = port->next;
2599 if (!port)
2600 return -1;
2602 dev = port->dev;
2603 *lastp = port->next;
2604 usb_attach(port, NULL);
2605 dev->handle_destroy(dev);
2606 port->next = free_usb_ports;
2607 free_usb_ports = port;
2608 return 0;
2611 static int usb_device_del(const char *devname)
2613 int bus_num, addr;
2614 const char *p;
2616 if (strstart(devname, "host:", &p))
2617 return usb_host_device_close(p);
2619 if (!used_usb_ports)
2620 return -1;
2622 p = strchr(devname, '.');
2623 if (!p)
2624 return -1;
2625 bus_num = strtoul(devname, NULL, 0);
2626 addr = strtoul(p + 1, NULL, 0);
2628 return usb_device_del_addr(bus_num, addr);
2631 static int usb_parse(const char *cmdline)
2633 return usb_device_add(cmdline, 0);
2636 void do_usb_add(Monitor *mon, const char *devname)
2638 usb_device_add(devname, 1);
2641 void do_usb_del(Monitor *mon, const char *devname)
2643 usb_device_del(devname);
2646 void usb_info(Monitor *mon)
2648 USBDevice *dev;
2649 USBPort *port;
2650 const char *speed_str;
2652 if (!usb_enabled) {
2653 monitor_printf(mon, "USB support not enabled\n");
2654 return;
2657 for (port = used_usb_ports; port; port = port->next) {
2658 dev = port->dev;
2659 if (!dev)
2660 continue;
2661 switch(dev->speed) {
2662 case USB_SPEED_LOW:
2663 speed_str = "1.5";
2664 break;
2665 case USB_SPEED_FULL:
2666 speed_str = "12";
2667 break;
2668 case USB_SPEED_HIGH:
2669 speed_str = "480";
2670 break;
2671 default:
2672 speed_str = "?";
2673 break;
2675 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2676 0, dev->addr, speed_str, dev->devname);
2680 /***********************************************************/
2681 /* PCMCIA/Cardbus */
2683 static struct pcmcia_socket_entry_s {
2684 PCMCIASocket *socket;
2685 struct pcmcia_socket_entry_s *next;
2686 } *pcmcia_sockets = 0;
2688 void pcmcia_socket_register(PCMCIASocket *socket)
2690 struct pcmcia_socket_entry_s *entry;
2692 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2693 entry->socket = socket;
2694 entry->next = pcmcia_sockets;
2695 pcmcia_sockets = entry;
2698 void pcmcia_socket_unregister(PCMCIASocket *socket)
2700 struct pcmcia_socket_entry_s *entry, **ptr;
2702 ptr = &pcmcia_sockets;
2703 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2704 if (entry->socket == socket) {
2705 *ptr = entry->next;
2706 qemu_free(entry);
2710 void pcmcia_info(Monitor *mon)
2712 struct pcmcia_socket_entry_s *iter;
2714 if (!pcmcia_sockets)
2715 monitor_printf(mon, "No PCMCIA sockets\n");
2717 for (iter = pcmcia_sockets; iter; iter = iter->next)
2718 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2719 iter->socket->attached ? iter->socket->card_string :
2720 "Empty");
2723 /***********************************************************/
2724 /* register display */
2726 struct DisplayAllocator default_allocator = {
2727 defaultallocator_create_displaysurface,
2728 defaultallocator_resize_displaysurface,
2729 defaultallocator_free_displaysurface
2732 void register_displaystate(DisplayState *ds)
2734 DisplayState **s;
2735 s = &display_state;
2736 while (*s != NULL)
2737 s = &(*s)->next;
2738 ds->next = NULL;
2739 *s = ds;
2742 DisplayState *get_displaystate(void)
2744 return display_state;
2747 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2749 if(ds->allocator == &default_allocator) ds->allocator = da;
2750 return ds->allocator;
2753 /* dumb display */
2755 static void dumb_display_init(void)
2757 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2758 ds->allocator = &default_allocator;
2759 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2760 register_displaystate(ds);
2763 /***********************************************************/
2764 /* I/O handling */
2766 typedef struct IOHandlerRecord {
2767 int fd;
2768 IOCanRWHandler *fd_read_poll;
2769 IOHandler *fd_read;
2770 IOHandler *fd_write;
2771 int deleted;
2772 void *opaque;
2773 /* temporary data */
2774 struct pollfd *ufd;
2775 struct IOHandlerRecord *next;
2776 } IOHandlerRecord;
2778 static IOHandlerRecord *first_io_handler;
2780 /* XXX: fd_read_poll should be suppressed, but an API change is
2781 necessary in the character devices to suppress fd_can_read(). */
2782 int qemu_set_fd_handler2(int fd,
2783 IOCanRWHandler *fd_read_poll,
2784 IOHandler *fd_read,
2785 IOHandler *fd_write,
2786 void *opaque)
2788 IOHandlerRecord **pioh, *ioh;
2790 if (!fd_read && !fd_write) {
2791 pioh = &first_io_handler;
2792 for(;;) {
2793 ioh = *pioh;
2794 if (ioh == NULL)
2795 break;
2796 if (ioh->fd == fd) {
2797 ioh->deleted = 1;
2798 break;
2800 pioh = &ioh->next;
2802 } else {
2803 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2804 if (ioh->fd == fd)
2805 goto found;
2807 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2808 ioh->next = first_io_handler;
2809 first_io_handler = ioh;
2810 found:
2811 ioh->fd = fd;
2812 ioh->fd_read_poll = fd_read_poll;
2813 ioh->fd_read = fd_read;
2814 ioh->fd_write = fd_write;
2815 ioh->opaque = opaque;
2816 ioh->deleted = 0;
2818 return 0;
2821 int qemu_set_fd_handler(int fd,
2822 IOHandler *fd_read,
2823 IOHandler *fd_write,
2824 void *opaque)
2826 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2829 #ifdef _WIN32
2830 /***********************************************************/
2831 /* Polling handling */
2833 typedef struct PollingEntry {
2834 PollingFunc *func;
2835 void *opaque;
2836 struct PollingEntry *next;
2837 } PollingEntry;
2839 static PollingEntry *first_polling_entry;
2841 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2843 PollingEntry **ppe, *pe;
2844 pe = qemu_mallocz(sizeof(PollingEntry));
2845 pe->func = func;
2846 pe->opaque = opaque;
2847 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2848 *ppe = pe;
2849 return 0;
2852 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2854 PollingEntry **ppe, *pe;
2855 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2856 pe = *ppe;
2857 if (pe->func == func && pe->opaque == opaque) {
2858 *ppe = pe->next;
2859 qemu_free(pe);
2860 break;
2865 /***********************************************************/
2866 /* Wait objects support */
2867 typedef struct WaitObjects {
2868 int num;
2869 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2870 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2871 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2872 } WaitObjects;
2874 static WaitObjects wait_objects = {0};
2876 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2878 WaitObjects *w = &wait_objects;
2880 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2881 return -1;
2882 w->events[w->num] = handle;
2883 w->func[w->num] = func;
2884 w->opaque[w->num] = opaque;
2885 w->num++;
2886 return 0;
2889 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2891 int i, found;
2892 WaitObjects *w = &wait_objects;
2894 found = 0;
2895 for (i = 0; i < w->num; i++) {
2896 if (w->events[i] == handle)
2897 found = 1;
2898 if (found) {
2899 w->events[i] = w->events[i + 1];
2900 w->func[i] = w->func[i + 1];
2901 w->opaque[i] = w->opaque[i + 1];
2904 if (found)
2905 w->num--;
2907 #endif
2909 /***********************************************************/
2910 /* ram save/restore */
2912 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2914 int v;
2916 v = qemu_get_byte(f);
2917 switch(v) {
2918 case 0:
2919 if (qemu_get_buffer(f, buf, len) != len)
2920 return -EIO;
2921 break;
2922 case 1:
2923 v = qemu_get_byte(f);
2924 memset(buf, v, len);
2925 break;
2926 default:
2927 return -EINVAL;
2930 if (qemu_file_has_error(f))
2931 return -EIO;
2933 return 0;
2936 static int ram_load_v1(QEMUFile *f, void *opaque)
2938 int ret;
2939 ram_addr_t i;
2941 if (qemu_get_be32(f) != last_ram_offset)
2942 return -EINVAL;
2943 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2944 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2945 if (ret)
2946 return ret;
2948 return 0;
2951 #define BDRV_HASH_BLOCK_SIZE 1024
2952 #define IOBUF_SIZE 4096
2953 #define RAM_CBLOCK_MAGIC 0xfabe
2955 typedef struct RamDecompressState {
2956 z_stream zstream;
2957 QEMUFile *f;
2958 uint8_t buf[IOBUF_SIZE];
2959 } RamDecompressState;
2961 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2963 int ret;
2964 memset(s, 0, sizeof(*s));
2965 s->f = f;
2966 ret = inflateInit(&s->zstream);
2967 if (ret != Z_OK)
2968 return -1;
2969 return 0;
2972 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2974 int ret, clen;
2976 s->zstream.avail_out = len;
2977 s->zstream.next_out = buf;
2978 while (s->zstream.avail_out > 0) {
2979 if (s->zstream.avail_in == 0) {
2980 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2981 return -1;
2982 clen = qemu_get_be16(s->f);
2983 if (clen > IOBUF_SIZE)
2984 return -1;
2985 qemu_get_buffer(s->f, s->buf, clen);
2986 s->zstream.avail_in = clen;
2987 s->zstream.next_in = s->buf;
2989 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2990 if (ret != Z_OK && ret != Z_STREAM_END) {
2991 return -1;
2994 return 0;
2997 static void ram_decompress_close(RamDecompressState *s)
2999 inflateEnd(&s->zstream);
3002 #define RAM_SAVE_FLAG_FULL 0x01
3003 #define RAM_SAVE_FLAG_COMPRESS 0x02
3004 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3005 #define RAM_SAVE_FLAG_PAGE 0x08
3006 #define RAM_SAVE_FLAG_EOS 0x10
3008 static int is_dup_page(uint8_t *page, uint8_t ch)
3010 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3011 uint32_t *array = (uint32_t *)page;
3012 int i;
3014 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3015 if (array[i] != val)
3016 return 0;
3019 return 1;
3022 static int ram_save_block(QEMUFile *f)
3024 static ram_addr_t current_addr = 0;
3025 ram_addr_t saved_addr = current_addr;
3026 ram_addr_t addr = 0;
3027 int found = 0;
3029 while (addr < last_ram_offset) {
3030 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3031 uint8_t *p;
3033 cpu_physical_memory_reset_dirty(current_addr,
3034 current_addr + TARGET_PAGE_SIZE,
3035 MIGRATION_DIRTY_FLAG);
3037 p = qemu_get_ram_ptr(current_addr);
3039 if (is_dup_page(p, *p)) {
3040 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3041 qemu_put_byte(f, *p);
3042 } else {
3043 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3044 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3047 found = 1;
3048 break;
3050 addr += TARGET_PAGE_SIZE;
3051 current_addr = (saved_addr + addr) % last_ram_offset;
3054 return found;
3057 static uint64_t bytes_transferred = 0;
3059 static ram_addr_t ram_save_remaining(void)
3061 ram_addr_t addr;
3062 ram_addr_t count = 0;
3064 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3065 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3066 count++;
3069 return count;
3072 uint64_t ram_bytes_remaining(void)
3074 return ram_save_remaining() * TARGET_PAGE_SIZE;
3077 uint64_t ram_bytes_transferred(void)
3079 return bytes_transferred;
3082 uint64_t ram_bytes_total(void)
3084 return last_ram_offset;
3087 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3089 ram_addr_t addr;
3090 uint64_t bytes_transferred_last;
3091 double bwidth = 0;
3092 uint64_t expected_time = 0;
3094 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3095 qemu_file_set_error(f);
3096 return 0;
3099 if (stage == 1) {
3100 /* Make sure all dirty bits are set */
3101 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3102 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3103 cpu_physical_memory_set_dirty(addr);
3106 /* Enable dirty memory tracking */
3107 cpu_physical_memory_set_dirty_tracking(1);
3109 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3112 bytes_transferred_last = bytes_transferred;
3113 bwidth = get_clock();
3115 while (!qemu_file_rate_limit(f)) {
3116 int ret;
3118 ret = ram_save_block(f);
3119 bytes_transferred += ret * TARGET_PAGE_SIZE;
3120 if (ret == 0) /* no more blocks */
3121 break;
3124 bwidth = get_clock() - bwidth;
3125 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3127 /* if we haven't transferred anything this round, force expected_time to a
3128 * a very high value, but without crashing */
3129 if (bwidth == 0)
3130 bwidth = 0.000001;
3132 /* try transferring iterative blocks of memory */
3134 if (stage == 3) {
3136 /* flush all remaining blocks regardless of rate limiting */
3137 while (ram_save_block(f) != 0) {
3138 bytes_transferred += TARGET_PAGE_SIZE;
3140 cpu_physical_memory_set_dirty_tracking(0);
3143 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3145 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3147 return (stage == 2) && (expected_time <= migrate_max_downtime());
3150 static int ram_load_dead(QEMUFile *f, void *opaque)
3152 RamDecompressState s1, *s = &s1;
3153 uint8_t buf[10];
3154 ram_addr_t i;
3156 if (ram_decompress_open(s, f) < 0)
3157 return -EINVAL;
3158 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3159 if (ram_decompress_buf(s, buf, 1) < 0) {
3160 fprintf(stderr, "Error while reading ram block header\n");
3161 goto error;
3163 if (buf[0] == 0) {
3164 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3165 BDRV_HASH_BLOCK_SIZE) < 0) {
3166 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3167 goto error;
3169 } else {
3170 error:
3171 printf("Error block header\n");
3172 return -EINVAL;
3175 ram_decompress_close(s);
3177 return 0;
3180 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3182 ram_addr_t addr;
3183 int flags;
3185 if (version_id == 1)
3186 return ram_load_v1(f, opaque);
3188 if (version_id == 2) {
3189 if (qemu_get_be32(f) != last_ram_offset)
3190 return -EINVAL;
3191 return ram_load_dead(f, opaque);
3194 if (version_id != 3)
3195 return -EINVAL;
3197 do {
3198 addr = qemu_get_be64(f);
3200 flags = addr & ~TARGET_PAGE_MASK;
3201 addr &= TARGET_PAGE_MASK;
3203 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3204 if (addr != last_ram_offset)
3205 return -EINVAL;
3208 if (flags & RAM_SAVE_FLAG_FULL) {
3209 if (ram_load_dead(f, opaque) < 0)
3210 return -EINVAL;
3213 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3214 uint8_t ch = qemu_get_byte(f);
3215 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3216 #ifndef _WIN32
3217 if (ch == 0 &&
3218 (!kvm_enabled() || kvm_has_sync_mmu())) {
3219 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3221 #endif
3222 } else if (flags & RAM_SAVE_FLAG_PAGE)
3223 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3224 } while (!(flags & RAM_SAVE_FLAG_EOS));
3226 return 0;
3229 void qemu_service_io(void)
3231 qemu_notify_event();
3234 /***********************************************************/
3235 /* bottom halves (can be seen as timers which expire ASAP) */
3237 struct QEMUBH {
3238 QEMUBHFunc *cb;
3239 void *opaque;
3240 int scheduled;
3241 int idle;
3242 int deleted;
3243 QEMUBH *next;
3246 static QEMUBH *first_bh = NULL;
3248 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3250 QEMUBH *bh;
3251 bh = qemu_mallocz(sizeof(QEMUBH));
3252 bh->cb = cb;
3253 bh->opaque = opaque;
3254 bh->next = first_bh;
3255 first_bh = bh;
3256 return bh;
3259 int qemu_bh_poll(void)
3261 QEMUBH *bh, **bhp;
3262 int ret;
3264 ret = 0;
3265 for (bh = first_bh; bh; bh = bh->next) {
3266 if (!bh->deleted && bh->scheduled) {
3267 bh->scheduled = 0;
3268 if (!bh->idle)
3269 ret = 1;
3270 bh->idle = 0;
3271 bh->cb(bh->opaque);
3275 /* remove deleted bhs */
3276 bhp = &first_bh;
3277 while (*bhp) {
3278 bh = *bhp;
3279 if (bh->deleted) {
3280 *bhp = bh->next;
3281 qemu_free(bh);
3282 } else
3283 bhp = &bh->next;
3286 return ret;
3289 void qemu_bh_schedule_idle(QEMUBH *bh)
3291 if (bh->scheduled)
3292 return;
3293 bh->scheduled = 1;
3294 bh->idle = 1;
3297 void qemu_bh_schedule(QEMUBH *bh)
3299 if (bh->scheduled)
3300 return;
3301 bh->scheduled = 1;
3302 bh->idle = 0;
3303 /* stop the currently executing CPU to execute the BH ASAP */
3304 qemu_notify_event();
3307 void qemu_bh_cancel(QEMUBH *bh)
3309 bh->scheduled = 0;
3312 void qemu_bh_delete(QEMUBH *bh)
3314 bh->scheduled = 0;
3315 bh->deleted = 1;
3318 static void qemu_bh_update_timeout(int *timeout)
3320 QEMUBH *bh;
3322 for (bh = first_bh; bh; bh = bh->next) {
3323 if (!bh->deleted && bh->scheduled) {
3324 if (bh->idle) {
3325 /* idle bottom halves will be polled at least
3326 * every 10ms */
3327 *timeout = MIN(10, *timeout);
3328 } else {
3329 /* non-idle bottom halves will be executed
3330 * immediately */
3331 *timeout = 0;
3332 break;
3338 /***********************************************************/
3339 /* machine registration */
3341 static QEMUMachine *first_machine = NULL;
3342 QEMUMachine *current_machine = NULL;
3344 int qemu_register_machine(QEMUMachine *m)
3346 QEMUMachine **pm;
3347 pm = &first_machine;
3348 while (*pm != NULL)
3349 pm = &(*pm)->next;
3350 m->next = NULL;
3351 *pm = m;
3352 return 0;
3355 static QEMUMachine *find_machine(const char *name)
3357 QEMUMachine *m;
3359 for(m = first_machine; m != NULL; m = m->next) {
3360 if (!strcmp(m->name, name))
3361 return m;
3362 if (m->alias && !strcmp(m->alias, name))
3363 return m;
3365 return NULL;
3368 static QEMUMachine *find_default_machine(void)
3370 QEMUMachine *m;
3372 for(m = first_machine; m != NULL; m = m->next) {
3373 if (m->is_default) {
3374 return m;
3377 return NULL;
3380 /***********************************************************/
3381 /* main execution loop */
3383 static void gui_update(void *opaque)
3385 uint64_t interval = GUI_REFRESH_INTERVAL;
3386 DisplayState *ds = opaque;
3387 DisplayChangeListener *dcl = ds->listeners;
3389 dpy_refresh(ds);
3391 while (dcl != NULL) {
3392 if (dcl->gui_timer_interval &&
3393 dcl->gui_timer_interval < interval)
3394 interval = dcl->gui_timer_interval;
3395 dcl = dcl->next;
3397 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3400 static void nographic_update(void *opaque)
3402 uint64_t interval = GUI_REFRESH_INTERVAL;
3404 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3407 struct vm_change_state_entry {
3408 VMChangeStateHandler *cb;
3409 void *opaque;
3410 LIST_ENTRY (vm_change_state_entry) entries;
3413 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3415 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3416 void *opaque)
3418 VMChangeStateEntry *e;
3420 e = qemu_mallocz(sizeof (*e));
3422 e->cb = cb;
3423 e->opaque = opaque;
3424 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3425 return e;
3428 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3430 LIST_REMOVE (e, entries);
3431 qemu_free (e);
3434 static void vm_state_notify(int running, int reason)
3436 VMChangeStateEntry *e;
3438 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3439 e->cb(e->opaque, running, reason);
3443 static void resume_all_vcpus(void);
3444 static void pause_all_vcpus(void);
3446 void vm_start(void)
3448 if (!vm_running) {
3449 cpu_enable_ticks();
3450 vm_running = 1;
3451 vm_state_notify(1, 0);
3452 qemu_rearm_alarm_timer(alarm_timer);
3453 resume_all_vcpus();
3457 /* reset/shutdown handler */
3459 typedef struct QEMUResetEntry {
3460 TAILQ_ENTRY(QEMUResetEntry) entry;
3461 QEMUResetHandler *func;
3462 void *opaque;
3463 } QEMUResetEntry;
3465 static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3466 TAILQ_HEAD_INITIALIZER(reset_handlers);
3467 static int reset_requested;
3468 static int shutdown_requested;
3469 static int powerdown_requested;
3470 static int debug_requested;
3471 static int vmstop_requested;
3473 int qemu_shutdown_requested(void)
3475 int r = shutdown_requested;
3476 shutdown_requested = 0;
3477 return r;
3480 int qemu_reset_requested(void)
3482 int r = reset_requested;
3483 reset_requested = 0;
3484 return r;
3487 int qemu_powerdown_requested(void)
3489 int r = powerdown_requested;
3490 powerdown_requested = 0;
3491 return r;
3494 static int qemu_debug_requested(void)
3496 int r = debug_requested;
3497 debug_requested = 0;
3498 return r;
3501 static int qemu_vmstop_requested(void)
3503 int r = vmstop_requested;
3504 vmstop_requested = 0;
3505 return r;
3508 static void do_vm_stop(int reason)
3510 if (vm_running) {
3511 cpu_disable_ticks();
3512 vm_running = 0;
3513 pause_all_vcpus();
3514 vm_state_notify(0, reason);
3518 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3520 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3522 re->func = func;
3523 re->opaque = opaque;
3524 TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3527 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3529 QEMUResetEntry *re;
3531 TAILQ_FOREACH(re, &reset_handlers, entry) {
3532 if (re->func == func && re->opaque == opaque) {
3533 TAILQ_REMOVE(&reset_handlers, re, entry);
3534 qemu_free(re);
3535 return;
3540 void qemu_system_reset(void)
3542 QEMUResetEntry *re, *nre;
3544 /* reset all devices */
3545 TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3546 re->func(re->opaque);
3550 void qemu_system_reset_request(void)
3552 if (no_reboot) {
3553 shutdown_requested = 1;
3554 } else {
3555 reset_requested = 1;
3557 qemu_notify_event();
3560 void qemu_system_shutdown_request(void)
3562 shutdown_requested = 1;
3563 qemu_notify_event();
3566 void qemu_system_powerdown_request(void)
3568 powerdown_requested = 1;
3569 qemu_notify_event();
3572 #ifdef CONFIG_IOTHREAD
3573 static void qemu_system_vmstop_request(int reason)
3575 vmstop_requested = reason;
3576 qemu_notify_event();
3578 #endif
3580 #ifndef _WIN32
3581 static int io_thread_fd = -1;
3583 static void qemu_event_increment(void)
3585 static const char byte = 0;
3587 if (io_thread_fd == -1)
3588 return;
3590 write(io_thread_fd, &byte, sizeof(byte));
3593 static void qemu_event_read(void *opaque)
3595 int fd = (unsigned long)opaque;
3596 ssize_t len;
3598 /* Drain the notify pipe */
3599 do {
3600 char buffer[512];
3601 len = read(fd, buffer, sizeof(buffer));
3602 } while ((len == -1 && errno == EINTR) || len > 0);
3605 static int qemu_event_init(void)
3607 int err;
3608 int fds[2];
3610 err = pipe(fds);
3611 if (err == -1)
3612 return -errno;
3614 err = fcntl_setfl(fds[0], O_NONBLOCK);
3615 if (err < 0)
3616 goto fail;
3618 err = fcntl_setfl(fds[1], O_NONBLOCK);
3619 if (err < 0)
3620 goto fail;
3622 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3623 (void *)(unsigned long)fds[0]);
3625 io_thread_fd = fds[1];
3626 return 0;
3628 fail:
3629 close(fds[0]);
3630 close(fds[1]);
3631 return err;
3633 #else
3634 HANDLE qemu_event_handle;
3636 static void dummy_event_handler(void *opaque)
3640 static int qemu_event_init(void)
3642 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3643 if (!qemu_event_handle) {
3644 perror("Failed CreateEvent");
3645 return -1;
3647 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3648 return 0;
3651 static void qemu_event_increment(void)
3653 SetEvent(qemu_event_handle);
3655 #endif
3657 static int cpu_can_run(CPUState *env)
3659 if (env->stop)
3660 return 0;
3661 if (env->stopped)
3662 return 0;
3663 return 1;
3666 #ifndef CONFIG_IOTHREAD
3667 static int qemu_init_main_loop(void)
3669 return qemu_event_init();
3672 void qemu_init_vcpu(void *_env)
3674 CPUState *env = _env;
3676 if (kvm_enabled())
3677 kvm_init_vcpu(env);
3678 return;
3681 int qemu_cpu_self(void *env)
3683 return 1;
3686 static void resume_all_vcpus(void)
3690 static void pause_all_vcpus(void)
3694 void qemu_cpu_kick(void *env)
3696 return;
3699 void qemu_notify_event(void)
3701 CPUState *env = cpu_single_env;
3703 if (env) {
3704 cpu_exit(env);
3705 #ifdef USE_KQEMU
3706 if (env->kqemu_enabled)
3707 kqemu_cpu_interrupt(env);
3708 #endif
3712 #define qemu_mutex_lock_iothread() do { } while (0)
3713 #define qemu_mutex_unlock_iothread() do { } while (0)
3715 void vm_stop(int reason)
3717 do_vm_stop(reason);
3720 #else /* CONFIG_IOTHREAD */
3722 #include "qemu-thread.h"
3724 QemuMutex qemu_global_mutex;
3725 static QemuMutex qemu_fair_mutex;
3727 static QemuThread io_thread;
3729 static QemuThread *tcg_cpu_thread;
3730 static QemuCond *tcg_halt_cond;
3732 static int qemu_system_ready;
3733 /* cpu creation */
3734 static QemuCond qemu_cpu_cond;
3735 /* system init */
3736 static QemuCond qemu_system_cond;
3737 static QemuCond qemu_pause_cond;
3739 static void block_io_signals(void);
3740 static void unblock_io_signals(void);
3741 static int tcg_has_work(void);
3743 static int qemu_init_main_loop(void)
3745 int ret;
3747 ret = qemu_event_init();
3748 if (ret)
3749 return ret;
3751 qemu_cond_init(&qemu_pause_cond);
3752 qemu_mutex_init(&qemu_fair_mutex);
3753 qemu_mutex_init(&qemu_global_mutex);
3754 qemu_mutex_lock(&qemu_global_mutex);
3756 unblock_io_signals();
3757 qemu_thread_self(&io_thread);
3759 return 0;
3762 static void qemu_wait_io_event(CPUState *env)
3764 while (!tcg_has_work())
3765 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3767 qemu_mutex_unlock(&qemu_global_mutex);
3770 * Users of qemu_global_mutex can be starved, having no chance
3771 * to acquire it since this path will get to it first.
3772 * So use another lock to provide fairness.
3774 qemu_mutex_lock(&qemu_fair_mutex);
3775 qemu_mutex_unlock(&qemu_fair_mutex);
3777 qemu_mutex_lock(&qemu_global_mutex);
3778 if (env->stop) {
3779 env->stop = 0;
3780 env->stopped = 1;
3781 qemu_cond_signal(&qemu_pause_cond);
3785 static int qemu_cpu_exec(CPUState *env);
3787 static void *kvm_cpu_thread_fn(void *arg)
3789 CPUState *env = arg;
3791 block_io_signals();
3792 qemu_thread_self(env->thread);
3794 /* signal CPU creation */
3795 qemu_mutex_lock(&qemu_global_mutex);
3796 env->created = 1;
3797 qemu_cond_signal(&qemu_cpu_cond);
3799 /* and wait for machine initialization */
3800 while (!qemu_system_ready)
3801 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3803 while (1) {
3804 if (cpu_can_run(env))
3805 qemu_cpu_exec(env);
3806 qemu_wait_io_event(env);
3809 return NULL;
3812 static void tcg_cpu_exec(void);
3814 static void *tcg_cpu_thread_fn(void *arg)
3816 CPUState *env = arg;
3818 block_io_signals();
3819 qemu_thread_self(env->thread);
3821 /* signal CPU creation */
3822 qemu_mutex_lock(&qemu_global_mutex);
3823 for (env = first_cpu; env != NULL; env = env->next_cpu)
3824 env->created = 1;
3825 qemu_cond_signal(&qemu_cpu_cond);
3827 /* and wait for machine initialization */
3828 while (!qemu_system_ready)
3829 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3831 while (1) {
3832 tcg_cpu_exec();
3833 qemu_wait_io_event(cur_cpu);
3836 return NULL;
3839 void qemu_cpu_kick(void *_env)
3841 CPUState *env = _env;
3842 qemu_cond_broadcast(env->halt_cond);
3843 if (kvm_enabled())
3844 qemu_thread_signal(env->thread, SIGUSR1);
3847 int qemu_cpu_self(void *env)
3849 return (cpu_single_env != NULL);
3852 static void cpu_signal(int sig)
3854 if (cpu_single_env)
3855 cpu_exit(cpu_single_env);
3858 static void block_io_signals(void)
3860 sigset_t set;
3861 struct sigaction sigact;
3863 sigemptyset(&set);
3864 sigaddset(&set, SIGUSR2);
3865 sigaddset(&set, SIGIO);
3866 sigaddset(&set, SIGALRM);
3867 pthread_sigmask(SIG_BLOCK, &set, NULL);
3869 sigemptyset(&set);
3870 sigaddset(&set, SIGUSR1);
3871 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3873 memset(&sigact, 0, sizeof(sigact));
3874 sigact.sa_handler = cpu_signal;
3875 sigaction(SIGUSR1, &sigact, NULL);
3878 static void unblock_io_signals(void)
3880 sigset_t set;
3882 sigemptyset(&set);
3883 sigaddset(&set, SIGUSR2);
3884 sigaddset(&set, SIGIO);
3885 sigaddset(&set, SIGALRM);
3886 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3888 sigemptyset(&set);
3889 sigaddset(&set, SIGUSR1);
3890 pthread_sigmask(SIG_BLOCK, &set, NULL);
3893 static void qemu_signal_lock(unsigned int msecs)
3895 qemu_mutex_lock(&qemu_fair_mutex);
3897 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3898 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3899 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3900 break;
3902 qemu_mutex_unlock(&qemu_fair_mutex);
3905 static void qemu_mutex_lock_iothread(void)
3907 if (kvm_enabled()) {
3908 qemu_mutex_lock(&qemu_fair_mutex);
3909 qemu_mutex_lock(&qemu_global_mutex);
3910 qemu_mutex_unlock(&qemu_fair_mutex);
3911 } else
3912 qemu_signal_lock(100);
3915 static void qemu_mutex_unlock_iothread(void)
3917 qemu_mutex_unlock(&qemu_global_mutex);
3920 static int all_vcpus_paused(void)
3922 CPUState *penv = first_cpu;
3924 while (penv) {
3925 if (!penv->stopped)
3926 return 0;
3927 penv = (CPUState *)penv->next_cpu;
3930 return 1;
3933 static void pause_all_vcpus(void)
3935 CPUState *penv = first_cpu;
3937 while (penv) {
3938 penv->stop = 1;
3939 qemu_thread_signal(penv->thread, SIGUSR1);
3940 qemu_cpu_kick(penv);
3941 penv = (CPUState *)penv->next_cpu;
3944 while (!all_vcpus_paused()) {
3945 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3946 penv = first_cpu;
3947 while (penv) {
3948 qemu_thread_signal(penv->thread, SIGUSR1);
3949 penv = (CPUState *)penv->next_cpu;
3954 static void resume_all_vcpus(void)
3956 CPUState *penv = first_cpu;
3958 while (penv) {
3959 penv->stop = 0;
3960 penv->stopped = 0;
3961 qemu_thread_signal(penv->thread, SIGUSR1);
3962 qemu_cpu_kick(penv);
3963 penv = (CPUState *)penv->next_cpu;
3967 static void tcg_init_vcpu(void *_env)
3969 CPUState *env = _env;
3970 /* share a single thread for all cpus with TCG */
3971 if (!tcg_cpu_thread) {
3972 env->thread = qemu_mallocz(sizeof(QemuThread));
3973 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3974 qemu_cond_init(env->halt_cond);
3975 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3976 while (env->created == 0)
3977 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3978 tcg_cpu_thread = env->thread;
3979 tcg_halt_cond = env->halt_cond;
3980 } else {
3981 env->thread = tcg_cpu_thread;
3982 env->halt_cond = tcg_halt_cond;
3986 static void kvm_start_vcpu(CPUState *env)
3988 kvm_init_vcpu(env);
3989 env->thread = qemu_mallocz(sizeof(QemuThread));
3990 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3991 qemu_cond_init(env->halt_cond);
3992 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3993 while (env->created == 0)
3994 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3997 void qemu_init_vcpu(void *_env)
3999 CPUState *env = _env;
4001 if (kvm_enabled())
4002 kvm_start_vcpu(env);
4003 else
4004 tcg_init_vcpu(env);
4007 void qemu_notify_event(void)
4009 qemu_event_increment();
4012 void vm_stop(int reason)
4014 QemuThread me;
4015 qemu_thread_self(&me);
4017 if (!qemu_thread_equal(&me, &io_thread)) {
4018 qemu_system_vmstop_request(reason);
4020 * FIXME: should not return to device code in case
4021 * vm_stop() has been requested.
4023 if (cpu_single_env) {
4024 cpu_exit(cpu_single_env);
4025 cpu_single_env->stop = 1;
4027 return;
4029 do_vm_stop(reason);
4032 #endif
4035 #ifdef _WIN32
4036 static void host_main_loop_wait(int *timeout)
4038 int ret, ret2, i;
4039 PollingEntry *pe;
4042 /* XXX: need to suppress polling by better using win32 events */
4043 ret = 0;
4044 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4045 ret |= pe->func(pe->opaque);
4047 if (ret == 0) {
4048 int err;
4049 WaitObjects *w = &wait_objects;
4051 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4052 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4053 if (w->func[ret - WAIT_OBJECT_0])
4054 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4056 /* Check for additional signaled events */
4057 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4059 /* Check if event is signaled */
4060 ret2 = WaitForSingleObject(w->events[i], 0);
4061 if(ret2 == WAIT_OBJECT_0) {
4062 if (w->func[i])
4063 w->func[i](w->opaque[i]);
4064 } else if (ret2 == WAIT_TIMEOUT) {
4065 } else {
4066 err = GetLastError();
4067 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4070 } else if (ret == WAIT_TIMEOUT) {
4071 } else {
4072 err = GetLastError();
4073 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4077 *timeout = 0;
4079 #else
4080 static void host_main_loop_wait(int *timeout)
4083 #endif
4085 void main_loop_wait(int timeout)
4087 IOHandlerRecord *ioh;
4088 fd_set rfds, wfds, xfds;
4089 int ret, nfds;
4090 struct timeval tv;
4092 qemu_bh_update_timeout(&timeout);
4094 host_main_loop_wait(&timeout);
4096 /* poll any events */
4097 /* XXX: separate device handlers from system ones */
4098 nfds = -1;
4099 FD_ZERO(&rfds);
4100 FD_ZERO(&wfds);
4101 FD_ZERO(&xfds);
4102 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4103 if (ioh->deleted)
4104 continue;
4105 if (ioh->fd_read &&
4106 (!ioh->fd_read_poll ||
4107 ioh->fd_read_poll(ioh->opaque) != 0)) {
4108 FD_SET(ioh->fd, &rfds);
4109 if (ioh->fd > nfds)
4110 nfds = ioh->fd;
4112 if (ioh->fd_write) {
4113 FD_SET(ioh->fd, &wfds);
4114 if (ioh->fd > nfds)
4115 nfds = ioh->fd;
4119 tv.tv_sec = timeout / 1000;
4120 tv.tv_usec = (timeout % 1000) * 1000;
4122 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4124 qemu_mutex_unlock_iothread();
4125 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4126 qemu_mutex_lock_iothread();
4127 if (ret > 0) {
4128 IOHandlerRecord **pioh;
4130 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4131 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4132 ioh->fd_read(ioh->opaque);
4134 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4135 ioh->fd_write(ioh->opaque);
4139 /* remove deleted IO handlers */
4140 pioh = &first_io_handler;
4141 while (*pioh) {
4142 ioh = *pioh;
4143 if (ioh->deleted) {
4144 *pioh = ioh->next;
4145 qemu_free(ioh);
4146 } else
4147 pioh = &ioh->next;
4151 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4153 /* rearm timer, if not periodic */
4154 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4155 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4156 qemu_rearm_alarm_timer(alarm_timer);
4159 /* vm time timers */
4160 if (vm_running) {
4161 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4162 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4163 qemu_get_clock(vm_clock));
4166 /* real time timers */
4167 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4168 qemu_get_clock(rt_clock));
4170 /* Check bottom-halves last in case any of the earlier events triggered
4171 them. */
4172 qemu_bh_poll();
4176 static int qemu_cpu_exec(CPUState *env)
4178 int ret;
4179 #ifdef CONFIG_PROFILER
4180 int64_t ti;
4181 #endif
4183 #ifdef CONFIG_PROFILER
4184 ti = profile_getclock();
4185 #endif
4186 if (use_icount) {
4187 int64_t count;
4188 int decr;
4189 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4190 env->icount_decr.u16.low = 0;
4191 env->icount_extra = 0;
4192 count = qemu_next_deadline();
4193 count = (count + (1 << icount_time_shift) - 1)
4194 >> icount_time_shift;
4195 qemu_icount += count;
4196 decr = (count > 0xffff) ? 0xffff : count;
4197 count -= decr;
4198 env->icount_decr.u16.low = decr;
4199 env->icount_extra = count;
4201 ret = cpu_exec(env);
4202 #ifdef CONFIG_PROFILER
4203 qemu_time += profile_getclock() - ti;
4204 #endif
4205 if (use_icount) {
4206 /* Fold pending instructions back into the
4207 instruction counter, and clear the interrupt flag. */
4208 qemu_icount -= (env->icount_decr.u16.low
4209 + env->icount_extra);
4210 env->icount_decr.u32 = 0;
4211 env->icount_extra = 0;
4213 return ret;
4216 static void tcg_cpu_exec(void)
4218 int ret = 0;
4220 if (next_cpu == NULL)
4221 next_cpu = first_cpu;
4222 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4223 CPUState *env = cur_cpu = next_cpu;
4225 if (!vm_running)
4226 break;
4227 if (timer_alarm_pending) {
4228 timer_alarm_pending = 0;
4229 break;
4231 if (cpu_can_run(env))
4232 ret = qemu_cpu_exec(env);
4233 if (ret == EXCP_DEBUG) {
4234 gdb_set_stop_cpu(env);
4235 debug_requested = 1;
4236 break;
4241 static int cpu_has_work(CPUState *env)
4243 if (env->stop)
4244 return 1;
4245 if (env->stopped)
4246 return 0;
4247 if (!env->halted)
4248 return 1;
4249 if (qemu_cpu_has_work(env))
4250 return 1;
4251 return 0;
4254 static int tcg_has_work(void)
4256 CPUState *env;
4258 for (env = first_cpu; env != NULL; env = env->next_cpu)
4259 if (cpu_has_work(env))
4260 return 1;
4261 return 0;
4264 static int qemu_calculate_timeout(void)
4266 #ifndef CONFIG_IOTHREAD
4267 int timeout;
4269 if (!vm_running)
4270 timeout = 5000;
4271 else if (tcg_has_work())
4272 timeout = 0;
4273 else if (!use_icount)
4274 timeout = 5000;
4275 else {
4276 /* XXX: use timeout computed from timers */
4277 int64_t add;
4278 int64_t delta;
4279 /* Advance virtual time to the next event. */
4280 if (use_icount == 1) {
4281 /* When not using an adaptive execution frequency
4282 we tend to get badly out of sync with real time,
4283 so just delay for a reasonable amount of time. */
4284 delta = 0;
4285 } else {
4286 delta = cpu_get_icount() - cpu_get_clock();
4288 if (delta > 0) {
4289 /* If virtual time is ahead of real time then just
4290 wait for IO. */
4291 timeout = (delta / 1000000) + 1;
4292 } else {
4293 /* Wait for either IO to occur or the next
4294 timer event. */
4295 add = qemu_next_deadline();
4296 /* We advance the timer before checking for IO.
4297 Limit the amount we advance so that early IO
4298 activity won't get the guest too far ahead. */
4299 if (add > 10000000)
4300 add = 10000000;
4301 delta += add;
4302 add = (add + (1 << icount_time_shift) - 1)
4303 >> icount_time_shift;
4304 qemu_icount += add;
4305 timeout = delta / 1000000;
4306 if (timeout < 0)
4307 timeout = 0;
4311 return timeout;
4312 #else /* CONFIG_IOTHREAD */
4313 return 1000;
4314 #endif
4317 static int vm_can_run(void)
4319 if (powerdown_requested)
4320 return 0;
4321 if (reset_requested)
4322 return 0;
4323 if (shutdown_requested)
4324 return 0;
4325 if (debug_requested)
4326 return 0;
4327 return 1;
4330 static void main_loop(void)
4332 int r;
4334 #ifdef CONFIG_IOTHREAD
4335 qemu_system_ready = 1;
4336 qemu_cond_broadcast(&qemu_system_cond);
4337 #endif
4339 for (;;) {
4340 do {
4341 #ifdef CONFIG_PROFILER
4342 int64_t ti;
4343 #endif
4344 #ifndef CONFIG_IOTHREAD
4345 tcg_cpu_exec();
4346 #endif
4347 #ifdef CONFIG_PROFILER
4348 ti = profile_getclock();
4349 #endif
4350 main_loop_wait(qemu_calculate_timeout());
4351 #ifdef CONFIG_PROFILER
4352 dev_time += profile_getclock() - ti;
4353 #endif
4354 } while (vm_can_run());
4356 if (qemu_debug_requested())
4357 vm_stop(EXCP_DEBUG);
4358 if (qemu_shutdown_requested()) {
4359 if (no_shutdown) {
4360 vm_stop(0);
4361 no_shutdown = 0;
4362 } else
4363 break;
4365 if (qemu_reset_requested()) {
4366 pause_all_vcpus();
4367 qemu_system_reset();
4368 resume_all_vcpus();
4370 if (qemu_powerdown_requested())
4371 qemu_system_powerdown();
4372 if ((r = qemu_vmstop_requested()))
4373 vm_stop(r);
4375 pause_all_vcpus();
4378 static void version(void)
4380 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4383 static void help(int exitcode)
4385 version();
4386 printf("usage: %s [options] [disk_image]\n"
4387 "\n"
4388 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4389 "\n"
4390 #define DEF(option, opt_arg, opt_enum, opt_help) \
4391 opt_help
4392 #define DEFHEADING(text) stringify(text) "\n"
4393 #include "qemu-options.h"
4394 #undef DEF
4395 #undef DEFHEADING
4396 #undef GEN_DOCS
4397 "\n"
4398 "During emulation, the following keys are useful:\n"
4399 "ctrl-alt-f toggle full screen\n"
4400 "ctrl-alt-n switch to virtual console 'n'\n"
4401 "ctrl-alt toggle mouse and keyboard grab\n"
4402 "\n"
4403 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4405 "qemu",
4406 DEFAULT_RAM_SIZE,
4407 #ifndef _WIN32
4408 DEFAULT_NETWORK_SCRIPT,
4409 DEFAULT_NETWORK_DOWN_SCRIPT,
4410 #endif
4411 DEFAULT_GDBSTUB_PORT,
4412 "/tmp/qemu.log");
4413 exit(exitcode);
4416 #define HAS_ARG 0x0001
4418 enum {
4419 #define DEF(option, opt_arg, opt_enum, opt_help) \
4420 opt_enum,
4421 #define DEFHEADING(text)
4422 #include "qemu-options.h"
4423 #undef DEF
4424 #undef DEFHEADING
4425 #undef GEN_DOCS
4428 typedef struct QEMUOption {
4429 const char *name;
4430 int flags;
4431 int index;
4432 } QEMUOption;
4434 static const QEMUOption qemu_options[] = {
4435 { "h", 0, QEMU_OPTION_h },
4436 #define DEF(option, opt_arg, opt_enum, opt_help) \
4437 { option, opt_arg, opt_enum },
4438 #define DEFHEADING(text)
4439 #include "qemu-options.h"
4440 #undef DEF
4441 #undef DEFHEADING
4442 #undef GEN_DOCS
4443 { NULL },
4446 #ifdef HAS_AUDIO
4447 struct soundhw soundhw[] = {
4448 #ifdef HAS_AUDIO_CHOICE
4449 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4451 "pcspk",
4452 "PC speaker",
4455 { .init_isa = pcspk_audio_init }
4457 #endif
4459 #ifdef CONFIG_SB16
4461 "sb16",
4462 "Creative Sound Blaster 16",
4465 { .init_isa = SB16_init }
4467 #endif
4469 #ifdef CONFIG_CS4231A
4471 "cs4231a",
4472 "CS4231A",
4475 { .init_isa = cs4231a_init }
4477 #endif
4479 #ifdef CONFIG_ADLIB
4481 "adlib",
4482 #ifdef HAS_YMF262
4483 "Yamaha YMF262 (OPL3)",
4484 #else
4485 "Yamaha YM3812 (OPL2)",
4486 #endif
4489 { .init_isa = Adlib_init }
4491 #endif
4493 #ifdef CONFIG_GUS
4495 "gus",
4496 "Gravis Ultrasound GF1",
4499 { .init_isa = GUS_init }
4501 #endif
4503 #ifdef CONFIG_AC97
4505 "ac97",
4506 "Intel 82801AA AC97 Audio",
4509 { .init_pci = ac97_init }
4511 #endif
4513 #ifdef CONFIG_ES1370
4515 "es1370",
4516 "ENSONIQ AudioPCI ES1370",
4519 { .init_pci = es1370_init }
4521 #endif
4523 #endif /* HAS_AUDIO_CHOICE */
4525 { NULL, NULL, 0, 0, { NULL } }
4528 static void select_soundhw (const char *optarg)
4530 struct soundhw *c;
4532 if (*optarg == '?') {
4533 show_valid_cards:
4535 printf ("Valid sound card names (comma separated):\n");
4536 for (c = soundhw; c->name; ++c) {
4537 printf ("%-11s %s\n", c->name, c->descr);
4539 printf ("\n-soundhw all will enable all of the above\n");
4540 exit (*optarg != '?');
4542 else {
4543 size_t l;
4544 const char *p;
4545 char *e;
4546 int bad_card = 0;
4548 if (!strcmp (optarg, "all")) {
4549 for (c = soundhw; c->name; ++c) {
4550 c->enabled = 1;
4552 return;
4555 p = optarg;
4556 while (*p) {
4557 e = strchr (p, ',');
4558 l = !e ? strlen (p) : (size_t) (e - p);
4560 for (c = soundhw; c->name; ++c) {
4561 if (!strncmp (c->name, p, l)) {
4562 c->enabled = 1;
4563 break;
4567 if (!c->name) {
4568 if (l > 80) {
4569 fprintf (stderr,
4570 "Unknown sound card name (too big to show)\n");
4572 else {
4573 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4574 (int) l, p);
4576 bad_card = 1;
4578 p += l + (e != NULL);
4581 if (bad_card)
4582 goto show_valid_cards;
4585 #endif
4587 static void select_vgahw (const char *p)
4589 const char *opts;
4591 cirrus_vga_enabled = 0;
4592 std_vga_enabled = 0;
4593 vmsvga_enabled = 0;
4594 xenfb_enabled = 0;
4595 if (strstart(p, "std", &opts)) {
4596 std_vga_enabled = 1;
4597 } else if (strstart(p, "cirrus", &opts)) {
4598 cirrus_vga_enabled = 1;
4599 } else if (strstart(p, "vmware", &opts)) {
4600 vmsvga_enabled = 1;
4601 } else if (strstart(p, "xenfb", &opts)) {
4602 xenfb_enabled = 1;
4603 } else if (!strstart(p, "none", &opts)) {
4604 invalid_vga:
4605 fprintf(stderr, "Unknown vga type: %s\n", p);
4606 exit(1);
4608 while (*opts) {
4609 const char *nextopt;
4611 if (strstart(opts, ",retrace=", &nextopt)) {
4612 opts = nextopt;
4613 if (strstart(opts, "dumb", &nextopt))
4614 vga_retrace_method = VGA_RETRACE_DUMB;
4615 else if (strstart(opts, "precise", &nextopt))
4616 vga_retrace_method = VGA_RETRACE_PRECISE;
4617 else goto invalid_vga;
4618 } else goto invalid_vga;
4619 opts = nextopt;
4623 #ifdef TARGET_I386
4624 static int balloon_parse(const char *arg)
4626 char buf[128];
4627 const char *p;
4629 if (!strcmp(arg, "none")) {
4630 virtio_balloon = 0;
4631 } else if (!strncmp(arg, "virtio", 6)) {
4632 virtio_balloon = 1;
4633 if (arg[6] == ',') {
4634 p = arg + 7;
4635 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4636 virtio_balloon_devaddr = strdup(buf);
4639 } else {
4640 return -1;
4642 return 0;
4644 #endif
4646 #ifdef _WIN32
4647 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4649 exit(STATUS_CONTROL_C_EXIT);
4650 return TRUE;
4652 #endif
4654 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4656 int pos = 0;
4657 uint8_t *uuid_ptr = uuid;
4659 if(strlen(str) != 36) {
4660 return -1;
4663 while (pos < 36) {
4664 if (pos == 8 || pos == 13 || pos == 18 || pos == 23) {
4665 if (str[pos] != '-') {
4666 return -1;
4668 pos++;
4669 } else {
4670 if (str[pos] >= '0' && str[pos] <= '9') {
4671 *uuid_ptr = (str[pos] - '0') << 4;
4672 } else if (str[pos] >= 'a' && str[pos] <= 'f') {
4673 *uuid_ptr = (str[pos] - 'a' + 0xa) << 4;
4674 } else if (str[pos] >= 'A' && str[pos] <= 'F') {
4675 *uuid_ptr = (str[pos] - 'A' + 0xa) << 4;
4677 pos++;
4678 if (str[pos] >= '0' && str[pos] <= '9') {
4679 *uuid_ptr += str[pos] - '0';
4680 } else if (str[pos] >= 'a' && str[pos] <= 'f') {
4681 *uuid_ptr += str[pos] - 'a' + 0xa;
4682 } else if (str[pos] >= 'A' && str[pos] <= 'F') {
4683 *uuid_ptr += str[pos] - 'A' + 0xa;
4685 pos++;
4689 #ifdef TARGET_I386
4690 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4691 #endif
4693 return 0;
4696 #define MAX_NET_CLIENTS 32
4698 #ifndef _WIN32
4700 static void termsig_handler(int signal)
4702 qemu_system_shutdown_request();
4705 static void sigchld_handler(int signal)
4707 waitpid(-1, NULL, WNOHANG);
4710 static void sighandler_setup(void)
4712 struct sigaction act;
4714 memset(&act, 0, sizeof(act));
4715 act.sa_handler = termsig_handler;
4716 sigaction(SIGINT, &act, NULL);
4717 sigaction(SIGHUP, &act, NULL);
4718 sigaction(SIGTERM, &act, NULL);
4720 act.sa_handler = sigchld_handler;
4721 act.sa_flags = SA_NOCLDSTOP;
4722 sigaction(SIGCHLD, &act, NULL);
4725 #endif
4727 #ifdef _WIN32
4728 /* Look for support files in the same directory as the executable. */
4729 static char *find_datadir(const char *argv0)
4731 char *p;
4732 char buf[MAX_PATH];
4733 DWORD len;
4735 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4736 if (len == 0) {
4737 return NULL;
4740 buf[len] = 0;
4741 p = buf + len - 1;
4742 while (p != buf && *p != '\\')
4743 p--;
4744 *p = 0;
4745 if (access(buf, R_OK) == 0) {
4746 return qemu_strdup(buf);
4748 return NULL;
4750 #else /* !_WIN32 */
4752 /* Find a likely location for support files using the location of the binary.
4753 For installed binaries this will be "$bindir/../share/qemu". When
4754 running from the build tree this will be "$bindir/../pc-bios". */
4755 #define SHARE_SUFFIX "/share/qemu"
4756 #define BUILD_SUFFIX "/pc-bios"
4757 static char *find_datadir(const char *argv0)
4759 char *dir;
4760 char *p = NULL;
4761 char *res;
4762 #ifdef PATH_MAX
4763 char buf[PATH_MAX];
4764 #endif
4765 size_t max_len;
4767 #if defined(__linux__)
4769 int len;
4770 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4771 if (len > 0) {
4772 buf[len] = 0;
4773 p = buf;
4776 #elif defined(__FreeBSD__)
4778 int len;
4779 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4780 if (len > 0) {
4781 buf[len] = 0;
4782 p = buf;
4785 #endif
4786 /* If we don't have any way of figuring out the actual executable
4787 location then try argv[0]. */
4788 if (!p) {
4789 #ifdef PATH_MAX
4790 p = buf;
4791 #endif
4792 p = realpath(argv0, p);
4793 if (!p) {
4794 return NULL;
4797 dir = dirname(p);
4798 dir = dirname(dir);
4800 max_len = strlen(dir) +
4801 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4802 res = qemu_mallocz(max_len);
4803 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4804 if (access(res, R_OK)) {
4805 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4806 if (access(res, R_OK)) {
4807 qemu_free(res);
4808 res = NULL;
4811 #ifndef PATH_MAX
4812 free(p);
4813 #endif
4814 return res;
4816 #undef SHARE_SUFFIX
4817 #undef BUILD_SUFFIX
4818 #endif
4820 char *qemu_find_file(int type, const char *name)
4822 int len;
4823 const char *subdir;
4824 char *buf;
4826 /* If name contains path separators then try it as a straight path. */
4827 if ((strchr(name, '/') || strchr(name, '\\'))
4828 && access(name, R_OK) == 0) {
4829 return strdup(name);
4831 switch (type) {
4832 case QEMU_FILE_TYPE_BIOS:
4833 subdir = "";
4834 break;
4835 case QEMU_FILE_TYPE_KEYMAP:
4836 subdir = "keymaps/";
4837 break;
4838 default:
4839 abort();
4841 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4842 buf = qemu_mallocz(len);
4843 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4844 if (access(buf, R_OK)) {
4845 qemu_free(buf);
4846 return NULL;
4848 return buf;
4851 struct device_config {
4852 enum {
4853 DEV_GENERIC, /* -device */
4854 DEV_USB, /* -usbdevice */
4855 DEV_BT, /* -bt */
4856 } type;
4857 const char *cmdline;
4858 TAILQ_ENTRY(device_config) next;
4860 TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4862 static void add_device_config(int type, const char *cmdline)
4864 struct device_config *conf;
4866 conf = qemu_mallocz(sizeof(*conf));
4867 conf->type = type;
4868 conf->cmdline = cmdline;
4869 TAILQ_INSERT_TAIL(&device_configs, conf, next);
4872 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4874 struct device_config *conf;
4875 int rc;
4877 TAILQ_FOREACH(conf, &device_configs, next) {
4878 if (conf->type != type)
4879 continue;
4880 rc = func(conf->cmdline);
4881 if (0 != rc)
4882 return rc;
4884 return 0;
4887 static int generic_parse(const char *cmdline)
4889 DeviceState *dev;
4891 dev = qdev_device_add(cmdline);
4892 if (!dev)
4893 return -1;
4894 return 0;
4897 int main(int argc, char **argv, char **envp)
4899 const char *gdbstub_dev = NULL;
4900 uint32_t boot_devices_bitmap = 0;
4901 int i;
4902 int snapshot, linux_boot, net_boot;
4903 const char *initrd_filename;
4904 const char *kernel_filename, *kernel_cmdline;
4905 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4906 DisplayState *ds;
4907 DisplayChangeListener *dcl;
4908 int cyls, heads, secs, translation;
4909 const char *net_clients[MAX_NET_CLIENTS];
4910 int nb_net_clients;
4911 QemuOpts *hda_opts = NULL;
4912 int optind;
4913 const char *r, *optarg;
4914 CharDriverState *monitor_hd = NULL;
4915 const char *monitor_device;
4916 const char *serial_devices[MAX_SERIAL_PORTS];
4917 int serial_device_index;
4918 const char *parallel_devices[MAX_PARALLEL_PORTS];
4919 int parallel_device_index;
4920 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4921 int virtio_console_index;
4922 const char *loadvm = NULL;
4923 QEMUMachine *machine;
4924 const char *cpu_model;
4925 #ifndef _WIN32
4926 int fds[2];
4927 #endif
4928 int tb_size;
4929 const char *pid_file = NULL;
4930 const char *incoming = NULL;
4931 #ifndef _WIN32
4932 int fd = 0;
4933 struct passwd *pwd = NULL;
4934 const char *chroot_dir = NULL;
4935 const char *run_as = NULL;
4936 #endif
4937 CPUState *env;
4938 int show_vnc_port = 0;
4940 qemu_cache_utils_init(envp);
4942 LIST_INIT (&vm_change_state_head);
4943 #ifndef _WIN32
4945 struct sigaction act;
4946 sigfillset(&act.sa_mask);
4947 act.sa_flags = 0;
4948 act.sa_handler = SIG_IGN;
4949 sigaction(SIGPIPE, &act, NULL);
4951 #else
4952 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4953 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4954 QEMU to run on a single CPU */
4956 HANDLE h;
4957 DWORD_PTR mask, smask;
4958 int i;
4959 h = GetCurrentProcess();
4960 if (GetProcessAffinityMask(h, &mask, &smask)) {
4961 for(i = 0; i < 32; i++) {
4962 if (mask & (1 << i))
4963 break;
4965 if (i != 32) {
4966 mask = 1 << i;
4967 SetProcessAffinityMask(h, mask);
4971 #endif
4973 module_call_init(MODULE_INIT_MACHINE);
4974 machine = find_default_machine();
4975 cpu_model = NULL;
4976 initrd_filename = NULL;
4977 ram_size = 0;
4978 snapshot = 0;
4979 kernel_filename = NULL;
4980 kernel_cmdline = "";
4981 cyls = heads = secs = 0;
4982 translation = BIOS_ATA_TRANSLATION_AUTO;
4983 monitor_device = "vc:80Cx24C";
4985 serial_devices[0] = "vc:80Cx24C";
4986 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4987 serial_devices[i] = NULL;
4988 serial_device_index = 0;
4990 parallel_devices[0] = "vc:80Cx24C";
4991 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4992 parallel_devices[i] = NULL;
4993 parallel_device_index = 0;
4995 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4996 virtio_consoles[i] = NULL;
4997 virtio_console_index = 0;
4999 for (i = 0; i < MAX_NODES; i++) {
5000 node_mem[i] = 0;
5001 node_cpumask[i] = 0;
5004 nb_net_clients = 0;
5005 nb_numa_nodes = 0;
5006 nb_nics = 0;
5008 tb_size = 0;
5009 autostart= 1;
5011 register_watchdogs();
5013 optind = 1;
5014 for(;;) {
5015 if (optind >= argc)
5016 break;
5017 r = argv[optind];
5018 if (r[0] != '-') {
5019 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
5020 } else {
5021 const QEMUOption *popt;
5023 optind++;
5024 /* Treat --foo the same as -foo. */
5025 if (r[1] == '-')
5026 r++;
5027 popt = qemu_options;
5028 for(;;) {
5029 if (!popt->name) {
5030 fprintf(stderr, "%s: invalid option -- '%s'\n",
5031 argv[0], r);
5032 exit(1);
5034 if (!strcmp(popt->name, r + 1))
5035 break;
5036 popt++;
5038 if (popt->flags & HAS_ARG) {
5039 if (optind >= argc) {
5040 fprintf(stderr, "%s: option '%s' requires an argument\n",
5041 argv[0], r);
5042 exit(1);
5044 optarg = argv[optind++];
5045 } else {
5046 optarg = NULL;
5049 switch(popt->index) {
5050 case QEMU_OPTION_M:
5051 machine = find_machine(optarg);
5052 if (!machine) {
5053 QEMUMachine *m;
5054 printf("Supported machines are:\n");
5055 for(m = first_machine; m != NULL; m = m->next) {
5056 if (m->alias)
5057 printf("%-10s %s (alias of %s)\n",
5058 m->alias, m->desc, m->name);
5059 printf("%-10s %s%s\n",
5060 m->name, m->desc,
5061 m->is_default ? " (default)" : "");
5063 exit(*optarg != '?');
5065 break;
5066 case QEMU_OPTION_cpu:
5067 /* hw initialization will check this */
5068 if (*optarg == '?') {
5069 /* XXX: implement xxx_cpu_list for targets that still miss it */
5070 #if defined(cpu_list)
5071 cpu_list(stdout, &fprintf);
5072 #endif
5073 exit(0);
5074 } else {
5075 cpu_model = optarg;
5077 break;
5078 case QEMU_OPTION_initrd:
5079 initrd_filename = optarg;
5080 break;
5081 case QEMU_OPTION_hda:
5082 if (cyls == 0)
5083 hda_opts = drive_add(optarg, HD_ALIAS, 0);
5084 else
5085 hda_opts = drive_add(optarg, HD_ALIAS
5086 ",cyls=%d,heads=%d,secs=%d%s",
5087 0, cyls, heads, secs,
5088 translation == BIOS_ATA_TRANSLATION_LBA ?
5089 ",trans=lba" :
5090 translation == BIOS_ATA_TRANSLATION_NONE ?
5091 ",trans=none" : "");
5092 break;
5093 case QEMU_OPTION_hdb:
5094 case QEMU_OPTION_hdc:
5095 case QEMU_OPTION_hdd:
5096 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5097 break;
5098 case QEMU_OPTION_drive:
5099 drive_add(NULL, "%s", optarg);
5100 break;
5101 case QEMU_OPTION_mtdblock:
5102 drive_add(optarg, MTD_ALIAS);
5103 break;
5104 case QEMU_OPTION_sd:
5105 drive_add(optarg, SD_ALIAS);
5106 break;
5107 case QEMU_OPTION_pflash:
5108 drive_add(optarg, PFLASH_ALIAS);
5109 break;
5110 case QEMU_OPTION_snapshot:
5111 snapshot = 1;
5112 break;
5113 case QEMU_OPTION_hdachs:
5115 const char *p;
5116 p = optarg;
5117 cyls = strtol(p, (char **)&p, 0);
5118 if (cyls < 1 || cyls > 16383)
5119 goto chs_fail;
5120 if (*p != ',')
5121 goto chs_fail;
5122 p++;
5123 heads = strtol(p, (char **)&p, 0);
5124 if (heads < 1 || heads > 16)
5125 goto chs_fail;
5126 if (*p != ',')
5127 goto chs_fail;
5128 p++;
5129 secs = strtol(p, (char **)&p, 0);
5130 if (secs < 1 || secs > 63)
5131 goto chs_fail;
5132 if (*p == ',') {
5133 p++;
5134 if (!strcmp(p, "none"))
5135 translation = BIOS_ATA_TRANSLATION_NONE;
5136 else if (!strcmp(p, "lba"))
5137 translation = BIOS_ATA_TRANSLATION_LBA;
5138 else if (!strcmp(p, "auto"))
5139 translation = BIOS_ATA_TRANSLATION_AUTO;
5140 else
5141 goto chs_fail;
5142 } else if (*p != '\0') {
5143 chs_fail:
5144 fprintf(stderr, "qemu: invalid physical CHS format\n");
5145 exit(1);
5147 if (hda_opts != NULL) {
5148 char num[16];
5149 snprintf(num, sizeof(num), "%d", cyls);
5150 qemu_opt_set(hda_opts, "cyls", num);
5151 snprintf(num, sizeof(num), "%d", heads);
5152 qemu_opt_set(hda_opts, "heads", num);
5153 snprintf(num, sizeof(num), "%d", secs);
5154 qemu_opt_set(hda_opts, "secs", num);
5155 if (translation == BIOS_ATA_TRANSLATION_LBA)
5156 qemu_opt_set(hda_opts, "trans", "lba");
5157 if (translation == BIOS_ATA_TRANSLATION_NONE)
5158 qemu_opt_set(hda_opts, "trans", "none");
5161 break;
5162 case QEMU_OPTION_numa:
5163 if (nb_numa_nodes >= MAX_NODES) {
5164 fprintf(stderr, "qemu: too many NUMA nodes\n");
5165 exit(1);
5167 numa_add(optarg);
5168 break;
5169 case QEMU_OPTION_nographic:
5170 display_type = DT_NOGRAPHIC;
5171 break;
5172 #ifdef CONFIG_CURSES
5173 case QEMU_OPTION_curses:
5174 display_type = DT_CURSES;
5175 break;
5176 #endif
5177 case QEMU_OPTION_portrait:
5178 graphic_rotate = 1;
5179 break;
5180 case QEMU_OPTION_kernel:
5181 kernel_filename = optarg;
5182 break;
5183 case QEMU_OPTION_append:
5184 kernel_cmdline = optarg;
5185 break;
5186 case QEMU_OPTION_cdrom:
5187 drive_add(optarg, CDROM_ALIAS);
5188 break;
5189 case QEMU_OPTION_boot:
5191 static const char * const params[] = {
5192 "order", "once", "menu", NULL
5194 char buf[sizeof(boot_devices)];
5195 char *standard_boot_devices;
5196 int legacy = 0;
5198 if (!strchr(optarg, '=')) {
5199 legacy = 1;
5200 pstrcpy(buf, sizeof(buf), optarg);
5201 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5202 fprintf(stderr,
5203 "qemu: unknown boot parameter '%s' in '%s'\n",
5204 buf, optarg);
5205 exit(1);
5208 if (legacy ||
5209 get_param_value(buf, sizeof(buf), "order", optarg)) {
5210 boot_devices_bitmap = parse_bootdevices(buf);
5211 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5213 if (!legacy) {
5214 if (get_param_value(buf, sizeof(buf),
5215 "once", optarg)) {
5216 boot_devices_bitmap |= parse_bootdevices(buf);
5217 standard_boot_devices = qemu_strdup(boot_devices);
5218 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5219 qemu_register_reset(restore_boot_devices,
5220 standard_boot_devices);
5222 if (get_param_value(buf, sizeof(buf),
5223 "menu", optarg)) {
5224 if (!strcmp(buf, "on")) {
5225 boot_menu = 1;
5226 } else if (!strcmp(buf, "off")) {
5227 boot_menu = 0;
5228 } else {
5229 fprintf(stderr,
5230 "qemu: invalid option value '%s'\n",
5231 buf);
5232 exit(1);
5237 break;
5238 case QEMU_OPTION_fda:
5239 case QEMU_OPTION_fdb:
5240 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5241 break;
5242 #ifdef TARGET_I386
5243 case QEMU_OPTION_no_fd_bootchk:
5244 fd_bootchk = 0;
5245 break;
5246 #endif
5247 case QEMU_OPTION_net:
5248 if (nb_net_clients >= MAX_NET_CLIENTS) {
5249 fprintf(stderr, "qemu: too many network clients\n");
5250 exit(1);
5252 net_clients[nb_net_clients] = optarg;
5253 nb_net_clients++;
5254 break;
5255 #ifdef CONFIG_SLIRP
5256 case QEMU_OPTION_tftp:
5257 legacy_tftp_prefix = optarg;
5258 break;
5259 case QEMU_OPTION_bootp:
5260 legacy_bootp_filename = optarg;
5261 break;
5262 #ifndef _WIN32
5263 case QEMU_OPTION_smb:
5264 net_slirp_smb(optarg);
5265 break;
5266 #endif
5267 case QEMU_OPTION_redir:
5268 net_slirp_redir(optarg);
5269 break;
5270 #endif
5271 case QEMU_OPTION_bt:
5272 add_device_config(DEV_BT, optarg);
5273 break;
5274 #ifdef HAS_AUDIO
5275 case QEMU_OPTION_audio_help:
5276 AUD_help ();
5277 exit (0);
5278 break;
5279 case QEMU_OPTION_soundhw:
5280 select_soundhw (optarg);
5281 break;
5282 #endif
5283 case QEMU_OPTION_h:
5284 help(0);
5285 break;
5286 case QEMU_OPTION_version:
5287 version();
5288 exit(0);
5289 break;
5290 case QEMU_OPTION_m: {
5291 uint64_t value;
5292 char *ptr;
5294 value = strtoul(optarg, &ptr, 10);
5295 switch (*ptr) {
5296 case 0: case 'M': case 'm':
5297 value <<= 20;
5298 break;
5299 case 'G': case 'g':
5300 value <<= 30;
5301 break;
5302 default:
5303 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5304 exit(1);
5307 /* On 32-bit hosts, QEMU is limited by virtual address space */
5308 if (value > (2047 << 20)
5309 #ifndef CONFIG_KQEMU
5310 && HOST_LONG_BITS == 32
5311 #endif
5313 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5314 exit(1);
5316 if (value != (uint64_t)(ram_addr_t)value) {
5317 fprintf(stderr, "qemu: ram size too large\n");
5318 exit(1);
5320 ram_size = value;
5321 break;
5323 case QEMU_OPTION_d:
5325 int mask;
5326 const CPULogItem *item;
5328 mask = cpu_str_to_log_mask(optarg);
5329 if (!mask) {
5330 printf("Log items (comma separated):\n");
5331 for(item = cpu_log_items; item->mask != 0; item++) {
5332 printf("%-10s %s\n", item->name, item->help);
5334 exit(1);
5336 cpu_set_log(mask);
5338 break;
5339 case QEMU_OPTION_s:
5340 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5341 break;
5342 case QEMU_OPTION_gdb:
5343 gdbstub_dev = optarg;
5344 break;
5345 case QEMU_OPTION_L:
5346 data_dir = optarg;
5347 break;
5348 case QEMU_OPTION_bios:
5349 bios_name = optarg;
5350 break;
5351 case QEMU_OPTION_singlestep:
5352 singlestep = 1;
5353 break;
5354 case QEMU_OPTION_S:
5355 autostart = 0;
5356 break;
5357 #ifndef _WIN32
5358 case QEMU_OPTION_k:
5359 keyboard_layout = optarg;
5360 break;
5361 #endif
5362 case QEMU_OPTION_localtime:
5363 rtc_utc = 0;
5364 break;
5365 case QEMU_OPTION_vga:
5366 select_vgahw (optarg);
5367 break;
5368 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5369 case QEMU_OPTION_g:
5371 const char *p;
5372 int w, h, depth;
5373 p = optarg;
5374 w = strtol(p, (char **)&p, 10);
5375 if (w <= 0) {
5376 graphic_error:
5377 fprintf(stderr, "qemu: invalid resolution or depth\n");
5378 exit(1);
5380 if (*p != 'x')
5381 goto graphic_error;
5382 p++;
5383 h = strtol(p, (char **)&p, 10);
5384 if (h <= 0)
5385 goto graphic_error;
5386 if (*p == 'x') {
5387 p++;
5388 depth = strtol(p, (char **)&p, 10);
5389 if (depth != 8 && depth != 15 && depth != 16 &&
5390 depth != 24 && depth != 32)
5391 goto graphic_error;
5392 } else if (*p == '\0') {
5393 depth = graphic_depth;
5394 } else {
5395 goto graphic_error;
5398 graphic_width = w;
5399 graphic_height = h;
5400 graphic_depth = depth;
5402 break;
5403 #endif
5404 case QEMU_OPTION_echr:
5406 char *r;
5407 term_escape_char = strtol(optarg, &r, 0);
5408 if (r == optarg)
5409 printf("Bad argument to echr\n");
5410 break;
5412 case QEMU_OPTION_monitor:
5413 monitor_device = optarg;
5414 break;
5415 case QEMU_OPTION_serial:
5416 if (serial_device_index >= MAX_SERIAL_PORTS) {
5417 fprintf(stderr, "qemu: too many serial ports\n");
5418 exit(1);
5420 serial_devices[serial_device_index] = optarg;
5421 serial_device_index++;
5422 break;
5423 case QEMU_OPTION_watchdog:
5424 i = select_watchdog(optarg);
5425 if (i > 0)
5426 exit (i == 1 ? 1 : 0);
5427 break;
5428 case QEMU_OPTION_watchdog_action:
5429 if (select_watchdog_action(optarg) == -1) {
5430 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5431 exit(1);
5433 break;
5434 case QEMU_OPTION_virtiocon:
5435 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5436 fprintf(stderr, "qemu: too many virtio consoles\n");
5437 exit(1);
5439 virtio_consoles[virtio_console_index] = optarg;
5440 virtio_console_index++;
5441 break;
5442 case QEMU_OPTION_parallel:
5443 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5444 fprintf(stderr, "qemu: too many parallel ports\n");
5445 exit(1);
5447 parallel_devices[parallel_device_index] = optarg;
5448 parallel_device_index++;
5449 break;
5450 case QEMU_OPTION_loadvm:
5451 loadvm = optarg;
5452 break;
5453 case QEMU_OPTION_full_screen:
5454 full_screen = 1;
5455 break;
5456 #ifdef CONFIG_SDL
5457 case QEMU_OPTION_no_frame:
5458 no_frame = 1;
5459 break;
5460 case QEMU_OPTION_alt_grab:
5461 alt_grab = 1;
5462 break;
5463 case QEMU_OPTION_no_quit:
5464 no_quit = 1;
5465 break;
5466 case QEMU_OPTION_sdl:
5467 display_type = DT_SDL;
5468 break;
5469 #endif
5470 case QEMU_OPTION_pidfile:
5471 pid_file = optarg;
5472 break;
5473 #ifdef TARGET_I386
5474 case QEMU_OPTION_win2k_hack:
5475 win2k_install_hack = 1;
5476 break;
5477 case QEMU_OPTION_rtc_td_hack:
5478 rtc_td_hack = 1;
5479 break;
5480 case QEMU_OPTION_acpitable:
5481 if(acpi_table_add(optarg) < 0) {
5482 fprintf(stderr, "Wrong acpi table provided\n");
5483 exit(1);
5485 break;
5486 case QEMU_OPTION_smbios:
5487 if(smbios_entry_add(optarg) < 0) {
5488 fprintf(stderr, "Wrong smbios provided\n");
5489 exit(1);
5491 break;
5492 #endif
5493 #ifdef CONFIG_KQEMU
5494 case QEMU_OPTION_enable_kqemu:
5495 kqemu_allowed = 1;
5496 break;
5497 case QEMU_OPTION_kernel_kqemu:
5498 kqemu_allowed = 2;
5499 break;
5500 #endif
5501 #ifdef CONFIG_KVM
5502 case QEMU_OPTION_enable_kvm:
5503 kvm_allowed = 1;
5504 #ifdef CONFIG_KQEMU
5505 kqemu_allowed = 0;
5506 #endif
5507 break;
5508 #endif
5509 case QEMU_OPTION_usb:
5510 usb_enabled = 1;
5511 break;
5512 case QEMU_OPTION_usbdevice:
5513 usb_enabled = 1;
5514 add_device_config(DEV_USB, optarg);
5515 break;
5516 case QEMU_OPTION_device:
5517 add_device_config(DEV_GENERIC, optarg);
5518 break;
5519 case QEMU_OPTION_smp:
5521 char *p;
5522 char option[128];
5523 smp_cpus = strtol(optarg, &p, 10);
5524 if (smp_cpus < 1) {
5525 fprintf(stderr, "Invalid number of CPUs\n");
5526 exit(1);
5528 if (*p++ != ',')
5529 break;
5530 if (get_param_value(option, 128, "maxcpus", p))
5531 max_cpus = strtol(option, NULL, 0);
5532 if (max_cpus < smp_cpus) {
5533 fprintf(stderr, "maxcpus must be equal to or greater than "
5534 "smp\n");
5535 exit(1);
5537 if (max_cpus > 255) {
5538 fprintf(stderr, "Unsupported number of maxcpus\n");
5539 exit(1);
5541 break;
5543 case QEMU_OPTION_vnc:
5544 display_type = DT_VNC;
5545 vnc_display = optarg;
5546 break;
5547 #ifdef TARGET_I386
5548 case QEMU_OPTION_no_acpi:
5549 acpi_enabled = 0;
5550 break;
5551 case QEMU_OPTION_no_hpet:
5552 no_hpet = 1;
5553 break;
5554 case QEMU_OPTION_balloon:
5555 if (balloon_parse(optarg) < 0) {
5556 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5557 exit(1);
5559 break;
5560 #endif
5561 case QEMU_OPTION_no_reboot:
5562 no_reboot = 1;
5563 break;
5564 case QEMU_OPTION_no_shutdown:
5565 no_shutdown = 1;
5566 break;
5567 case QEMU_OPTION_show_cursor:
5568 cursor_hide = 0;
5569 break;
5570 case QEMU_OPTION_uuid:
5571 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5572 fprintf(stderr, "Fail to parse UUID string."
5573 " Wrong format.\n");
5574 exit(1);
5576 break;
5577 #ifndef _WIN32
5578 case QEMU_OPTION_daemonize:
5579 daemonize = 1;
5580 break;
5581 #endif
5582 case QEMU_OPTION_option_rom:
5583 if (nb_option_roms >= MAX_OPTION_ROMS) {
5584 fprintf(stderr, "Too many option ROMs\n");
5585 exit(1);
5587 option_rom[nb_option_roms] = optarg;
5588 nb_option_roms++;
5589 break;
5590 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5591 case QEMU_OPTION_semihosting:
5592 semihosting_enabled = 1;
5593 break;
5594 #endif
5595 case QEMU_OPTION_name:
5596 qemu_name = qemu_strdup(optarg);
5598 char *p = strchr(qemu_name, ',');
5599 if (p != NULL) {
5600 *p++ = 0;
5601 if (strncmp(p, "process=", 8)) {
5602 fprintf(stderr, "Unknown subargument %s to -name", p);
5603 exit(1);
5605 p += 8;
5606 set_proc_name(p);
5609 break;
5610 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5611 case QEMU_OPTION_prom_env:
5612 if (nb_prom_envs >= MAX_PROM_ENVS) {
5613 fprintf(stderr, "Too many prom variables\n");
5614 exit(1);
5616 prom_envs[nb_prom_envs] = optarg;
5617 nb_prom_envs++;
5618 break;
5619 #endif
5620 #ifdef TARGET_ARM
5621 case QEMU_OPTION_old_param:
5622 old_param = 1;
5623 break;
5624 #endif
5625 case QEMU_OPTION_clock:
5626 configure_alarms(optarg);
5627 break;
5628 case QEMU_OPTION_startdate:
5630 struct tm tm;
5631 time_t rtc_start_date;
5632 if (!strcmp(optarg, "now")) {
5633 rtc_date_offset = -1;
5634 } else {
5635 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5636 &tm.tm_year,
5637 &tm.tm_mon,
5638 &tm.tm_mday,
5639 &tm.tm_hour,
5640 &tm.tm_min,
5641 &tm.tm_sec) == 6) {
5642 /* OK */
5643 } else if (sscanf(optarg, "%d-%d-%d",
5644 &tm.tm_year,
5645 &tm.tm_mon,
5646 &tm.tm_mday) == 3) {
5647 tm.tm_hour = 0;
5648 tm.tm_min = 0;
5649 tm.tm_sec = 0;
5650 } else {
5651 goto date_fail;
5653 tm.tm_year -= 1900;
5654 tm.tm_mon--;
5655 rtc_start_date = mktimegm(&tm);
5656 if (rtc_start_date == -1) {
5657 date_fail:
5658 fprintf(stderr, "Invalid date format. Valid format are:\n"
5659 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5660 exit(1);
5662 rtc_date_offset = time(NULL) - rtc_start_date;
5665 break;
5666 case QEMU_OPTION_tb_size:
5667 tb_size = strtol(optarg, NULL, 0);
5668 if (tb_size < 0)
5669 tb_size = 0;
5670 break;
5671 case QEMU_OPTION_icount:
5672 use_icount = 1;
5673 if (strcmp(optarg, "auto") == 0) {
5674 icount_time_shift = -1;
5675 } else {
5676 icount_time_shift = strtol(optarg, NULL, 0);
5678 break;
5679 case QEMU_OPTION_incoming:
5680 incoming = optarg;
5681 break;
5682 #ifndef _WIN32
5683 case QEMU_OPTION_chroot:
5684 chroot_dir = optarg;
5685 break;
5686 case QEMU_OPTION_runas:
5687 run_as = optarg;
5688 break;
5689 #endif
5690 #ifdef CONFIG_XEN
5691 case QEMU_OPTION_xen_domid:
5692 xen_domid = atoi(optarg);
5693 break;
5694 case QEMU_OPTION_xen_create:
5695 xen_mode = XEN_CREATE;
5696 break;
5697 case QEMU_OPTION_xen_attach:
5698 xen_mode = XEN_ATTACH;
5699 break;
5700 #endif
5705 /* If no data_dir is specified then try to find it relative to the
5706 executable path. */
5707 if (!data_dir) {
5708 data_dir = find_datadir(argv[0]);
5710 /* If all else fails use the install patch specified when building. */
5711 if (!data_dir) {
5712 data_dir = CONFIG_QEMU_SHAREDIR;
5715 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5716 if (kvm_allowed && kqemu_allowed) {
5717 fprintf(stderr,
5718 "You can not enable both KVM and kqemu at the same time\n");
5719 exit(1);
5721 #endif
5724 * Default to max_cpus = smp_cpus, in case the user doesn't
5725 * specify a max_cpus value.
5727 if (!max_cpus)
5728 max_cpus = smp_cpus;
5730 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5731 if (smp_cpus > machine->max_cpus) {
5732 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5733 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5734 machine->max_cpus);
5735 exit(1);
5738 if (display_type == DT_NOGRAPHIC) {
5739 if (serial_device_index == 0)
5740 serial_devices[0] = "stdio";
5741 if (parallel_device_index == 0)
5742 parallel_devices[0] = "null";
5743 if (strncmp(monitor_device, "vc", 2) == 0)
5744 monitor_device = "stdio";
5747 #ifndef _WIN32
5748 if (daemonize) {
5749 pid_t pid;
5751 if (pipe(fds) == -1)
5752 exit(1);
5754 pid = fork();
5755 if (pid > 0) {
5756 uint8_t status;
5757 ssize_t len;
5759 close(fds[1]);
5761 again:
5762 len = read(fds[0], &status, 1);
5763 if (len == -1 && (errno == EINTR))
5764 goto again;
5766 if (len != 1)
5767 exit(1);
5768 else if (status == 1) {
5769 fprintf(stderr, "Could not acquire pidfile\n");
5770 exit(1);
5771 } else
5772 exit(0);
5773 } else if (pid < 0)
5774 exit(1);
5776 setsid();
5778 pid = fork();
5779 if (pid > 0)
5780 exit(0);
5781 else if (pid < 0)
5782 exit(1);
5784 umask(027);
5786 signal(SIGTSTP, SIG_IGN);
5787 signal(SIGTTOU, SIG_IGN);
5788 signal(SIGTTIN, SIG_IGN);
5791 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5792 if (daemonize) {
5793 uint8_t status = 1;
5794 write(fds[1], &status, 1);
5795 } else
5796 fprintf(stderr, "Could not acquire pid file\n");
5797 exit(1);
5799 #endif
5801 #ifdef CONFIG_KQEMU
5802 if (smp_cpus > 1)
5803 kqemu_allowed = 0;
5804 #endif
5805 if (qemu_init_main_loop()) {
5806 fprintf(stderr, "qemu_init_main_loop failed\n");
5807 exit(1);
5809 linux_boot = (kernel_filename != NULL);
5811 if (!linux_boot && *kernel_cmdline != '\0') {
5812 fprintf(stderr, "-append only allowed with -kernel option\n");
5813 exit(1);
5816 if (!linux_boot && initrd_filename != NULL) {
5817 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5818 exit(1);
5821 #ifndef _WIN32
5822 /* Win32 doesn't support line-buffering and requires size >= 2 */
5823 setvbuf(stdout, NULL, _IOLBF, 0);
5824 #endif
5826 init_timers();
5827 if (init_timer_alarm() < 0) {
5828 fprintf(stderr, "could not initialize alarm timer\n");
5829 exit(1);
5831 if (use_icount && icount_time_shift < 0) {
5832 use_icount = 2;
5833 /* 125MIPS seems a reasonable initial guess at the guest speed.
5834 It will be corrected fairly quickly anyway. */
5835 icount_time_shift = 3;
5836 init_icount_adjust();
5839 #ifdef _WIN32
5840 socket_init();
5841 #endif
5843 /* init network clients */
5844 if (nb_net_clients == 0) {
5845 /* if no clients, we use a default config */
5846 net_clients[nb_net_clients++] = "nic";
5847 #ifdef CONFIG_SLIRP
5848 net_clients[nb_net_clients++] = "user";
5849 #endif
5852 for(i = 0;i < nb_net_clients; i++) {
5853 if (net_client_parse(net_clients[i]) < 0)
5854 exit(1);
5857 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5858 net_set_boot_mask(net_boot);
5860 net_client_check();
5862 /* init the bluetooth world */
5863 if (foreach_device_config(DEV_BT, bt_parse))
5864 exit(1);
5866 /* init the memory */
5867 if (ram_size == 0)
5868 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5870 #ifdef CONFIG_KQEMU
5871 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5872 guest ram allocation. It needs to go away. */
5873 if (kqemu_allowed) {
5874 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5875 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5876 if (!kqemu_phys_ram_base) {
5877 fprintf(stderr, "Could not allocate physical memory\n");
5878 exit(1);
5881 #endif
5883 /* init the dynamic translator */
5884 cpu_exec_init_all(tb_size * 1024 * 1024);
5886 bdrv_init();
5888 /* we always create the cdrom drive, even if no disk is there */
5889 drive_add(NULL, CDROM_ALIAS);
5891 /* we always create at least one floppy */
5892 drive_add(NULL, FD_ALIAS, 0);
5894 /* we always create one sd slot, even if no card is in it */
5895 drive_add(NULL, SD_ALIAS);
5897 /* open the virtual block devices */
5898 if (snapshot)
5899 qemu_opts_foreach(&drive_opt_list, drive_enable_snapshot, NULL, 0);
5900 if (qemu_opts_foreach(&drive_opt_list, drive_init_func, machine, 1) != 0)
5901 exit(1);
5903 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5904 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5906 #ifndef _WIN32
5907 /* must be after terminal init, SDL library changes signal handlers */
5908 sighandler_setup();
5909 #endif
5911 /* Maintain compatibility with multiple stdio monitors */
5912 if (!strcmp(monitor_device,"stdio")) {
5913 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5914 const char *devname = serial_devices[i];
5915 if (devname && !strcmp(devname,"mon:stdio")) {
5916 monitor_device = NULL;
5917 break;
5918 } else if (devname && !strcmp(devname,"stdio")) {
5919 monitor_device = NULL;
5920 serial_devices[i] = "mon:stdio";
5921 break;
5926 if (nb_numa_nodes > 0) {
5927 int i;
5929 if (nb_numa_nodes > smp_cpus) {
5930 nb_numa_nodes = smp_cpus;
5933 /* If no memory size if given for any node, assume the default case
5934 * and distribute the available memory equally across all nodes
5936 for (i = 0; i < nb_numa_nodes; i++) {
5937 if (node_mem[i] != 0)
5938 break;
5940 if (i == nb_numa_nodes) {
5941 uint64_t usedmem = 0;
5943 /* On Linux, the each node's border has to be 8MB aligned,
5944 * the final node gets the rest.
5946 for (i = 0; i < nb_numa_nodes - 1; i++) {
5947 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5948 usedmem += node_mem[i];
5950 node_mem[i] = ram_size - usedmem;
5953 for (i = 0; i < nb_numa_nodes; i++) {
5954 if (node_cpumask[i] != 0)
5955 break;
5957 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5958 * must cope with this anyway, because there are BIOSes out there in
5959 * real machines which also use this scheme.
5961 if (i == nb_numa_nodes) {
5962 for (i = 0; i < smp_cpus; i++) {
5963 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5968 if (kvm_enabled()) {
5969 int ret;
5971 ret = kvm_init(smp_cpus);
5972 if (ret < 0) {
5973 fprintf(stderr, "failed to initialize KVM\n");
5974 exit(1);
5978 if (monitor_device) {
5979 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5980 if (!monitor_hd) {
5981 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5982 exit(1);
5986 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5987 const char *devname = serial_devices[i];
5988 if (devname && strcmp(devname, "none")) {
5989 char label[32];
5990 snprintf(label, sizeof(label), "serial%d", i);
5991 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5992 if (!serial_hds[i]) {
5993 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5994 devname);
5995 exit(1);
6000 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6001 const char *devname = parallel_devices[i];
6002 if (devname && strcmp(devname, "none")) {
6003 char label[32];
6004 snprintf(label, sizeof(label), "parallel%d", i);
6005 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6006 if (!parallel_hds[i]) {
6007 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6008 devname);
6009 exit(1);
6014 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6015 const char *devname = virtio_consoles[i];
6016 if (devname && strcmp(devname, "none")) {
6017 char label[32];
6018 snprintf(label, sizeof(label), "virtcon%d", i);
6019 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6020 if (!virtcon_hds[i]) {
6021 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6022 devname);
6023 exit(1);
6028 module_call_init(MODULE_INIT_DEVICE);
6030 if (machine->compat_props) {
6031 qdev_prop_register_compat(machine->compat_props);
6033 machine->init(ram_size, boot_devices,
6034 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6037 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6038 for (i = 0; i < nb_numa_nodes; i++) {
6039 if (node_cpumask[i] & (1 << env->cpu_index)) {
6040 env->numa_node = i;
6045 current_machine = machine;
6047 /* init USB devices */
6048 if (usb_enabled) {
6049 foreach_device_config(DEV_USB, usb_parse);
6052 /* init generic devices */
6053 if (foreach_device_config(DEV_GENERIC, generic_parse))
6054 exit(1);
6056 if (!display_state)
6057 dumb_display_init();
6058 /* just use the first displaystate for the moment */
6059 ds = display_state;
6061 if (display_type == DT_DEFAULT) {
6062 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6063 display_type = DT_SDL;
6064 #else
6065 display_type = DT_VNC;
6066 vnc_display = "localhost:0,to=99";
6067 show_vnc_port = 1;
6068 #endif
6072 switch (display_type) {
6073 case DT_NOGRAPHIC:
6074 break;
6075 #if defined(CONFIG_CURSES)
6076 case DT_CURSES:
6077 curses_display_init(ds, full_screen);
6078 break;
6079 #endif
6080 #if defined(CONFIG_SDL)
6081 case DT_SDL:
6082 sdl_display_init(ds, full_screen, no_frame);
6083 break;
6084 #elif defined(CONFIG_COCOA)
6085 case DT_SDL:
6086 cocoa_display_init(ds, full_screen);
6087 break;
6088 #endif
6089 case DT_VNC:
6090 vnc_display_init(ds);
6091 if (vnc_display_open(ds, vnc_display) < 0)
6092 exit(1);
6094 if (show_vnc_port) {
6095 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6097 break;
6098 default:
6099 break;
6101 dpy_resize(ds);
6103 dcl = ds->listeners;
6104 while (dcl != NULL) {
6105 if (dcl->dpy_refresh != NULL) {
6106 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6107 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6109 dcl = dcl->next;
6112 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6113 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6114 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6117 text_consoles_set_display(display_state);
6118 qemu_chr_initial_reset();
6120 if (monitor_device && monitor_hd)
6121 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6123 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6124 const char *devname = serial_devices[i];
6125 if (devname && strcmp(devname, "none")) {
6126 if (strstart(devname, "vc", 0))
6127 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6131 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6132 const char *devname = parallel_devices[i];
6133 if (devname && strcmp(devname, "none")) {
6134 if (strstart(devname, "vc", 0))
6135 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6139 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6140 const char *devname = virtio_consoles[i];
6141 if (virtcon_hds[i] && devname) {
6142 if (strstart(devname, "vc", 0))
6143 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6147 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6148 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6149 gdbstub_dev);
6150 exit(1);
6153 if (loadvm)
6154 do_loadvm(cur_mon, loadvm);
6156 if (incoming) {
6157 autostart = 0;
6158 qemu_start_incoming_migration(incoming);
6161 else if (autostart)
6162 vm_start();
6164 #ifndef _WIN32
6165 if (daemonize) {
6166 uint8_t status = 0;
6167 ssize_t len;
6169 again1:
6170 len = write(fds[1], &status, 1);
6171 if (len == -1 && (errno == EINTR))
6172 goto again1;
6174 if (len != 1)
6175 exit(1);
6177 chdir("/");
6178 TFR(fd = open("/dev/null", O_RDWR));
6179 if (fd == -1)
6180 exit(1);
6183 if (run_as) {
6184 pwd = getpwnam(run_as);
6185 if (!pwd) {
6186 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6187 exit(1);
6191 if (chroot_dir) {
6192 if (chroot(chroot_dir) < 0) {
6193 fprintf(stderr, "chroot failed\n");
6194 exit(1);
6196 chdir("/");
6199 if (run_as) {
6200 if (setgid(pwd->pw_gid) < 0) {
6201 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6202 exit(1);
6204 if (setuid(pwd->pw_uid) < 0) {
6205 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6206 exit(1);
6208 if (setuid(0) != -1) {
6209 fprintf(stderr, "Dropping privileges failed\n");
6210 exit(1);
6214 if (daemonize) {
6215 dup2(fd, 0);
6216 dup2(fd, 1);
6217 dup2(fd, 2);
6219 close(fd);
6221 #endif
6223 main_loop();
6224 quit_timers();
6225 net_cleanup();
6227 return 0;