consolidate user cpu_{in, out}[bwl] into ioport-user.c
[qemu/aliguori-queue.git] / vl.c
blob918f259f39aec7090e8ce3bc53587e5bff15a2ba
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <libgen.h>
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
49 #endif
50 #ifdef __linux__
51 #include <linux/if_tun.h>
52 #endif
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef HOST_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
60 #include <libutil.h>
61 #else
62 #include <util.h>
63 #endif
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
66 #else
67 #ifdef __linux__
68 #include <pty.h>
69 #include <malloc.h>
70 #include <linux/rtc.h>
72 /* For the benefit of older linux systems which don't supply it,
73 we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
75 #include "hpet.h"
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
79 #endif
80 #ifdef __sun__
81 #include <sys/stat.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
91 #include <net/if.h>
92 #include <syslog.h>
93 #include <stropts.h>
94 #endif
95 #endif
96 #endif
98 #if defined(__OpenBSD__)
99 #include <util.h>
100 #endif
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
104 #endif
106 #ifdef _WIN32
107 #include <windows.h>
108 #include <malloc.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
113 #endif
115 #ifdef CONFIG_SDL
116 #if defined(__APPLE__) || defined(main)
117 #include <SDL.h>
118 int qemu_main(int argc, char **argv, char **envp);
119 int main(int argc, char **argv)
121 return qemu_main(argc, argv, NULL);
123 #undef main
124 #define main qemu_main
125 #endif
126 #endif /* CONFIG_SDL */
128 #ifdef CONFIG_COCOA
129 #undef main
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
133 #include "hw/hw.h"
134 #include "hw/boards.h"
135 #include "hw/usb.h"
136 #include "hw/pcmcia.h"
137 #include "hw/pc.h"
138 #include "hw/audiodev.h"
139 #include "hw/isa.h"
140 #include "hw/baum.h"
141 #include "hw/bt.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
144 #include "hw/xen.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 /* Max number of USB devices that can be specified on the commandline. */
176 #define MAX_USB_CMDLINE 8
178 /* Max number of bluetooth switches on the commandline. */
179 #define MAX_BT_CMDLINE 10
181 static const char *data_dir;
182 const char *bios_name = NULL;
183 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
184 to store the VM snapshots */
185 DriveInfo drives_table[MAX_DRIVES+1];
186 int nb_drives;
187 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
188 static DisplayState *display_state;
189 DisplayType display_type = DT_DEFAULT;
190 const char* keyboard_layout = NULL;
191 int64_t ticks_per_sec;
192 ram_addr_t ram_size;
193 int nb_nics;
194 NICInfo nd_table[MAX_NICS];
195 int vm_running;
196 static int autostart;
197 static int rtc_utc = 1;
198 static int rtc_date_offset = -1; /* -1 means no change */
199 int cirrus_vga_enabled = 1;
200 int std_vga_enabled = 0;
201 int vmsvga_enabled = 0;
202 int xenfb_enabled = 0;
203 #ifdef TARGET_SPARC
204 int graphic_width = 1024;
205 int graphic_height = 768;
206 int graphic_depth = 8;
207 #else
208 int graphic_width = 800;
209 int graphic_height = 600;
210 int graphic_depth = 15;
211 #endif
212 static int full_screen = 0;
213 #ifdef CONFIG_SDL
214 static int no_frame = 0;
215 #endif
216 int no_quit = 0;
217 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
218 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
219 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
220 #ifdef TARGET_I386
221 int win2k_install_hack = 0;
222 int rtc_td_hack = 0;
223 #endif
224 int usb_enabled = 0;
225 int singlestep = 0;
226 int smp_cpus = 1;
227 const char *vnc_display;
228 int acpi_enabled = 1;
229 int no_hpet = 0;
230 int virtio_balloon = 1;
231 const char *virtio_balloon_devaddr;
232 int fd_bootchk = 1;
233 int no_reboot = 0;
234 int no_shutdown = 0;
235 int cursor_hide = 1;
236 int graphic_rotate = 0;
237 #ifndef _WIN32
238 int daemonize = 0;
239 #endif
240 WatchdogTimerModel *watchdog = NULL;
241 int watchdog_action = WDT_RESET;
242 const char *option_rom[MAX_OPTION_ROMS];
243 int nb_option_roms;
244 int semihosting_enabled = 0;
245 #ifdef TARGET_ARM
246 int old_param = 0;
247 #endif
248 const char *qemu_name;
249 int alt_grab = 0;
250 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
251 unsigned int nb_prom_envs = 0;
252 const char *prom_envs[MAX_PROM_ENVS];
253 #endif
254 int nb_drives_opt;
255 struct drive_opt drives_opt[MAX_DRIVES];
257 int nb_numa_nodes;
258 uint64_t node_mem[MAX_NODES];
259 uint64_t node_cpumask[MAX_NODES];
261 static CPUState *cur_cpu;
262 static CPUState *next_cpu;
263 static int timer_alarm_pending = 1;
264 /* Conversion factor from emulated instructions to virtual clock ticks. */
265 static int icount_time_shift;
266 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
267 #define MAX_ICOUNT_SHIFT 10
268 /* Compensate for varying guest execution speed. */
269 static int64_t qemu_icount_bias;
270 static QEMUTimer *icount_rt_timer;
271 static QEMUTimer *icount_vm_timer;
272 static QEMUTimer *nographic_timer;
274 uint8_t qemu_uuid[16];
276 /***********************************************************/
277 /* x86 ISA bus support */
279 target_phys_addr_t isa_mem_base = 0;
280 PicState2 *isa_pic;
282 /***********************************************************/
283 void hw_error(const char *fmt, ...)
285 va_list ap;
286 CPUState *env;
288 va_start(ap, fmt);
289 fprintf(stderr, "qemu: hardware error: ");
290 vfprintf(stderr, fmt, ap);
291 fprintf(stderr, "\n");
292 for(env = first_cpu; env != NULL; env = env->next_cpu) {
293 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
294 #ifdef TARGET_I386
295 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
296 #else
297 cpu_dump_state(env, stderr, fprintf, 0);
298 #endif
300 va_end(ap);
301 abort();
304 /***************/
305 /* ballooning */
307 static QEMUBalloonEvent *qemu_balloon_event;
308 void *qemu_balloon_event_opaque;
310 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
312 qemu_balloon_event = func;
313 qemu_balloon_event_opaque = opaque;
316 void qemu_balloon(ram_addr_t target)
318 if (qemu_balloon_event)
319 qemu_balloon_event(qemu_balloon_event_opaque, target);
322 ram_addr_t qemu_balloon_status(void)
324 if (qemu_balloon_event)
325 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
326 return 0;
329 /***********************************************************/
330 /* keyboard/mouse */
332 static QEMUPutKBDEvent *qemu_put_kbd_event;
333 static void *qemu_put_kbd_event_opaque;
334 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
335 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
337 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
339 qemu_put_kbd_event_opaque = opaque;
340 qemu_put_kbd_event = func;
343 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
344 void *opaque, int absolute,
345 const char *name)
347 QEMUPutMouseEntry *s, *cursor;
349 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
351 s->qemu_put_mouse_event = func;
352 s->qemu_put_mouse_event_opaque = opaque;
353 s->qemu_put_mouse_event_absolute = absolute;
354 s->qemu_put_mouse_event_name = qemu_strdup(name);
355 s->next = NULL;
357 if (!qemu_put_mouse_event_head) {
358 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
359 return s;
362 cursor = qemu_put_mouse_event_head;
363 while (cursor->next != NULL)
364 cursor = cursor->next;
366 cursor->next = s;
367 qemu_put_mouse_event_current = s;
369 return s;
372 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
374 QEMUPutMouseEntry *prev = NULL, *cursor;
376 if (!qemu_put_mouse_event_head || entry == NULL)
377 return;
379 cursor = qemu_put_mouse_event_head;
380 while (cursor != NULL && cursor != entry) {
381 prev = cursor;
382 cursor = cursor->next;
385 if (cursor == NULL) // does not exist or list empty
386 return;
387 else if (prev == NULL) { // entry is head
388 qemu_put_mouse_event_head = cursor->next;
389 if (qemu_put_mouse_event_current == entry)
390 qemu_put_mouse_event_current = cursor->next;
391 qemu_free(entry->qemu_put_mouse_event_name);
392 qemu_free(entry);
393 return;
396 prev->next = entry->next;
398 if (qemu_put_mouse_event_current == entry)
399 qemu_put_mouse_event_current = prev;
401 qemu_free(entry->qemu_put_mouse_event_name);
402 qemu_free(entry);
405 void kbd_put_keycode(int keycode)
407 if (qemu_put_kbd_event) {
408 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
412 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
414 QEMUPutMouseEvent *mouse_event;
415 void *mouse_event_opaque;
416 int width;
418 if (!qemu_put_mouse_event_current) {
419 return;
422 mouse_event =
423 qemu_put_mouse_event_current->qemu_put_mouse_event;
424 mouse_event_opaque =
425 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
427 if (mouse_event) {
428 if (graphic_rotate) {
429 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
430 width = 0x7fff;
431 else
432 width = graphic_width - 1;
433 mouse_event(mouse_event_opaque,
434 width - dy, dx, dz, buttons_state);
435 } else
436 mouse_event(mouse_event_opaque,
437 dx, dy, dz, buttons_state);
441 int kbd_mouse_is_absolute(void)
443 if (!qemu_put_mouse_event_current)
444 return 0;
446 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
449 void do_info_mice(Monitor *mon)
451 QEMUPutMouseEntry *cursor;
452 int index = 0;
454 if (!qemu_put_mouse_event_head) {
455 monitor_printf(mon, "No mouse devices connected\n");
456 return;
459 monitor_printf(mon, "Mouse devices available:\n");
460 cursor = qemu_put_mouse_event_head;
461 while (cursor != NULL) {
462 monitor_printf(mon, "%c Mouse #%d: %s\n",
463 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
464 index, cursor->qemu_put_mouse_event_name);
465 index++;
466 cursor = cursor->next;
470 void do_mouse_set(Monitor *mon, int index)
472 QEMUPutMouseEntry *cursor;
473 int i = 0;
475 if (!qemu_put_mouse_event_head) {
476 monitor_printf(mon, "No mouse devices connected\n");
477 return;
480 cursor = qemu_put_mouse_event_head;
481 while (cursor != NULL && index != i) {
482 i++;
483 cursor = cursor->next;
486 if (cursor != NULL)
487 qemu_put_mouse_event_current = cursor;
488 else
489 monitor_printf(mon, "Mouse at given index not found\n");
492 /* compute with 96 bit intermediate result: (a*b)/c */
493 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
495 union {
496 uint64_t ll;
497 struct {
498 #ifdef WORDS_BIGENDIAN
499 uint32_t high, low;
500 #else
501 uint32_t low, high;
502 #endif
503 } l;
504 } u, res;
505 uint64_t rl, rh;
507 u.ll = a;
508 rl = (uint64_t)u.l.low * (uint64_t)b;
509 rh = (uint64_t)u.l.high * (uint64_t)b;
510 rh += (rl >> 32);
511 res.l.high = rh / c;
512 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
513 return res.ll;
516 /***********************************************************/
517 /* real time host monotonic timer */
519 #define QEMU_TIMER_BASE 1000000000LL
521 #ifdef WIN32
523 static int64_t clock_freq;
525 static void init_get_clock(void)
527 LARGE_INTEGER freq;
528 int ret;
529 ret = QueryPerformanceFrequency(&freq);
530 if (ret == 0) {
531 fprintf(stderr, "Could not calibrate ticks\n");
532 exit(1);
534 clock_freq = freq.QuadPart;
537 static int64_t get_clock(void)
539 LARGE_INTEGER ti;
540 QueryPerformanceCounter(&ti);
541 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
544 #else
546 static int use_rt_clock;
548 static void init_get_clock(void)
550 use_rt_clock = 0;
551 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
552 || defined(__DragonFly__)
554 struct timespec ts;
555 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
556 use_rt_clock = 1;
559 #endif
562 static int64_t get_clock(void)
564 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
565 || defined(__DragonFly__)
566 if (use_rt_clock) {
567 struct timespec ts;
568 clock_gettime(CLOCK_MONOTONIC, &ts);
569 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
570 } else
571 #endif
573 /* XXX: using gettimeofday leads to problems if the date
574 changes, so it should be avoided. */
575 struct timeval tv;
576 gettimeofday(&tv, NULL);
577 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
580 #endif
582 /* Return the virtual CPU time, based on the instruction counter. */
583 static int64_t cpu_get_icount(void)
585 int64_t icount;
586 CPUState *env = cpu_single_env;;
587 icount = qemu_icount;
588 if (env) {
589 if (!can_do_io(env))
590 fprintf(stderr, "Bad clock read\n");
591 icount -= (env->icount_decr.u16.low + env->icount_extra);
593 return qemu_icount_bias + (icount << icount_time_shift);
596 /***********************************************************/
597 /* guest cycle counter */
599 static int64_t cpu_ticks_prev;
600 static int64_t cpu_ticks_offset;
601 static int64_t cpu_clock_offset;
602 static int cpu_ticks_enabled;
604 /* return the host CPU cycle counter and handle stop/restart */
605 int64_t cpu_get_ticks(void)
607 if (use_icount) {
608 return cpu_get_icount();
610 if (!cpu_ticks_enabled) {
611 return cpu_ticks_offset;
612 } else {
613 int64_t ticks;
614 ticks = cpu_get_real_ticks();
615 if (cpu_ticks_prev > ticks) {
616 /* Note: non increasing ticks may happen if the host uses
617 software suspend */
618 cpu_ticks_offset += cpu_ticks_prev - ticks;
620 cpu_ticks_prev = ticks;
621 return ticks + cpu_ticks_offset;
625 /* return the host CPU monotonic timer and handle stop/restart */
626 static int64_t cpu_get_clock(void)
628 int64_t ti;
629 if (!cpu_ticks_enabled) {
630 return cpu_clock_offset;
631 } else {
632 ti = get_clock();
633 return ti + cpu_clock_offset;
637 /* enable cpu_get_ticks() */
638 void cpu_enable_ticks(void)
640 if (!cpu_ticks_enabled) {
641 cpu_ticks_offset -= cpu_get_real_ticks();
642 cpu_clock_offset -= get_clock();
643 cpu_ticks_enabled = 1;
647 /* disable cpu_get_ticks() : the clock is stopped. You must not call
648 cpu_get_ticks() after that. */
649 void cpu_disable_ticks(void)
651 if (cpu_ticks_enabled) {
652 cpu_ticks_offset = cpu_get_ticks();
653 cpu_clock_offset = cpu_get_clock();
654 cpu_ticks_enabled = 0;
658 /***********************************************************/
659 /* timers */
661 #define QEMU_TIMER_REALTIME 0
662 #define QEMU_TIMER_VIRTUAL 1
664 struct QEMUClock {
665 int type;
666 /* XXX: add frequency */
669 struct QEMUTimer {
670 QEMUClock *clock;
671 int64_t expire_time;
672 QEMUTimerCB *cb;
673 void *opaque;
674 struct QEMUTimer *next;
677 struct qemu_alarm_timer {
678 char const *name;
679 unsigned int flags;
681 int (*start)(struct qemu_alarm_timer *t);
682 void (*stop)(struct qemu_alarm_timer *t);
683 void (*rearm)(struct qemu_alarm_timer *t);
684 void *priv;
687 #define ALARM_FLAG_DYNTICKS 0x1
688 #define ALARM_FLAG_EXPIRED 0x2
690 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
692 return t && (t->flags & ALARM_FLAG_DYNTICKS);
695 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
697 if (!alarm_has_dynticks(t))
698 return;
700 t->rearm(t);
703 /* TODO: MIN_TIMER_REARM_US should be optimized */
704 #define MIN_TIMER_REARM_US 250
706 static struct qemu_alarm_timer *alarm_timer;
708 #ifdef _WIN32
710 struct qemu_alarm_win32 {
711 MMRESULT timerId;
712 unsigned int period;
713 } alarm_win32_data = {0, -1};
715 static int win32_start_timer(struct qemu_alarm_timer *t);
716 static void win32_stop_timer(struct qemu_alarm_timer *t);
717 static void win32_rearm_timer(struct qemu_alarm_timer *t);
719 #else
721 static int unix_start_timer(struct qemu_alarm_timer *t);
722 static void unix_stop_timer(struct qemu_alarm_timer *t);
724 #ifdef __linux__
726 static int dynticks_start_timer(struct qemu_alarm_timer *t);
727 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
728 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
730 static int hpet_start_timer(struct qemu_alarm_timer *t);
731 static void hpet_stop_timer(struct qemu_alarm_timer *t);
733 static int rtc_start_timer(struct qemu_alarm_timer *t);
734 static void rtc_stop_timer(struct qemu_alarm_timer *t);
736 #endif /* __linux__ */
738 #endif /* _WIN32 */
740 /* Correlation between real and virtual time is always going to be
741 fairly approximate, so ignore small variation.
742 When the guest is idle real and virtual time will be aligned in
743 the IO wait loop. */
744 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
746 static void icount_adjust(void)
748 int64_t cur_time;
749 int64_t cur_icount;
750 int64_t delta;
751 static int64_t last_delta;
752 /* If the VM is not running, then do nothing. */
753 if (!vm_running)
754 return;
756 cur_time = cpu_get_clock();
757 cur_icount = qemu_get_clock(vm_clock);
758 delta = cur_icount - cur_time;
759 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
760 if (delta > 0
761 && last_delta + ICOUNT_WOBBLE < delta * 2
762 && icount_time_shift > 0) {
763 /* The guest is getting too far ahead. Slow time down. */
764 icount_time_shift--;
766 if (delta < 0
767 && last_delta - ICOUNT_WOBBLE > delta * 2
768 && icount_time_shift < MAX_ICOUNT_SHIFT) {
769 /* The guest is getting too far behind. Speed time up. */
770 icount_time_shift++;
772 last_delta = delta;
773 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
776 static void icount_adjust_rt(void * opaque)
778 qemu_mod_timer(icount_rt_timer,
779 qemu_get_clock(rt_clock) + 1000);
780 icount_adjust();
783 static void icount_adjust_vm(void * opaque)
785 qemu_mod_timer(icount_vm_timer,
786 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
787 icount_adjust();
790 static void init_icount_adjust(void)
792 /* Have both realtime and virtual time triggers for speed adjustment.
793 The realtime trigger catches emulated time passing too slowly,
794 the virtual time trigger catches emulated time passing too fast.
795 Realtime triggers occur even when idle, so use them less frequently
796 than VM triggers. */
797 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
798 qemu_mod_timer(icount_rt_timer,
799 qemu_get_clock(rt_clock) + 1000);
800 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
801 qemu_mod_timer(icount_vm_timer,
802 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
805 static struct qemu_alarm_timer alarm_timers[] = {
806 #ifndef _WIN32
807 #ifdef __linux__
808 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
809 dynticks_stop_timer, dynticks_rearm_timer, NULL},
810 /* HPET - if available - is preferred */
811 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
812 /* ...otherwise try RTC */
813 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
814 #endif
815 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
816 #else
817 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
818 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
819 {"win32", 0, win32_start_timer,
820 win32_stop_timer, NULL, &alarm_win32_data},
821 #endif
822 {NULL, }
825 static void show_available_alarms(void)
827 int i;
829 printf("Available alarm timers, in order of precedence:\n");
830 for (i = 0; alarm_timers[i].name; i++)
831 printf("%s\n", alarm_timers[i].name);
834 static void configure_alarms(char const *opt)
836 int i;
837 int cur = 0;
838 int count = ARRAY_SIZE(alarm_timers) - 1;
839 char *arg;
840 char *name;
841 struct qemu_alarm_timer tmp;
843 if (!strcmp(opt, "?")) {
844 show_available_alarms();
845 exit(0);
848 arg = strdup(opt);
850 /* Reorder the array */
851 name = strtok(arg, ",");
852 while (name) {
853 for (i = 0; i < count && alarm_timers[i].name; i++) {
854 if (!strcmp(alarm_timers[i].name, name))
855 break;
858 if (i == count) {
859 fprintf(stderr, "Unknown clock %s\n", name);
860 goto next;
863 if (i < cur)
864 /* Ignore */
865 goto next;
867 /* Swap */
868 tmp = alarm_timers[i];
869 alarm_timers[i] = alarm_timers[cur];
870 alarm_timers[cur] = tmp;
872 cur++;
873 next:
874 name = strtok(NULL, ",");
877 free(arg);
879 if (cur) {
880 /* Disable remaining timers */
881 for (i = cur; i < count; i++)
882 alarm_timers[i].name = NULL;
883 } else {
884 show_available_alarms();
885 exit(1);
889 QEMUClock *rt_clock;
890 QEMUClock *vm_clock;
892 static QEMUTimer *active_timers[2];
894 static QEMUClock *qemu_new_clock(int type)
896 QEMUClock *clock;
897 clock = qemu_mallocz(sizeof(QEMUClock));
898 clock->type = type;
899 return clock;
902 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
904 QEMUTimer *ts;
906 ts = qemu_mallocz(sizeof(QEMUTimer));
907 ts->clock = clock;
908 ts->cb = cb;
909 ts->opaque = opaque;
910 return ts;
913 void qemu_free_timer(QEMUTimer *ts)
915 qemu_free(ts);
918 /* stop a timer, but do not dealloc it */
919 void qemu_del_timer(QEMUTimer *ts)
921 QEMUTimer **pt, *t;
923 /* NOTE: this code must be signal safe because
924 qemu_timer_expired() can be called from a signal. */
925 pt = &active_timers[ts->clock->type];
926 for(;;) {
927 t = *pt;
928 if (!t)
929 break;
930 if (t == ts) {
931 *pt = t->next;
932 break;
934 pt = &t->next;
938 /* modify the current timer so that it will be fired when current_time
939 >= expire_time. The corresponding callback will be called. */
940 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
942 QEMUTimer **pt, *t;
944 qemu_del_timer(ts);
946 /* add the timer in the sorted list */
947 /* NOTE: this code must be signal safe because
948 qemu_timer_expired() can be called from a signal. */
949 pt = &active_timers[ts->clock->type];
950 for(;;) {
951 t = *pt;
952 if (!t)
953 break;
954 if (t->expire_time > expire_time)
955 break;
956 pt = &t->next;
958 ts->expire_time = expire_time;
959 ts->next = *pt;
960 *pt = ts;
962 /* Rearm if necessary */
963 if (pt == &active_timers[ts->clock->type]) {
964 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
965 qemu_rearm_alarm_timer(alarm_timer);
967 /* Interrupt execution to force deadline recalculation. */
968 if (use_icount)
969 qemu_notify_event();
973 int qemu_timer_pending(QEMUTimer *ts)
975 QEMUTimer *t;
976 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
977 if (t == ts)
978 return 1;
980 return 0;
983 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
985 if (!timer_head)
986 return 0;
987 return (timer_head->expire_time <= current_time);
990 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
992 QEMUTimer *ts;
994 for(;;) {
995 ts = *ptimer_head;
996 if (!ts || ts->expire_time > current_time)
997 break;
998 /* remove timer from the list before calling the callback */
999 *ptimer_head = ts->next;
1000 ts->next = NULL;
1002 /* run the callback (the timer list can be modified) */
1003 ts->cb(ts->opaque);
1007 int64_t qemu_get_clock(QEMUClock *clock)
1009 switch(clock->type) {
1010 case QEMU_TIMER_REALTIME:
1011 return get_clock() / 1000000;
1012 default:
1013 case QEMU_TIMER_VIRTUAL:
1014 if (use_icount) {
1015 return cpu_get_icount();
1016 } else {
1017 return cpu_get_clock();
1022 static void init_timers(void)
1024 init_get_clock();
1025 ticks_per_sec = QEMU_TIMER_BASE;
1026 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1027 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1030 /* save a timer */
1031 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1033 uint64_t expire_time;
1035 if (qemu_timer_pending(ts)) {
1036 expire_time = ts->expire_time;
1037 } else {
1038 expire_time = -1;
1040 qemu_put_be64(f, expire_time);
1043 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1045 uint64_t expire_time;
1047 expire_time = qemu_get_be64(f);
1048 if (expire_time != -1) {
1049 qemu_mod_timer(ts, expire_time);
1050 } else {
1051 qemu_del_timer(ts);
1055 static void timer_save(QEMUFile *f, void *opaque)
1057 if (cpu_ticks_enabled) {
1058 hw_error("cannot save state if virtual timers are running");
1060 qemu_put_be64(f, cpu_ticks_offset);
1061 qemu_put_be64(f, ticks_per_sec);
1062 qemu_put_be64(f, cpu_clock_offset);
1065 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1067 if (version_id != 1 && version_id != 2)
1068 return -EINVAL;
1069 if (cpu_ticks_enabled) {
1070 return -EINVAL;
1072 cpu_ticks_offset=qemu_get_be64(f);
1073 ticks_per_sec=qemu_get_be64(f);
1074 if (version_id == 2) {
1075 cpu_clock_offset=qemu_get_be64(f);
1077 return 0;
1080 static void qemu_event_increment(void);
1082 #ifdef _WIN32
1083 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1084 DWORD_PTR dwUser, DWORD_PTR dw1,
1085 DWORD_PTR dw2)
1086 #else
1087 static void host_alarm_handler(int host_signum)
1088 #endif
1090 #if 0
1091 #define DISP_FREQ 1000
1093 static int64_t delta_min = INT64_MAX;
1094 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1095 static int count;
1096 ti = qemu_get_clock(vm_clock);
1097 if (last_clock != 0) {
1098 delta = ti - last_clock;
1099 if (delta < delta_min)
1100 delta_min = delta;
1101 if (delta > delta_max)
1102 delta_max = delta;
1103 delta_cum += delta;
1104 if (++count == DISP_FREQ) {
1105 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1106 muldiv64(delta_min, 1000000, ticks_per_sec),
1107 muldiv64(delta_max, 1000000, ticks_per_sec),
1108 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1109 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1110 count = 0;
1111 delta_min = INT64_MAX;
1112 delta_max = 0;
1113 delta_cum = 0;
1116 last_clock = ti;
1118 #endif
1119 if (alarm_has_dynticks(alarm_timer) ||
1120 (!use_icount &&
1121 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1122 qemu_get_clock(vm_clock))) ||
1123 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1124 qemu_get_clock(rt_clock))) {
1125 qemu_event_increment();
1126 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1128 #ifndef CONFIG_IOTHREAD
1129 if (next_cpu) {
1130 /* stop the currently executing cpu because a timer occured */
1131 cpu_exit(next_cpu);
1132 #ifdef CONFIG_KQEMU
1133 if (next_cpu->kqemu_enabled) {
1134 kqemu_cpu_interrupt(next_cpu);
1136 #endif
1138 #endif
1139 timer_alarm_pending = 1;
1140 qemu_notify_event();
1144 static int64_t qemu_next_deadline(void)
1146 int64_t delta;
1148 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1149 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1150 qemu_get_clock(vm_clock);
1151 } else {
1152 /* To avoid problems with overflow limit this to 2^32. */
1153 delta = INT32_MAX;
1156 if (delta < 0)
1157 delta = 0;
1159 return delta;
1162 #if defined(__linux__) || defined(_WIN32)
1163 static uint64_t qemu_next_deadline_dyntick(void)
1165 int64_t delta;
1166 int64_t rtdelta;
1168 if (use_icount)
1169 delta = INT32_MAX;
1170 else
1171 delta = (qemu_next_deadline() + 999) / 1000;
1173 if (active_timers[QEMU_TIMER_REALTIME]) {
1174 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1175 qemu_get_clock(rt_clock))*1000;
1176 if (rtdelta < delta)
1177 delta = rtdelta;
1180 if (delta < MIN_TIMER_REARM_US)
1181 delta = MIN_TIMER_REARM_US;
1183 return delta;
1185 #endif
1187 #ifndef _WIN32
1189 /* Sets a specific flag */
1190 static int fcntl_setfl(int fd, int flag)
1192 int flags;
1194 flags = fcntl(fd, F_GETFL);
1195 if (flags == -1)
1196 return -errno;
1198 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1199 return -errno;
1201 return 0;
1204 #if defined(__linux__)
1206 #define RTC_FREQ 1024
1208 static void enable_sigio_timer(int fd)
1210 struct sigaction act;
1212 /* timer signal */
1213 sigfillset(&act.sa_mask);
1214 act.sa_flags = 0;
1215 act.sa_handler = host_alarm_handler;
1217 sigaction(SIGIO, &act, NULL);
1218 fcntl_setfl(fd, O_ASYNC);
1219 fcntl(fd, F_SETOWN, getpid());
1222 static int hpet_start_timer(struct qemu_alarm_timer *t)
1224 struct hpet_info info;
1225 int r, fd;
1227 fd = open("/dev/hpet", O_RDONLY);
1228 if (fd < 0)
1229 return -1;
1231 /* Set frequency */
1232 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1233 if (r < 0) {
1234 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1235 "error, but for better emulation accuracy type:\n"
1236 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1237 goto fail;
1240 /* Check capabilities */
1241 r = ioctl(fd, HPET_INFO, &info);
1242 if (r < 0)
1243 goto fail;
1245 /* Enable periodic mode */
1246 r = ioctl(fd, HPET_EPI, 0);
1247 if (info.hi_flags && (r < 0))
1248 goto fail;
1250 /* Enable interrupt */
1251 r = ioctl(fd, HPET_IE_ON, 0);
1252 if (r < 0)
1253 goto fail;
1255 enable_sigio_timer(fd);
1256 t->priv = (void *)(long)fd;
1258 return 0;
1259 fail:
1260 close(fd);
1261 return -1;
1264 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1266 int fd = (long)t->priv;
1268 close(fd);
1271 static int rtc_start_timer(struct qemu_alarm_timer *t)
1273 int rtc_fd;
1274 unsigned long current_rtc_freq = 0;
1276 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1277 if (rtc_fd < 0)
1278 return -1;
1279 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1280 if (current_rtc_freq != RTC_FREQ &&
1281 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1282 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1283 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1284 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1285 goto fail;
1287 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1288 fail:
1289 close(rtc_fd);
1290 return -1;
1293 enable_sigio_timer(rtc_fd);
1295 t->priv = (void *)(long)rtc_fd;
1297 return 0;
1300 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1302 int rtc_fd = (long)t->priv;
1304 close(rtc_fd);
1307 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1309 struct sigevent ev;
1310 timer_t host_timer;
1311 struct sigaction act;
1313 sigfillset(&act.sa_mask);
1314 act.sa_flags = 0;
1315 act.sa_handler = host_alarm_handler;
1317 sigaction(SIGALRM, &act, NULL);
1320 * Initialize ev struct to 0 to avoid valgrind complaining
1321 * about uninitialized data in timer_create call
1323 memset(&ev, 0, sizeof(ev));
1324 ev.sigev_value.sival_int = 0;
1325 ev.sigev_notify = SIGEV_SIGNAL;
1326 ev.sigev_signo = SIGALRM;
1328 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1329 perror("timer_create");
1331 /* disable dynticks */
1332 fprintf(stderr, "Dynamic Ticks disabled\n");
1334 return -1;
1337 t->priv = (void *)(long)host_timer;
1339 return 0;
1342 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1344 timer_t host_timer = (timer_t)(long)t->priv;
1346 timer_delete(host_timer);
1349 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1351 timer_t host_timer = (timer_t)(long)t->priv;
1352 struct itimerspec timeout;
1353 int64_t nearest_delta_us = INT64_MAX;
1354 int64_t current_us;
1356 if (!active_timers[QEMU_TIMER_REALTIME] &&
1357 !active_timers[QEMU_TIMER_VIRTUAL])
1358 return;
1360 nearest_delta_us = qemu_next_deadline_dyntick();
1362 /* check whether a timer is already running */
1363 if (timer_gettime(host_timer, &timeout)) {
1364 perror("gettime");
1365 fprintf(stderr, "Internal timer error: aborting\n");
1366 exit(1);
1368 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1369 if (current_us && current_us <= nearest_delta_us)
1370 return;
1372 timeout.it_interval.tv_sec = 0;
1373 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1374 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1375 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1376 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1377 perror("settime");
1378 fprintf(stderr, "Internal timer error: aborting\n");
1379 exit(1);
1383 #endif /* defined(__linux__) */
1385 static int unix_start_timer(struct qemu_alarm_timer *t)
1387 struct sigaction act;
1388 struct itimerval itv;
1389 int err;
1391 /* timer signal */
1392 sigfillset(&act.sa_mask);
1393 act.sa_flags = 0;
1394 act.sa_handler = host_alarm_handler;
1396 sigaction(SIGALRM, &act, NULL);
1398 itv.it_interval.tv_sec = 0;
1399 /* for i386 kernel 2.6 to get 1 ms */
1400 itv.it_interval.tv_usec = 999;
1401 itv.it_value.tv_sec = 0;
1402 itv.it_value.tv_usec = 10 * 1000;
1404 err = setitimer(ITIMER_REAL, &itv, NULL);
1405 if (err)
1406 return -1;
1408 return 0;
1411 static void unix_stop_timer(struct qemu_alarm_timer *t)
1413 struct itimerval itv;
1415 memset(&itv, 0, sizeof(itv));
1416 setitimer(ITIMER_REAL, &itv, NULL);
1419 #endif /* !defined(_WIN32) */
1422 #ifdef _WIN32
1424 static int win32_start_timer(struct qemu_alarm_timer *t)
1426 TIMECAPS tc;
1427 struct qemu_alarm_win32 *data = t->priv;
1428 UINT flags;
1430 memset(&tc, 0, sizeof(tc));
1431 timeGetDevCaps(&tc, sizeof(tc));
1433 if (data->period < tc.wPeriodMin)
1434 data->period = tc.wPeriodMin;
1436 timeBeginPeriod(data->period);
1438 flags = TIME_CALLBACK_FUNCTION;
1439 if (alarm_has_dynticks(t))
1440 flags |= TIME_ONESHOT;
1441 else
1442 flags |= TIME_PERIODIC;
1444 data->timerId = timeSetEvent(1, // interval (ms)
1445 data->period, // resolution
1446 host_alarm_handler, // function
1447 (DWORD)t, // parameter
1448 flags);
1450 if (!data->timerId) {
1451 perror("Failed to initialize win32 alarm timer");
1452 timeEndPeriod(data->period);
1453 return -1;
1456 return 0;
1459 static void win32_stop_timer(struct qemu_alarm_timer *t)
1461 struct qemu_alarm_win32 *data = t->priv;
1463 timeKillEvent(data->timerId);
1464 timeEndPeriod(data->period);
1467 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1469 struct qemu_alarm_win32 *data = t->priv;
1470 uint64_t nearest_delta_us;
1472 if (!active_timers[QEMU_TIMER_REALTIME] &&
1473 !active_timers[QEMU_TIMER_VIRTUAL])
1474 return;
1476 nearest_delta_us = qemu_next_deadline_dyntick();
1477 nearest_delta_us /= 1000;
1479 timeKillEvent(data->timerId);
1481 data->timerId = timeSetEvent(1,
1482 data->period,
1483 host_alarm_handler,
1484 (DWORD)t,
1485 TIME_ONESHOT | TIME_PERIODIC);
1487 if (!data->timerId) {
1488 perror("Failed to re-arm win32 alarm timer");
1490 timeEndPeriod(data->period);
1491 exit(1);
1495 #endif /* _WIN32 */
1497 static int init_timer_alarm(void)
1499 struct qemu_alarm_timer *t = NULL;
1500 int i, err = -1;
1502 for (i = 0; alarm_timers[i].name; i++) {
1503 t = &alarm_timers[i];
1505 err = t->start(t);
1506 if (!err)
1507 break;
1510 if (err) {
1511 err = -ENOENT;
1512 goto fail;
1515 alarm_timer = t;
1517 return 0;
1519 fail:
1520 return err;
1523 static void quit_timers(void)
1525 alarm_timer->stop(alarm_timer);
1526 alarm_timer = NULL;
1529 /***********************************************************/
1530 /* host time/date access */
1531 void qemu_get_timedate(struct tm *tm, int offset)
1533 time_t ti;
1534 struct tm *ret;
1536 time(&ti);
1537 ti += offset;
1538 if (rtc_date_offset == -1) {
1539 if (rtc_utc)
1540 ret = gmtime(&ti);
1541 else
1542 ret = localtime(&ti);
1543 } else {
1544 ti -= rtc_date_offset;
1545 ret = gmtime(&ti);
1548 memcpy(tm, ret, sizeof(struct tm));
1551 int qemu_timedate_diff(struct tm *tm)
1553 time_t seconds;
1555 if (rtc_date_offset == -1)
1556 if (rtc_utc)
1557 seconds = mktimegm(tm);
1558 else
1559 seconds = mktime(tm);
1560 else
1561 seconds = mktimegm(tm) + rtc_date_offset;
1563 return seconds - time(NULL);
1566 #ifdef _WIN32
1567 static void socket_cleanup(void)
1569 WSACleanup();
1572 static int socket_init(void)
1574 WSADATA Data;
1575 int ret, err;
1577 ret = WSAStartup(MAKEWORD(2,2), &Data);
1578 if (ret != 0) {
1579 err = WSAGetLastError();
1580 fprintf(stderr, "WSAStartup: %d\n", err);
1581 return -1;
1583 atexit(socket_cleanup);
1584 return 0;
1586 #endif
1588 int get_next_param_value(char *buf, int buf_size,
1589 const char *tag, const char **pstr)
1591 const char *p;
1592 char option[128];
1594 p = *pstr;
1595 for(;;) {
1596 p = get_opt_name(option, sizeof(option), p, '=');
1597 if (*p != '=')
1598 break;
1599 p++;
1600 if (!strcmp(tag, option)) {
1601 *pstr = get_opt_value(buf, buf_size, p);
1602 if (**pstr == ',') {
1603 (*pstr)++;
1605 return strlen(buf);
1606 } else {
1607 p = get_opt_value(NULL, 0, p);
1609 if (*p != ',')
1610 break;
1611 p++;
1613 return 0;
1616 int get_param_value(char *buf, int buf_size,
1617 const char *tag, const char *str)
1619 return get_next_param_value(buf, buf_size, tag, &str);
1622 int check_params(char *buf, int buf_size,
1623 const char * const *params, const char *str)
1625 const char *p;
1626 int i;
1628 p = str;
1629 while (*p != '\0') {
1630 p = get_opt_name(buf, buf_size, p, '=');
1631 if (*p != '=') {
1632 return -1;
1634 p++;
1635 for (i = 0; params[i] != NULL; i++) {
1636 if (!strcmp(params[i], buf)) {
1637 break;
1640 if (params[i] == NULL) {
1641 return -1;
1643 p = get_opt_value(NULL, 0, p);
1644 if (*p != ',') {
1645 break;
1647 p++;
1649 return 0;
1652 /***********************************************************/
1653 /* Bluetooth support */
1654 static int nb_hcis;
1655 static int cur_hci;
1656 static struct HCIInfo *hci_table[MAX_NICS];
1658 static struct bt_vlan_s {
1659 struct bt_scatternet_s net;
1660 int id;
1661 struct bt_vlan_s *next;
1662 } *first_bt_vlan;
1664 /* find or alloc a new bluetooth "VLAN" */
1665 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1667 struct bt_vlan_s **pvlan, *vlan;
1668 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1669 if (vlan->id == id)
1670 return &vlan->net;
1672 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1673 vlan->id = id;
1674 pvlan = &first_bt_vlan;
1675 while (*pvlan != NULL)
1676 pvlan = &(*pvlan)->next;
1677 *pvlan = vlan;
1678 return &vlan->net;
1681 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1685 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1687 return -ENOTSUP;
1690 static struct HCIInfo null_hci = {
1691 .cmd_send = null_hci_send,
1692 .sco_send = null_hci_send,
1693 .acl_send = null_hci_send,
1694 .bdaddr_set = null_hci_addr_set,
1697 struct HCIInfo *qemu_next_hci(void)
1699 if (cur_hci == nb_hcis)
1700 return &null_hci;
1702 return hci_table[cur_hci++];
1705 static struct HCIInfo *hci_init(const char *str)
1707 char *endp;
1708 struct bt_scatternet_s *vlan = 0;
1710 if (!strcmp(str, "null"))
1711 /* null */
1712 return &null_hci;
1713 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1714 /* host[:hciN] */
1715 return bt_host_hci(str[4] ? str + 5 : "hci0");
1716 else if (!strncmp(str, "hci", 3)) {
1717 /* hci[,vlan=n] */
1718 if (str[3]) {
1719 if (!strncmp(str + 3, ",vlan=", 6)) {
1720 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1721 if (*endp)
1722 vlan = 0;
1724 } else
1725 vlan = qemu_find_bt_vlan(0);
1726 if (vlan)
1727 return bt_new_hci(vlan);
1730 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1732 return 0;
1735 static int bt_hci_parse(const char *str)
1737 struct HCIInfo *hci;
1738 bdaddr_t bdaddr;
1740 if (nb_hcis >= MAX_NICS) {
1741 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1742 return -1;
1745 hci = hci_init(str);
1746 if (!hci)
1747 return -1;
1749 bdaddr.b[0] = 0x52;
1750 bdaddr.b[1] = 0x54;
1751 bdaddr.b[2] = 0x00;
1752 bdaddr.b[3] = 0x12;
1753 bdaddr.b[4] = 0x34;
1754 bdaddr.b[5] = 0x56 + nb_hcis;
1755 hci->bdaddr_set(hci, bdaddr.b);
1757 hci_table[nb_hcis++] = hci;
1759 return 0;
1762 static void bt_vhci_add(int vlan_id)
1764 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1766 if (!vlan->slave)
1767 fprintf(stderr, "qemu: warning: adding a VHCI to "
1768 "an empty scatternet %i\n", vlan_id);
1770 bt_vhci_init(bt_new_hci(vlan));
1773 static struct bt_device_s *bt_device_add(const char *opt)
1775 struct bt_scatternet_s *vlan;
1776 int vlan_id = 0;
1777 char *endp = strstr(opt, ",vlan=");
1778 int len = (endp ? endp - opt : strlen(opt)) + 1;
1779 char devname[10];
1781 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1783 if (endp) {
1784 vlan_id = strtol(endp + 6, &endp, 0);
1785 if (*endp) {
1786 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1787 return 0;
1791 vlan = qemu_find_bt_vlan(vlan_id);
1793 if (!vlan->slave)
1794 fprintf(stderr, "qemu: warning: adding a slave device to "
1795 "an empty scatternet %i\n", vlan_id);
1797 if (!strcmp(devname, "keyboard"))
1798 return bt_keyboard_init(vlan);
1800 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1801 return 0;
1804 static int bt_parse(const char *opt)
1806 const char *endp, *p;
1807 int vlan;
1809 if (strstart(opt, "hci", &endp)) {
1810 if (!*endp || *endp == ',') {
1811 if (*endp)
1812 if (!strstart(endp, ",vlan=", 0))
1813 opt = endp + 1;
1815 return bt_hci_parse(opt);
1817 } else if (strstart(opt, "vhci", &endp)) {
1818 if (!*endp || *endp == ',') {
1819 if (*endp) {
1820 if (strstart(endp, ",vlan=", &p)) {
1821 vlan = strtol(p, (char **) &endp, 0);
1822 if (*endp) {
1823 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1824 return 1;
1826 } else {
1827 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1828 return 1;
1830 } else
1831 vlan = 0;
1833 bt_vhci_add(vlan);
1834 return 0;
1836 } else if (strstart(opt, "device:", &endp))
1837 return !bt_device_add(endp);
1839 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1840 return 1;
1843 /***********************************************************/
1844 /* QEMU Block devices */
1846 #define HD_ALIAS "index=%d,media=disk"
1847 #define CDROM_ALIAS "index=2,media=cdrom"
1848 #define FD_ALIAS "index=%d,if=floppy"
1849 #define PFLASH_ALIAS "if=pflash"
1850 #define MTD_ALIAS "if=mtd"
1851 #define SD_ALIAS "index=0,if=sd"
1853 static int drive_opt_get_free_idx(void)
1855 int index;
1857 for (index = 0; index < MAX_DRIVES; index++)
1858 if (!drives_opt[index].used) {
1859 drives_opt[index].used = 1;
1860 return index;
1863 return -1;
1866 static int drive_get_free_idx(void)
1868 int index;
1870 for (index = 0; index < MAX_DRIVES; index++)
1871 if (!drives_table[index].used) {
1872 drives_table[index].used = 1;
1873 return index;
1876 return -1;
1879 int drive_add(const char *file, const char *fmt, ...)
1881 va_list ap;
1882 int index = drive_opt_get_free_idx();
1884 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
1885 fprintf(stderr, "qemu: too many drives\n");
1886 return -1;
1889 drives_opt[index].file = file;
1890 va_start(ap, fmt);
1891 vsnprintf(drives_opt[index].opt,
1892 sizeof(drives_opt[0].opt), fmt, ap);
1893 va_end(ap);
1895 nb_drives_opt++;
1896 return index;
1899 void drive_remove(int index)
1901 drives_opt[index].used = 0;
1902 nb_drives_opt--;
1905 int drive_get_index(BlockInterfaceType type, int bus, int unit)
1907 int index;
1909 /* seek interface, bus and unit */
1911 for (index = 0; index < MAX_DRIVES; index++)
1912 if (drives_table[index].type == type &&
1913 drives_table[index].bus == bus &&
1914 drives_table[index].unit == unit &&
1915 drives_table[index].used)
1916 return index;
1918 return -1;
1921 int drive_get_max_bus(BlockInterfaceType type)
1923 int max_bus;
1924 int index;
1926 max_bus = -1;
1927 for (index = 0; index < nb_drives; index++) {
1928 if(drives_table[index].type == type &&
1929 drives_table[index].bus > max_bus)
1930 max_bus = drives_table[index].bus;
1932 return max_bus;
1935 const char *drive_get_serial(BlockDriverState *bdrv)
1937 int index;
1939 for (index = 0; index < nb_drives; index++)
1940 if (drives_table[index].bdrv == bdrv)
1941 return drives_table[index].serial;
1943 return "\0";
1946 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1948 int index;
1950 for (index = 0; index < nb_drives; index++)
1951 if (drives_table[index].bdrv == bdrv)
1952 return drives_table[index].onerror;
1954 return BLOCK_ERR_STOP_ENOSPC;
1957 static void bdrv_format_print(void *opaque, const char *name)
1959 fprintf(stderr, " %s", name);
1962 void drive_uninit(BlockDriverState *bdrv)
1964 int i;
1966 for (i = 0; i < MAX_DRIVES; i++)
1967 if (drives_table[i].bdrv == bdrv) {
1968 drives_table[i].bdrv = NULL;
1969 drives_table[i].used = 0;
1970 drive_remove(drives_table[i].drive_opt_idx);
1971 nb_drives--;
1972 break;
1976 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
1978 char buf[128];
1979 char file[1024];
1980 char devname[128];
1981 char serial[21];
1982 const char *mediastr = "";
1983 BlockInterfaceType type;
1984 enum { MEDIA_DISK, MEDIA_CDROM } media;
1985 int bus_id, unit_id;
1986 int cyls, heads, secs, translation;
1987 BlockDriverState *bdrv;
1988 BlockDriver *drv = NULL;
1989 QEMUMachine *machine = opaque;
1990 int max_devs;
1991 int index;
1992 int cache;
1993 int bdrv_flags, onerror;
1994 const char *devaddr;
1995 int drives_table_idx;
1996 char *str = arg->opt;
1997 static const char * const params[] = { "bus", "unit", "if", "index",
1998 "cyls", "heads", "secs", "trans",
1999 "media", "snapshot", "file",
2000 "cache", "format", "serial",
2001 "werror", "addr",
2002 NULL };
2004 if (check_params(buf, sizeof(buf), params, str) < 0) {
2005 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2006 buf, str);
2007 return -1;
2010 file[0] = 0;
2011 cyls = heads = secs = 0;
2012 bus_id = 0;
2013 unit_id = -1;
2014 translation = BIOS_ATA_TRANSLATION_AUTO;
2015 index = -1;
2016 cache = 1;
2018 if (machine->use_scsi) {
2019 type = IF_SCSI;
2020 max_devs = MAX_SCSI_DEVS;
2021 pstrcpy(devname, sizeof(devname), "scsi");
2022 } else {
2023 type = IF_IDE;
2024 max_devs = MAX_IDE_DEVS;
2025 pstrcpy(devname, sizeof(devname), "ide");
2027 media = MEDIA_DISK;
2029 /* extract parameters */
2031 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2032 bus_id = strtol(buf, NULL, 0);
2033 if (bus_id < 0) {
2034 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2035 return -1;
2039 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2040 unit_id = strtol(buf, NULL, 0);
2041 if (unit_id < 0) {
2042 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2043 return -1;
2047 if (get_param_value(buf, sizeof(buf), "if", str)) {
2048 pstrcpy(devname, sizeof(devname), buf);
2049 if (!strcmp(buf, "ide")) {
2050 type = IF_IDE;
2051 max_devs = MAX_IDE_DEVS;
2052 } else if (!strcmp(buf, "scsi")) {
2053 type = IF_SCSI;
2054 max_devs = MAX_SCSI_DEVS;
2055 } else if (!strcmp(buf, "floppy")) {
2056 type = IF_FLOPPY;
2057 max_devs = 0;
2058 } else if (!strcmp(buf, "pflash")) {
2059 type = IF_PFLASH;
2060 max_devs = 0;
2061 } else if (!strcmp(buf, "mtd")) {
2062 type = IF_MTD;
2063 max_devs = 0;
2064 } else if (!strcmp(buf, "sd")) {
2065 type = IF_SD;
2066 max_devs = 0;
2067 } else if (!strcmp(buf, "virtio")) {
2068 type = IF_VIRTIO;
2069 max_devs = 0;
2070 } else if (!strcmp(buf, "xen")) {
2071 type = IF_XEN;
2072 max_devs = 0;
2073 } else {
2074 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2075 return -1;
2079 if (get_param_value(buf, sizeof(buf), "index", str)) {
2080 index = strtol(buf, NULL, 0);
2081 if (index < 0) {
2082 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2083 return -1;
2087 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2088 cyls = strtol(buf, NULL, 0);
2091 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2092 heads = strtol(buf, NULL, 0);
2095 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2096 secs = strtol(buf, NULL, 0);
2099 if (cyls || heads || secs) {
2100 if (cyls < 1 || cyls > 16383) {
2101 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2102 return -1;
2104 if (heads < 1 || heads > 16) {
2105 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2106 return -1;
2108 if (secs < 1 || secs > 63) {
2109 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2110 return -1;
2114 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2115 if (!cyls) {
2116 fprintf(stderr,
2117 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2118 str);
2119 return -1;
2121 if (!strcmp(buf, "none"))
2122 translation = BIOS_ATA_TRANSLATION_NONE;
2123 else if (!strcmp(buf, "lba"))
2124 translation = BIOS_ATA_TRANSLATION_LBA;
2125 else if (!strcmp(buf, "auto"))
2126 translation = BIOS_ATA_TRANSLATION_AUTO;
2127 else {
2128 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2129 return -1;
2133 if (get_param_value(buf, sizeof(buf), "media", str)) {
2134 if (!strcmp(buf, "disk")) {
2135 media = MEDIA_DISK;
2136 } else if (!strcmp(buf, "cdrom")) {
2137 if (cyls || secs || heads) {
2138 fprintf(stderr,
2139 "qemu: '%s' invalid physical CHS format\n", str);
2140 return -1;
2142 media = MEDIA_CDROM;
2143 } else {
2144 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2145 return -1;
2149 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2150 if (!strcmp(buf, "on"))
2151 snapshot = 1;
2152 else if (!strcmp(buf, "off"))
2153 snapshot = 0;
2154 else {
2155 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2156 return -1;
2160 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2161 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2162 cache = 0;
2163 else if (!strcmp(buf, "writethrough"))
2164 cache = 1;
2165 else if (!strcmp(buf, "writeback"))
2166 cache = 2;
2167 else {
2168 fprintf(stderr, "qemu: invalid cache option\n");
2169 return -1;
2173 if (get_param_value(buf, sizeof(buf), "format", str)) {
2174 if (strcmp(buf, "?") == 0) {
2175 fprintf(stderr, "qemu: Supported formats:");
2176 bdrv_iterate_format(bdrv_format_print, NULL);
2177 fprintf(stderr, "\n");
2178 return -1;
2180 drv = bdrv_find_format(buf);
2181 if (!drv) {
2182 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2183 return -1;
2187 if (arg->file == NULL)
2188 get_param_value(file, sizeof(file), "file", str);
2189 else
2190 pstrcpy(file, sizeof(file), arg->file);
2192 if (!get_param_value(serial, sizeof(serial), "serial", str))
2193 memset(serial, 0, sizeof(serial));
2195 onerror = BLOCK_ERR_STOP_ENOSPC;
2196 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2197 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2198 fprintf(stderr, "werror is no supported by this format\n");
2199 return -1;
2201 if (!strcmp(buf, "ignore"))
2202 onerror = BLOCK_ERR_IGNORE;
2203 else if (!strcmp(buf, "enospc"))
2204 onerror = BLOCK_ERR_STOP_ENOSPC;
2205 else if (!strcmp(buf, "stop"))
2206 onerror = BLOCK_ERR_STOP_ANY;
2207 else if (!strcmp(buf, "report"))
2208 onerror = BLOCK_ERR_REPORT;
2209 else {
2210 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2211 return -1;
2215 devaddr = NULL;
2216 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2217 if (type != IF_VIRTIO) {
2218 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2219 return -1;
2221 devaddr = strdup(buf);
2224 /* compute bus and unit according index */
2226 if (index != -1) {
2227 if (bus_id != 0 || unit_id != -1) {
2228 fprintf(stderr,
2229 "qemu: '%s' index cannot be used with bus and unit\n", str);
2230 return -1;
2232 if (max_devs == 0)
2234 unit_id = index;
2235 bus_id = 0;
2236 } else {
2237 unit_id = index % max_devs;
2238 bus_id = index / max_devs;
2242 /* if user doesn't specify a unit_id,
2243 * try to find the first free
2246 if (unit_id == -1) {
2247 unit_id = 0;
2248 while (drive_get_index(type, bus_id, unit_id) != -1) {
2249 unit_id++;
2250 if (max_devs && unit_id >= max_devs) {
2251 unit_id -= max_devs;
2252 bus_id++;
2257 /* check unit id */
2259 if (max_devs && unit_id >= max_devs) {
2260 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2261 str, unit_id, max_devs - 1);
2262 return -1;
2266 * ignore multiple definitions
2269 if (drive_get_index(type, bus_id, unit_id) != -1)
2270 return -2;
2272 /* init */
2274 if (type == IF_IDE || type == IF_SCSI)
2275 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2276 if (max_devs)
2277 snprintf(buf, sizeof(buf), "%s%i%s%i",
2278 devname, bus_id, mediastr, unit_id);
2279 else
2280 snprintf(buf, sizeof(buf), "%s%s%i",
2281 devname, mediastr, unit_id);
2282 bdrv = bdrv_new(buf);
2283 drives_table_idx = drive_get_free_idx();
2284 drives_table[drives_table_idx].bdrv = bdrv;
2285 drives_table[drives_table_idx].devaddr = devaddr;
2286 drives_table[drives_table_idx].type = type;
2287 drives_table[drives_table_idx].bus = bus_id;
2288 drives_table[drives_table_idx].unit = unit_id;
2289 drives_table[drives_table_idx].onerror = onerror;
2290 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2291 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2292 nb_drives++;
2294 switch(type) {
2295 case IF_IDE:
2296 case IF_SCSI:
2297 case IF_XEN:
2298 switch(media) {
2299 case MEDIA_DISK:
2300 if (cyls != 0) {
2301 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2302 bdrv_set_translation_hint(bdrv, translation);
2304 break;
2305 case MEDIA_CDROM:
2306 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2307 break;
2309 break;
2310 case IF_SD:
2311 /* FIXME: This isn't really a floppy, but it's a reasonable
2312 approximation. */
2313 case IF_FLOPPY:
2314 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2315 break;
2316 case IF_PFLASH:
2317 case IF_MTD:
2318 case IF_VIRTIO:
2319 break;
2320 case IF_COUNT:
2321 abort();
2323 if (!file[0])
2324 return -2;
2325 bdrv_flags = 0;
2326 if (snapshot) {
2327 bdrv_flags |= BDRV_O_SNAPSHOT;
2328 cache = 2; /* always use write-back with snapshot */
2330 if (cache == 0) /* no caching */
2331 bdrv_flags |= BDRV_O_NOCACHE;
2332 else if (cache == 2) /* write-back */
2333 bdrv_flags |= BDRV_O_CACHE_WB;
2334 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2335 fprintf(stderr, "qemu: could not open disk image %s\n",
2336 file);
2337 return -1;
2339 if (bdrv_key_required(bdrv))
2340 autostart = 0;
2341 return drives_table_idx;
2344 static void numa_add(const char *optarg)
2346 char option[128];
2347 char *endptr;
2348 unsigned long long value, endvalue;
2349 int nodenr;
2351 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2352 if (!strcmp(option, "node")) {
2353 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2354 nodenr = nb_numa_nodes;
2355 } else {
2356 nodenr = strtoull(option, NULL, 10);
2359 if (get_param_value(option, 128, "mem", optarg) == 0) {
2360 node_mem[nodenr] = 0;
2361 } else {
2362 value = strtoull(option, &endptr, 0);
2363 switch (*endptr) {
2364 case 0: case 'M': case 'm':
2365 value <<= 20;
2366 break;
2367 case 'G': case 'g':
2368 value <<= 30;
2369 break;
2371 node_mem[nodenr] = value;
2373 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2374 node_cpumask[nodenr] = 0;
2375 } else {
2376 value = strtoull(option, &endptr, 10);
2377 if (value >= 64) {
2378 value = 63;
2379 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2380 } else {
2381 if (*endptr == '-') {
2382 endvalue = strtoull(endptr+1, &endptr, 10);
2383 if (endvalue >= 63) {
2384 endvalue = 62;
2385 fprintf(stderr,
2386 "only 63 CPUs in NUMA mode supported.\n");
2388 value = (1 << (endvalue + 1)) - (1 << value);
2389 } else {
2390 value = 1 << value;
2393 node_cpumask[nodenr] = value;
2395 nb_numa_nodes++;
2397 return;
2400 /***********************************************************/
2401 /* USB devices */
2403 static USBPort *used_usb_ports;
2404 static USBPort *free_usb_ports;
2406 /* ??? Maybe change this to register a hub to keep track of the topology. */
2407 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2408 usb_attachfn attach)
2410 port->opaque = opaque;
2411 port->index = index;
2412 port->attach = attach;
2413 port->next = free_usb_ports;
2414 free_usb_ports = port;
2417 int usb_device_add_dev(USBDevice *dev)
2419 USBPort *port;
2421 /* Find a USB port to add the device to. */
2422 port = free_usb_ports;
2423 if (!port->next) {
2424 USBDevice *hub;
2426 /* Create a new hub and chain it on. */
2427 free_usb_ports = NULL;
2428 port->next = used_usb_ports;
2429 used_usb_ports = port;
2431 hub = usb_hub_init(VM_USB_HUB_SIZE);
2432 usb_attach(port, hub);
2433 port = free_usb_ports;
2436 free_usb_ports = port->next;
2437 port->next = used_usb_ports;
2438 used_usb_ports = port;
2439 usb_attach(port, dev);
2440 return 0;
2443 static void usb_msd_password_cb(void *opaque, int err)
2445 USBDevice *dev = opaque;
2447 if (!err)
2448 usb_device_add_dev(dev);
2449 else
2450 dev->handle_destroy(dev);
2453 static int usb_device_add(const char *devname, int is_hotplug)
2455 const char *p;
2456 USBDevice *dev;
2458 if (!free_usb_ports)
2459 return -1;
2461 if (strstart(devname, "host:", &p)) {
2462 dev = usb_host_device_open(p);
2463 } else if (!strcmp(devname, "mouse")) {
2464 dev = usb_mouse_init();
2465 } else if (!strcmp(devname, "tablet")) {
2466 dev = usb_tablet_init();
2467 } else if (!strcmp(devname, "keyboard")) {
2468 dev = usb_keyboard_init();
2469 } else if (strstart(devname, "disk:", &p)) {
2470 BlockDriverState *bs;
2472 dev = usb_msd_init(p);
2473 if (!dev)
2474 return -1;
2475 bs = usb_msd_get_bdrv(dev);
2476 if (bdrv_key_required(bs)) {
2477 autostart = 0;
2478 if (is_hotplug) {
2479 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2480 dev);
2481 return 0;
2484 } else if (!strcmp(devname, "wacom-tablet")) {
2485 dev = usb_wacom_init();
2486 } else if (strstart(devname, "serial:", &p)) {
2487 dev = usb_serial_init(p);
2488 #ifdef CONFIG_BRLAPI
2489 } else if (!strcmp(devname, "braille")) {
2490 dev = usb_baum_init();
2491 #endif
2492 } else if (strstart(devname, "net:", &p)) {
2493 int nic = nb_nics;
2495 if (net_client_init(NULL, "nic", p) < 0)
2496 return -1;
2497 nd_table[nic].model = "usb";
2498 dev = usb_net_init(&nd_table[nic]);
2499 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2500 dev = usb_bt_init(devname[2] ? hci_init(p) :
2501 bt_new_hci(qemu_find_bt_vlan(0)));
2502 } else {
2503 return -1;
2505 if (!dev)
2506 return -1;
2508 return usb_device_add_dev(dev);
2511 int usb_device_del_addr(int bus_num, int addr)
2513 USBPort *port;
2514 USBPort **lastp;
2515 USBDevice *dev;
2517 if (!used_usb_ports)
2518 return -1;
2520 if (bus_num != 0)
2521 return -1;
2523 lastp = &used_usb_ports;
2524 port = used_usb_ports;
2525 while (port && port->dev->addr != addr) {
2526 lastp = &port->next;
2527 port = port->next;
2530 if (!port)
2531 return -1;
2533 dev = port->dev;
2534 *lastp = port->next;
2535 usb_attach(port, NULL);
2536 dev->handle_destroy(dev);
2537 port->next = free_usb_ports;
2538 free_usb_ports = port;
2539 return 0;
2542 static int usb_device_del(const char *devname)
2544 int bus_num, addr;
2545 const char *p;
2547 if (strstart(devname, "host:", &p))
2548 return usb_host_device_close(p);
2550 if (!used_usb_ports)
2551 return -1;
2553 p = strchr(devname, '.');
2554 if (!p)
2555 return -1;
2556 bus_num = strtoul(devname, NULL, 0);
2557 addr = strtoul(p + 1, NULL, 0);
2559 return usb_device_del_addr(bus_num, addr);
2562 void do_usb_add(Monitor *mon, const char *devname)
2564 usb_device_add(devname, 1);
2567 void do_usb_del(Monitor *mon, const char *devname)
2569 usb_device_del(devname);
2572 void usb_info(Monitor *mon)
2574 USBDevice *dev;
2575 USBPort *port;
2576 const char *speed_str;
2578 if (!usb_enabled) {
2579 monitor_printf(mon, "USB support not enabled\n");
2580 return;
2583 for (port = used_usb_ports; port; port = port->next) {
2584 dev = port->dev;
2585 if (!dev)
2586 continue;
2587 switch(dev->speed) {
2588 case USB_SPEED_LOW:
2589 speed_str = "1.5";
2590 break;
2591 case USB_SPEED_FULL:
2592 speed_str = "12";
2593 break;
2594 case USB_SPEED_HIGH:
2595 speed_str = "480";
2596 break;
2597 default:
2598 speed_str = "?";
2599 break;
2601 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2602 0, dev->addr, speed_str, dev->devname);
2606 /***********************************************************/
2607 /* PCMCIA/Cardbus */
2609 static struct pcmcia_socket_entry_s {
2610 PCMCIASocket *socket;
2611 struct pcmcia_socket_entry_s *next;
2612 } *pcmcia_sockets = 0;
2614 void pcmcia_socket_register(PCMCIASocket *socket)
2616 struct pcmcia_socket_entry_s *entry;
2618 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2619 entry->socket = socket;
2620 entry->next = pcmcia_sockets;
2621 pcmcia_sockets = entry;
2624 void pcmcia_socket_unregister(PCMCIASocket *socket)
2626 struct pcmcia_socket_entry_s *entry, **ptr;
2628 ptr = &pcmcia_sockets;
2629 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2630 if (entry->socket == socket) {
2631 *ptr = entry->next;
2632 qemu_free(entry);
2636 void pcmcia_info(Monitor *mon)
2638 struct pcmcia_socket_entry_s *iter;
2640 if (!pcmcia_sockets)
2641 monitor_printf(mon, "No PCMCIA sockets\n");
2643 for (iter = pcmcia_sockets; iter; iter = iter->next)
2644 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2645 iter->socket->attached ? iter->socket->card_string :
2646 "Empty");
2649 /***********************************************************/
2650 /* register display */
2652 struct DisplayAllocator default_allocator = {
2653 defaultallocator_create_displaysurface,
2654 defaultallocator_resize_displaysurface,
2655 defaultallocator_free_displaysurface
2658 void register_displaystate(DisplayState *ds)
2660 DisplayState **s;
2661 s = &display_state;
2662 while (*s != NULL)
2663 s = &(*s)->next;
2664 ds->next = NULL;
2665 *s = ds;
2668 DisplayState *get_displaystate(void)
2670 return display_state;
2673 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2675 if(ds->allocator == &default_allocator) ds->allocator = da;
2676 return ds->allocator;
2679 /* dumb display */
2681 static void dumb_display_init(void)
2683 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2684 ds->allocator = &default_allocator;
2685 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2686 register_displaystate(ds);
2689 /***********************************************************/
2690 /* I/O handling */
2692 typedef struct IOHandlerRecord {
2693 int fd;
2694 IOCanRWHandler *fd_read_poll;
2695 IOHandler *fd_read;
2696 IOHandler *fd_write;
2697 int deleted;
2698 void *opaque;
2699 /* temporary data */
2700 struct pollfd *ufd;
2701 struct IOHandlerRecord *next;
2702 } IOHandlerRecord;
2704 static IOHandlerRecord *first_io_handler;
2706 /* XXX: fd_read_poll should be suppressed, but an API change is
2707 necessary in the character devices to suppress fd_can_read(). */
2708 int qemu_set_fd_handler2(int fd,
2709 IOCanRWHandler *fd_read_poll,
2710 IOHandler *fd_read,
2711 IOHandler *fd_write,
2712 void *opaque)
2714 IOHandlerRecord **pioh, *ioh;
2716 if (!fd_read && !fd_write) {
2717 pioh = &first_io_handler;
2718 for(;;) {
2719 ioh = *pioh;
2720 if (ioh == NULL)
2721 break;
2722 if (ioh->fd == fd) {
2723 ioh->deleted = 1;
2724 break;
2726 pioh = &ioh->next;
2728 } else {
2729 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2730 if (ioh->fd == fd)
2731 goto found;
2733 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2734 ioh->next = first_io_handler;
2735 first_io_handler = ioh;
2736 found:
2737 ioh->fd = fd;
2738 ioh->fd_read_poll = fd_read_poll;
2739 ioh->fd_read = fd_read;
2740 ioh->fd_write = fd_write;
2741 ioh->opaque = opaque;
2742 ioh->deleted = 0;
2744 return 0;
2747 int qemu_set_fd_handler(int fd,
2748 IOHandler *fd_read,
2749 IOHandler *fd_write,
2750 void *opaque)
2752 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2755 #ifdef _WIN32
2756 /***********************************************************/
2757 /* Polling handling */
2759 typedef struct PollingEntry {
2760 PollingFunc *func;
2761 void *opaque;
2762 struct PollingEntry *next;
2763 } PollingEntry;
2765 static PollingEntry *first_polling_entry;
2767 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2769 PollingEntry **ppe, *pe;
2770 pe = qemu_mallocz(sizeof(PollingEntry));
2771 pe->func = func;
2772 pe->opaque = opaque;
2773 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2774 *ppe = pe;
2775 return 0;
2778 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2780 PollingEntry **ppe, *pe;
2781 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2782 pe = *ppe;
2783 if (pe->func == func && pe->opaque == opaque) {
2784 *ppe = pe->next;
2785 qemu_free(pe);
2786 break;
2791 /***********************************************************/
2792 /* Wait objects support */
2793 typedef struct WaitObjects {
2794 int num;
2795 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2796 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2797 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2798 } WaitObjects;
2800 static WaitObjects wait_objects = {0};
2802 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2804 WaitObjects *w = &wait_objects;
2806 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2807 return -1;
2808 w->events[w->num] = handle;
2809 w->func[w->num] = func;
2810 w->opaque[w->num] = opaque;
2811 w->num++;
2812 return 0;
2815 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2817 int i, found;
2818 WaitObjects *w = &wait_objects;
2820 found = 0;
2821 for (i = 0; i < w->num; i++) {
2822 if (w->events[i] == handle)
2823 found = 1;
2824 if (found) {
2825 w->events[i] = w->events[i + 1];
2826 w->func[i] = w->func[i + 1];
2827 w->opaque[i] = w->opaque[i + 1];
2830 if (found)
2831 w->num--;
2833 #endif
2835 /***********************************************************/
2836 /* ram save/restore */
2838 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2840 int v;
2842 v = qemu_get_byte(f);
2843 switch(v) {
2844 case 0:
2845 if (qemu_get_buffer(f, buf, len) != len)
2846 return -EIO;
2847 break;
2848 case 1:
2849 v = qemu_get_byte(f);
2850 memset(buf, v, len);
2851 break;
2852 default:
2853 return -EINVAL;
2856 if (qemu_file_has_error(f))
2857 return -EIO;
2859 return 0;
2862 static int ram_load_v1(QEMUFile *f, void *opaque)
2864 int ret;
2865 ram_addr_t i;
2867 if (qemu_get_be32(f) != last_ram_offset)
2868 return -EINVAL;
2869 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2870 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2871 if (ret)
2872 return ret;
2874 return 0;
2877 #define BDRV_HASH_BLOCK_SIZE 1024
2878 #define IOBUF_SIZE 4096
2879 #define RAM_CBLOCK_MAGIC 0xfabe
2881 typedef struct RamDecompressState {
2882 z_stream zstream;
2883 QEMUFile *f;
2884 uint8_t buf[IOBUF_SIZE];
2885 } RamDecompressState;
2887 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2889 int ret;
2890 memset(s, 0, sizeof(*s));
2891 s->f = f;
2892 ret = inflateInit(&s->zstream);
2893 if (ret != Z_OK)
2894 return -1;
2895 return 0;
2898 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2900 int ret, clen;
2902 s->zstream.avail_out = len;
2903 s->zstream.next_out = buf;
2904 while (s->zstream.avail_out > 0) {
2905 if (s->zstream.avail_in == 0) {
2906 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2907 return -1;
2908 clen = qemu_get_be16(s->f);
2909 if (clen > IOBUF_SIZE)
2910 return -1;
2911 qemu_get_buffer(s->f, s->buf, clen);
2912 s->zstream.avail_in = clen;
2913 s->zstream.next_in = s->buf;
2915 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2916 if (ret != Z_OK && ret != Z_STREAM_END) {
2917 return -1;
2920 return 0;
2923 static void ram_decompress_close(RamDecompressState *s)
2925 inflateEnd(&s->zstream);
2928 #define RAM_SAVE_FLAG_FULL 0x01
2929 #define RAM_SAVE_FLAG_COMPRESS 0x02
2930 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2931 #define RAM_SAVE_FLAG_PAGE 0x08
2932 #define RAM_SAVE_FLAG_EOS 0x10
2934 static int is_dup_page(uint8_t *page, uint8_t ch)
2936 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2937 uint32_t *array = (uint32_t *)page;
2938 int i;
2940 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2941 if (array[i] != val)
2942 return 0;
2945 return 1;
2948 static int ram_save_block(QEMUFile *f)
2950 static ram_addr_t current_addr = 0;
2951 ram_addr_t saved_addr = current_addr;
2952 ram_addr_t addr = 0;
2953 int found = 0;
2955 while (addr < last_ram_offset) {
2956 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2957 uint8_t *p;
2959 cpu_physical_memory_reset_dirty(current_addr,
2960 current_addr + TARGET_PAGE_SIZE,
2961 MIGRATION_DIRTY_FLAG);
2963 p = qemu_get_ram_ptr(current_addr);
2965 if (is_dup_page(p, *p)) {
2966 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2967 qemu_put_byte(f, *p);
2968 } else {
2969 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2970 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2973 found = 1;
2974 break;
2976 addr += TARGET_PAGE_SIZE;
2977 current_addr = (saved_addr + addr) % last_ram_offset;
2980 return found;
2983 static uint64_t bytes_transferred = 0;
2985 static ram_addr_t ram_save_remaining(void)
2987 ram_addr_t addr;
2988 ram_addr_t count = 0;
2990 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2991 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2992 count++;
2995 return count;
2998 uint64_t ram_bytes_remaining(void)
3000 return ram_save_remaining() * TARGET_PAGE_SIZE;
3003 uint64_t ram_bytes_transferred(void)
3005 return bytes_transferred;
3008 uint64_t ram_bytes_total(void)
3010 return last_ram_offset;
3013 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3015 ram_addr_t addr;
3016 uint64_t bytes_transferred_last;
3017 double bwidth = 0;
3018 uint64_t expected_time = 0;
3020 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3021 qemu_file_set_error(f);
3022 return 0;
3025 if (stage == 1) {
3026 /* Make sure all dirty bits are set */
3027 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3028 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3029 cpu_physical_memory_set_dirty(addr);
3032 /* Enable dirty memory tracking */
3033 cpu_physical_memory_set_dirty_tracking(1);
3035 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3038 bytes_transferred_last = bytes_transferred;
3039 bwidth = get_clock();
3041 while (!qemu_file_rate_limit(f)) {
3042 int ret;
3044 ret = ram_save_block(f);
3045 bytes_transferred += ret * TARGET_PAGE_SIZE;
3046 if (ret == 0) /* no more blocks */
3047 break;
3050 bwidth = get_clock() - bwidth;
3051 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3053 /* if we haven't transferred anything this round, force expected_time to a
3054 * a very high value, but without crashing */
3055 if (bwidth == 0)
3056 bwidth = 0.000001;
3058 /* try transferring iterative blocks of memory */
3060 if (stage == 3) {
3062 /* flush all remaining blocks regardless of rate limiting */
3063 while (ram_save_block(f) != 0) {
3064 bytes_transferred += TARGET_PAGE_SIZE;
3066 cpu_physical_memory_set_dirty_tracking(0);
3069 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3071 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3073 return (stage == 2) && (expected_time <= migrate_max_downtime());
3076 static int ram_load_dead(QEMUFile *f, void *opaque)
3078 RamDecompressState s1, *s = &s1;
3079 uint8_t buf[10];
3080 ram_addr_t i;
3082 if (ram_decompress_open(s, f) < 0)
3083 return -EINVAL;
3084 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3085 if (ram_decompress_buf(s, buf, 1) < 0) {
3086 fprintf(stderr, "Error while reading ram block header\n");
3087 goto error;
3089 if (buf[0] == 0) {
3090 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3091 BDRV_HASH_BLOCK_SIZE) < 0) {
3092 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3093 goto error;
3095 } else {
3096 error:
3097 printf("Error block header\n");
3098 return -EINVAL;
3101 ram_decompress_close(s);
3103 return 0;
3106 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3108 ram_addr_t addr;
3109 int flags;
3111 if (version_id == 1)
3112 return ram_load_v1(f, opaque);
3114 if (version_id == 2) {
3115 if (qemu_get_be32(f) != last_ram_offset)
3116 return -EINVAL;
3117 return ram_load_dead(f, opaque);
3120 if (version_id != 3)
3121 return -EINVAL;
3123 do {
3124 addr = qemu_get_be64(f);
3126 flags = addr & ~TARGET_PAGE_MASK;
3127 addr &= TARGET_PAGE_MASK;
3129 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3130 if (addr != last_ram_offset)
3131 return -EINVAL;
3134 if (flags & RAM_SAVE_FLAG_FULL) {
3135 if (ram_load_dead(f, opaque) < 0)
3136 return -EINVAL;
3139 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3140 uint8_t ch = qemu_get_byte(f);
3141 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3142 #ifndef _WIN32
3143 if (ch == 0 &&
3144 (!kvm_enabled() || kvm_has_sync_mmu())) {
3145 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3147 #endif
3148 } else if (flags & RAM_SAVE_FLAG_PAGE)
3149 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3150 } while (!(flags & RAM_SAVE_FLAG_EOS));
3152 return 0;
3155 void qemu_service_io(void)
3157 qemu_notify_event();
3160 /***********************************************************/
3161 /* bottom halves (can be seen as timers which expire ASAP) */
3163 struct QEMUBH {
3164 QEMUBHFunc *cb;
3165 void *opaque;
3166 int scheduled;
3167 int idle;
3168 int deleted;
3169 QEMUBH *next;
3172 static QEMUBH *first_bh = NULL;
3174 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3176 QEMUBH *bh;
3177 bh = qemu_mallocz(sizeof(QEMUBH));
3178 bh->cb = cb;
3179 bh->opaque = opaque;
3180 bh->next = first_bh;
3181 first_bh = bh;
3182 return bh;
3185 int qemu_bh_poll(void)
3187 QEMUBH *bh, **bhp;
3188 int ret;
3190 ret = 0;
3191 for (bh = first_bh; bh; bh = bh->next) {
3192 if (!bh->deleted && bh->scheduled) {
3193 bh->scheduled = 0;
3194 if (!bh->idle)
3195 ret = 1;
3196 bh->idle = 0;
3197 bh->cb(bh->opaque);
3201 /* remove deleted bhs */
3202 bhp = &first_bh;
3203 while (*bhp) {
3204 bh = *bhp;
3205 if (bh->deleted) {
3206 *bhp = bh->next;
3207 qemu_free(bh);
3208 } else
3209 bhp = &bh->next;
3212 return ret;
3215 void qemu_bh_schedule_idle(QEMUBH *bh)
3217 if (bh->scheduled)
3218 return;
3219 bh->scheduled = 1;
3220 bh->idle = 1;
3223 void qemu_bh_schedule(QEMUBH *bh)
3225 if (bh->scheduled)
3226 return;
3227 bh->scheduled = 1;
3228 bh->idle = 0;
3229 /* stop the currently executing CPU to execute the BH ASAP */
3230 qemu_notify_event();
3233 void qemu_bh_cancel(QEMUBH *bh)
3235 bh->scheduled = 0;
3238 void qemu_bh_delete(QEMUBH *bh)
3240 bh->scheduled = 0;
3241 bh->deleted = 1;
3244 static void qemu_bh_update_timeout(int *timeout)
3246 QEMUBH *bh;
3248 for (bh = first_bh; bh; bh = bh->next) {
3249 if (!bh->deleted && bh->scheduled) {
3250 if (bh->idle) {
3251 /* idle bottom halves will be polled at least
3252 * every 10ms */
3253 *timeout = MIN(10, *timeout);
3254 } else {
3255 /* non-idle bottom halves will be executed
3256 * immediately */
3257 *timeout = 0;
3258 break;
3264 /***********************************************************/
3265 /* machine registration */
3267 static QEMUMachine *first_machine = NULL;
3268 QEMUMachine *current_machine = NULL;
3270 int qemu_register_machine(QEMUMachine *m)
3272 QEMUMachine **pm;
3273 pm = &first_machine;
3274 while (*pm != NULL)
3275 pm = &(*pm)->next;
3276 m->next = NULL;
3277 *pm = m;
3278 return 0;
3281 static QEMUMachine *find_machine(const char *name)
3283 QEMUMachine *m;
3285 for(m = first_machine; m != NULL; m = m->next) {
3286 if (!strcmp(m->name, name))
3287 return m;
3289 return NULL;
3292 static QEMUMachine *find_default_machine(void)
3294 QEMUMachine *m;
3296 for(m = first_machine; m != NULL; m = m->next) {
3297 if (m->is_default) {
3298 return m;
3301 return NULL;
3304 /***********************************************************/
3305 /* main execution loop */
3307 static void gui_update(void *opaque)
3309 uint64_t interval = GUI_REFRESH_INTERVAL;
3310 DisplayState *ds = opaque;
3311 DisplayChangeListener *dcl = ds->listeners;
3313 dpy_refresh(ds);
3315 while (dcl != NULL) {
3316 if (dcl->gui_timer_interval &&
3317 dcl->gui_timer_interval < interval)
3318 interval = dcl->gui_timer_interval;
3319 dcl = dcl->next;
3321 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3324 static void nographic_update(void *opaque)
3326 uint64_t interval = GUI_REFRESH_INTERVAL;
3328 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3331 struct vm_change_state_entry {
3332 VMChangeStateHandler *cb;
3333 void *opaque;
3334 LIST_ENTRY (vm_change_state_entry) entries;
3337 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3339 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3340 void *opaque)
3342 VMChangeStateEntry *e;
3344 e = qemu_mallocz(sizeof (*e));
3346 e->cb = cb;
3347 e->opaque = opaque;
3348 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3349 return e;
3352 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3354 LIST_REMOVE (e, entries);
3355 qemu_free (e);
3358 static void vm_state_notify(int running, int reason)
3360 VMChangeStateEntry *e;
3362 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3363 e->cb(e->opaque, running, reason);
3367 static void resume_all_vcpus(void);
3368 static void pause_all_vcpus(void);
3370 void vm_start(void)
3372 if (!vm_running) {
3373 cpu_enable_ticks();
3374 vm_running = 1;
3375 vm_state_notify(1, 0);
3376 qemu_rearm_alarm_timer(alarm_timer);
3377 resume_all_vcpus();
3381 /* reset/shutdown handler */
3383 typedef struct QEMUResetEntry {
3384 QEMUResetHandler *func;
3385 void *opaque;
3386 struct QEMUResetEntry *next;
3387 } QEMUResetEntry;
3389 static QEMUResetEntry *first_reset_entry;
3390 static int reset_requested;
3391 static int shutdown_requested;
3392 static int powerdown_requested;
3393 static int debug_requested;
3394 static int vmstop_requested;
3396 int qemu_shutdown_requested(void)
3398 int r = shutdown_requested;
3399 shutdown_requested = 0;
3400 return r;
3403 int qemu_reset_requested(void)
3405 int r = reset_requested;
3406 reset_requested = 0;
3407 return r;
3410 int qemu_powerdown_requested(void)
3412 int r = powerdown_requested;
3413 powerdown_requested = 0;
3414 return r;
3417 static int qemu_debug_requested(void)
3419 int r = debug_requested;
3420 debug_requested = 0;
3421 return r;
3424 static int qemu_vmstop_requested(void)
3426 int r = vmstop_requested;
3427 vmstop_requested = 0;
3428 return r;
3431 static void do_vm_stop(int reason)
3433 if (vm_running) {
3434 cpu_disable_ticks();
3435 vm_running = 0;
3436 pause_all_vcpus();
3437 vm_state_notify(0, reason);
3441 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3443 QEMUResetEntry **pre, *re;
3445 pre = &first_reset_entry;
3446 while (*pre != NULL)
3447 pre = &(*pre)->next;
3448 re = qemu_mallocz(sizeof(QEMUResetEntry));
3449 re->func = func;
3450 re->opaque = opaque;
3451 re->next = NULL;
3452 *pre = re;
3455 void qemu_system_reset(void)
3457 QEMUResetEntry *re;
3459 /* reset all devices */
3460 for(re = first_reset_entry; re != NULL; re = re->next) {
3461 re->func(re->opaque);
3465 void qemu_system_reset_request(void)
3467 if (no_reboot) {
3468 shutdown_requested = 1;
3469 } else {
3470 reset_requested = 1;
3472 qemu_notify_event();
3475 void qemu_system_shutdown_request(void)
3477 shutdown_requested = 1;
3478 qemu_notify_event();
3481 void qemu_system_powerdown_request(void)
3483 powerdown_requested = 1;
3484 qemu_notify_event();
3487 #ifdef CONFIG_IOTHREAD
3488 static void qemu_system_vmstop_request(int reason)
3490 vmstop_requested = reason;
3491 qemu_notify_event();
3493 #endif
3495 #ifndef _WIN32
3496 static int io_thread_fd = -1;
3498 static void qemu_event_increment(void)
3500 static const char byte = 0;
3502 if (io_thread_fd == -1)
3503 return;
3505 write(io_thread_fd, &byte, sizeof(byte));
3508 static void qemu_event_read(void *opaque)
3510 int fd = (unsigned long)opaque;
3511 ssize_t len;
3513 /* Drain the notify pipe */
3514 do {
3515 char buffer[512];
3516 len = read(fd, buffer, sizeof(buffer));
3517 } while ((len == -1 && errno == EINTR) || len > 0);
3520 static int qemu_event_init(void)
3522 int err;
3523 int fds[2];
3525 err = pipe(fds);
3526 if (err == -1)
3527 return -errno;
3529 err = fcntl_setfl(fds[0], O_NONBLOCK);
3530 if (err < 0)
3531 goto fail;
3533 err = fcntl_setfl(fds[1], O_NONBLOCK);
3534 if (err < 0)
3535 goto fail;
3537 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3538 (void *)(unsigned long)fds[0]);
3540 io_thread_fd = fds[1];
3541 return 0;
3543 fail:
3544 close(fds[0]);
3545 close(fds[1]);
3546 return err;
3548 #else
3549 HANDLE qemu_event_handle;
3551 static void dummy_event_handler(void *opaque)
3555 static int qemu_event_init(void)
3557 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3558 if (!qemu_event_handle) {
3559 perror("Failed CreateEvent");
3560 return -1;
3562 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3563 return 0;
3566 static void qemu_event_increment(void)
3568 SetEvent(qemu_event_handle);
3570 #endif
3572 static int cpu_can_run(CPUState *env)
3574 if (env->stop)
3575 return 0;
3576 if (env->stopped)
3577 return 0;
3578 return 1;
3581 #ifndef CONFIG_IOTHREAD
3582 static int qemu_init_main_loop(void)
3584 return qemu_event_init();
3587 void qemu_init_vcpu(void *_env)
3589 CPUState *env = _env;
3591 if (kvm_enabled())
3592 kvm_init_vcpu(env);
3593 return;
3596 int qemu_cpu_self(void *env)
3598 return 1;
3601 static void resume_all_vcpus(void)
3605 static void pause_all_vcpus(void)
3609 void qemu_cpu_kick(void *env)
3611 return;
3614 void qemu_notify_event(void)
3616 CPUState *env = cpu_single_env;
3618 if (env) {
3619 cpu_exit(env);
3620 #ifdef USE_KQEMU
3621 if (env->kqemu_enabled)
3622 kqemu_cpu_interrupt(env);
3623 #endif
3627 #define qemu_mutex_lock_iothread() do { } while (0)
3628 #define qemu_mutex_unlock_iothread() do { } while (0)
3630 void vm_stop(int reason)
3632 do_vm_stop(reason);
3635 #else /* CONFIG_IOTHREAD */
3637 #include "qemu-thread.h"
3639 QemuMutex qemu_global_mutex;
3640 static QemuMutex qemu_fair_mutex;
3642 static QemuThread io_thread;
3644 static QemuThread *tcg_cpu_thread;
3645 static QemuCond *tcg_halt_cond;
3647 static int qemu_system_ready;
3648 /* cpu creation */
3649 static QemuCond qemu_cpu_cond;
3650 /* system init */
3651 static QemuCond qemu_system_cond;
3652 static QemuCond qemu_pause_cond;
3654 static void block_io_signals(void);
3655 static void unblock_io_signals(void);
3656 static int tcg_has_work(void);
3658 static int qemu_init_main_loop(void)
3660 int ret;
3662 ret = qemu_event_init();
3663 if (ret)
3664 return ret;
3666 qemu_cond_init(&qemu_pause_cond);
3667 qemu_mutex_init(&qemu_fair_mutex);
3668 qemu_mutex_init(&qemu_global_mutex);
3669 qemu_mutex_lock(&qemu_global_mutex);
3671 unblock_io_signals();
3672 qemu_thread_self(&io_thread);
3674 return 0;
3677 static void qemu_wait_io_event(CPUState *env)
3679 while (!tcg_has_work())
3680 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3682 qemu_mutex_unlock(&qemu_global_mutex);
3685 * Users of qemu_global_mutex can be starved, having no chance
3686 * to acquire it since this path will get to it first.
3687 * So use another lock to provide fairness.
3689 qemu_mutex_lock(&qemu_fair_mutex);
3690 qemu_mutex_unlock(&qemu_fair_mutex);
3692 qemu_mutex_lock(&qemu_global_mutex);
3693 if (env->stop) {
3694 env->stop = 0;
3695 env->stopped = 1;
3696 qemu_cond_signal(&qemu_pause_cond);
3700 static int qemu_cpu_exec(CPUState *env);
3702 static void *kvm_cpu_thread_fn(void *arg)
3704 CPUState *env = arg;
3706 block_io_signals();
3707 qemu_thread_self(env->thread);
3709 /* signal CPU creation */
3710 qemu_mutex_lock(&qemu_global_mutex);
3711 env->created = 1;
3712 qemu_cond_signal(&qemu_cpu_cond);
3714 /* and wait for machine initialization */
3715 while (!qemu_system_ready)
3716 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3718 while (1) {
3719 if (cpu_can_run(env))
3720 qemu_cpu_exec(env);
3721 qemu_wait_io_event(env);
3724 return NULL;
3727 static void tcg_cpu_exec(void);
3729 static void *tcg_cpu_thread_fn(void *arg)
3731 CPUState *env = arg;
3733 block_io_signals();
3734 qemu_thread_self(env->thread);
3736 /* signal CPU creation */
3737 qemu_mutex_lock(&qemu_global_mutex);
3738 for (env = first_cpu; env != NULL; env = env->next_cpu)
3739 env->created = 1;
3740 qemu_cond_signal(&qemu_cpu_cond);
3742 /* and wait for machine initialization */
3743 while (!qemu_system_ready)
3744 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3746 while (1) {
3747 tcg_cpu_exec();
3748 qemu_wait_io_event(cur_cpu);
3751 return NULL;
3754 void qemu_cpu_kick(void *_env)
3756 CPUState *env = _env;
3757 qemu_cond_broadcast(env->halt_cond);
3758 if (kvm_enabled())
3759 qemu_thread_signal(env->thread, SIGUSR1);
3762 int qemu_cpu_self(void *env)
3764 return (cpu_single_env != NULL);
3767 static void cpu_signal(int sig)
3769 if (cpu_single_env)
3770 cpu_exit(cpu_single_env);
3773 static void block_io_signals(void)
3775 sigset_t set;
3776 struct sigaction sigact;
3778 sigemptyset(&set);
3779 sigaddset(&set, SIGUSR2);
3780 sigaddset(&set, SIGIO);
3781 sigaddset(&set, SIGALRM);
3782 pthread_sigmask(SIG_BLOCK, &set, NULL);
3784 sigemptyset(&set);
3785 sigaddset(&set, SIGUSR1);
3786 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3788 memset(&sigact, 0, sizeof(sigact));
3789 sigact.sa_handler = cpu_signal;
3790 sigaction(SIGUSR1, &sigact, NULL);
3793 static void unblock_io_signals(void)
3795 sigset_t set;
3797 sigemptyset(&set);
3798 sigaddset(&set, SIGUSR2);
3799 sigaddset(&set, SIGIO);
3800 sigaddset(&set, SIGALRM);
3801 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3803 sigemptyset(&set);
3804 sigaddset(&set, SIGUSR1);
3805 pthread_sigmask(SIG_BLOCK, &set, NULL);
3808 static void qemu_signal_lock(unsigned int msecs)
3810 qemu_mutex_lock(&qemu_fair_mutex);
3812 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3813 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3814 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3815 break;
3817 qemu_mutex_unlock(&qemu_fair_mutex);
3820 static void qemu_mutex_lock_iothread(void)
3822 if (kvm_enabled()) {
3823 qemu_mutex_lock(&qemu_fair_mutex);
3824 qemu_mutex_lock(&qemu_global_mutex);
3825 qemu_mutex_unlock(&qemu_fair_mutex);
3826 } else
3827 qemu_signal_lock(100);
3830 static void qemu_mutex_unlock_iothread(void)
3832 qemu_mutex_unlock(&qemu_global_mutex);
3835 static int all_vcpus_paused(void)
3837 CPUState *penv = first_cpu;
3839 while (penv) {
3840 if (!penv->stopped)
3841 return 0;
3842 penv = (CPUState *)penv->next_cpu;
3845 return 1;
3848 static void pause_all_vcpus(void)
3850 CPUState *penv = first_cpu;
3852 while (penv) {
3853 penv->stop = 1;
3854 qemu_thread_signal(penv->thread, SIGUSR1);
3855 qemu_cpu_kick(penv);
3856 penv = (CPUState *)penv->next_cpu;
3859 while (!all_vcpus_paused()) {
3860 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3861 penv = first_cpu;
3862 while (penv) {
3863 qemu_thread_signal(penv->thread, SIGUSR1);
3864 penv = (CPUState *)penv->next_cpu;
3869 static void resume_all_vcpus(void)
3871 CPUState *penv = first_cpu;
3873 while (penv) {
3874 penv->stop = 0;
3875 penv->stopped = 0;
3876 qemu_thread_signal(penv->thread, SIGUSR1);
3877 qemu_cpu_kick(penv);
3878 penv = (CPUState *)penv->next_cpu;
3882 static void tcg_init_vcpu(void *_env)
3884 CPUState *env = _env;
3885 /* share a single thread for all cpus with TCG */
3886 if (!tcg_cpu_thread) {
3887 env->thread = qemu_mallocz(sizeof(QemuThread));
3888 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3889 qemu_cond_init(env->halt_cond);
3890 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3891 while (env->created == 0)
3892 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3893 tcg_cpu_thread = env->thread;
3894 tcg_halt_cond = env->halt_cond;
3895 } else {
3896 env->thread = tcg_cpu_thread;
3897 env->halt_cond = tcg_halt_cond;
3901 static void kvm_start_vcpu(CPUState *env)
3903 kvm_init_vcpu(env);
3904 env->thread = qemu_mallocz(sizeof(QemuThread));
3905 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3906 qemu_cond_init(env->halt_cond);
3907 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3908 while (env->created == 0)
3909 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3912 void qemu_init_vcpu(void *_env)
3914 CPUState *env = _env;
3916 if (kvm_enabled())
3917 kvm_start_vcpu(env);
3918 else
3919 tcg_init_vcpu(env);
3922 void qemu_notify_event(void)
3924 qemu_event_increment();
3927 void vm_stop(int reason)
3929 QemuThread me;
3930 qemu_thread_self(&me);
3932 if (!qemu_thread_equal(&me, &io_thread)) {
3933 qemu_system_vmstop_request(reason);
3935 * FIXME: should not return to device code in case
3936 * vm_stop() has been requested.
3938 if (cpu_single_env) {
3939 cpu_exit(cpu_single_env);
3940 cpu_single_env->stop = 1;
3942 return;
3944 do_vm_stop(reason);
3947 #endif
3950 #ifdef _WIN32
3951 static void host_main_loop_wait(int *timeout)
3953 int ret, ret2, i;
3954 PollingEntry *pe;
3957 /* XXX: need to suppress polling by better using win32 events */
3958 ret = 0;
3959 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3960 ret |= pe->func(pe->opaque);
3962 if (ret == 0) {
3963 int err;
3964 WaitObjects *w = &wait_objects;
3966 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3967 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3968 if (w->func[ret - WAIT_OBJECT_0])
3969 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3971 /* Check for additional signaled events */
3972 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3974 /* Check if event is signaled */
3975 ret2 = WaitForSingleObject(w->events[i], 0);
3976 if(ret2 == WAIT_OBJECT_0) {
3977 if (w->func[i])
3978 w->func[i](w->opaque[i]);
3979 } else if (ret2 == WAIT_TIMEOUT) {
3980 } else {
3981 err = GetLastError();
3982 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3985 } else if (ret == WAIT_TIMEOUT) {
3986 } else {
3987 err = GetLastError();
3988 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3992 *timeout = 0;
3994 #else
3995 static void host_main_loop_wait(int *timeout)
3998 #endif
4000 void main_loop_wait(int timeout)
4002 IOHandlerRecord *ioh;
4003 fd_set rfds, wfds, xfds;
4004 int ret, nfds;
4005 struct timeval tv;
4007 qemu_bh_update_timeout(&timeout);
4009 host_main_loop_wait(&timeout);
4011 /* poll any events */
4012 /* XXX: separate device handlers from system ones */
4013 nfds = -1;
4014 FD_ZERO(&rfds);
4015 FD_ZERO(&wfds);
4016 FD_ZERO(&xfds);
4017 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4018 if (ioh->deleted)
4019 continue;
4020 if (ioh->fd_read &&
4021 (!ioh->fd_read_poll ||
4022 ioh->fd_read_poll(ioh->opaque) != 0)) {
4023 FD_SET(ioh->fd, &rfds);
4024 if (ioh->fd > nfds)
4025 nfds = ioh->fd;
4027 if (ioh->fd_write) {
4028 FD_SET(ioh->fd, &wfds);
4029 if (ioh->fd > nfds)
4030 nfds = ioh->fd;
4034 tv.tv_sec = timeout / 1000;
4035 tv.tv_usec = (timeout % 1000) * 1000;
4037 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4039 qemu_mutex_unlock_iothread();
4040 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4041 qemu_mutex_lock_iothread();
4042 if (ret > 0) {
4043 IOHandlerRecord **pioh;
4045 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4046 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4047 ioh->fd_read(ioh->opaque);
4049 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4050 ioh->fd_write(ioh->opaque);
4054 /* remove deleted IO handlers */
4055 pioh = &first_io_handler;
4056 while (*pioh) {
4057 ioh = *pioh;
4058 if (ioh->deleted) {
4059 *pioh = ioh->next;
4060 qemu_free(ioh);
4061 } else
4062 pioh = &ioh->next;
4066 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4068 /* rearm timer, if not periodic */
4069 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4070 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4071 qemu_rearm_alarm_timer(alarm_timer);
4074 /* vm time timers */
4075 if (vm_running) {
4076 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4077 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4078 qemu_get_clock(vm_clock));
4081 /* real time timers */
4082 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4083 qemu_get_clock(rt_clock));
4085 /* Check bottom-halves last in case any of the earlier events triggered
4086 them. */
4087 qemu_bh_poll();
4091 static int qemu_cpu_exec(CPUState *env)
4093 int ret;
4094 #ifdef CONFIG_PROFILER
4095 int64_t ti;
4096 #endif
4098 #ifdef CONFIG_PROFILER
4099 ti = profile_getclock();
4100 #endif
4101 if (use_icount) {
4102 int64_t count;
4103 int decr;
4104 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4105 env->icount_decr.u16.low = 0;
4106 env->icount_extra = 0;
4107 count = qemu_next_deadline();
4108 count = (count + (1 << icount_time_shift) - 1)
4109 >> icount_time_shift;
4110 qemu_icount += count;
4111 decr = (count > 0xffff) ? 0xffff : count;
4112 count -= decr;
4113 env->icount_decr.u16.low = decr;
4114 env->icount_extra = count;
4116 ret = cpu_exec(env);
4117 #ifdef CONFIG_PROFILER
4118 qemu_time += profile_getclock() - ti;
4119 #endif
4120 if (use_icount) {
4121 /* Fold pending instructions back into the
4122 instruction counter, and clear the interrupt flag. */
4123 qemu_icount -= (env->icount_decr.u16.low
4124 + env->icount_extra);
4125 env->icount_decr.u32 = 0;
4126 env->icount_extra = 0;
4128 return ret;
4131 static void tcg_cpu_exec(void)
4133 int ret = 0;
4135 if (next_cpu == NULL)
4136 next_cpu = first_cpu;
4137 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4138 CPUState *env = cur_cpu = next_cpu;
4140 if (!vm_running)
4141 break;
4142 if (timer_alarm_pending) {
4143 timer_alarm_pending = 0;
4144 break;
4146 if (cpu_can_run(env))
4147 ret = qemu_cpu_exec(env);
4148 if (ret == EXCP_DEBUG) {
4149 gdb_set_stop_cpu(env);
4150 debug_requested = 1;
4151 break;
4156 static int cpu_has_work(CPUState *env)
4158 if (env->stop)
4159 return 1;
4160 if (env->stopped)
4161 return 0;
4162 if (!env->halted)
4163 return 1;
4164 if (qemu_cpu_has_work(env))
4165 return 1;
4166 return 0;
4169 static int tcg_has_work(void)
4171 CPUState *env;
4173 for (env = first_cpu; env != NULL; env = env->next_cpu)
4174 if (cpu_has_work(env))
4175 return 1;
4176 return 0;
4179 static int qemu_calculate_timeout(void)
4181 #ifndef CONFIG_IOTHREAD
4182 int timeout;
4184 if (!vm_running)
4185 timeout = 5000;
4186 else if (tcg_has_work())
4187 timeout = 0;
4188 else if (!use_icount)
4189 timeout = 5000;
4190 else {
4191 /* XXX: use timeout computed from timers */
4192 int64_t add;
4193 int64_t delta;
4194 /* Advance virtual time to the next event. */
4195 if (use_icount == 1) {
4196 /* When not using an adaptive execution frequency
4197 we tend to get badly out of sync with real time,
4198 so just delay for a reasonable amount of time. */
4199 delta = 0;
4200 } else {
4201 delta = cpu_get_icount() - cpu_get_clock();
4203 if (delta > 0) {
4204 /* If virtual time is ahead of real time then just
4205 wait for IO. */
4206 timeout = (delta / 1000000) + 1;
4207 } else {
4208 /* Wait for either IO to occur or the next
4209 timer event. */
4210 add = qemu_next_deadline();
4211 /* We advance the timer before checking for IO.
4212 Limit the amount we advance so that early IO
4213 activity won't get the guest too far ahead. */
4214 if (add > 10000000)
4215 add = 10000000;
4216 delta += add;
4217 add = (add + (1 << icount_time_shift) - 1)
4218 >> icount_time_shift;
4219 qemu_icount += add;
4220 timeout = delta / 1000000;
4221 if (timeout < 0)
4222 timeout = 0;
4226 return timeout;
4227 #else /* CONFIG_IOTHREAD */
4228 return 1000;
4229 #endif
4232 static int vm_can_run(void)
4234 if (powerdown_requested)
4235 return 0;
4236 if (reset_requested)
4237 return 0;
4238 if (shutdown_requested)
4239 return 0;
4240 if (debug_requested)
4241 return 0;
4242 return 1;
4245 static void main_loop(void)
4247 int r;
4249 #ifdef CONFIG_IOTHREAD
4250 qemu_system_ready = 1;
4251 qemu_cond_broadcast(&qemu_system_cond);
4252 #endif
4254 for (;;) {
4255 do {
4256 #ifdef CONFIG_PROFILER
4257 int64_t ti;
4258 #endif
4259 #ifndef CONFIG_IOTHREAD
4260 tcg_cpu_exec();
4261 #endif
4262 #ifdef CONFIG_PROFILER
4263 ti = profile_getclock();
4264 #endif
4265 main_loop_wait(qemu_calculate_timeout());
4266 #ifdef CONFIG_PROFILER
4267 dev_time += profile_getclock() - ti;
4268 #endif
4269 } while (vm_can_run());
4271 if (qemu_debug_requested())
4272 vm_stop(EXCP_DEBUG);
4273 if (qemu_shutdown_requested()) {
4274 if (no_shutdown) {
4275 vm_stop(0);
4276 no_shutdown = 0;
4277 } else
4278 break;
4280 if (qemu_reset_requested()) {
4281 pause_all_vcpus();
4282 qemu_system_reset();
4283 resume_all_vcpus();
4285 if (qemu_powerdown_requested())
4286 qemu_system_powerdown();
4287 if ((r = qemu_vmstop_requested()))
4288 vm_stop(r);
4290 pause_all_vcpus();
4293 static void version(void)
4295 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4298 static void help(int exitcode)
4300 version();
4301 printf("usage: %s [options] [disk_image]\n"
4302 "\n"
4303 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4304 "\n"
4305 #define DEF(option, opt_arg, opt_enum, opt_help) \
4306 opt_help
4307 #define DEFHEADING(text) stringify(text) "\n"
4308 #include "qemu-options.h"
4309 #undef DEF
4310 #undef DEFHEADING
4311 #undef GEN_DOCS
4312 "\n"
4313 "During emulation, the following keys are useful:\n"
4314 "ctrl-alt-f toggle full screen\n"
4315 "ctrl-alt-n switch to virtual console 'n'\n"
4316 "ctrl-alt toggle mouse and keyboard grab\n"
4317 "\n"
4318 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4320 "qemu",
4321 DEFAULT_RAM_SIZE,
4322 #ifndef _WIN32
4323 DEFAULT_NETWORK_SCRIPT,
4324 DEFAULT_NETWORK_DOWN_SCRIPT,
4325 #endif
4326 DEFAULT_GDBSTUB_PORT,
4327 "/tmp/qemu.log");
4328 exit(exitcode);
4331 #define HAS_ARG 0x0001
4333 enum {
4334 #define DEF(option, opt_arg, opt_enum, opt_help) \
4335 opt_enum,
4336 #define DEFHEADING(text)
4337 #include "qemu-options.h"
4338 #undef DEF
4339 #undef DEFHEADING
4340 #undef GEN_DOCS
4343 typedef struct QEMUOption {
4344 const char *name;
4345 int flags;
4346 int index;
4347 } QEMUOption;
4349 static const QEMUOption qemu_options[] = {
4350 { "h", 0, QEMU_OPTION_h },
4351 #define DEF(option, opt_arg, opt_enum, opt_help) \
4352 { option, opt_arg, opt_enum },
4353 #define DEFHEADING(text)
4354 #include "qemu-options.h"
4355 #undef DEF
4356 #undef DEFHEADING
4357 #undef GEN_DOCS
4358 { NULL },
4361 #ifdef HAS_AUDIO
4362 struct soundhw soundhw[] = {
4363 #ifdef HAS_AUDIO_CHOICE
4364 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4366 "pcspk",
4367 "PC speaker",
4370 { .init_isa = pcspk_audio_init }
4372 #endif
4374 #ifdef CONFIG_SB16
4376 "sb16",
4377 "Creative Sound Blaster 16",
4380 { .init_isa = SB16_init }
4382 #endif
4384 #ifdef CONFIG_CS4231A
4386 "cs4231a",
4387 "CS4231A",
4390 { .init_isa = cs4231a_init }
4392 #endif
4394 #ifdef CONFIG_ADLIB
4396 "adlib",
4397 #ifdef HAS_YMF262
4398 "Yamaha YMF262 (OPL3)",
4399 #else
4400 "Yamaha YM3812 (OPL2)",
4401 #endif
4404 { .init_isa = Adlib_init }
4406 #endif
4408 #ifdef CONFIG_GUS
4410 "gus",
4411 "Gravis Ultrasound GF1",
4414 { .init_isa = GUS_init }
4416 #endif
4418 #ifdef CONFIG_AC97
4420 "ac97",
4421 "Intel 82801AA AC97 Audio",
4424 { .init_pci = ac97_init }
4426 #endif
4428 #ifdef CONFIG_ES1370
4430 "es1370",
4431 "ENSONIQ AudioPCI ES1370",
4434 { .init_pci = es1370_init }
4436 #endif
4438 #endif /* HAS_AUDIO_CHOICE */
4440 { NULL, NULL, 0, 0, { NULL } }
4443 static void select_soundhw (const char *optarg)
4445 struct soundhw *c;
4447 if (*optarg == '?') {
4448 show_valid_cards:
4450 printf ("Valid sound card names (comma separated):\n");
4451 for (c = soundhw; c->name; ++c) {
4452 printf ("%-11s %s\n", c->name, c->descr);
4454 printf ("\n-soundhw all will enable all of the above\n");
4455 exit (*optarg != '?');
4457 else {
4458 size_t l;
4459 const char *p;
4460 char *e;
4461 int bad_card = 0;
4463 if (!strcmp (optarg, "all")) {
4464 for (c = soundhw; c->name; ++c) {
4465 c->enabled = 1;
4467 return;
4470 p = optarg;
4471 while (*p) {
4472 e = strchr (p, ',');
4473 l = !e ? strlen (p) : (size_t) (e - p);
4475 for (c = soundhw; c->name; ++c) {
4476 if (!strncmp (c->name, p, l)) {
4477 c->enabled = 1;
4478 break;
4482 if (!c->name) {
4483 if (l > 80) {
4484 fprintf (stderr,
4485 "Unknown sound card name (too big to show)\n");
4487 else {
4488 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4489 (int) l, p);
4491 bad_card = 1;
4493 p += l + (e != NULL);
4496 if (bad_card)
4497 goto show_valid_cards;
4500 #endif
4502 static void select_vgahw (const char *p)
4504 const char *opts;
4506 cirrus_vga_enabled = 0;
4507 std_vga_enabled = 0;
4508 vmsvga_enabled = 0;
4509 xenfb_enabled = 0;
4510 if (strstart(p, "std", &opts)) {
4511 std_vga_enabled = 1;
4512 } else if (strstart(p, "cirrus", &opts)) {
4513 cirrus_vga_enabled = 1;
4514 } else if (strstart(p, "vmware", &opts)) {
4515 vmsvga_enabled = 1;
4516 } else if (strstart(p, "xenfb", &opts)) {
4517 xenfb_enabled = 1;
4518 } else if (!strstart(p, "none", &opts)) {
4519 invalid_vga:
4520 fprintf(stderr, "Unknown vga type: %s\n", p);
4521 exit(1);
4523 while (*opts) {
4524 const char *nextopt;
4526 if (strstart(opts, ",retrace=", &nextopt)) {
4527 opts = nextopt;
4528 if (strstart(opts, "dumb", &nextopt))
4529 vga_retrace_method = VGA_RETRACE_DUMB;
4530 else if (strstart(opts, "precise", &nextopt))
4531 vga_retrace_method = VGA_RETRACE_PRECISE;
4532 else goto invalid_vga;
4533 } else goto invalid_vga;
4534 opts = nextopt;
4538 #ifdef TARGET_I386
4539 static int balloon_parse(const char *arg)
4541 char buf[128];
4542 const char *p;
4544 if (!strcmp(arg, "none")) {
4545 virtio_balloon = 0;
4546 } else if (!strncmp(arg, "virtio", 6)) {
4547 virtio_balloon = 1;
4548 if (arg[6] == ',') {
4549 p = arg + 7;
4550 if (get_param_value(buf, sizeof(buf), "addr", p)) {
4551 virtio_balloon_devaddr = strdup(buf);
4554 } else {
4555 return -1;
4557 return 0;
4559 #endif
4561 #ifdef _WIN32
4562 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4564 exit(STATUS_CONTROL_C_EXIT);
4565 return TRUE;
4567 #endif
4569 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4571 int ret;
4573 if(strlen(str) != 36)
4574 return -1;
4576 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4577 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4578 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4580 if(ret != 16)
4581 return -1;
4583 #ifdef TARGET_I386
4584 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4585 #endif
4587 return 0;
4590 #define MAX_NET_CLIENTS 32
4592 #ifndef _WIN32
4594 static void termsig_handler(int signal)
4596 qemu_system_shutdown_request();
4599 static void sigchld_handler(int signal)
4601 waitpid(-1, NULL, WNOHANG);
4604 static void sighandler_setup(void)
4606 struct sigaction act;
4608 memset(&act, 0, sizeof(act));
4609 act.sa_handler = termsig_handler;
4610 sigaction(SIGINT, &act, NULL);
4611 sigaction(SIGHUP, &act, NULL);
4612 sigaction(SIGTERM, &act, NULL);
4614 act.sa_handler = sigchld_handler;
4615 act.sa_flags = SA_NOCLDSTOP;
4616 sigaction(SIGCHLD, &act, NULL);
4619 #endif
4621 #ifdef _WIN32
4622 /* Look for support files in the same directory as the executable. */
4623 static char *find_datadir(const char *argv0)
4625 char *p;
4626 char buf[MAX_PATH];
4627 DWORD len;
4629 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4630 if (len == 0) {
4631 return NULL;
4634 buf[len] = 0;
4635 p = buf + len - 1;
4636 while (p != buf && *p != '\\')
4637 p--;
4638 *p = 0;
4639 if (access(buf, R_OK) == 0) {
4640 return qemu_strdup(buf);
4642 return NULL;
4644 #else /* !_WIN32 */
4646 /* Find a likely location for support files using the location of the binary.
4647 For installed binaries this will be "$bindir/../share/qemu". When
4648 running from the build tree this will be "$bindir/../pc-bios". */
4649 #define SHARE_SUFFIX "/share/qemu"
4650 #define BUILD_SUFFIX "/pc-bios"
4651 static char *find_datadir(const char *argv0)
4653 char *dir;
4654 char *p = NULL;
4655 char *res;
4656 #ifdef PATH_MAX
4657 char buf[PATH_MAX];
4658 #endif
4659 size_t max_len;
4661 #if defined(__linux__)
4663 int len;
4664 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4665 if (len > 0) {
4666 buf[len] = 0;
4667 p = buf;
4670 #elif defined(__FreeBSD__)
4672 int len;
4673 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4674 if (len > 0) {
4675 buf[len] = 0;
4676 p = buf;
4679 #endif
4680 /* If we don't have any way of figuring out the actual executable
4681 location then try argv[0]. */
4682 if (!p) {
4683 #ifdef PATH_MAX
4684 p = buf;
4685 #endif
4686 p = realpath(argv0, p);
4687 if (!p) {
4688 return NULL;
4691 dir = dirname(p);
4692 dir = dirname(dir);
4694 max_len = strlen(dir) +
4695 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4696 res = qemu_mallocz(max_len);
4697 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4698 if (access(res, R_OK)) {
4699 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4700 if (access(res, R_OK)) {
4701 qemu_free(res);
4702 res = NULL;
4705 #ifndef PATH_MAX
4706 free(p);
4707 #endif
4708 return res;
4710 #undef SHARE_SUFFIX
4711 #undef BUILD_SUFFIX
4712 #endif
4714 char *qemu_find_file(int type, const char *name)
4716 int len;
4717 const char *subdir;
4718 char *buf;
4720 /* If name contains path separators then try it as a straight path. */
4721 if ((strchr(name, '/') || strchr(name, '\\'))
4722 && access(name, R_OK) == 0) {
4723 return strdup(name);
4725 switch (type) {
4726 case QEMU_FILE_TYPE_BIOS:
4727 subdir = "";
4728 break;
4729 case QEMU_FILE_TYPE_KEYMAP:
4730 subdir = "keymaps/";
4731 break;
4732 default:
4733 abort();
4735 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4736 buf = qemu_mallocz(len);
4737 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4738 if (access(buf, R_OK)) {
4739 qemu_free(buf);
4740 return NULL;
4742 return buf;
4745 int main(int argc, char **argv, char **envp)
4747 const char *gdbstub_dev = NULL;
4748 uint32_t boot_devices_bitmap = 0;
4749 int i;
4750 int snapshot, linux_boot, net_boot;
4751 const char *initrd_filename;
4752 const char *kernel_filename, *kernel_cmdline;
4753 const char *boot_devices = "";
4754 DisplayState *ds;
4755 DisplayChangeListener *dcl;
4756 int cyls, heads, secs, translation;
4757 const char *net_clients[MAX_NET_CLIENTS];
4758 int nb_net_clients;
4759 const char *bt_opts[MAX_BT_CMDLINE];
4760 int nb_bt_opts;
4761 int hda_index;
4762 int optind;
4763 const char *r, *optarg;
4764 CharDriverState *monitor_hd = NULL;
4765 const char *monitor_device;
4766 const char *serial_devices[MAX_SERIAL_PORTS];
4767 int serial_device_index;
4768 const char *parallel_devices[MAX_PARALLEL_PORTS];
4769 int parallel_device_index;
4770 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4771 int virtio_console_index;
4772 const char *loadvm = NULL;
4773 QEMUMachine *machine;
4774 const char *cpu_model;
4775 const char *usb_devices[MAX_USB_CMDLINE];
4776 int usb_devices_index;
4777 #ifndef _WIN32
4778 int fds[2];
4779 #endif
4780 int tb_size;
4781 const char *pid_file = NULL;
4782 const char *incoming = NULL;
4783 #ifndef _WIN32
4784 int fd = 0;
4785 struct passwd *pwd = NULL;
4786 const char *chroot_dir = NULL;
4787 const char *run_as = NULL;
4788 #endif
4789 CPUState *env;
4790 int show_vnc_port = 0;
4792 qemu_cache_utils_init(envp);
4794 LIST_INIT (&vm_change_state_head);
4795 #ifndef _WIN32
4797 struct sigaction act;
4798 sigfillset(&act.sa_mask);
4799 act.sa_flags = 0;
4800 act.sa_handler = SIG_IGN;
4801 sigaction(SIGPIPE, &act, NULL);
4803 #else
4804 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4805 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4806 QEMU to run on a single CPU */
4808 HANDLE h;
4809 DWORD mask, smask;
4810 int i;
4811 h = GetCurrentProcess();
4812 if (GetProcessAffinityMask(h, &mask, &smask)) {
4813 for(i = 0; i < 32; i++) {
4814 if (mask & (1 << i))
4815 break;
4817 if (i != 32) {
4818 mask = 1 << i;
4819 SetProcessAffinityMask(h, mask);
4823 #endif
4825 module_call_init(MODULE_INIT_MACHINE);
4826 machine = find_default_machine();
4827 cpu_model = NULL;
4828 initrd_filename = NULL;
4829 ram_size = 0;
4830 snapshot = 0;
4831 kernel_filename = NULL;
4832 kernel_cmdline = "";
4833 cyls = heads = secs = 0;
4834 translation = BIOS_ATA_TRANSLATION_AUTO;
4835 monitor_device = "vc:80Cx24C";
4837 serial_devices[0] = "vc:80Cx24C";
4838 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4839 serial_devices[i] = NULL;
4840 serial_device_index = 0;
4842 parallel_devices[0] = "vc:80Cx24C";
4843 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4844 parallel_devices[i] = NULL;
4845 parallel_device_index = 0;
4847 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4848 virtio_consoles[i] = NULL;
4849 virtio_console_index = 0;
4851 for (i = 0; i < MAX_NODES; i++) {
4852 node_mem[i] = 0;
4853 node_cpumask[i] = 0;
4856 usb_devices_index = 0;
4858 nb_net_clients = 0;
4859 nb_bt_opts = 0;
4860 nb_drives = 0;
4861 nb_drives_opt = 0;
4862 nb_numa_nodes = 0;
4863 hda_index = -1;
4865 nb_nics = 0;
4867 tb_size = 0;
4868 autostart= 1;
4870 register_watchdogs();
4872 optind = 1;
4873 for(;;) {
4874 if (optind >= argc)
4875 break;
4876 r = argv[optind];
4877 if (r[0] != '-') {
4878 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4879 } else {
4880 const QEMUOption *popt;
4882 optind++;
4883 /* Treat --foo the same as -foo. */
4884 if (r[1] == '-')
4885 r++;
4886 popt = qemu_options;
4887 for(;;) {
4888 if (!popt->name) {
4889 fprintf(stderr, "%s: invalid option -- '%s'\n",
4890 argv[0], r);
4891 exit(1);
4893 if (!strcmp(popt->name, r + 1))
4894 break;
4895 popt++;
4897 if (popt->flags & HAS_ARG) {
4898 if (optind >= argc) {
4899 fprintf(stderr, "%s: option '%s' requires an argument\n",
4900 argv[0], r);
4901 exit(1);
4903 optarg = argv[optind++];
4904 } else {
4905 optarg = NULL;
4908 switch(popt->index) {
4909 case QEMU_OPTION_M:
4910 machine = find_machine(optarg);
4911 if (!machine) {
4912 QEMUMachine *m;
4913 printf("Supported machines are:\n");
4914 for(m = first_machine; m != NULL; m = m->next) {
4915 printf("%-10s %s%s\n",
4916 m->name, m->desc,
4917 m->is_default ? " (default)" : "");
4919 exit(*optarg != '?');
4921 break;
4922 case QEMU_OPTION_cpu:
4923 /* hw initialization will check this */
4924 if (*optarg == '?') {
4925 /* XXX: implement xxx_cpu_list for targets that still miss it */
4926 #if defined(cpu_list)
4927 cpu_list(stdout, &fprintf);
4928 #endif
4929 exit(0);
4930 } else {
4931 cpu_model = optarg;
4933 break;
4934 case QEMU_OPTION_initrd:
4935 initrd_filename = optarg;
4936 break;
4937 case QEMU_OPTION_hda:
4938 if (cyls == 0)
4939 hda_index = drive_add(optarg, HD_ALIAS, 0);
4940 else
4941 hda_index = drive_add(optarg, HD_ALIAS
4942 ",cyls=%d,heads=%d,secs=%d%s",
4943 0, cyls, heads, secs,
4944 translation == BIOS_ATA_TRANSLATION_LBA ?
4945 ",trans=lba" :
4946 translation == BIOS_ATA_TRANSLATION_NONE ?
4947 ",trans=none" : "");
4948 break;
4949 case QEMU_OPTION_hdb:
4950 case QEMU_OPTION_hdc:
4951 case QEMU_OPTION_hdd:
4952 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4953 break;
4954 case QEMU_OPTION_drive:
4955 drive_add(NULL, "%s", optarg);
4956 break;
4957 case QEMU_OPTION_mtdblock:
4958 drive_add(optarg, MTD_ALIAS);
4959 break;
4960 case QEMU_OPTION_sd:
4961 drive_add(optarg, SD_ALIAS);
4962 break;
4963 case QEMU_OPTION_pflash:
4964 drive_add(optarg, PFLASH_ALIAS);
4965 break;
4966 case QEMU_OPTION_snapshot:
4967 snapshot = 1;
4968 break;
4969 case QEMU_OPTION_hdachs:
4971 const char *p;
4972 p = optarg;
4973 cyls = strtol(p, (char **)&p, 0);
4974 if (cyls < 1 || cyls > 16383)
4975 goto chs_fail;
4976 if (*p != ',')
4977 goto chs_fail;
4978 p++;
4979 heads = strtol(p, (char **)&p, 0);
4980 if (heads < 1 || heads > 16)
4981 goto chs_fail;
4982 if (*p != ',')
4983 goto chs_fail;
4984 p++;
4985 secs = strtol(p, (char **)&p, 0);
4986 if (secs < 1 || secs > 63)
4987 goto chs_fail;
4988 if (*p == ',') {
4989 p++;
4990 if (!strcmp(p, "none"))
4991 translation = BIOS_ATA_TRANSLATION_NONE;
4992 else if (!strcmp(p, "lba"))
4993 translation = BIOS_ATA_TRANSLATION_LBA;
4994 else if (!strcmp(p, "auto"))
4995 translation = BIOS_ATA_TRANSLATION_AUTO;
4996 else
4997 goto chs_fail;
4998 } else if (*p != '\0') {
4999 chs_fail:
5000 fprintf(stderr, "qemu: invalid physical CHS format\n");
5001 exit(1);
5003 if (hda_index != -1)
5004 snprintf(drives_opt[hda_index].opt,
5005 sizeof(drives_opt[hda_index].opt),
5006 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5007 0, cyls, heads, secs,
5008 translation == BIOS_ATA_TRANSLATION_LBA ?
5009 ",trans=lba" :
5010 translation == BIOS_ATA_TRANSLATION_NONE ?
5011 ",trans=none" : "");
5013 break;
5014 case QEMU_OPTION_numa:
5015 if (nb_numa_nodes >= MAX_NODES) {
5016 fprintf(stderr, "qemu: too many NUMA nodes\n");
5017 exit(1);
5019 numa_add(optarg);
5020 break;
5021 case QEMU_OPTION_nographic:
5022 display_type = DT_NOGRAPHIC;
5023 break;
5024 #ifdef CONFIG_CURSES
5025 case QEMU_OPTION_curses:
5026 display_type = DT_CURSES;
5027 break;
5028 #endif
5029 case QEMU_OPTION_portrait:
5030 graphic_rotate = 1;
5031 break;
5032 case QEMU_OPTION_kernel:
5033 kernel_filename = optarg;
5034 break;
5035 case QEMU_OPTION_append:
5036 kernel_cmdline = optarg;
5037 break;
5038 case QEMU_OPTION_cdrom:
5039 drive_add(optarg, CDROM_ALIAS);
5040 break;
5041 case QEMU_OPTION_boot:
5042 boot_devices = optarg;
5043 /* We just do some generic consistency checks */
5045 /* Could easily be extended to 64 devices if needed */
5046 const char *p;
5048 boot_devices_bitmap = 0;
5049 for (p = boot_devices; *p != '\0'; p++) {
5050 /* Allowed boot devices are:
5051 * a b : floppy disk drives
5052 * c ... f : IDE disk drives
5053 * g ... m : machine implementation dependant drives
5054 * n ... p : network devices
5055 * It's up to each machine implementation to check
5056 * if the given boot devices match the actual hardware
5057 * implementation and firmware features.
5059 if (*p < 'a' || *p > 'q') {
5060 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5061 exit(1);
5063 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5064 fprintf(stderr,
5065 "Boot device '%c' was given twice\n",*p);
5066 exit(1);
5068 boot_devices_bitmap |= 1 << (*p - 'a');
5071 break;
5072 case QEMU_OPTION_fda:
5073 case QEMU_OPTION_fdb:
5074 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5075 break;
5076 #ifdef TARGET_I386
5077 case QEMU_OPTION_no_fd_bootchk:
5078 fd_bootchk = 0;
5079 break;
5080 #endif
5081 case QEMU_OPTION_net:
5082 if (nb_net_clients >= MAX_NET_CLIENTS) {
5083 fprintf(stderr, "qemu: too many network clients\n");
5084 exit(1);
5086 net_clients[nb_net_clients] = optarg;
5087 nb_net_clients++;
5088 break;
5089 #ifdef CONFIG_SLIRP
5090 case QEMU_OPTION_tftp:
5091 legacy_tftp_prefix = optarg;
5092 break;
5093 case QEMU_OPTION_bootp:
5094 legacy_bootp_filename = optarg;
5095 break;
5096 #ifndef _WIN32
5097 case QEMU_OPTION_smb:
5098 net_slirp_smb(optarg);
5099 break;
5100 #endif
5101 case QEMU_OPTION_redir:
5102 net_slirp_redir(optarg);
5103 break;
5104 #endif
5105 case QEMU_OPTION_bt:
5106 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5107 fprintf(stderr, "qemu: too many bluetooth options\n");
5108 exit(1);
5110 bt_opts[nb_bt_opts++] = optarg;
5111 break;
5112 #ifdef HAS_AUDIO
5113 case QEMU_OPTION_audio_help:
5114 AUD_help ();
5115 exit (0);
5116 break;
5117 case QEMU_OPTION_soundhw:
5118 select_soundhw (optarg);
5119 break;
5120 #endif
5121 case QEMU_OPTION_h:
5122 help(0);
5123 break;
5124 case QEMU_OPTION_version:
5125 version();
5126 exit(0);
5127 break;
5128 case QEMU_OPTION_m: {
5129 uint64_t value;
5130 char *ptr;
5132 value = strtoul(optarg, &ptr, 10);
5133 switch (*ptr) {
5134 case 0: case 'M': case 'm':
5135 value <<= 20;
5136 break;
5137 case 'G': case 'g':
5138 value <<= 30;
5139 break;
5140 default:
5141 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5142 exit(1);
5145 /* On 32-bit hosts, QEMU is limited by virtual address space */
5146 if (value > (2047 << 20)
5147 #ifndef CONFIG_KQEMU
5148 && HOST_LONG_BITS == 32
5149 #endif
5151 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5152 exit(1);
5154 if (value != (uint64_t)(ram_addr_t)value) {
5155 fprintf(stderr, "qemu: ram size too large\n");
5156 exit(1);
5158 ram_size = value;
5159 break;
5161 case QEMU_OPTION_d:
5163 int mask;
5164 const CPULogItem *item;
5166 mask = cpu_str_to_log_mask(optarg);
5167 if (!mask) {
5168 printf("Log items (comma separated):\n");
5169 for(item = cpu_log_items; item->mask != 0; item++) {
5170 printf("%-10s %s\n", item->name, item->help);
5172 exit(1);
5174 cpu_set_log(mask);
5176 break;
5177 case QEMU_OPTION_s:
5178 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5179 break;
5180 case QEMU_OPTION_gdb:
5181 gdbstub_dev = optarg;
5182 break;
5183 case QEMU_OPTION_L:
5184 data_dir = optarg;
5185 break;
5186 case QEMU_OPTION_bios:
5187 bios_name = optarg;
5188 break;
5189 case QEMU_OPTION_singlestep:
5190 singlestep = 1;
5191 break;
5192 case QEMU_OPTION_S:
5193 autostart = 0;
5194 break;
5195 #ifndef _WIN32
5196 case QEMU_OPTION_k:
5197 keyboard_layout = optarg;
5198 break;
5199 #endif
5200 case QEMU_OPTION_localtime:
5201 rtc_utc = 0;
5202 break;
5203 case QEMU_OPTION_vga:
5204 select_vgahw (optarg);
5205 break;
5206 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5207 case QEMU_OPTION_g:
5209 const char *p;
5210 int w, h, depth;
5211 p = optarg;
5212 w = strtol(p, (char **)&p, 10);
5213 if (w <= 0) {
5214 graphic_error:
5215 fprintf(stderr, "qemu: invalid resolution or depth\n");
5216 exit(1);
5218 if (*p != 'x')
5219 goto graphic_error;
5220 p++;
5221 h = strtol(p, (char **)&p, 10);
5222 if (h <= 0)
5223 goto graphic_error;
5224 if (*p == 'x') {
5225 p++;
5226 depth = strtol(p, (char **)&p, 10);
5227 if (depth != 8 && depth != 15 && depth != 16 &&
5228 depth != 24 && depth != 32)
5229 goto graphic_error;
5230 } else if (*p == '\0') {
5231 depth = graphic_depth;
5232 } else {
5233 goto graphic_error;
5236 graphic_width = w;
5237 graphic_height = h;
5238 graphic_depth = depth;
5240 break;
5241 #endif
5242 case QEMU_OPTION_echr:
5244 char *r;
5245 term_escape_char = strtol(optarg, &r, 0);
5246 if (r == optarg)
5247 printf("Bad argument to echr\n");
5248 break;
5250 case QEMU_OPTION_monitor:
5251 monitor_device = optarg;
5252 break;
5253 case QEMU_OPTION_serial:
5254 if (serial_device_index >= MAX_SERIAL_PORTS) {
5255 fprintf(stderr, "qemu: too many serial ports\n");
5256 exit(1);
5258 serial_devices[serial_device_index] = optarg;
5259 serial_device_index++;
5260 break;
5261 case QEMU_OPTION_watchdog:
5262 i = select_watchdog(optarg);
5263 if (i > 0)
5264 exit (i == 1 ? 1 : 0);
5265 break;
5266 case QEMU_OPTION_watchdog_action:
5267 if (select_watchdog_action(optarg) == -1) {
5268 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5269 exit(1);
5271 break;
5272 case QEMU_OPTION_virtiocon:
5273 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5274 fprintf(stderr, "qemu: too many virtio consoles\n");
5275 exit(1);
5277 virtio_consoles[virtio_console_index] = optarg;
5278 virtio_console_index++;
5279 break;
5280 case QEMU_OPTION_parallel:
5281 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5282 fprintf(stderr, "qemu: too many parallel ports\n");
5283 exit(1);
5285 parallel_devices[parallel_device_index] = optarg;
5286 parallel_device_index++;
5287 break;
5288 case QEMU_OPTION_loadvm:
5289 loadvm = optarg;
5290 break;
5291 case QEMU_OPTION_full_screen:
5292 full_screen = 1;
5293 break;
5294 #ifdef CONFIG_SDL
5295 case QEMU_OPTION_no_frame:
5296 no_frame = 1;
5297 break;
5298 case QEMU_OPTION_alt_grab:
5299 alt_grab = 1;
5300 break;
5301 case QEMU_OPTION_no_quit:
5302 no_quit = 1;
5303 break;
5304 case QEMU_OPTION_sdl:
5305 display_type = DT_SDL;
5306 break;
5307 #endif
5308 case QEMU_OPTION_pidfile:
5309 pid_file = optarg;
5310 break;
5311 #ifdef TARGET_I386
5312 case QEMU_OPTION_win2k_hack:
5313 win2k_install_hack = 1;
5314 break;
5315 case QEMU_OPTION_rtc_td_hack:
5316 rtc_td_hack = 1;
5317 break;
5318 case QEMU_OPTION_acpitable:
5319 if(acpi_table_add(optarg) < 0) {
5320 fprintf(stderr, "Wrong acpi table provided\n");
5321 exit(1);
5323 break;
5324 case QEMU_OPTION_smbios:
5325 if(smbios_entry_add(optarg) < 0) {
5326 fprintf(stderr, "Wrong smbios provided\n");
5327 exit(1);
5329 break;
5330 #endif
5331 #ifdef CONFIG_KQEMU
5332 case QEMU_OPTION_no_kqemu:
5333 kqemu_allowed = 0;
5334 break;
5335 case QEMU_OPTION_kernel_kqemu:
5336 kqemu_allowed = 2;
5337 break;
5338 #endif
5339 #ifdef CONFIG_KVM
5340 case QEMU_OPTION_enable_kvm:
5341 kvm_allowed = 1;
5342 #ifdef CONFIG_KQEMU
5343 kqemu_allowed = 0;
5344 #endif
5345 break;
5346 #endif
5347 case QEMU_OPTION_usb:
5348 usb_enabled = 1;
5349 break;
5350 case QEMU_OPTION_usbdevice:
5351 usb_enabled = 1;
5352 if (usb_devices_index >= MAX_USB_CMDLINE) {
5353 fprintf(stderr, "Too many USB devices\n");
5354 exit(1);
5356 usb_devices[usb_devices_index] = optarg;
5357 usb_devices_index++;
5358 break;
5359 case QEMU_OPTION_smp:
5360 smp_cpus = atoi(optarg);
5361 if (smp_cpus < 1) {
5362 fprintf(stderr, "Invalid number of CPUs\n");
5363 exit(1);
5365 break;
5366 case QEMU_OPTION_vnc:
5367 display_type = DT_VNC;
5368 vnc_display = optarg;
5369 break;
5370 #ifdef TARGET_I386
5371 case QEMU_OPTION_no_acpi:
5372 acpi_enabled = 0;
5373 break;
5374 case QEMU_OPTION_no_hpet:
5375 no_hpet = 1;
5376 break;
5377 case QEMU_OPTION_balloon:
5378 if (balloon_parse(optarg) < 0) {
5379 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5380 exit(1);
5382 break;
5383 #endif
5384 case QEMU_OPTION_no_reboot:
5385 no_reboot = 1;
5386 break;
5387 case QEMU_OPTION_no_shutdown:
5388 no_shutdown = 1;
5389 break;
5390 case QEMU_OPTION_show_cursor:
5391 cursor_hide = 0;
5392 break;
5393 case QEMU_OPTION_uuid:
5394 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5395 fprintf(stderr, "Fail to parse UUID string."
5396 " Wrong format.\n");
5397 exit(1);
5399 break;
5400 #ifndef _WIN32
5401 case QEMU_OPTION_daemonize:
5402 daemonize = 1;
5403 break;
5404 #endif
5405 case QEMU_OPTION_option_rom:
5406 if (nb_option_roms >= MAX_OPTION_ROMS) {
5407 fprintf(stderr, "Too many option ROMs\n");
5408 exit(1);
5410 option_rom[nb_option_roms] = optarg;
5411 nb_option_roms++;
5412 break;
5413 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5414 case QEMU_OPTION_semihosting:
5415 semihosting_enabled = 1;
5416 break;
5417 #endif
5418 case QEMU_OPTION_name:
5419 qemu_name = optarg;
5420 break;
5421 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5422 case QEMU_OPTION_prom_env:
5423 if (nb_prom_envs >= MAX_PROM_ENVS) {
5424 fprintf(stderr, "Too many prom variables\n");
5425 exit(1);
5427 prom_envs[nb_prom_envs] = optarg;
5428 nb_prom_envs++;
5429 break;
5430 #endif
5431 #ifdef TARGET_ARM
5432 case QEMU_OPTION_old_param:
5433 old_param = 1;
5434 break;
5435 #endif
5436 case QEMU_OPTION_clock:
5437 configure_alarms(optarg);
5438 break;
5439 case QEMU_OPTION_startdate:
5441 struct tm tm;
5442 time_t rtc_start_date;
5443 if (!strcmp(optarg, "now")) {
5444 rtc_date_offset = -1;
5445 } else {
5446 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5447 &tm.tm_year,
5448 &tm.tm_mon,
5449 &tm.tm_mday,
5450 &tm.tm_hour,
5451 &tm.tm_min,
5452 &tm.tm_sec) == 6) {
5453 /* OK */
5454 } else if (sscanf(optarg, "%d-%d-%d",
5455 &tm.tm_year,
5456 &tm.tm_mon,
5457 &tm.tm_mday) == 3) {
5458 tm.tm_hour = 0;
5459 tm.tm_min = 0;
5460 tm.tm_sec = 0;
5461 } else {
5462 goto date_fail;
5464 tm.tm_year -= 1900;
5465 tm.tm_mon--;
5466 rtc_start_date = mktimegm(&tm);
5467 if (rtc_start_date == -1) {
5468 date_fail:
5469 fprintf(stderr, "Invalid date format. Valid format are:\n"
5470 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5471 exit(1);
5473 rtc_date_offset = time(NULL) - rtc_start_date;
5476 break;
5477 case QEMU_OPTION_tb_size:
5478 tb_size = strtol(optarg, NULL, 0);
5479 if (tb_size < 0)
5480 tb_size = 0;
5481 break;
5482 case QEMU_OPTION_icount:
5483 use_icount = 1;
5484 if (strcmp(optarg, "auto") == 0) {
5485 icount_time_shift = -1;
5486 } else {
5487 icount_time_shift = strtol(optarg, NULL, 0);
5489 break;
5490 case QEMU_OPTION_incoming:
5491 incoming = optarg;
5492 break;
5493 #ifndef _WIN32
5494 case QEMU_OPTION_chroot:
5495 chroot_dir = optarg;
5496 break;
5497 case QEMU_OPTION_runas:
5498 run_as = optarg;
5499 break;
5500 #endif
5501 #ifdef CONFIG_XEN
5502 case QEMU_OPTION_xen_domid:
5503 xen_domid = atoi(optarg);
5504 break;
5505 case QEMU_OPTION_xen_create:
5506 xen_mode = XEN_CREATE;
5507 break;
5508 case QEMU_OPTION_xen_attach:
5509 xen_mode = XEN_ATTACH;
5510 break;
5511 #endif
5516 /* If no data_dir is specified then try to find it relative to the
5517 executable path. */
5518 if (!data_dir) {
5519 data_dir = find_datadir(argv[0]);
5521 /* If all else fails use the install patch specified when building. */
5522 if (!data_dir) {
5523 data_dir = CONFIG_QEMU_SHAREDIR;
5526 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5527 if (kvm_allowed && kqemu_allowed) {
5528 fprintf(stderr,
5529 "You can not enable both KVM and kqemu at the same time\n");
5530 exit(1);
5532 #endif
5534 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5535 if (smp_cpus > machine->max_cpus) {
5536 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5537 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5538 machine->max_cpus);
5539 exit(1);
5542 if (display_type == DT_NOGRAPHIC) {
5543 if (serial_device_index == 0)
5544 serial_devices[0] = "stdio";
5545 if (parallel_device_index == 0)
5546 parallel_devices[0] = "null";
5547 if (strncmp(monitor_device, "vc", 2) == 0)
5548 monitor_device = "stdio";
5551 #ifndef _WIN32
5552 if (daemonize) {
5553 pid_t pid;
5555 if (pipe(fds) == -1)
5556 exit(1);
5558 pid = fork();
5559 if (pid > 0) {
5560 uint8_t status;
5561 ssize_t len;
5563 close(fds[1]);
5565 again:
5566 len = read(fds[0], &status, 1);
5567 if (len == -1 && (errno == EINTR))
5568 goto again;
5570 if (len != 1)
5571 exit(1);
5572 else if (status == 1) {
5573 fprintf(stderr, "Could not acquire pidfile\n");
5574 exit(1);
5575 } else
5576 exit(0);
5577 } else if (pid < 0)
5578 exit(1);
5580 setsid();
5582 pid = fork();
5583 if (pid > 0)
5584 exit(0);
5585 else if (pid < 0)
5586 exit(1);
5588 umask(027);
5590 signal(SIGTSTP, SIG_IGN);
5591 signal(SIGTTOU, SIG_IGN);
5592 signal(SIGTTIN, SIG_IGN);
5595 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5596 if (daemonize) {
5597 uint8_t status = 1;
5598 write(fds[1], &status, 1);
5599 } else
5600 fprintf(stderr, "Could not acquire pid file\n");
5601 exit(1);
5603 #endif
5605 #ifdef CONFIG_KQEMU
5606 if (smp_cpus > 1)
5607 kqemu_allowed = 0;
5608 #endif
5609 if (qemu_init_main_loop()) {
5610 fprintf(stderr, "qemu_init_main_loop failed\n");
5611 exit(1);
5613 linux_boot = (kernel_filename != NULL);
5615 if (!linux_boot && *kernel_cmdline != '\0') {
5616 fprintf(stderr, "-append only allowed with -kernel option\n");
5617 exit(1);
5620 if (!linux_boot && initrd_filename != NULL) {
5621 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5622 exit(1);
5625 /* boot to floppy or the default cd if no hard disk defined yet */
5626 if (!boot_devices[0]) {
5627 boot_devices = "cad";
5629 setvbuf(stdout, NULL, _IOLBF, 0);
5631 init_timers();
5632 if (init_timer_alarm() < 0) {
5633 fprintf(stderr, "could not initialize alarm timer\n");
5634 exit(1);
5636 if (use_icount && icount_time_shift < 0) {
5637 use_icount = 2;
5638 /* 125MIPS seems a reasonable initial guess at the guest speed.
5639 It will be corrected fairly quickly anyway. */
5640 icount_time_shift = 3;
5641 init_icount_adjust();
5644 #ifdef _WIN32
5645 socket_init();
5646 #endif
5648 /* init network clients */
5649 if (nb_net_clients == 0) {
5650 /* if no clients, we use a default config */
5651 net_clients[nb_net_clients++] = "nic";
5652 #ifdef CONFIG_SLIRP
5653 net_clients[nb_net_clients++] = "user";
5654 #endif
5657 for(i = 0;i < nb_net_clients; i++) {
5658 if (net_client_parse(net_clients[i]) < 0)
5659 exit(1);
5662 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5663 net_set_boot_mask(net_boot);
5665 net_client_check();
5667 /* init the bluetooth world */
5668 for (i = 0; i < nb_bt_opts; i++)
5669 if (bt_parse(bt_opts[i]))
5670 exit(1);
5672 /* init the memory */
5673 if (ram_size == 0)
5674 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5676 #ifdef CONFIG_KQEMU
5677 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5678 guest ram allocation. It needs to go away. */
5679 if (kqemu_allowed) {
5680 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5681 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5682 if (!kqemu_phys_ram_base) {
5683 fprintf(stderr, "Could not allocate physical memory\n");
5684 exit(1);
5687 #endif
5689 /* init the dynamic translator */
5690 cpu_exec_init_all(tb_size * 1024 * 1024);
5692 bdrv_init();
5694 /* we always create the cdrom drive, even if no disk is there */
5696 if (nb_drives_opt < MAX_DRIVES)
5697 drive_add(NULL, CDROM_ALIAS);
5699 /* we always create at least one floppy */
5701 if (nb_drives_opt < MAX_DRIVES)
5702 drive_add(NULL, FD_ALIAS, 0);
5704 /* we always create one sd slot, even if no card is in it */
5706 if (nb_drives_opt < MAX_DRIVES)
5707 drive_add(NULL, SD_ALIAS);
5709 /* open the virtual block devices */
5711 for(i = 0; i < nb_drives_opt; i++)
5712 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5713 exit(1);
5715 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5716 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5718 #ifndef _WIN32
5719 /* must be after terminal init, SDL library changes signal handlers */
5720 sighandler_setup();
5721 #endif
5723 /* Maintain compatibility with multiple stdio monitors */
5724 if (!strcmp(monitor_device,"stdio")) {
5725 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5726 const char *devname = serial_devices[i];
5727 if (devname && !strcmp(devname,"mon:stdio")) {
5728 monitor_device = NULL;
5729 break;
5730 } else if (devname && !strcmp(devname,"stdio")) {
5731 monitor_device = NULL;
5732 serial_devices[i] = "mon:stdio";
5733 break;
5738 if (nb_numa_nodes > 0) {
5739 int i;
5741 if (nb_numa_nodes > smp_cpus) {
5742 nb_numa_nodes = smp_cpus;
5745 /* If no memory size if given for any node, assume the default case
5746 * and distribute the available memory equally across all nodes
5748 for (i = 0; i < nb_numa_nodes; i++) {
5749 if (node_mem[i] != 0)
5750 break;
5752 if (i == nb_numa_nodes) {
5753 uint64_t usedmem = 0;
5755 /* On Linux, the each node's border has to be 8MB aligned,
5756 * the final node gets the rest.
5758 for (i = 0; i < nb_numa_nodes - 1; i++) {
5759 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5760 usedmem += node_mem[i];
5762 node_mem[i] = ram_size - usedmem;
5765 for (i = 0; i < nb_numa_nodes; i++) {
5766 if (node_cpumask[i] != 0)
5767 break;
5769 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5770 * must cope with this anyway, because there are BIOSes out there in
5771 * real machines which also use this scheme.
5773 if (i == nb_numa_nodes) {
5774 for (i = 0; i < smp_cpus; i++) {
5775 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5780 if (kvm_enabled()) {
5781 int ret;
5783 ret = kvm_init(smp_cpus);
5784 if (ret < 0) {
5785 fprintf(stderr, "failed to initialize KVM\n");
5786 exit(1);
5790 if (monitor_device) {
5791 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5792 if (!monitor_hd) {
5793 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5794 exit(1);
5798 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5799 const char *devname = serial_devices[i];
5800 if (devname && strcmp(devname, "none")) {
5801 char label[32];
5802 snprintf(label, sizeof(label), "serial%d", i);
5803 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5804 if (!serial_hds[i]) {
5805 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5806 devname);
5807 exit(1);
5812 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5813 const char *devname = parallel_devices[i];
5814 if (devname && strcmp(devname, "none")) {
5815 char label[32];
5816 snprintf(label, sizeof(label), "parallel%d", i);
5817 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5818 if (!parallel_hds[i]) {
5819 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5820 devname);
5821 exit(1);
5826 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5827 const char *devname = virtio_consoles[i];
5828 if (devname && strcmp(devname, "none")) {
5829 char label[32];
5830 snprintf(label, sizeof(label), "virtcon%d", i);
5831 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5832 if (!virtcon_hds[i]) {
5833 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5834 devname);
5835 exit(1);
5840 module_call_init(MODULE_INIT_DEVICE);
5842 machine->init(ram_size, boot_devices,
5843 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5846 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5847 for (i = 0; i < nb_numa_nodes; i++) {
5848 if (node_cpumask[i] & (1 << env->cpu_index)) {
5849 env->numa_node = i;
5854 current_machine = machine;
5856 /* init USB devices */
5857 if (usb_enabled) {
5858 for(i = 0; i < usb_devices_index; i++) {
5859 if (usb_device_add(usb_devices[i], 0) < 0) {
5860 fprintf(stderr, "Warning: could not add USB device %s\n",
5861 usb_devices[i]);
5866 if (!display_state)
5867 dumb_display_init();
5868 /* just use the first displaystate for the moment */
5869 ds = display_state;
5871 if (display_type == DT_DEFAULT) {
5872 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5873 display_type = DT_SDL;
5874 #else
5875 display_type = DT_VNC;
5876 vnc_display = "localhost:0,to=99";
5877 show_vnc_port = 1;
5878 #endif
5882 switch (display_type) {
5883 case DT_NOGRAPHIC:
5884 break;
5885 #if defined(CONFIG_CURSES)
5886 case DT_CURSES:
5887 curses_display_init(ds, full_screen);
5888 break;
5889 #endif
5890 #if defined(CONFIG_SDL)
5891 case DT_SDL:
5892 sdl_display_init(ds, full_screen, no_frame);
5893 break;
5894 #elif defined(CONFIG_COCOA)
5895 case DT_SDL:
5896 cocoa_display_init(ds, full_screen);
5897 break;
5898 #endif
5899 case DT_VNC:
5900 vnc_display_init(ds);
5901 if (vnc_display_open(ds, vnc_display) < 0)
5902 exit(1);
5904 if (show_vnc_port) {
5905 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5907 break;
5908 default:
5909 break;
5911 dpy_resize(ds);
5913 dcl = ds->listeners;
5914 while (dcl != NULL) {
5915 if (dcl->dpy_refresh != NULL) {
5916 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5917 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5919 dcl = dcl->next;
5922 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5923 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5924 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5927 text_consoles_set_display(display_state);
5928 qemu_chr_initial_reset();
5930 if (monitor_device && monitor_hd)
5931 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5933 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5934 const char *devname = serial_devices[i];
5935 if (devname && strcmp(devname, "none")) {
5936 if (strstart(devname, "vc", 0))
5937 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5941 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5942 const char *devname = parallel_devices[i];
5943 if (devname && strcmp(devname, "none")) {
5944 if (strstart(devname, "vc", 0))
5945 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5949 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5950 const char *devname = virtio_consoles[i];
5951 if (virtcon_hds[i] && devname) {
5952 if (strstart(devname, "vc", 0))
5953 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5957 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5958 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5959 gdbstub_dev);
5960 exit(1);
5963 if (loadvm)
5964 do_loadvm(cur_mon, loadvm);
5966 if (incoming) {
5967 autostart = 0; /* fixme how to deal with -daemonize */
5968 qemu_start_incoming_migration(incoming);
5971 if (autostart)
5972 vm_start();
5974 #ifndef _WIN32
5975 if (daemonize) {
5976 uint8_t status = 0;
5977 ssize_t len;
5979 again1:
5980 len = write(fds[1], &status, 1);
5981 if (len == -1 && (errno == EINTR))
5982 goto again1;
5984 if (len != 1)
5985 exit(1);
5987 chdir("/");
5988 TFR(fd = open("/dev/null", O_RDWR));
5989 if (fd == -1)
5990 exit(1);
5993 if (run_as) {
5994 pwd = getpwnam(run_as);
5995 if (!pwd) {
5996 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5997 exit(1);
6001 if (chroot_dir) {
6002 if (chroot(chroot_dir) < 0) {
6003 fprintf(stderr, "chroot failed\n");
6004 exit(1);
6006 chdir("/");
6009 if (run_as) {
6010 if (setgid(pwd->pw_gid) < 0) {
6011 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6012 exit(1);
6014 if (setuid(pwd->pw_uid) < 0) {
6015 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6016 exit(1);
6018 if (setuid(0) != -1) {
6019 fprintf(stderr, "Dropping privileges failed\n");
6020 exit(1);
6024 if (daemonize) {
6025 dup2(fd, 0);
6026 dup2(fd, 1);
6027 dup2(fd, 2);
6029 close(fd);
6031 #endif
6033 main_loop();
6034 quit_timers();
6035 net_cleanup();
6037 return 0;