Merge branch 'upstream-merge'
[qemu-kvm/markmc.git] / vl.c
blob23f46fda9940b30aa4b319056359ee9d89447f5e
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <libgen.h>
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #include <arpa/inet.h>
48 #include <dirent.h>
49 #include <netdb.h>
50 #include <sys/select.h>
51 #ifdef CONFIG_BSD
52 #include <sys/stat.h>
53 #if defined(__FreeBSD__) || defined(__DragonFly__)
54 #include <libutil.h>
55 #else
56 #include <util.h>
57 #endif
58 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
59 #include <freebsd/stdlib.h>
60 #else
61 #ifdef __linux__
62 #include <pty.h>
63 #include <malloc.h>
64 #include <linux/rtc.h>
65 #include <sys/prctl.h>
67 /* For the benefit of older linux systems which don't supply it,
68 we use a local copy of hpet.h. */
69 /* #include <linux/hpet.h> */
70 #include "hpet.h"
72 #include <linux/ppdev.h>
73 #include <linux/parport.h>
74 #endif
75 #ifdef __sun__
76 #include <sys/stat.h>
77 #include <sys/ethernet.h>
78 #include <sys/sockio.h>
79 #include <netinet/arp.h>
80 #include <netinet/in.h>
81 #include <netinet/in_systm.h>
82 #include <netinet/ip.h>
83 #include <netinet/ip_icmp.h> // must come after ip.h
84 #include <netinet/udp.h>
85 #include <netinet/tcp.h>
86 #include <net/if.h>
87 #include <syslog.h>
88 #include <stropts.h>
89 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
90 discussion about Solaris header problems */
91 extern int madvise(caddr_t, size_t, int);
92 #endif
93 #endif
94 #endif
96 #if defined(__OpenBSD__)
97 #include <util.h>
98 #endif
100 #if defined(CONFIG_VDE)
101 #include <libvdeplug.h>
102 #endif
104 #ifdef _WIN32
105 #include <windows.h>
106 #include <mmsystem.h>
107 #endif
109 #ifdef CONFIG_SDL
110 #if defined(__APPLE__) || defined(main)
111 #include <SDL.h>
112 int qemu_main(int argc, char **argv, char **envp);
113 int main(int argc, char **argv)
115 return qemu_main(argc, argv, NULL);
117 #undef main
118 #define main qemu_main
119 #endif
120 #endif /* CONFIG_SDL */
122 #ifdef CONFIG_COCOA
123 #undef main
124 #define main qemu_main
125 #endif /* CONFIG_COCOA */
127 #include "hw/hw.h"
128 #include "hw/boards.h"
129 #include "hw/usb.h"
130 #include "hw/pcmcia.h"
131 #include "hw/pc.h"
132 #include "hw/audiodev.h"
133 #include "hw/isa.h"
134 #include "hw/baum.h"
135 #include "hw/bt.h"
136 #include "hw/watchdog.h"
137 #include "hw/smbios.h"
138 #include "hw/xen.h"
139 #include "hw/qdev.h"
140 #include "hw/loader.h"
141 #include "bt-host.h"
142 #include "net.h"
143 #include "monitor.h"
144 #include "console.h"
145 #include "sysemu.h"
146 #include "gdbstub.h"
147 #include "qemu-timer.h"
148 #include "qemu-char.h"
149 #include "cache-utils.h"
150 #include "block.h"
151 #include "dma.h"
152 #include "audio/audio.h"
153 #include "migration.h"
154 #include "kvm.h"
155 #include "balloon.h"
156 #include "qemu-option.h"
157 #include "qemu-config.h"
158 #include "qemu-kvm.h"
159 #include "hw/device-assignment.h"
161 #include "disas.h"
163 #include "exec-all.h"
165 #include "qemu_socket.h"
167 #include "slirp/libslirp.h"
169 #include "qemu-queue.h"
171 //#define DEBUG_NET
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 /* Maximum number of monitor devices */
177 #define MAX_MONITOR_DEVICES 10
179 static const char *data_dir;
180 const char *bios_name = NULL;
181 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
182 to store the VM snapshots */
183 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
184 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
185 DriveInfo *extboot_drive = NULL;
186 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
187 static DisplayState *display_state;
188 DisplayType display_type = DT_DEFAULT;
189 const char* keyboard_layout = NULL;
190 ram_addr_t ram_size;
191 int nb_nics;
192 NICInfo nd_table[MAX_NICS];
193 int vm_running;
194 int autostart;
195 static int rtc_utc = 1;
196 static int rtc_date_offset = -1; /* -1 means no change */
197 QEMUClock *rtc_clock;
198 int vga_interface_type = VGA_CIRRUS;
199 #ifdef TARGET_SPARC
200 int graphic_width = 1024;
201 int graphic_height = 768;
202 int graphic_depth = 8;
203 #else
204 int graphic_width = 800;
205 int graphic_height = 600;
206 int graphic_depth = 15;
207 #endif
208 static int full_screen = 0;
209 #ifdef CONFIG_SDL
210 static int no_frame = 0;
211 #endif
212 int no_quit = 0;
213 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
214 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
215 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
216 #ifdef TARGET_I386
217 int win2k_install_hack = 0;
218 int rtc_td_hack = 0;
219 #endif
220 int usb_enabled = 0;
221 int singlestep = 0;
222 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
223 int assigned_devices_index;
224 int smp_cpus = 1;
225 int max_cpus = 0;
226 int smp_cores = 1;
227 int smp_threads = 1;
228 const char *vnc_display;
229 int acpi_enabled = 1;
230 #ifdef TARGET_I386
231 int no_hpet = 0;
232 #endif
233 int fd_bootchk = 1;
234 int no_reboot = 0;
235 int no_shutdown = 0;
236 int cursor_hide = 1;
237 int graphic_rotate = 0;
238 uint8_t irq0override = 1;
239 #ifndef _WIN32
240 int daemonize = 0;
241 #endif
242 const char *watchdog;
243 const char *option_rom[MAX_OPTION_ROMS];
244 int nb_option_roms;
245 int semihosting_enabled = 0;
246 int time_drift_fix = 0;
247 unsigned int kvm_shadow_memory = 0;
248 const char *mem_path = NULL;
249 #ifdef MAP_POPULATE
250 int mem_prealloc = 1; /* force preallocation of physical target memory */
251 #endif
252 #ifdef TARGET_ARM
253 int old_param = 0;
254 #endif
255 const char *qemu_name;
256 int alt_grab = 0;
257 int ctrl_grab = 0;
258 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
259 unsigned int nb_prom_envs = 0;
260 const char *prom_envs[MAX_PROM_ENVS];
261 #endif
262 const char *nvram = NULL;
263 int boot_menu;
265 int nb_numa_nodes;
266 uint64_t node_mem[MAX_NODES];
267 uint64_t node_cpumask[MAX_NODES];
269 static CPUState *cur_cpu;
270 static CPUState *next_cpu;
271 static int timer_alarm_pending = 1;
272 /* Conversion factor from emulated instructions to virtual clock ticks. */
273 static int icount_time_shift;
274 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
275 #define MAX_ICOUNT_SHIFT 10
276 /* Compensate for varying guest execution speed. */
277 static int64_t qemu_icount_bias;
278 static QEMUTimer *icount_rt_timer;
279 static QEMUTimer *icount_vm_timer;
280 static QEMUTimer *nographic_timer;
282 uint8_t qemu_uuid[16];
284 static QEMUBootSetHandler *boot_set_handler;
285 static void *boot_set_opaque;
287 /***********************************************************/
288 /* x86 ISA bus support */
290 target_phys_addr_t isa_mem_base = 0;
291 PicState2 *isa_pic;
293 /***********************************************************/
294 void hw_error(const char *fmt, ...)
296 va_list ap;
297 CPUState *env;
299 va_start(ap, fmt);
300 fprintf(stderr, "qemu: hardware error: ");
301 vfprintf(stderr, fmt, ap);
302 fprintf(stderr, "\n");
303 for(env = first_cpu; env != NULL; env = env->next_cpu) {
304 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
305 #ifdef TARGET_I386
306 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
307 #else
308 cpu_dump_state(env, stderr, fprintf, 0);
309 #endif
311 va_end(ap);
312 abort();
315 static void set_proc_name(const char *s)
317 #if defined(__linux__) && defined(PR_SET_NAME)
318 char name[16];
319 if (!s)
320 return;
321 name[sizeof(name) - 1] = 0;
322 strncpy(name, s, sizeof(name));
323 /* Could rewrite argv[0] too, but that's a bit more complicated.
324 This simple way is enough for `top'. */
325 prctl(PR_SET_NAME, name);
326 #endif
329 /***************/
330 /* ballooning */
332 static QEMUBalloonEvent *qemu_balloon_event;
333 void *qemu_balloon_event_opaque;
335 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
337 qemu_balloon_event = func;
338 qemu_balloon_event_opaque = opaque;
341 void qemu_balloon(ram_addr_t target)
343 if (qemu_balloon_event)
344 qemu_balloon_event(qemu_balloon_event_opaque, target);
347 ram_addr_t qemu_balloon_status(void)
349 if (qemu_balloon_event)
350 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
351 return 0;
354 /***********************************************************/
355 /* keyboard/mouse */
357 static QEMUPutKBDEvent *qemu_put_kbd_event;
358 static void *qemu_put_kbd_event_opaque;
359 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
360 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
362 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
364 qemu_put_kbd_event_opaque = opaque;
365 qemu_put_kbd_event = func;
368 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
369 void *opaque, int absolute,
370 const char *name)
372 QEMUPutMouseEntry *s, *cursor;
374 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
376 s->qemu_put_mouse_event = func;
377 s->qemu_put_mouse_event_opaque = opaque;
378 s->qemu_put_mouse_event_absolute = absolute;
379 s->qemu_put_mouse_event_name = qemu_strdup(name);
380 s->next = NULL;
382 if (!qemu_put_mouse_event_head) {
383 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
384 return s;
387 cursor = qemu_put_mouse_event_head;
388 while (cursor->next != NULL)
389 cursor = cursor->next;
391 cursor->next = s;
392 qemu_put_mouse_event_current = s;
394 return s;
397 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
399 QEMUPutMouseEntry *prev = NULL, *cursor;
401 if (!qemu_put_mouse_event_head || entry == NULL)
402 return;
404 cursor = qemu_put_mouse_event_head;
405 while (cursor != NULL && cursor != entry) {
406 prev = cursor;
407 cursor = cursor->next;
410 if (cursor == NULL) // does not exist or list empty
411 return;
412 else if (prev == NULL) { // entry is head
413 qemu_put_mouse_event_head = cursor->next;
414 if (qemu_put_mouse_event_current == entry)
415 qemu_put_mouse_event_current = cursor->next;
416 qemu_free(entry->qemu_put_mouse_event_name);
417 qemu_free(entry);
418 return;
421 prev->next = entry->next;
423 if (qemu_put_mouse_event_current == entry)
424 qemu_put_mouse_event_current = prev;
426 qemu_free(entry->qemu_put_mouse_event_name);
427 qemu_free(entry);
430 void kbd_put_keycode(int keycode)
432 if (qemu_put_kbd_event) {
433 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
437 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
439 QEMUPutMouseEvent *mouse_event;
440 void *mouse_event_opaque;
441 int width;
443 if (!qemu_put_mouse_event_current) {
444 return;
447 mouse_event =
448 qemu_put_mouse_event_current->qemu_put_mouse_event;
449 mouse_event_opaque =
450 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
452 if (mouse_event) {
453 if (graphic_rotate) {
454 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
455 width = 0x7fff;
456 else
457 width = graphic_width - 1;
458 mouse_event(mouse_event_opaque,
459 width - dy, dx, dz, buttons_state);
460 } else
461 mouse_event(mouse_event_opaque,
462 dx, dy, dz, buttons_state);
466 int kbd_mouse_is_absolute(void)
468 if (!qemu_put_mouse_event_current)
469 return 0;
471 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
474 void do_info_mice(Monitor *mon)
476 QEMUPutMouseEntry *cursor;
477 int index = 0;
479 if (!qemu_put_mouse_event_head) {
480 monitor_printf(mon, "No mouse devices connected\n");
481 return;
484 monitor_printf(mon, "Mouse devices available:\n");
485 cursor = qemu_put_mouse_event_head;
486 while (cursor != NULL) {
487 monitor_printf(mon, "%c Mouse #%d: %s\n",
488 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
489 index, cursor->qemu_put_mouse_event_name);
490 index++;
491 cursor = cursor->next;
495 void do_mouse_set(Monitor *mon, const QDict *qdict)
497 QEMUPutMouseEntry *cursor;
498 int i = 0;
499 int index = qdict_get_int(qdict, "index");
501 if (!qemu_put_mouse_event_head) {
502 monitor_printf(mon, "No mouse devices connected\n");
503 return;
506 cursor = qemu_put_mouse_event_head;
507 while (cursor != NULL && index != i) {
508 i++;
509 cursor = cursor->next;
512 if (cursor != NULL)
513 qemu_put_mouse_event_current = cursor;
514 else
515 monitor_printf(mon, "Mouse at given index not found\n");
518 /* compute with 96 bit intermediate result: (a*b)/c */
519 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
521 union {
522 uint64_t ll;
523 struct {
524 #ifdef HOST_WORDS_BIGENDIAN
525 uint32_t high, low;
526 #else
527 uint32_t low, high;
528 #endif
529 } l;
530 } u, res;
531 uint64_t rl, rh;
533 u.ll = a;
534 rl = (uint64_t)u.l.low * (uint64_t)b;
535 rh = (uint64_t)u.l.high * (uint64_t)b;
536 rh += (rl >> 32);
537 res.l.high = rh / c;
538 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
539 return res.ll;
542 /***********************************************************/
543 /* real time host monotonic timer */
545 static int64_t get_clock_realtime(void)
547 struct timeval tv;
549 gettimeofday(&tv, NULL);
550 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
553 #ifdef WIN32
555 static int64_t clock_freq;
557 static void init_get_clock(void)
559 LARGE_INTEGER freq;
560 int ret;
561 ret = QueryPerformanceFrequency(&freq);
562 if (ret == 0) {
563 fprintf(stderr, "Could not calibrate ticks\n");
564 exit(1);
566 clock_freq = freq.QuadPart;
569 static int64_t get_clock(void)
571 LARGE_INTEGER ti;
572 QueryPerformanceCounter(&ti);
573 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
576 #else
578 static int use_rt_clock;
580 static void init_get_clock(void)
582 use_rt_clock = 0;
583 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
584 || defined(__DragonFly__)
586 struct timespec ts;
587 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
588 use_rt_clock = 1;
591 #endif
594 static int64_t get_clock(void)
596 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
597 || defined(__DragonFly__)
598 if (use_rt_clock) {
599 struct timespec ts;
600 clock_gettime(CLOCK_MONOTONIC, &ts);
601 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
602 } else
603 #endif
605 /* XXX: using gettimeofday leads to problems if the date
606 changes, so it should be avoided. */
607 return get_clock_realtime();
610 #endif
612 /* Return the virtual CPU time, based on the instruction counter. */
613 static int64_t cpu_get_icount(void)
615 int64_t icount;
616 CPUState *env = cpu_single_env;;
617 icount = qemu_icount;
618 if (env) {
619 if (!can_do_io(env))
620 fprintf(stderr, "Bad clock read\n");
621 icount -= (env->icount_decr.u16.low + env->icount_extra);
623 return qemu_icount_bias + (icount << icount_time_shift);
626 /***********************************************************/
627 /* guest cycle counter */
629 typedef struct TimersState {
630 int64_t cpu_ticks_prev;
631 int64_t cpu_ticks_offset;
632 int64_t cpu_clock_offset;
633 int32_t cpu_ticks_enabled;
634 int64_t dummy;
635 } TimersState;
637 TimersState timers_state;
639 /* return the host CPU cycle counter and handle stop/restart */
640 int64_t cpu_get_ticks(void)
642 if (use_icount) {
643 return cpu_get_icount();
645 if (!timers_state.cpu_ticks_enabled) {
646 return timers_state.cpu_ticks_offset;
647 } else {
648 int64_t ticks;
649 ticks = cpu_get_real_ticks();
650 if (timers_state.cpu_ticks_prev > ticks) {
651 /* Note: non increasing ticks may happen if the host uses
652 software suspend */
653 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
655 timers_state.cpu_ticks_prev = ticks;
656 return ticks + timers_state.cpu_ticks_offset;
660 /* return the host CPU monotonic timer and handle stop/restart */
661 static int64_t cpu_get_clock(void)
663 int64_t ti;
664 if (!timers_state.cpu_ticks_enabled) {
665 return timers_state.cpu_clock_offset;
666 } else {
667 ti = get_clock();
668 return ti + timers_state.cpu_clock_offset;
672 /* enable cpu_get_ticks() */
673 void cpu_enable_ticks(void)
675 if (!timers_state.cpu_ticks_enabled) {
676 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
677 timers_state.cpu_clock_offset -= get_clock();
678 timers_state.cpu_ticks_enabled = 1;
682 /* disable cpu_get_ticks() : the clock is stopped. You must not call
683 cpu_get_ticks() after that. */
684 void cpu_disable_ticks(void)
686 if (timers_state.cpu_ticks_enabled) {
687 timers_state.cpu_ticks_offset = cpu_get_ticks();
688 timers_state.cpu_clock_offset = cpu_get_clock();
689 timers_state.cpu_ticks_enabled = 0;
693 /***********************************************************/
694 /* timers */
696 #define QEMU_CLOCK_REALTIME 0
697 #define QEMU_CLOCK_VIRTUAL 1
698 #define QEMU_CLOCK_HOST 2
700 struct QEMUClock {
701 int type;
702 /* XXX: add frequency */
705 struct QEMUTimer {
706 QEMUClock *clock;
707 int64_t expire_time;
708 QEMUTimerCB *cb;
709 void *opaque;
710 struct QEMUTimer *next;
713 struct qemu_alarm_timer {
714 char const *name;
715 unsigned int flags;
717 int (*start)(struct qemu_alarm_timer *t);
718 void (*stop)(struct qemu_alarm_timer *t);
719 void (*rearm)(struct qemu_alarm_timer *t);
720 void *priv;
723 #define ALARM_FLAG_DYNTICKS 0x1
724 #define ALARM_FLAG_EXPIRED 0x2
726 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
728 return t && (t->flags & ALARM_FLAG_DYNTICKS);
731 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
733 if (!alarm_has_dynticks(t))
734 return;
736 t->rearm(t);
739 /* TODO: MIN_TIMER_REARM_US should be optimized */
740 #define MIN_TIMER_REARM_US 250
742 static struct qemu_alarm_timer *alarm_timer;
744 #ifdef _WIN32
746 struct qemu_alarm_win32 {
747 MMRESULT timerId;
748 unsigned int period;
749 } alarm_win32_data = {0, -1};
751 static int win32_start_timer(struct qemu_alarm_timer *t);
752 static void win32_stop_timer(struct qemu_alarm_timer *t);
753 static void win32_rearm_timer(struct qemu_alarm_timer *t);
755 #else
757 static int unix_start_timer(struct qemu_alarm_timer *t);
758 static void unix_stop_timer(struct qemu_alarm_timer *t);
760 #ifdef __linux__
762 static int dynticks_start_timer(struct qemu_alarm_timer *t);
763 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
764 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
766 static int hpet_start_timer(struct qemu_alarm_timer *t);
767 static void hpet_stop_timer(struct qemu_alarm_timer *t);
769 static int rtc_start_timer(struct qemu_alarm_timer *t);
770 static void rtc_stop_timer(struct qemu_alarm_timer *t);
772 #endif /* __linux__ */
774 #endif /* _WIN32 */
776 /* Correlation between real and virtual time is always going to be
777 fairly approximate, so ignore small variation.
778 When the guest is idle real and virtual time will be aligned in
779 the IO wait loop. */
780 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
782 static void icount_adjust(void)
784 int64_t cur_time;
785 int64_t cur_icount;
786 int64_t delta;
787 static int64_t last_delta;
788 /* If the VM is not running, then do nothing. */
789 if (!vm_running)
790 return;
792 cur_time = cpu_get_clock();
793 cur_icount = qemu_get_clock(vm_clock);
794 delta = cur_icount - cur_time;
795 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
796 if (delta > 0
797 && last_delta + ICOUNT_WOBBLE < delta * 2
798 && icount_time_shift > 0) {
799 /* The guest is getting too far ahead. Slow time down. */
800 icount_time_shift--;
802 if (delta < 0
803 && last_delta - ICOUNT_WOBBLE > delta * 2
804 && icount_time_shift < MAX_ICOUNT_SHIFT) {
805 /* The guest is getting too far behind. Speed time up. */
806 icount_time_shift++;
808 last_delta = delta;
809 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
812 static void icount_adjust_rt(void * opaque)
814 qemu_mod_timer(icount_rt_timer,
815 qemu_get_clock(rt_clock) + 1000);
816 icount_adjust();
819 static void icount_adjust_vm(void * opaque)
821 qemu_mod_timer(icount_vm_timer,
822 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
823 icount_adjust();
826 static void init_icount_adjust(void)
828 /* Have both realtime and virtual time triggers for speed adjustment.
829 The realtime trigger catches emulated time passing too slowly,
830 the virtual time trigger catches emulated time passing too fast.
831 Realtime triggers occur even when idle, so use them less frequently
832 than VM triggers. */
833 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
834 qemu_mod_timer(icount_rt_timer,
835 qemu_get_clock(rt_clock) + 1000);
836 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
837 qemu_mod_timer(icount_vm_timer,
838 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
841 static struct qemu_alarm_timer alarm_timers[] = {
842 #ifndef _WIN32
843 #ifdef __linux__
844 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
845 dynticks_stop_timer, dynticks_rearm_timer, NULL},
846 /* HPET - if available - is preferred */
847 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
848 /* ...otherwise try RTC */
849 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
850 #endif
851 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
852 #else
853 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
854 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
855 {"win32", 0, win32_start_timer,
856 win32_stop_timer, NULL, &alarm_win32_data},
857 #endif
858 {NULL, }
861 static void show_available_alarms(void)
863 int i;
865 printf("Available alarm timers, in order of precedence:\n");
866 for (i = 0; alarm_timers[i].name; i++)
867 printf("%s\n", alarm_timers[i].name);
870 static void configure_alarms(char const *opt)
872 int i;
873 int cur = 0;
874 int count = ARRAY_SIZE(alarm_timers) - 1;
875 char *arg;
876 char *name;
877 struct qemu_alarm_timer tmp;
879 if (!strcmp(opt, "?")) {
880 show_available_alarms();
881 exit(0);
884 arg = qemu_strdup(opt);
886 /* Reorder the array */
887 name = strtok(arg, ",");
888 while (name) {
889 for (i = 0; i < count && alarm_timers[i].name; i++) {
890 if (!strcmp(alarm_timers[i].name, name))
891 break;
894 if (i == count) {
895 fprintf(stderr, "Unknown clock %s\n", name);
896 goto next;
899 if (i < cur)
900 /* Ignore */
901 goto next;
903 /* Swap */
904 tmp = alarm_timers[i];
905 alarm_timers[i] = alarm_timers[cur];
906 alarm_timers[cur] = tmp;
908 cur++;
909 next:
910 name = strtok(NULL, ",");
913 qemu_free(arg);
915 if (cur) {
916 /* Disable remaining timers */
917 for (i = cur; i < count; i++)
918 alarm_timers[i].name = NULL;
919 } else {
920 show_available_alarms();
921 exit(1);
925 #define QEMU_NUM_CLOCKS 3
927 QEMUClock *rt_clock;
928 QEMUClock *vm_clock;
929 QEMUClock *host_clock;
931 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
933 static QEMUClock *qemu_new_clock(int type)
935 QEMUClock *clock;
936 clock = qemu_mallocz(sizeof(QEMUClock));
937 clock->type = type;
938 return clock;
941 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
943 QEMUTimer *ts;
945 ts = qemu_mallocz(sizeof(QEMUTimer));
946 ts->clock = clock;
947 ts->cb = cb;
948 ts->opaque = opaque;
949 return ts;
952 void qemu_free_timer(QEMUTimer *ts)
954 qemu_free(ts);
957 /* stop a timer, but do not dealloc it */
958 void qemu_del_timer(QEMUTimer *ts)
960 QEMUTimer **pt, *t;
962 /* NOTE: this code must be signal safe because
963 qemu_timer_expired() can be called from a signal. */
964 pt = &active_timers[ts->clock->type];
965 for(;;) {
966 t = *pt;
967 if (!t)
968 break;
969 if (t == ts) {
970 *pt = t->next;
971 break;
973 pt = &t->next;
977 /* modify the current timer so that it will be fired when current_time
978 >= expire_time. The corresponding callback will be called. */
979 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
981 QEMUTimer **pt, *t;
983 qemu_del_timer(ts);
985 /* add the timer in the sorted list */
986 /* NOTE: this code must be signal safe because
987 qemu_timer_expired() can be called from a signal. */
988 pt = &active_timers[ts->clock->type];
989 for(;;) {
990 t = *pt;
991 if (!t)
992 break;
993 if (t->expire_time > expire_time)
994 break;
995 pt = &t->next;
997 ts->expire_time = expire_time;
998 ts->next = *pt;
999 *pt = ts;
1001 /* Rearm if necessary */
1002 if (pt == &active_timers[ts->clock->type]) {
1003 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1004 qemu_rearm_alarm_timer(alarm_timer);
1006 /* Interrupt execution to force deadline recalculation. */
1007 if (use_icount)
1008 qemu_notify_event();
1012 int qemu_timer_pending(QEMUTimer *ts)
1014 QEMUTimer *t;
1015 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1016 if (t == ts)
1017 return 1;
1019 return 0;
1022 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1024 if (!timer_head)
1025 return 0;
1026 return (timer_head->expire_time <= current_time);
1029 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1031 QEMUTimer *ts;
1033 for(;;) {
1034 ts = *ptimer_head;
1035 if (!ts || ts->expire_time > current_time)
1036 break;
1037 /* remove timer from the list before calling the callback */
1038 *ptimer_head = ts->next;
1039 ts->next = NULL;
1041 /* run the callback (the timer list can be modified) */
1042 ts->cb(ts->opaque);
1046 int64_t qemu_get_clock(QEMUClock *clock)
1048 switch(clock->type) {
1049 case QEMU_CLOCK_REALTIME:
1050 return get_clock() / 1000000;
1051 default:
1052 case QEMU_CLOCK_VIRTUAL:
1053 if (use_icount) {
1054 return cpu_get_icount();
1055 } else {
1056 return cpu_get_clock();
1058 case QEMU_CLOCK_HOST:
1059 return get_clock_realtime();
1063 static void init_clocks(void)
1065 init_get_clock();
1066 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
1067 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
1068 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
1070 rtc_clock = host_clock;
1073 /* save a timer */
1074 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1076 uint64_t expire_time;
1078 if (qemu_timer_pending(ts)) {
1079 expire_time = ts->expire_time;
1080 } else {
1081 expire_time = -1;
1083 qemu_put_be64(f, expire_time);
1086 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1088 uint64_t expire_time;
1090 expire_time = qemu_get_be64(f);
1091 if (expire_time != -1) {
1092 qemu_mod_timer(ts, expire_time);
1093 } else {
1094 qemu_del_timer(ts);
1098 static const VMStateDescription vmstate_timers = {
1099 .name = "timer",
1100 .version_id = 2,
1101 .minimum_version_id = 1,
1102 .minimum_version_id_old = 1,
1103 .fields = (VMStateField []) {
1104 VMSTATE_INT64(cpu_ticks_offset, TimersState),
1105 VMSTATE_INT64(dummy, TimersState),
1106 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1107 VMSTATE_END_OF_LIST()
1111 static void qemu_event_increment(void);
1113 #ifdef _WIN32
1114 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1115 DWORD_PTR dwUser, DWORD_PTR dw1,
1116 DWORD_PTR dw2)
1117 #else
1118 static void host_alarm_handler(int host_signum)
1119 #endif
1121 #if 0
1122 #define DISP_FREQ 1000
1124 static int64_t delta_min = INT64_MAX;
1125 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1126 static int count;
1127 ti = qemu_get_clock(vm_clock);
1128 if (last_clock != 0) {
1129 delta = ti - last_clock;
1130 if (delta < delta_min)
1131 delta_min = delta;
1132 if (delta > delta_max)
1133 delta_max = delta;
1134 delta_cum += delta;
1135 if (++count == DISP_FREQ) {
1136 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1137 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1138 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1139 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1140 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1141 count = 0;
1142 delta_min = INT64_MAX;
1143 delta_max = 0;
1144 delta_cum = 0;
1147 last_clock = ti;
1149 #endif
1150 if (alarm_has_dynticks(alarm_timer) ||
1151 (!use_icount &&
1152 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1153 qemu_get_clock(vm_clock))) ||
1154 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1155 qemu_get_clock(rt_clock)) ||
1156 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1157 qemu_get_clock(host_clock))) {
1158 qemu_event_increment();
1159 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1161 #ifndef CONFIG_IOTHREAD
1162 if (next_cpu) {
1163 /* stop the currently executing cpu because a timer occured */
1164 cpu_exit(next_cpu);
1166 #endif
1167 timer_alarm_pending = 1;
1168 qemu_notify_event();
1172 static int64_t qemu_next_deadline(void)
1174 /* To avoid problems with overflow limit this to 2^32. */
1175 int64_t delta = INT32_MAX;
1177 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1178 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1179 qemu_get_clock(vm_clock);
1181 if (active_timers[QEMU_CLOCK_HOST]) {
1182 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1183 qemu_get_clock(host_clock);
1184 if (hdelta < delta)
1185 delta = hdelta;
1188 if (delta < 0)
1189 delta = 0;
1191 return delta;
1194 #if defined(__linux__)
1195 static uint64_t qemu_next_deadline_dyntick(void)
1197 int64_t delta;
1198 int64_t rtdelta;
1200 if (use_icount)
1201 delta = INT32_MAX;
1202 else
1203 delta = (qemu_next_deadline() + 999) / 1000;
1205 if (active_timers[QEMU_CLOCK_REALTIME]) {
1206 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1207 qemu_get_clock(rt_clock))*1000;
1208 if (rtdelta < delta)
1209 delta = rtdelta;
1212 if (delta < MIN_TIMER_REARM_US)
1213 delta = MIN_TIMER_REARM_US;
1215 return delta;
1217 #endif
1219 #ifndef _WIN32
1221 /* Sets a specific flag */
1222 static int fcntl_setfl(int fd, int flag)
1224 int flags;
1226 flags = fcntl(fd, F_GETFL);
1227 if (flags == -1)
1228 return -errno;
1230 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1231 return -errno;
1233 return 0;
1236 #if defined(__linux__)
1238 #define RTC_FREQ 1024
1240 static void enable_sigio_timer(int fd)
1242 struct sigaction act;
1244 /* timer signal */
1245 sigfillset(&act.sa_mask);
1246 act.sa_flags = 0;
1247 act.sa_handler = host_alarm_handler;
1249 sigaction(SIGIO, &act, NULL);
1250 fcntl_setfl(fd, O_ASYNC);
1251 fcntl(fd, F_SETOWN, getpid());
1254 static int hpet_start_timer(struct qemu_alarm_timer *t)
1256 struct hpet_info info;
1257 int r, fd;
1259 fd = open("/dev/hpet", O_RDONLY);
1260 if (fd < 0)
1261 return -1;
1263 /* Set frequency */
1264 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1265 if (r < 0) {
1266 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1267 "error, but for better emulation accuracy type:\n"
1268 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1269 goto fail;
1272 /* Check capabilities */
1273 r = ioctl(fd, HPET_INFO, &info);
1274 if (r < 0)
1275 goto fail;
1277 /* Enable periodic mode */
1278 r = ioctl(fd, HPET_EPI, 0);
1279 if (info.hi_flags && (r < 0))
1280 goto fail;
1282 /* Enable interrupt */
1283 r = ioctl(fd, HPET_IE_ON, 0);
1284 if (r < 0)
1285 goto fail;
1287 enable_sigio_timer(fd);
1288 t->priv = (void *)(long)fd;
1290 return 0;
1291 fail:
1292 close(fd);
1293 return -1;
1296 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1298 int fd = (long)t->priv;
1300 close(fd);
1303 static int rtc_start_timer(struct qemu_alarm_timer *t)
1305 int rtc_fd;
1306 unsigned long current_rtc_freq = 0;
1308 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1309 if (rtc_fd < 0)
1310 return -1;
1311 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1312 if (current_rtc_freq != RTC_FREQ &&
1313 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1314 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1315 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1316 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1317 goto fail;
1319 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1320 fail:
1321 close(rtc_fd);
1322 return -1;
1325 enable_sigio_timer(rtc_fd);
1327 t->priv = (void *)(long)rtc_fd;
1329 return 0;
1332 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1334 int rtc_fd = (long)t->priv;
1336 close(rtc_fd);
1339 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1341 struct sigevent ev;
1342 timer_t host_timer;
1343 struct sigaction act;
1345 sigfillset(&act.sa_mask);
1346 act.sa_flags = 0;
1347 act.sa_handler = host_alarm_handler;
1349 sigaction(SIGALRM, &act, NULL);
1352 * Initialize ev struct to 0 to avoid valgrind complaining
1353 * about uninitialized data in timer_create call
1355 memset(&ev, 0, sizeof(ev));
1356 ev.sigev_value.sival_int = 0;
1357 ev.sigev_notify = SIGEV_SIGNAL;
1358 ev.sigev_signo = SIGALRM;
1360 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1361 perror("timer_create");
1363 /* disable dynticks */
1364 fprintf(stderr, "Dynamic Ticks disabled\n");
1366 return -1;
1369 t->priv = (void *)(long)host_timer;
1371 return 0;
1374 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1376 timer_t host_timer = (timer_t)(long)t->priv;
1378 timer_delete(host_timer);
1381 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1383 timer_t host_timer = (timer_t)(long)t->priv;
1384 struct itimerspec timeout;
1385 int64_t nearest_delta_us = INT64_MAX;
1386 int64_t current_us;
1388 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1389 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1390 !active_timers[QEMU_CLOCK_HOST])
1391 return;
1393 nearest_delta_us = qemu_next_deadline_dyntick();
1395 /* check whether a timer is already running */
1396 if (timer_gettime(host_timer, &timeout)) {
1397 perror("gettime");
1398 fprintf(stderr, "Internal timer error: aborting\n");
1399 exit(1);
1401 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1402 if (current_us && current_us <= nearest_delta_us)
1403 return;
1405 timeout.it_interval.tv_sec = 0;
1406 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1407 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1408 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1409 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1410 perror("settime");
1411 fprintf(stderr, "Internal timer error: aborting\n");
1412 exit(1);
1416 #endif /* defined(__linux__) */
1418 static int unix_start_timer(struct qemu_alarm_timer *t)
1420 struct sigaction act;
1421 struct itimerval itv;
1422 int err;
1424 /* timer signal */
1425 sigfillset(&act.sa_mask);
1426 act.sa_flags = 0;
1427 act.sa_handler = host_alarm_handler;
1429 sigaction(SIGALRM, &act, NULL);
1431 itv.it_interval.tv_sec = 0;
1432 /* for i386 kernel 2.6 to get 1 ms */
1433 itv.it_interval.tv_usec = 999;
1434 itv.it_value.tv_sec = 0;
1435 itv.it_value.tv_usec = 10 * 1000;
1437 err = setitimer(ITIMER_REAL, &itv, NULL);
1438 if (err)
1439 return -1;
1441 return 0;
1444 static void unix_stop_timer(struct qemu_alarm_timer *t)
1446 struct itimerval itv;
1448 memset(&itv, 0, sizeof(itv));
1449 setitimer(ITIMER_REAL, &itv, NULL);
1452 #endif /* !defined(_WIN32) */
1455 #ifdef _WIN32
1457 static int win32_start_timer(struct qemu_alarm_timer *t)
1459 TIMECAPS tc;
1460 struct qemu_alarm_win32 *data = t->priv;
1461 UINT flags;
1463 memset(&tc, 0, sizeof(tc));
1464 timeGetDevCaps(&tc, sizeof(tc));
1466 if (data->period < tc.wPeriodMin)
1467 data->period = tc.wPeriodMin;
1469 timeBeginPeriod(data->period);
1471 flags = TIME_CALLBACK_FUNCTION;
1472 if (alarm_has_dynticks(t))
1473 flags |= TIME_ONESHOT;
1474 else
1475 flags |= TIME_PERIODIC;
1477 data->timerId = timeSetEvent(1, // interval (ms)
1478 data->period, // resolution
1479 host_alarm_handler, // function
1480 (DWORD)t, // parameter
1481 flags);
1483 if (!data->timerId) {
1484 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1485 GetLastError());
1486 timeEndPeriod(data->period);
1487 return -1;
1490 return 0;
1493 static void win32_stop_timer(struct qemu_alarm_timer *t)
1495 struct qemu_alarm_win32 *data = t->priv;
1497 timeKillEvent(data->timerId);
1498 timeEndPeriod(data->period);
1501 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1503 struct qemu_alarm_win32 *data = t->priv;
1505 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1506 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1507 !active_timers[QEMU_CLOCK_HOST])
1508 return;
1510 timeKillEvent(data->timerId);
1512 data->timerId = timeSetEvent(1,
1513 data->period,
1514 host_alarm_handler,
1515 (DWORD)t,
1516 TIME_ONESHOT | TIME_PERIODIC);
1518 if (!data->timerId) {
1519 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1520 GetLastError());
1522 timeEndPeriod(data->period);
1523 exit(1);
1527 #endif /* _WIN32 */
1529 static int init_timer_alarm(void)
1531 struct qemu_alarm_timer *t = NULL;
1532 int i, err = -1;
1534 for (i = 0; alarm_timers[i].name; i++) {
1535 t = &alarm_timers[i];
1537 err = t->start(t);
1538 if (!err)
1539 break;
1542 if (err) {
1543 err = -ENOENT;
1544 goto fail;
1547 alarm_timer = t;
1549 return 0;
1551 fail:
1552 return err;
1555 static void quit_timers(void)
1557 alarm_timer->stop(alarm_timer);
1558 alarm_timer = NULL;
1561 /***********************************************************/
1562 /* host time/date access */
1563 void qemu_get_timedate(struct tm *tm, int offset)
1565 time_t ti;
1566 struct tm *ret;
1568 time(&ti);
1569 ti += offset;
1570 if (rtc_date_offset == -1) {
1571 if (rtc_utc)
1572 ret = gmtime(&ti);
1573 else
1574 ret = localtime(&ti);
1575 } else {
1576 ti -= rtc_date_offset;
1577 ret = gmtime(&ti);
1580 memcpy(tm, ret, sizeof(struct tm));
1583 int qemu_timedate_diff(struct tm *tm)
1585 time_t seconds;
1587 if (rtc_date_offset == -1)
1588 if (rtc_utc)
1589 seconds = mktimegm(tm);
1590 else
1591 seconds = mktime(tm);
1592 else
1593 seconds = mktimegm(tm) + rtc_date_offset;
1595 return seconds - time(NULL);
1598 static void configure_rtc_date_offset(const char *startdate, int legacy)
1600 time_t rtc_start_date;
1601 struct tm tm;
1603 if (!strcmp(startdate, "now") && legacy) {
1604 rtc_date_offset = -1;
1605 } else {
1606 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1607 &tm.tm_year,
1608 &tm.tm_mon,
1609 &tm.tm_mday,
1610 &tm.tm_hour,
1611 &tm.tm_min,
1612 &tm.tm_sec) == 6) {
1613 /* OK */
1614 } else if (sscanf(startdate, "%d-%d-%d",
1615 &tm.tm_year,
1616 &tm.tm_mon,
1617 &tm.tm_mday) == 3) {
1618 tm.tm_hour = 0;
1619 tm.tm_min = 0;
1620 tm.tm_sec = 0;
1621 } else {
1622 goto date_fail;
1624 tm.tm_year -= 1900;
1625 tm.tm_mon--;
1626 rtc_start_date = mktimegm(&tm);
1627 if (rtc_start_date == -1) {
1628 date_fail:
1629 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1630 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1631 exit(1);
1633 rtc_date_offset = time(NULL) - rtc_start_date;
1637 static void configure_rtc(QemuOpts *opts)
1639 const char *value;
1641 value = qemu_opt_get(opts, "base");
1642 if (value) {
1643 if (!strcmp(value, "utc")) {
1644 rtc_utc = 1;
1645 } else if (!strcmp(value, "localtime")) {
1646 rtc_utc = 0;
1647 } else {
1648 configure_rtc_date_offset(value, 0);
1651 value = qemu_opt_get(opts, "clock");
1652 if (value) {
1653 if (!strcmp(value, "host")) {
1654 rtc_clock = host_clock;
1655 } else if (!strcmp(value, "vm")) {
1656 rtc_clock = vm_clock;
1657 } else {
1658 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1659 exit(1);
1662 #ifdef CONFIG_TARGET_I386
1663 value = qemu_opt_get(opts, "driftfix");
1664 if (value) {
1665 if (!strcmp(buf, "slew")) {
1666 rtc_td_hack = 1;
1667 } else if (!strcmp(buf, "none")) {
1668 rtc_td_hack = 0;
1669 } else {
1670 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1671 exit(1);
1674 #endif
1677 #ifdef _WIN32
1678 static void socket_cleanup(void)
1680 WSACleanup();
1683 static int socket_init(void)
1685 WSADATA Data;
1686 int ret, err;
1688 ret = WSAStartup(MAKEWORD(2,2), &Data);
1689 if (ret != 0) {
1690 err = WSAGetLastError();
1691 fprintf(stderr, "WSAStartup: %d\n", err);
1692 return -1;
1694 atexit(socket_cleanup);
1695 return 0;
1697 #endif
1699 /***********************************************************/
1700 /* Bluetooth support */
1701 static int nb_hcis;
1702 static int cur_hci;
1703 static struct HCIInfo *hci_table[MAX_NICS];
1705 static struct bt_vlan_s {
1706 struct bt_scatternet_s net;
1707 int id;
1708 struct bt_vlan_s *next;
1709 } *first_bt_vlan;
1711 /* find or alloc a new bluetooth "VLAN" */
1712 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1714 struct bt_vlan_s **pvlan, *vlan;
1715 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1716 if (vlan->id == id)
1717 return &vlan->net;
1719 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1720 vlan->id = id;
1721 pvlan = &first_bt_vlan;
1722 while (*pvlan != NULL)
1723 pvlan = &(*pvlan)->next;
1724 *pvlan = vlan;
1725 return &vlan->net;
1728 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1732 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1734 return -ENOTSUP;
1737 static struct HCIInfo null_hci = {
1738 .cmd_send = null_hci_send,
1739 .sco_send = null_hci_send,
1740 .acl_send = null_hci_send,
1741 .bdaddr_set = null_hci_addr_set,
1744 struct HCIInfo *qemu_next_hci(void)
1746 if (cur_hci == nb_hcis)
1747 return &null_hci;
1749 return hci_table[cur_hci++];
1752 static struct HCIInfo *hci_init(const char *str)
1754 char *endp;
1755 struct bt_scatternet_s *vlan = 0;
1757 if (!strcmp(str, "null"))
1758 /* null */
1759 return &null_hci;
1760 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1761 /* host[:hciN] */
1762 return bt_host_hci(str[4] ? str + 5 : "hci0");
1763 else if (!strncmp(str, "hci", 3)) {
1764 /* hci[,vlan=n] */
1765 if (str[3]) {
1766 if (!strncmp(str + 3, ",vlan=", 6)) {
1767 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1768 if (*endp)
1769 vlan = 0;
1771 } else
1772 vlan = qemu_find_bt_vlan(0);
1773 if (vlan)
1774 return bt_new_hci(vlan);
1777 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1779 return 0;
1782 static int bt_hci_parse(const char *str)
1784 struct HCIInfo *hci;
1785 bdaddr_t bdaddr;
1787 if (nb_hcis >= MAX_NICS) {
1788 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1789 return -1;
1792 hci = hci_init(str);
1793 if (!hci)
1794 return -1;
1796 bdaddr.b[0] = 0x52;
1797 bdaddr.b[1] = 0x54;
1798 bdaddr.b[2] = 0x00;
1799 bdaddr.b[3] = 0x12;
1800 bdaddr.b[4] = 0x34;
1801 bdaddr.b[5] = 0x56 + nb_hcis;
1802 hci->bdaddr_set(hci, bdaddr.b);
1804 hci_table[nb_hcis++] = hci;
1806 return 0;
1809 static void bt_vhci_add(int vlan_id)
1811 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1813 if (!vlan->slave)
1814 fprintf(stderr, "qemu: warning: adding a VHCI to "
1815 "an empty scatternet %i\n", vlan_id);
1817 bt_vhci_init(bt_new_hci(vlan));
1820 static struct bt_device_s *bt_device_add(const char *opt)
1822 struct bt_scatternet_s *vlan;
1823 int vlan_id = 0;
1824 char *endp = strstr(opt, ",vlan=");
1825 int len = (endp ? endp - opt : strlen(opt)) + 1;
1826 char devname[10];
1828 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1830 if (endp) {
1831 vlan_id = strtol(endp + 6, &endp, 0);
1832 if (*endp) {
1833 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1834 return 0;
1838 vlan = qemu_find_bt_vlan(vlan_id);
1840 if (!vlan->slave)
1841 fprintf(stderr, "qemu: warning: adding a slave device to "
1842 "an empty scatternet %i\n", vlan_id);
1844 if (!strcmp(devname, "keyboard"))
1845 return bt_keyboard_init(vlan);
1847 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1848 return 0;
1851 static int bt_parse(const char *opt)
1853 const char *endp, *p;
1854 int vlan;
1856 if (strstart(opt, "hci", &endp)) {
1857 if (!*endp || *endp == ',') {
1858 if (*endp)
1859 if (!strstart(endp, ",vlan=", 0))
1860 opt = endp + 1;
1862 return bt_hci_parse(opt);
1864 } else if (strstart(opt, "vhci", &endp)) {
1865 if (!*endp || *endp == ',') {
1866 if (*endp) {
1867 if (strstart(endp, ",vlan=", &p)) {
1868 vlan = strtol(p, (char **) &endp, 0);
1869 if (*endp) {
1870 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1871 return 1;
1873 } else {
1874 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1875 return 1;
1877 } else
1878 vlan = 0;
1880 bt_vhci_add(vlan);
1881 return 0;
1883 } else if (strstart(opt, "device:", &endp))
1884 return !bt_device_add(endp);
1886 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1887 return 1;
1890 /***********************************************************/
1891 /* QEMU Block devices */
1893 #define HD_ALIAS "index=%d,media=disk"
1894 #define CDROM_ALIAS "index=2,media=cdrom"
1895 #define FD_ALIAS "index=%d,if=floppy"
1896 #define PFLASH_ALIAS "if=pflash"
1897 #define MTD_ALIAS "if=mtd"
1898 #define SD_ALIAS "index=0,if=sd"
1900 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1902 va_list ap;
1903 char optstr[1024];
1904 QemuOpts *opts;
1906 va_start(ap, fmt);
1907 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1908 va_end(ap);
1910 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1911 if (!opts) {
1912 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1913 __FUNCTION__, optstr);
1914 return NULL;
1916 if (file)
1917 qemu_opt_set(opts, "file", file);
1918 return opts;
1921 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1923 DriveInfo *dinfo;
1925 /* seek interface, bus and unit */
1927 QTAILQ_FOREACH(dinfo, &drives, next) {
1928 if (dinfo->type == type &&
1929 dinfo->bus == bus &&
1930 dinfo->unit == unit)
1931 return dinfo;
1934 return NULL;
1937 DriveInfo *drive_get_by_id(const char *id)
1939 DriveInfo *dinfo;
1941 QTAILQ_FOREACH(dinfo, &drives, next) {
1942 if (strcmp(id, dinfo->id))
1943 continue;
1944 return dinfo;
1946 return NULL;
1949 int drive_get_max_bus(BlockInterfaceType type)
1951 int max_bus;
1952 DriveInfo *dinfo;
1954 max_bus = -1;
1955 QTAILQ_FOREACH(dinfo, &drives, next) {
1956 if(dinfo->type == type &&
1957 dinfo->bus > max_bus)
1958 max_bus = dinfo->bus;
1960 return max_bus;
1963 const char *drive_get_serial(BlockDriverState *bdrv)
1965 DriveInfo *dinfo;
1967 QTAILQ_FOREACH(dinfo, &drives, next) {
1968 if (dinfo->bdrv == bdrv)
1969 return dinfo->serial;
1972 return "\0";
1975 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1977 DriveInfo *dinfo;
1979 QTAILQ_FOREACH(dinfo, &drives, next) {
1980 if (dinfo->bdrv == bdrv)
1981 return dinfo->onerror;
1984 return BLOCK_ERR_STOP_ENOSPC;
1987 static void bdrv_format_print(void *opaque, const char *name)
1989 fprintf(stderr, " %s", name);
1992 void drive_uninit(DriveInfo *dinfo)
1994 qemu_opts_del(dinfo->opts);
1995 bdrv_delete(dinfo->bdrv);
1996 QTAILQ_REMOVE(&drives, dinfo, next);
1997 qemu_free(dinfo);
2000 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
2001 int *fatal_error)
2003 const char *buf;
2004 const char *file = NULL;
2005 char devname[128];
2006 const char *serial;
2007 const char *mediastr = "";
2008 BlockInterfaceType type;
2009 enum { MEDIA_DISK, MEDIA_CDROM } media;
2010 int bus_id, unit_id;
2011 int cyls, heads, secs, translation;
2012 BlockDriver *drv = NULL;
2013 QEMUMachine *machine = opaque;
2014 int max_devs;
2015 int index;
2016 int cache;
2017 int aio = 0;
2018 int bdrv_flags, onerror;
2019 const char *devaddr;
2020 DriveInfo *dinfo;
2021 int is_extboot = 0;
2022 int snapshot = 0;
2024 *fatal_error = 1;
2026 translation = BIOS_ATA_TRANSLATION_AUTO;
2027 cache = 1;
2029 if (machine && machine->use_scsi) {
2030 type = IF_SCSI;
2031 max_devs = MAX_SCSI_DEVS;
2032 pstrcpy(devname, sizeof(devname), "scsi");
2033 } else {
2034 type = IF_IDE;
2035 max_devs = MAX_IDE_DEVS;
2036 pstrcpy(devname, sizeof(devname), "ide");
2038 media = MEDIA_DISK;
2040 /* extract parameters */
2041 bus_id = qemu_opt_get_number(opts, "bus", 0);
2042 unit_id = qemu_opt_get_number(opts, "unit", -1);
2043 index = qemu_opt_get_number(opts, "index", -1);
2045 cyls = qemu_opt_get_number(opts, "cyls", 0);
2046 heads = qemu_opt_get_number(opts, "heads", 0);
2047 secs = qemu_opt_get_number(opts, "secs", 0);
2049 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2051 file = qemu_opt_get(opts, "file");
2052 serial = qemu_opt_get(opts, "serial");
2054 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2055 pstrcpy(devname, sizeof(devname), buf);
2056 if (!strcmp(buf, "ide")) {
2057 type = IF_IDE;
2058 max_devs = MAX_IDE_DEVS;
2059 } else if (!strcmp(buf, "scsi")) {
2060 type = IF_SCSI;
2061 max_devs = MAX_SCSI_DEVS;
2062 } else if (!strcmp(buf, "floppy")) {
2063 type = IF_FLOPPY;
2064 max_devs = 0;
2065 } else if (!strcmp(buf, "pflash")) {
2066 type = IF_PFLASH;
2067 max_devs = 0;
2068 } else if (!strcmp(buf, "mtd")) {
2069 type = IF_MTD;
2070 max_devs = 0;
2071 } else if (!strcmp(buf, "sd")) {
2072 type = IF_SD;
2073 max_devs = 0;
2074 } else if (!strcmp(buf, "virtio")) {
2075 type = IF_VIRTIO;
2076 max_devs = 0;
2077 } else if (!strcmp(buf, "xen")) {
2078 type = IF_XEN;
2079 max_devs = 0;
2080 } else if (!strcmp(buf, "none")) {
2081 type = IF_NONE;
2082 max_devs = 0;
2083 } else {
2084 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2085 return NULL;
2089 if (cyls || heads || secs) {
2090 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2091 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2092 return NULL;
2094 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2095 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2096 return NULL;
2098 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2099 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2100 return NULL;
2104 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2105 if (!cyls) {
2106 fprintf(stderr,
2107 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2108 buf);
2109 return NULL;
2111 if (!strcmp(buf, "none"))
2112 translation = BIOS_ATA_TRANSLATION_NONE;
2113 else if (!strcmp(buf, "lba"))
2114 translation = BIOS_ATA_TRANSLATION_LBA;
2115 else if (!strcmp(buf, "auto"))
2116 translation = BIOS_ATA_TRANSLATION_AUTO;
2117 else {
2118 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2119 return NULL;
2123 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2124 if (!strcmp(buf, "disk")) {
2125 media = MEDIA_DISK;
2126 } else if (!strcmp(buf, "cdrom")) {
2127 if (cyls || secs || heads) {
2128 fprintf(stderr,
2129 "qemu: '%s' invalid physical CHS format\n", buf);
2130 return NULL;
2132 media = MEDIA_CDROM;
2133 } else {
2134 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2135 return NULL;
2139 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2140 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2141 cache = 0;
2142 else if (!strcmp(buf, "writethrough"))
2143 cache = 1;
2144 else if (!strcmp(buf, "writeback"))
2145 cache = 2;
2146 else {
2147 fprintf(stderr, "qemu: invalid cache option\n");
2148 return NULL;
2152 #ifdef CONFIG_LINUX_AIO
2153 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2154 if (!strcmp(buf, "threads"))
2155 aio = 0;
2156 else if (!strcmp(buf, "native"))
2157 aio = 1;
2158 else {
2159 fprintf(stderr, "qemu: invalid aio option\n");
2160 return NULL;
2163 #endif
2165 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2166 if (strcmp(buf, "?") == 0) {
2167 fprintf(stderr, "qemu: Supported formats:");
2168 bdrv_iterate_format(bdrv_format_print, NULL);
2169 fprintf(stderr, "\n");
2170 return NULL;
2172 drv = bdrv_find_format(buf);
2173 if (!drv) {
2174 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2175 return NULL;
2179 is_extboot = qemu_opt_get_bool(opts, "boot", 0);
2180 if (is_extboot && extboot_drive) {
2181 fprintf(stderr, "qemu: two bootable drives specified\n");
2182 return NULL;
2185 onerror = BLOCK_ERR_STOP_ENOSPC;
2186 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2187 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2188 fprintf(stderr, "werror is no supported by this format\n");
2189 return NULL;
2191 if (!strcmp(buf, "ignore"))
2192 onerror = BLOCK_ERR_IGNORE;
2193 else if (!strcmp(buf, "enospc"))
2194 onerror = BLOCK_ERR_STOP_ENOSPC;
2195 else if (!strcmp(buf, "stop"))
2196 onerror = BLOCK_ERR_STOP_ANY;
2197 else if (!strcmp(buf, "report"))
2198 onerror = BLOCK_ERR_REPORT;
2199 else {
2200 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2201 return NULL;
2205 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2206 if (type != IF_VIRTIO) {
2207 fprintf(stderr, "addr is not supported\n");
2208 return NULL;
2212 /* compute bus and unit according index */
2214 if (index != -1) {
2215 if (bus_id != 0 || unit_id != -1) {
2216 fprintf(stderr,
2217 "qemu: index cannot be used with bus and unit\n");
2218 return NULL;
2220 if (max_devs == 0)
2222 unit_id = index;
2223 bus_id = 0;
2224 } else {
2225 unit_id = index % max_devs;
2226 bus_id = index / max_devs;
2230 /* if user doesn't specify a unit_id,
2231 * try to find the first free
2234 if (unit_id == -1) {
2235 unit_id = 0;
2236 while (drive_get(type, bus_id, unit_id) != NULL) {
2237 unit_id++;
2238 if (max_devs && unit_id >= max_devs) {
2239 unit_id -= max_devs;
2240 bus_id++;
2245 /* check unit id */
2247 if (max_devs && unit_id >= max_devs) {
2248 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2249 unit_id, max_devs - 1);
2250 return NULL;
2254 * ignore multiple definitions
2257 if (drive_get(type, bus_id, unit_id) != NULL) {
2258 *fatal_error = 0;
2259 return NULL;
2262 /* init */
2264 dinfo = qemu_mallocz(sizeof(*dinfo));
2265 if ((buf = qemu_opts_id(opts)) != NULL) {
2266 dinfo->id = qemu_strdup(buf);
2267 } else {
2268 /* no id supplied -> create one */
2269 dinfo->id = qemu_mallocz(32);
2270 if (type == IF_IDE || type == IF_SCSI)
2271 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2272 if (max_devs)
2273 snprintf(dinfo->id, 32, "%s%i%s%i",
2274 devname, bus_id, mediastr, unit_id);
2275 else
2276 snprintf(dinfo->id, 32, "%s%s%i",
2277 devname, mediastr, unit_id);
2279 dinfo->bdrv = bdrv_new(dinfo->id);
2280 dinfo->devaddr = devaddr;
2281 dinfo->type = type;
2282 dinfo->bus = bus_id;
2283 dinfo->unit = unit_id;
2284 dinfo->onerror = onerror;
2285 dinfo->opts = opts;
2286 if (serial)
2287 strncpy(dinfo->serial, serial, sizeof(serial));
2288 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2289 if (is_extboot) {
2290 extboot_drive = dinfo;
2293 switch(type) {
2294 case IF_IDE:
2295 case IF_SCSI:
2296 case IF_XEN:
2297 case IF_NONE:
2298 switch(media) {
2299 case MEDIA_DISK:
2300 if (cyls != 0) {
2301 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2302 bdrv_set_translation_hint(dinfo->bdrv, translation);
2304 break;
2305 case MEDIA_CDROM:
2306 bdrv_set_type_hint(dinfo->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(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2315 break;
2316 case IF_PFLASH:
2317 case IF_MTD:
2318 break;
2319 case IF_VIRTIO:
2320 /* add virtio block device */
2321 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2322 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2323 qemu_opt_set(opts, "drive", dinfo->id);
2324 if (devaddr)
2325 qemu_opt_set(opts, "addr", devaddr);
2326 break;
2327 case IF_COUNT:
2328 abort();
2330 if (!file) {
2331 *fatal_error = 0;
2332 return NULL;
2334 bdrv_flags = 0;
2335 if (snapshot) {
2336 bdrv_flags |= BDRV_O_SNAPSHOT;
2337 cache = 2; /* always use write-back with snapshot */
2339 if (cache == 0) /* no caching */
2340 bdrv_flags |= BDRV_O_NOCACHE;
2341 else if (cache == 2) /* write-back */
2342 bdrv_flags |= BDRV_O_CACHE_WB;
2344 if (aio == 1) {
2345 bdrv_flags |= BDRV_O_NATIVE_AIO;
2346 } else {
2347 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2350 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2351 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2352 file, strerror(errno));
2353 return NULL;
2356 if (bdrv_key_required(dinfo->bdrv))
2357 autostart = 0;
2358 *fatal_error = 0;
2359 return dinfo;
2362 static int drive_init_func(QemuOpts *opts, void *opaque)
2364 QEMUMachine *machine = opaque;
2365 int fatal_error = 0;
2367 if (drive_init(opts, machine, &fatal_error) == NULL) {
2368 if (fatal_error)
2369 return 1;
2371 return 0;
2374 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2376 if (NULL == qemu_opt_get(opts, "snapshot")) {
2377 qemu_opt_set(opts, "snapshot", "on");
2379 return 0;
2382 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2384 boot_set_handler = func;
2385 boot_set_opaque = opaque;
2388 int qemu_boot_set(const char *boot_devices)
2390 if (!boot_set_handler) {
2391 return -EINVAL;
2393 return boot_set_handler(boot_set_opaque, boot_devices);
2396 static int parse_bootdevices(char *devices)
2398 /* We just do some generic consistency checks */
2399 const char *p;
2400 int bitmap = 0;
2402 for (p = devices; *p != '\0'; p++) {
2403 /* Allowed boot devices are:
2404 * a-b: floppy disk drives
2405 * c-f: IDE disk drives
2406 * g-m: machine implementation dependant drives
2407 * n-p: network devices
2408 * It's up to each machine implementation to check if the given boot
2409 * devices match the actual hardware implementation and firmware
2410 * features.
2412 if (*p < 'a' || *p > 'p') {
2413 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2414 exit(1);
2416 if (bitmap & (1 << (*p - 'a'))) {
2417 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2418 exit(1);
2420 bitmap |= 1 << (*p - 'a');
2422 return bitmap;
2425 static void restore_boot_devices(void *opaque)
2427 char *standard_boot_devices = opaque;
2429 qemu_boot_set(standard_boot_devices);
2431 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2432 qemu_free(standard_boot_devices);
2435 static void numa_add(const char *optarg)
2437 char option[128];
2438 char *endptr;
2439 unsigned long long value, endvalue;
2440 int nodenr;
2442 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2443 if (!strcmp(option, "node")) {
2444 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2445 nodenr = nb_numa_nodes;
2446 } else {
2447 nodenr = strtoull(option, NULL, 10);
2450 if (get_param_value(option, 128, "mem", optarg) == 0) {
2451 node_mem[nodenr] = 0;
2452 } else {
2453 value = strtoull(option, &endptr, 0);
2454 switch (*endptr) {
2455 case 0: case 'M': case 'm':
2456 value <<= 20;
2457 break;
2458 case 'G': case 'g':
2459 value <<= 30;
2460 break;
2462 node_mem[nodenr] = value;
2464 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2465 node_cpumask[nodenr] = 0;
2466 } else {
2467 value = strtoull(option, &endptr, 10);
2468 if (value >= 64) {
2469 value = 63;
2470 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2471 } else {
2472 if (*endptr == '-') {
2473 endvalue = strtoull(endptr+1, &endptr, 10);
2474 if (endvalue >= 63) {
2475 endvalue = 62;
2476 fprintf(stderr,
2477 "only 63 CPUs in NUMA mode supported.\n");
2479 value = (1 << (endvalue + 1)) - (1 << value);
2480 } else {
2481 value = 1 << value;
2484 node_cpumask[nodenr] = value;
2486 nb_numa_nodes++;
2488 return;
2491 static void smp_parse(const char *optarg)
2493 int smp, sockets = 0, threads = 0, cores = 0;
2494 char *endptr;
2495 char option[128];
2497 smp = strtoul(optarg, &endptr, 10);
2498 if (endptr != optarg) {
2499 if (*endptr == ',') {
2500 endptr++;
2503 if (get_param_value(option, 128, "sockets", endptr) != 0)
2504 sockets = strtoull(option, NULL, 10);
2505 if (get_param_value(option, 128, "cores", endptr) != 0)
2506 cores = strtoull(option, NULL, 10);
2507 if (get_param_value(option, 128, "threads", endptr) != 0)
2508 threads = strtoull(option, NULL, 10);
2509 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2510 max_cpus = strtoull(option, NULL, 10);
2512 /* compute missing values, prefer sockets over cores over threads */
2513 if (smp == 0 || sockets == 0) {
2514 sockets = sockets > 0 ? sockets : 1;
2515 cores = cores > 0 ? cores : 1;
2516 threads = threads > 0 ? threads : 1;
2517 if (smp == 0) {
2518 smp = cores * threads * sockets;
2519 } else {
2520 sockets = smp / (cores * threads);
2522 } else {
2523 if (cores == 0) {
2524 threads = threads > 0 ? threads : 1;
2525 cores = smp / (sockets * threads);
2526 } else {
2527 if (sockets == 0) {
2528 sockets = smp / (cores * threads);
2529 } else {
2530 threads = smp / (cores * sockets);
2534 smp_cpus = smp;
2535 smp_cores = cores > 0 ? cores : 1;
2536 smp_threads = threads > 0 ? threads : 1;
2537 if (max_cpus == 0)
2538 max_cpus = smp_cpus;
2541 /***********************************************************/
2542 /* USB devices */
2544 static void usb_msd_password_cb(void *opaque, int err)
2546 USBDevice *dev = opaque;
2548 if (!err)
2549 usb_device_attach(dev);
2550 else
2551 dev->info->handle_destroy(dev);
2554 static struct {
2555 const char *name;
2556 const char *qdev;
2557 } usbdevs[] = {
2559 .name = "mouse",
2560 .qdev = "QEMU USB Mouse",
2562 .name = "tablet",
2563 .qdev = "QEMU USB Tablet",
2565 .name = "keyboard",
2566 .qdev = "QEMU USB Keyboard",
2568 .name = "wacom-tablet",
2569 .qdev = "QEMU PenPartner Tablet",
2573 static int usb_device_add(const char *devname, int is_hotplug)
2575 const char *p;
2576 USBBus *bus = usb_bus_find(-1 /* any */);
2577 USBDevice *dev = NULL;
2578 int i;
2580 if (!usb_enabled)
2581 return -1;
2583 /* simple devices which don't need extra care */
2584 for (i = 0; i < ARRAY_SIZE(usbdevs); i++) {
2585 if (strcmp(devname, usbdevs[i].name) != 0)
2586 continue;
2587 dev = usb_create_simple(bus, usbdevs[i].qdev);
2588 goto done;
2591 /* the other ones */
2592 if (strstart(devname, "host:", &p)) {
2593 dev = usb_host_device_open(p);
2594 } else if (strstart(devname, "disk:", &p)) {
2595 BlockDriverState *bs;
2597 dev = usb_msd_init(p);
2598 if (!dev)
2599 return -1;
2600 bs = usb_msd_get_bdrv(dev);
2601 if (bdrv_key_required(bs)) {
2602 autostart = 0;
2603 if (is_hotplug) {
2604 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2605 dev);
2606 return 0;
2609 } else if (strstart(devname, "serial:", &p)) {
2610 dev = usb_serial_init(p);
2611 #ifdef CONFIG_BRLAPI
2612 } else if (!strcmp(devname, "braille")) {
2613 dev = usb_baum_init();
2614 #endif
2615 } else if (strstart(devname, "net:", &p)) {
2616 QemuOpts *opts;
2617 int idx;
2619 opts = qemu_opts_parse(&qemu_net_opts, p, NULL);
2620 if (!opts) {
2621 return -1;
2624 qemu_opt_set(opts, "type", "nic");
2625 qemu_opt_set(opts, "model", "usb");
2627 idx = net_client_init(NULL, opts, 0);
2628 if (idx == -1) {
2629 return -1;
2632 dev = usb_net_init(&nd_table[idx]);
2633 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2634 dev = usb_bt_init(devname[2] ? hci_init(p) :
2635 bt_new_hci(qemu_find_bt_vlan(0)));
2636 } else {
2637 return -1;
2639 if (!dev)
2640 return -1;
2642 done:
2643 return 0;
2646 static int usb_device_del(const char *devname)
2648 int bus_num, addr;
2649 const char *p;
2651 if (strstart(devname, "host:", &p))
2652 return usb_host_device_close(p);
2654 if (!usb_enabled)
2655 return -1;
2657 p = strchr(devname, '.');
2658 if (!p)
2659 return -1;
2660 bus_num = strtoul(devname, NULL, 0);
2661 addr = strtoul(p + 1, NULL, 0);
2663 return usb_device_delete_addr(bus_num, addr);
2666 static int usb_parse(const char *cmdline)
2668 return usb_device_add(cmdline, 0);
2671 void do_usb_add(Monitor *mon, const QDict *qdict)
2673 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2676 void do_usb_del(Monitor *mon, const QDict *qdict)
2678 usb_device_del(qdict_get_str(qdict, "devname"));
2681 /***********************************************************/
2682 /* PCMCIA/Cardbus */
2684 static struct pcmcia_socket_entry_s {
2685 PCMCIASocket *socket;
2686 struct pcmcia_socket_entry_s *next;
2687 } *pcmcia_sockets = 0;
2689 void pcmcia_socket_register(PCMCIASocket *socket)
2691 struct pcmcia_socket_entry_s *entry;
2693 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2694 entry->socket = socket;
2695 entry->next = pcmcia_sockets;
2696 pcmcia_sockets = entry;
2699 void pcmcia_socket_unregister(PCMCIASocket *socket)
2701 struct pcmcia_socket_entry_s *entry, **ptr;
2703 ptr = &pcmcia_sockets;
2704 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2705 if (entry->socket == socket) {
2706 *ptr = entry->next;
2707 qemu_free(entry);
2711 void pcmcia_info(Monitor *mon)
2713 struct pcmcia_socket_entry_s *iter;
2715 if (!pcmcia_sockets)
2716 monitor_printf(mon, "No PCMCIA sockets\n");
2718 for (iter = pcmcia_sockets; iter; iter = iter->next)
2719 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2720 iter->socket->attached ? iter->socket->card_string :
2721 "Empty");
2724 /***********************************************************/
2725 /* register display */
2727 struct DisplayAllocator default_allocator = {
2728 defaultallocator_create_displaysurface,
2729 defaultallocator_resize_displaysurface,
2730 defaultallocator_free_displaysurface
2733 void register_displaystate(DisplayState *ds)
2735 DisplayState **s;
2736 s = &display_state;
2737 while (*s != NULL)
2738 s = &(*s)->next;
2739 ds->next = NULL;
2740 *s = ds;
2743 DisplayState *get_displaystate(void)
2745 return display_state;
2748 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2750 if(ds->allocator == &default_allocator) ds->allocator = da;
2751 return ds->allocator;
2754 /* dumb display */
2756 static void dumb_display_init(void)
2758 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2759 ds->allocator = &default_allocator;
2760 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2761 register_displaystate(ds);
2764 /***********************************************************/
2765 /* I/O handling */
2767 typedef struct IOHandlerRecord {
2768 int fd;
2769 IOCanRWHandler *fd_read_poll;
2770 IOHandler *fd_read;
2771 IOHandler *fd_write;
2772 int deleted;
2773 void *opaque;
2774 /* temporary data */
2775 struct pollfd *ufd;
2776 struct IOHandlerRecord *next;
2777 } IOHandlerRecord;
2779 static IOHandlerRecord *first_io_handler;
2781 /* XXX: fd_read_poll should be suppressed, but an API change is
2782 necessary in the character devices to suppress fd_can_read(). */
2783 int qemu_set_fd_handler2(int fd,
2784 IOCanRWHandler *fd_read_poll,
2785 IOHandler *fd_read,
2786 IOHandler *fd_write,
2787 void *opaque)
2789 IOHandlerRecord **pioh, *ioh;
2791 if (!fd_read && !fd_write) {
2792 pioh = &first_io_handler;
2793 for(;;) {
2794 ioh = *pioh;
2795 if (ioh == NULL)
2796 break;
2797 if (ioh->fd == fd) {
2798 ioh->deleted = 1;
2799 break;
2801 pioh = &ioh->next;
2803 } else {
2804 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2805 if (ioh->fd == fd)
2806 goto found;
2808 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2809 ioh->next = first_io_handler;
2810 first_io_handler = ioh;
2811 found:
2812 ioh->fd = fd;
2813 ioh->fd_read_poll = fd_read_poll;
2814 ioh->fd_read = fd_read;
2815 ioh->fd_write = fd_write;
2816 ioh->opaque = opaque;
2817 ioh->deleted = 0;
2819 qemu_notify_event();
2820 return 0;
2823 int qemu_set_fd_handler(int fd,
2824 IOHandler *fd_read,
2825 IOHandler *fd_write,
2826 void *opaque)
2828 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2831 #ifdef _WIN32
2832 /***********************************************************/
2833 /* Polling handling */
2835 typedef struct PollingEntry {
2836 PollingFunc *func;
2837 void *opaque;
2838 struct PollingEntry *next;
2839 } PollingEntry;
2841 static PollingEntry *first_polling_entry;
2843 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2845 PollingEntry **ppe, *pe;
2846 pe = qemu_mallocz(sizeof(PollingEntry));
2847 pe->func = func;
2848 pe->opaque = opaque;
2849 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2850 *ppe = pe;
2851 return 0;
2854 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2856 PollingEntry **ppe, *pe;
2857 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2858 pe = *ppe;
2859 if (pe->func == func && pe->opaque == opaque) {
2860 *ppe = pe->next;
2861 qemu_free(pe);
2862 break;
2867 /***********************************************************/
2868 /* Wait objects support */
2869 typedef struct WaitObjects {
2870 int num;
2871 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2872 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2873 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2874 } WaitObjects;
2876 static WaitObjects wait_objects = {0};
2878 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2880 WaitObjects *w = &wait_objects;
2882 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2883 return -1;
2884 w->events[w->num] = handle;
2885 w->func[w->num] = func;
2886 w->opaque[w->num] = opaque;
2887 w->num++;
2888 return 0;
2891 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2893 int i, found;
2894 WaitObjects *w = &wait_objects;
2896 found = 0;
2897 for (i = 0; i < w->num; i++) {
2898 if (w->events[i] == handle)
2899 found = 1;
2900 if (found) {
2901 w->events[i] = w->events[i + 1];
2902 w->func[i] = w->func[i + 1];
2903 w->opaque[i] = w->opaque[i + 1];
2906 if (found)
2907 w->num--;
2909 #endif
2911 /***********************************************************/
2912 /* ram save/restore */
2914 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2915 #define RAM_SAVE_FLAG_COMPRESS 0x02
2916 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2917 #define RAM_SAVE_FLAG_PAGE 0x08
2918 #define RAM_SAVE_FLAG_EOS 0x10
2920 static int is_dup_page(uint8_t *page, uint8_t ch)
2922 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2923 uint32_t *array = (uint32_t *)page;
2924 int i;
2926 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2927 if (array[i] != val)
2928 return 0;
2931 return 1;
2934 static int ram_save_block(QEMUFile *f)
2936 static ram_addr_t current_addr = 0;
2937 ram_addr_t saved_addr = current_addr;
2938 ram_addr_t addr = 0;
2939 int found = 0;
2941 while (addr < last_ram_offset) {
2942 if (kvm_enabled() && current_addr == 0) {
2943 int r;
2944 r = kvm_update_dirty_pages_log();
2945 if (r) {
2946 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
2947 qemu_file_set_error(f);
2948 return 0;
2951 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2952 uint8_t *p;
2954 cpu_physical_memory_reset_dirty(current_addr,
2955 current_addr + TARGET_PAGE_SIZE,
2956 MIGRATION_DIRTY_FLAG);
2958 p = qemu_get_ram_ptr(current_addr);
2960 if (is_dup_page(p, *p)) {
2961 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2962 qemu_put_byte(f, *p);
2963 } else {
2964 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2965 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2968 found = 1;
2969 break;
2971 addr += TARGET_PAGE_SIZE;
2972 current_addr = (saved_addr + addr) % last_ram_offset;
2975 return found;
2978 static uint64_t bytes_transferred = 0;
2980 static ram_addr_t ram_save_remaining(void)
2982 ram_addr_t addr;
2983 ram_addr_t count = 0;
2985 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2986 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2987 count++;
2990 return count;
2993 uint64_t ram_bytes_remaining(void)
2995 return ram_save_remaining() * TARGET_PAGE_SIZE;
2998 uint64_t ram_bytes_transferred(void)
3000 return bytes_transferred;
3003 uint64_t ram_bytes_total(void)
3005 return last_ram_offset;
3008 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3010 ram_addr_t addr;
3011 uint64_t bytes_transferred_last;
3012 double bwidth = 0;
3013 uint64_t expected_time = 0;
3015 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3016 qemu_file_set_error(f);
3017 return 0;
3020 if (stage == 1) {
3021 /* Make sure all dirty bits are set */
3022 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3023 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3024 cpu_physical_memory_set_dirty(addr);
3027 /* Enable dirty memory tracking */
3028 cpu_physical_memory_set_dirty_tracking(1);
3030 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3033 bytes_transferred_last = bytes_transferred;
3034 bwidth = get_clock();
3036 while (!qemu_file_rate_limit(f)) {
3037 int ret;
3039 ret = ram_save_block(f);
3040 bytes_transferred += ret * TARGET_PAGE_SIZE;
3041 if (ret == 0) /* no more blocks */
3042 break;
3045 bwidth = get_clock() - bwidth;
3046 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3048 /* if we haven't transferred anything this round, force expected_time to a
3049 * a very high value, but without crashing */
3050 if (bwidth == 0)
3051 bwidth = 0.000001;
3053 /* try transferring iterative blocks of memory */
3055 if (stage == 3) {
3057 /* flush all remaining blocks regardless of rate limiting */
3058 while (ram_save_block(f) != 0) {
3059 bytes_transferred += TARGET_PAGE_SIZE;
3061 cpu_physical_memory_set_dirty_tracking(0);
3064 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3066 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3068 return (stage == 2) && (expected_time <= migrate_max_downtime());
3071 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3073 ram_addr_t addr;
3074 int flags;
3076 if (version_id != 3)
3077 return -EINVAL;
3079 do {
3080 addr = qemu_get_be64(f);
3082 flags = addr & ~TARGET_PAGE_MASK;
3083 addr &= TARGET_PAGE_MASK;
3085 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3086 if (addr != last_ram_offset)
3087 return -EINVAL;
3090 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3091 uint8_t ch = qemu_get_byte(f);
3092 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3093 #ifndef _WIN32
3094 if (ch == 0 &&
3095 (!kvm_enabled() || kvm_has_sync_mmu())) {
3096 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3098 #endif
3099 } else if (flags & RAM_SAVE_FLAG_PAGE)
3100 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3101 } while (!(flags & RAM_SAVE_FLAG_EOS));
3103 return 0;
3106 void qemu_service_io(void)
3108 qemu_notify_event();
3111 /***********************************************************/
3112 /* machine registration */
3114 static QEMUMachine *first_machine = NULL;
3115 QEMUMachine *current_machine = NULL;
3117 int qemu_register_machine(QEMUMachine *m)
3119 QEMUMachine **pm;
3120 pm = &first_machine;
3121 while (*pm != NULL)
3122 pm = &(*pm)->next;
3123 m->next = NULL;
3124 *pm = m;
3125 return 0;
3128 static QEMUMachine *find_machine(const char *name)
3130 QEMUMachine *m;
3132 for(m = first_machine; m != NULL; m = m->next) {
3133 if (!strcmp(m->name, name))
3134 return m;
3135 if (m->alias && !strcmp(m->alias, name))
3136 return m;
3138 return NULL;
3141 static QEMUMachine *find_default_machine(void)
3143 QEMUMachine *m;
3145 for(m = first_machine; m != NULL; m = m->next) {
3146 if (m->is_default) {
3147 return m;
3150 return NULL;
3153 /***********************************************************/
3154 /* main execution loop */
3156 static void gui_update(void *opaque)
3158 uint64_t interval = GUI_REFRESH_INTERVAL;
3159 DisplayState *ds = opaque;
3160 DisplayChangeListener *dcl = ds->listeners;
3162 dpy_refresh(ds);
3164 while (dcl != NULL) {
3165 if (dcl->gui_timer_interval &&
3166 dcl->gui_timer_interval < interval)
3167 interval = dcl->gui_timer_interval;
3168 dcl = dcl->next;
3170 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3173 static void nographic_update(void *opaque)
3175 uint64_t interval = GUI_REFRESH_INTERVAL;
3177 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3180 struct vm_change_state_entry {
3181 VMChangeStateHandler *cb;
3182 void *opaque;
3183 QLIST_ENTRY (vm_change_state_entry) entries;
3186 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3188 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3189 void *opaque)
3191 VMChangeStateEntry *e;
3193 e = qemu_mallocz(sizeof (*e));
3195 e->cb = cb;
3196 e->opaque = opaque;
3197 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3198 return e;
3201 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3203 QLIST_REMOVE (e, entries);
3204 qemu_free (e);
3207 static void vm_state_notify(int running, int reason)
3209 VMChangeStateEntry *e;
3211 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3212 e->cb(e->opaque, running, reason);
3216 static void resume_all_vcpus(void);
3217 static void pause_all_vcpus(void);
3219 void vm_start(void)
3221 if (!vm_running) {
3222 cpu_enable_ticks();
3223 vm_running = 1;
3224 vm_state_notify(1, 0);
3225 qemu_rearm_alarm_timer(alarm_timer);
3226 resume_all_vcpus();
3230 /* reset/shutdown handler */
3232 typedef struct QEMUResetEntry {
3233 QTAILQ_ENTRY(QEMUResetEntry) entry;
3234 QEMUResetHandler *func;
3235 void *opaque;
3236 } QEMUResetEntry;
3238 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3239 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3240 static int reset_requested;
3241 static int shutdown_requested;
3242 static int powerdown_requested;
3243 static int debug_requested;
3244 static int vmstop_requested;
3246 int qemu_no_shutdown(void)
3248 int r = no_shutdown;
3249 no_shutdown = 0;
3250 return r;
3253 int qemu_shutdown_requested(void)
3255 int r = shutdown_requested;
3256 shutdown_requested = 0;
3257 return r;
3260 int qemu_reset_requested(void)
3262 int r = reset_requested;
3263 reset_requested = 0;
3264 return r;
3267 int qemu_powerdown_requested(void)
3269 int r = powerdown_requested;
3270 powerdown_requested = 0;
3271 return r;
3274 static int qemu_debug_requested(void)
3276 int r = debug_requested;
3277 debug_requested = 0;
3278 return r;
3281 static int qemu_vmstop_requested(void)
3283 int r = vmstop_requested;
3284 vmstop_requested = 0;
3285 return r;
3288 static void do_vm_stop(int reason)
3290 if (vm_running) {
3291 cpu_disable_ticks();
3292 vm_running = 0;
3293 pause_all_vcpus();
3294 vm_state_notify(0, reason);
3298 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3300 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3302 re->func = func;
3303 re->opaque = opaque;
3304 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3307 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3309 QEMUResetEntry *re;
3311 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3312 if (re->func == func && re->opaque == opaque) {
3313 QTAILQ_REMOVE(&reset_handlers, re, entry);
3314 qemu_free(re);
3315 return;
3320 void qemu_system_reset(void)
3322 QEMUResetEntry *re, *nre;
3324 /* reset all devices */
3325 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3326 re->func(re->opaque);
3330 void qemu_system_reset_request(void)
3332 if (no_reboot) {
3333 shutdown_requested = 1;
3334 } else {
3335 reset_requested = 1;
3337 if (cpu_single_env) {
3338 cpu_single_env->stopped = 1;
3340 qemu_notify_event();
3343 void qemu_system_shutdown_request(void)
3345 shutdown_requested = 1;
3346 qemu_notify_event();
3349 void qemu_system_powerdown_request(void)
3351 powerdown_requested = 1;
3352 qemu_notify_event();
3355 #ifdef CONFIG_IOTHREAD
3356 static void qemu_system_vmstop_request(int reason)
3358 vmstop_requested = reason;
3359 qemu_notify_event();
3361 #endif
3363 #ifndef _WIN32
3364 static int io_thread_fd = -1;
3366 static void qemu_event_increment(void)
3368 static const char byte = 0;
3370 if (io_thread_fd == -1)
3371 return;
3373 write(io_thread_fd, &byte, sizeof(byte));
3376 static void qemu_event_read(void *opaque)
3378 int fd = (unsigned long)opaque;
3379 ssize_t len;
3381 /* Drain the notify pipe */
3382 do {
3383 char buffer[512];
3384 len = read(fd, buffer, sizeof(buffer));
3385 } while ((len == -1 && errno == EINTR) || len > 0);
3388 static int qemu_event_init(void)
3390 int err;
3391 int fds[2];
3393 err = pipe(fds);
3394 if (err == -1)
3395 return -errno;
3397 err = fcntl_setfl(fds[0], O_NONBLOCK);
3398 if (err < 0)
3399 goto fail;
3401 err = fcntl_setfl(fds[1], O_NONBLOCK);
3402 if (err < 0)
3403 goto fail;
3405 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3406 (void *)(unsigned long)fds[0]);
3408 io_thread_fd = fds[1];
3409 return 0;
3411 fail:
3412 close(fds[0]);
3413 close(fds[1]);
3414 return err;
3416 #else
3417 HANDLE qemu_event_handle;
3419 static void dummy_event_handler(void *opaque)
3423 static int qemu_event_init(void)
3425 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3426 if (!qemu_event_handle) {
3427 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3428 return -1;
3430 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3431 return 0;
3434 static void qemu_event_increment(void)
3436 if (!SetEvent(qemu_event_handle)) {
3437 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3438 GetLastError());
3439 exit (1);
3442 #endif
3444 static int cpu_can_run(CPUState *env)
3446 if (env->stop)
3447 return 0;
3448 if (env->stopped)
3449 return 0;
3450 return 1;
3453 #ifndef CONFIG_IOTHREAD
3454 static int qemu_init_main_loop(void)
3456 return qemu_event_init();
3459 void qemu_init_vcpu(void *_env)
3461 CPUState *env = _env;
3463 if (kvm_enabled())
3464 kvm_init_vcpu(env);
3465 env->nr_cores = smp_cores;
3466 env->nr_threads = smp_threads;
3467 return;
3470 int qemu_cpu_self(void *env)
3472 return 1;
3475 static void resume_all_vcpus(void)
3479 static void pause_all_vcpus(void)
3483 void qemu_cpu_kick(void *env)
3485 return;
3488 void qemu_notify_event(void)
3490 CPUState *env = cpu_single_env;
3492 if (kvm_enabled()) {
3493 qemu_kvm_notify_work();
3494 return;
3496 if (env) {
3497 cpu_exit(env);
3501 #ifdef KVM_UPSTREAM
3502 void qemu_mutex_lock_iothread(void) {}
3503 void qemu_mutex_unlock_iothread(void) {}
3504 #endif
3506 void vm_stop(int reason)
3508 do_vm_stop(reason);
3511 #else /* CONFIG_IOTHREAD */
3513 #include "qemu-thread.h"
3515 QemuMutex qemu_global_mutex;
3516 static QemuMutex qemu_fair_mutex;
3518 static QemuThread io_thread;
3520 static QemuThread *tcg_cpu_thread;
3521 static QemuCond *tcg_halt_cond;
3523 static int qemu_system_ready;
3524 /* cpu creation */
3525 static QemuCond qemu_cpu_cond;
3526 /* system init */
3527 static QemuCond qemu_system_cond;
3528 static QemuCond qemu_pause_cond;
3530 static void block_io_signals(void);
3531 static void unblock_io_signals(void);
3532 static int tcg_has_work(void);
3534 static int qemu_init_main_loop(void)
3536 int ret;
3538 ret = qemu_event_init();
3539 if (ret)
3540 return ret;
3542 qemu_cond_init(&qemu_pause_cond);
3543 qemu_mutex_init(&qemu_fair_mutex);
3544 qemu_mutex_init(&qemu_global_mutex);
3545 qemu_mutex_lock(&qemu_global_mutex);
3547 unblock_io_signals();
3548 qemu_thread_self(&io_thread);
3550 return 0;
3553 static void qemu_wait_io_event(CPUState *env)
3555 while (!tcg_has_work())
3556 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3558 qemu_mutex_unlock(&qemu_global_mutex);
3561 * Users of qemu_global_mutex can be starved, having no chance
3562 * to acquire it since this path will get to it first.
3563 * So use another lock to provide fairness.
3565 qemu_mutex_lock(&qemu_fair_mutex);
3566 qemu_mutex_unlock(&qemu_fair_mutex);
3568 qemu_mutex_lock(&qemu_global_mutex);
3569 if (env->stop) {
3570 env->stop = 0;
3571 env->stopped = 1;
3572 qemu_cond_signal(&qemu_pause_cond);
3576 static int qemu_cpu_exec(CPUState *env);
3578 static void *kvm_cpu_thread_fn(void *arg)
3580 CPUState *env = arg;
3582 block_io_signals();
3583 qemu_thread_self(env->thread);
3584 if (kvm_enabled())
3585 kvm_init_vcpu(env);
3587 /* signal CPU creation */
3588 qemu_mutex_lock(&qemu_global_mutex);
3589 env->created = 1;
3590 qemu_cond_signal(&qemu_cpu_cond);
3592 /* and wait for machine initialization */
3593 while (!qemu_system_ready)
3594 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3596 while (1) {
3597 if (cpu_can_run(env))
3598 qemu_cpu_exec(env);
3599 qemu_wait_io_event(env);
3602 return NULL;
3605 static void tcg_cpu_exec(void);
3607 static void *tcg_cpu_thread_fn(void *arg)
3609 CPUState *env = arg;
3611 block_io_signals();
3612 qemu_thread_self(env->thread);
3614 /* signal CPU creation */
3615 qemu_mutex_lock(&qemu_global_mutex);
3616 for (env = first_cpu; env != NULL; env = env->next_cpu)
3617 env->created = 1;
3618 qemu_cond_signal(&qemu_cpu_cond);
3620 /* and wait for machine initialization */
3621 while (!qemu_system_ready)
3622 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3624 while (1) {
3625 tcg_cpu_exec();
3626 qemu_wait_io_event(cur_cpu);
3629 return NULL;
3632 void qemu_cpu_kick(void *_env)
3634 CPUState *env = _env;
3635 qemu_cond_broadcast(env->halt_cond);
3636 if (kvm_enabled())
3637 qemu_thread_signal(env->thread, SIGUSR1);
3640 int qemu_cpu_self(void *_env)
3642 CPUState *env = _env;
3643 QemuThread this;
3645 qemu_thread_self(&this);
3647 return qemu_thread_equal(&this, env->thread);
3650 static void cpu_signal(int sig)
3652 if (cpu_single_env)
3653 cpu_exit(cpu_single_env);
3656 static void block_io_signals(void)
3658 sigset_t set;
3659 struct sigaction sigact;
3661 sigemptyset(&set);
3662 sigaddset(&set, SIGUSR2);
3663 sigaddset(&set, SIGIO);
3664 sigaddset(&set, SIGALRM);
3665 pthread_sigmask(SIG_BLOCK, &set, NULL);
3667 sigemptyset(&set);
3668 sigaddset(&set, SIGUSR1);
3669 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3671 memset(&sigact, 0, sizeof(sigact));
3672 sigact.sa_handler = cpu_signal;
3673 sigaction(SIGUSR1, &sigact, NULL);
3676 static void unblock_io_signals(void)
3678 sigset_t set;
3680 sigemptyset(&set);
3681 sigaddset(&set, SIGUSR2);
3682 sigaddset(&set, SIGIO);
3683 sigaddset(&set, SIGALRM);
3684 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3686 sigemptyset(&set);
3687 sigaddset(&set, SIGUSR1);
3688 pthread_sigmask(SIG_BLOCK, &set, NULL);
3691 static void qemu_signal_lock(unsigned int msecs)
3693 qemu_mutex_lock(&qemu_fair_mutex);
3695 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3696 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3697 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3698 break;
3700 qemu_mutex_unlock(&qemu_fair_mutex);
3703 void qemu_mutex_lock_iothread(void)
3705 if (kvm_enabled()) {
3706 qemu_mutex_lock(&qemu_fair_mutex);
3707 qemu_mutex_lock(&qemu_global_mutex);
3708 qemu_mutex_unlock(&qemu_fair_mutex);
3709 } else
3710 qemu_signal_lock(100);
3713 void qemu_mutex_unlock_iothread(void)
3715 qemu_mutex_unlock(&qemu_global_mutex);
3718 static int all_vcpus_paused(void)
3720 CPUState *penv = first_cpu;
3722 while (penv) {
3723 if (!penv->stopped)
3724 return 0;
3725 penv = (CPUState *)penv->next_cpu;
3728 return 1;
3731 static void pause_all_vcpus(void)
3733 CPUState *penv = first_cpu;
3735 while (penv) {
3736 penv->stop = 1;
3737 qemu_thread_signal(penv->thread, SIGUSR1);
3738 qemu_cpu_kick(penv);
3739 penv = (CPUState *)penv->next_cpu;
3742 while (!all_vcpus_paused()) {
3743 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3744 penv = first_cpu;
3745 while (penv) {
3746 qemu_thread_signal(penv->thread, SIGUSR1);
3747 penv = (CPUState *)penv->next_cpu;
3752 static void resume_all_vcpus(void)
3754 CPUState *penv = first_cpu;
3756 while (penv) {
3757 penv->stop = 0;
3758 penv->stopped = 0;
3759 qemu_thread_signal(penv->thread, SIGUSR1);
3760 qemu_cpu_kick(penv);
3761 penv = (CPUState *)penv->next_cpu;
3765 static void tcg_init_vcpu(void *_env)
3767 CPUState *env = _env;
3768 /* share a single thread for all cpus with TCG */
3769 if (!tcg_cpu_thread) {
3770 env->thread = qemu_mallocz(sizeof(QemuThread));
3771 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3772 qemu_cond_init(env->halt_cond);
3773 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3774 while (env->created == 0)
3775 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3776 tcg_cpu_thread = env->thread;
3777 tcg_halt_cond = env->halt_cond;
3778 } else {
3779 env->thread = tcg_cpu_thread;
3780 env->halt_cond = tcg_halt_cond;
3784 static void kvm_start_vcpu(CPUState *env)
3786 env->thread = qemu_mallocz(sizeof(QemuThread));
3787 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3788 qemu_cond_init(env->halt_cond);
3789 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3790 while (env->created == 0)
3791 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3794 void qemu_init_vcpu(void *_env)
3796 CPUState *env = _env;
3798 if (kvm_enabled())
3799 kvm_start_vcpu(env);
3800 else
3801 tcg_init_vcpu(env);
3802 env->nr_cores = smp_cores;
3803 env->nr_threads = smp_threads;
3806 void qemu_notify_event(void)
3808 qemu_event_increment();
3811 void vm_stop(int reason)
3813 QemuThread me;
3814 qemu_thread_self(&me);
3816 if (!qemu_thread_equal(&me, &io_thread)) {
3817 qemu_system_vmstop_request(reason);
3819 * FIXME: should not return to device code in case
3820 * vm_stop() has been requested.
3822 if (cpu_single_env) {
3823 cpu_exit(cpu_single_env);
3824 cpu_single_env->stop = 1;
3826 return;
3828 do_vm_stop(reason);
3831 #endif
3834 #ifdef _WIN32
3835 static void host_main_loop_wait(int *timeout)
3837 int ret, ret2, i;
3838 PollingEntry *pe;
3841 /* XXX: need to suppress polling by better using win32 events */
3842 ret = 0;
3843 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3844 ret |= pe->func(pe->opaque);
3846 if (ret == 0) {
3847 int err;
3848 WaitObjects *w = &wait_objects;
3850 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3851 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3852 if (w->func[ret - WAIT_OBJECT_0])
3853 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3855 /* Check for additional signaled events */
3856 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3858 /* Check if event is signaled */
3859 ret2 = WaitForSingleObject(w->events[i], 0);
3860 if(ret2 == WAIT_OBJECT_0) {
3861 if (w->func[i])
3862 w->func[i](w->opaque[i]);
3863 } else if (ret2 == WAIT_TIMEOUT) {
3864 } else {
3865 err = GetLastError();
3866 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3869 } else if (ret == WAIT_TIMEOUT) {
3870 } else {
3871 err = GetLastError();
3872 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3876 *timeout = 0;
3878 #else
3879 static void host_main_loop_wait(int *timeout)
3882 #endif
3884 void main_loop_wait(int timeout)
3886 IOHandlerRecord *ioh;
3887 fd_set rfds, wfds, xfds;
3888 int ret, nfds;
3889 struct timeval tv;
3891 qemu_bh_update_timeout(&timeout);
3893 host_main_loop_wait(&timeout);
3895 /* poll any events */
3896 /* XXX: separate device handlers from system ones */
3897 nfds = -1;
3898 FD_ZERO(&rfds);
3899 FD_ZERO(&wfds);
3900 FD_ZERO(&xfds);
3901 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3902 if (ioh->deleted)
3903 continue;
3904 if (ioh->fd_read &&
3905 (!ioh->fd_read_poll ||
3906 ioh->fd_read_poll(ioh->opaque) != 0)) {
3907 FD_SET(ioh->fd, &rfds);
3908 if (ioh->fd > nfds)
3909 nfds = ioh->fd;
3911 if (ioh->fd_write) {
3912 FD_SET(ioh->fd, &wfds);
3913 if (ioh->fd > nfds)
3914 nfds = ioh->fd;
3918 tv.tv_sec = timeout / 1000;
3919 tv.tv_usec = (timeout % 1000) * 1000;
3921 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3923 qemu_mutex_unlock_iothread();
3924 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3925 qemu_mutex_lock_iothread();
3926 if (ret > 0) {
3927 IOHandlerRecord **pioh;
3929 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3930 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3931 ioh->fd_read(ioh->opaque);
3932 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3933 FD_CLR(ioh->fd, &rfds);
3935 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3936 ioh->fd_write(ioh->opaque);
3940 /* remove deleted IO handlers */
3941 pioh = &first_io_handler;
3942 while (*pioh) {
3943 ioh = *pioh;
3944 if (ioh->deleted) {
3945 *pioh = ioh->next;
3946 qemu_free(ioh);
3947 } else
3948 pioh = &ioh->next;
3952 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3954 /* rearm timer, if not periodic */
3955 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3956 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3957 qemu_rearm_alarm_timer(alarm_timer);
3960 /* vm time timers */
3961 if (vm_running) {
3962 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3963 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3964 qemu_get_clock(vm_clock));
3967 /* real time timers */
3968 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3969 qemu_get_clock(rt_clock));
3971 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3972 qemu_get_clock(host_clock));
3974 /* Check bottom-halves last in case any of the earlier events triggered
3975 them. */
3976 qemu_bh_poll();
3980 static int qemu_cpu_exec(CPUState *env)
3982 int ret;
3983 #ifdef CONFIG_PROFILER
3984 int64_t ti;
3985 #endif
3987 #ifdef CONFIG_PROFILER
3988 ti = profile_getclock();
3989 #endif
3990 if (use_icount) {
3991 int64_t count;
3992 int decr;
3993 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3994 env->icount_decr.u16.low = 0;
3995 env->icount_extra = 0;
3996 count = qemu_next_deadline();
3997 count = (count + (1 << icount_time_shift) - 1)
3998 >> icount_time_shift;
3999 qemu_icount += count;
4000 decr = (count > 0xffff) ? 0xffff : count;
4001 count -= decr;
4002 env->icount_decr.u16.low = decr;
4003 env->icount_extra = count;
4005 ret = cpu_exec(env);
4006 #ifdef CONFIG_PROFILER
4007 qemu_time += profile_getclock() - ti;
4008 #endif
4009 if (use_icount) {
4010 /* Fold pending instructions back into the
4011 instruction counter, and clear the interrupt flag. */
4012 qemu_icount -= (env->icount_decr.u16.low
4013 + env->icount_extra);
4014 env->icount_decr.u32 = 0;
4015 env->icount_extra = 0;
4017 return ret;
4020 static void tcg_cpu_exec(void)
4022 int ret = 0;
4024 if (next_cpu == NULL)
4025 next_cpu = first_cpu;
4026 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4027 CPUState *env = cur_cpu = next_cpu;
4029 if (!vm_running)
4030 break;
4031 if (timer_alarm_pending) {
4032 timer_alarm_pending = 0;
4033 break;
4035 if (cpu_can_run(env))
4036 ret = qemu_cpu_exec(env);
4037 if (ret == EXCP_DEBUG) {
4038 gdb_set_stop_cpu(env);
4039 debug_requested = 1;
4040 break;
4045 static int cpu_has_work(CPUState *env)
4047 if (env->stop)
4048 return 1;
4049 if (env->stopped)
4050 return 0;
4051 if (!env->halted)
4052 return 1;
4053 if (qemu_cpu_has_work(env))
4054 return 1;
4055 return 0;
4058 static int tcg_has_work(void)
4060 CPUState *env;
4062 for (env = first_cpu; env != NULL; env = env->next_cpu)
4063 if (cpu_has_work(env))
4064 return 1;
4065 return 0;
4068 static int qemu_calculate_timeout(void)
4070 #ifndef CONFIG_IOTHREAD
4071 int timeout;
4073 if (!vm_running)
4074 timeout = 5000;
4075 else if (tcg_has_work())
4076 timeout = 0;
4077 else if (!use_icount)
4078 timeout = 5000;
4079 else {
4080 /* XXX: use timeout computed from timers */
4081 int64_t add;
4082 int64_t delta;
4083 /* Advance virtual time to the next event. */
4084 if (use_icount == 1) {
4085 /* When not using an adaptive execution frequency
4086 we tend to get badly out of sync with real time,
4087 so just delay for a reasonable amount of time. */
4088 delta = 0;
4089 } else {
4090 delta = cpu_get_icount() - cpu_get_clock();
4092 if (delta > 0) {
4093 /* If virtual time is ahead of real time then just
4094 wait for IO. */
4095 timeout = (delta / 1000000) + 1;
4096 } else {
4097 /* Wait for either IO to occur or the next
4098 timer event. */
4099 add = qemu_next_deadline();
4100 /* We advance the timer before checking for IO.
4101 Limit the amount we advance so that early IO
4102 activity won't get the guest too far ahead. */
4103 if (add > 10000000)
4104 add = 10000000;
4105 delta += add;
4106 add = (add + (1 << icount_time_shift) - 1)
4107 >> icount_time_shift;
4108 qemu_icount += add;
4109 timeout = delta / 1000000;
4110 if (timeout < 0)
4111 timeout = 0;
4115 return timeout;
4116 #else /* CONFIG_IOTHREAD */
4117 return 1000;
4118 #endif
4121 static int vm_can_run(void)
4123 if (powerdown_requested)
4124 return 0;
4125 if (reset_requested)
4126 return 0;
4127 if (shutdown_requested)
4128 return 0;
4129 if (debug_requested)
4130 return 0;
4131 return 1;
4134 qemu_irq qemu_system_powerdown;
4136 static void main_loop(void)
4138 int r;
4140 if (kvm_enabled()) {
4141 kvm_main_loop();
4142 cpu_disable_ticks();
4143 return;
4146 #ifdef CONFIG_IOTHREAD
4147 qemu_system_ready = 1;
4148 qemu_cond_broadcast(&qemu_system_cond);
4149 #endif
4151 for (;;) {
4152 do {
4153 #ifdef CONFIG_PROFILER
4154 int64_t ti;
4155 #endif
4156 #ifndef CONFIG_IOTHREAD
4157 tcg_cpu_exec();
4158 #endif
4159 #ifdef CONFIG_PROFILER
4160 ti = profile_getclock();
4161 #endif
4162 main_loop_wait(qemu_calculate_timeout());
4163 #ifdef CONFIG_PROFILER
4164 dev_time += profile_getclock() - ti;
4165 #endif
4166 } while (vm_can_run());
4168 if (qemu_debug_requested())
4169 vm_stop(EXCP_DEBUG);
4170 if (qemu_shutdown_requested()) {
4171 if (no_shutdown) {
4172 vm_stop(0);
4173 no_shutdown = 0;
4174 } else
4175 break;
4177 if (qemu_reset_requested()) {
4178 pause_all_vcpus();
4179 qemu_system_reset();
4180 resume_all_vcpus();
4182 if (qemu_powerdown_requested()) {
4183 qemu_irq_raise(qemu_system_powerdown);
4185 if ((r = qemu_vmstop_requested()))
4186 vm_stop(r);
4188 pause_all_vcpus();
4191 static void version(void)
4193 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4196 static void help(int exitcode)
4198 version();
4199 printf("usage: %s [options] [disk_image]\n"
4200 "\n"
4201 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4202 "\n"
4203 #define DEF(option, opt_arg, opt_enum, opt_help) \
4204 opt_help
4205 #define DEFHEADING(text) stringify(text) "\n"
4206 #include "qemu-options.h"
4207 #undef DEF
4208 #undef DEFHEADING
4209 #undef GEN_DOCS
4210 "\n"
4211 "During emulation, the following keys are useful:\n"
4212 "ctrl-alt-f toggle full screen\n"
4213 "ctrl-alt-n switch to virtual console 'n'\n"
4214 "ctrl-alt toggle mouse and keyboard grab\n"
4215 "\n"
4216 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4218 "qemu",
4219 DEFAULT_RAM_SIZE,
4220 #ifndef _WIN32
4221 DEFAULT_NETWORK_SCRIPT,
4222 DEFAULT_NETWORK_DOWN_SCRIPT,
4223 #endif
4224 DEFAULT_GDBSTUB_PORT,
4225 "/tmp/qemu.log");
4226 exit(exitcode);
4229 #define HAS_ARG 0x0001
4231 enum {
4232 #define DEF(option, opt_arg, opt_enum, opt_help) \
4233 opt_enum,
4234 #define DEFHEADING(text)
4235 #include "qemu-options.h"
4236 #undef DEF
4237 #undef DEFHEADING
4238 #undef GEN_DOCS
4241 typedef struct QEMUOption {
4242 const char *name;
4243 int flags;
4244 int index;
4245 } QEMUOption;
4247 static const QEMUOption qemu_options[] = {
4248 { "h", 0, QEMU_OPTION_h },
4249 #define DEF(option, opt_arg, opt_enum, opt_help) \
4250 { option, opt_arg, opt_enum },
4251 #define DEFHEADING(text)
4252 #include "qemu-options.h"
4253 #undef DEF
4254 #undef DEFHEADING
4255 #undef GEN_DOCS
4256 { NULL },
4259 #ifdef HAS_AUDIO
4260 struct soundhw soundhw[] = {
4261 #ifdef HAS_AUDIO_CHOICE
4262 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4264 "pcspk",
4265 "PC speaker",
4268 { .init_isa = pcspk_audio_init }
4270 #endif
4272 #ifdef CONFIG_SB16
4274 "sb16",
4275 "Creative Sound Blaster 16",
4278 { .init_isa = SB16_init }
4280 #endif
4282 #ifdef CONFIG_CS4231A
4284 "cs4231a",
4285 "CS4231A",
4288 { .init_isa = cs4231a_init }
4290 #endif
4292 #ifdef CONFIG_ADLIB
4294 "adlib",
4295 #ifdef HAS_YMF262
4296 "Yamaha YMF262 (OPL3)",
4297 #else
4298 "Yamaha YM3812 (OPL2)",
4299 #endif
4302 { .init_isa = Adlib_init }
4304 #endif
4306 #ifdef CONFIG_GUS
4308 "gus",
4309 "Gravis Ultrasound GF1",
4312 { .init_isa = GUS_init }
4314 #endif
4316 #ifdef CONFIG_AC97
4318 "ac97",
4319 "Intel 82801AA AC97 Audio",
4322 { .init_pci = ac97_init }
4324 #endif
4326 #ifdef CONFIG_ES1370
4328 "es1370",
4329 "ENSONIQ AudioPCI ES1370",
4332 { .init_pci = es1370_init }
4334 #endif
4336 #endif /* HAS_AUDIO_CHOICE */
4338 { NULL, NULL, 0, 0, { NULL } }
4341 static void select_soundhw (const char *optarg)
4343 struct soundhw *c;
4345 if (*optarg == '?') {
4346 show_valid_cards:
4348 printf ("Valid sound card names (comma separated):\n");
4349 for (c = soundhw; c->name; ++c) {
4350 printf ("%-11s %s\n", c->name, c->descr);
4352 printf ("\n-soundhw all will enable all of the above\n");
4353 exit (*optarg != '?');
4355 else {
4356 size_t l;
4357 const char *p;
4358 char *e;
4359 int bad_card = 0;
4361 if (!strcmp (optarg, "all")) {
4362 for (c = soundhw; c->name; ++c) {
4363 c->enabled = 1;
4365 return;
4368 p = optarg;
4369 while (*p) {
4370 e = strchr (p, ',');
4371 l = !e ? strlen (p) : (size_t) (e - p);
4373 for (c = soundhw; c->name; ++c) {
4374 if (!strncmp (c->name, p, l) && !c->name[l]) {
4375 c->enabled = 1;
4376 break;
4380 if (!c->name) {
4381 if (l > 80) {
4382 fprintf (stderr,
4383 "Unknown sound card name (too big to show)\n");
4385 else {
4386 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4387 (int) l, p);
4389 bad_card = 1;
4391 p += l + (e != NULL);
4394 if (bad_card)
4395 goto show_valid_cards;
4398 #endif
4400 static void select_vgahw (const char *p)
4402 const char *opts;
4404 vga_interface_type = VGA_NONE;
4405 if (strstart(p, "std", &opts)) {
4406 vga_interface_type = VGA_STD;
4407 } else if (strstart(p, "cirrus", &opts)) {
4408 vga_interface_type = VGA_CIRRUS;
4409 } else if (strstart(p, "vmware", &opts)) {
4410 vga_interface_type = VGA_VMWARE;
4411 } else if (strstart(p, "xenfb", &opts)) {
4412 vga_interface_type = VGA_XENFB;
4413 } else if (!strstart(p, "none", &opts)) {
4414 invalid_vga:
4415 fprintf(stderr, "Unknown vga type: %s\n", p);
4416 exit(1);
4418 while (*opts) {
4419 const char *nextopt;
4421 if (strstart(opts, ",retrace=", &nextopt)) {
4422 opts = nextopt;
4423 if (strstart(opts, "dumb", &nextopt))
4424 vga_retrace_method = VGA_RETRACE_DUMB;
4425 else if (strstart(opts, "precise", &nextopt))
4426 vga_retrace_method = VGA_RETRACE_PRECISE;
4427 else goto invalid_vga;
4428 } else goto invalid_vga;
4429 opts = nextopt;
4433 #ifdef TARGET_I386
4434 static int balloon_parse(const char *arg)
4436 QemuOpts *opts;
4438 if (strcmp(arg, "none") == 0) {
4439 return 0;
4442 if (!strncmp(arg, "virtio", 6)) {
4443 if (arg[6] == ',') {
4444 /* have params -> parse them */
4445 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4446 if (!opts)
4447 return -1;
4448 } else {
4449 /* create empty opts */
4450 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4452 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4453 return 0;
4456 return -1;
4458 #endif
4460 #ifdef _WIN32
4461 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4463 exit(STATUS_CONTROL_C_EXIT);
4464 return TRUE;
4466 #endif
4468 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4470 int ret;
4472 if(strlen(str) != 36)
4473 return -1;
4475 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4476 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4477 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4479 if(ret != 16)
4480 return -1;
4482 #ifdef TARGET_I386
4483 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4484 #endif
4486 return 0;
4489 #ifndef _WIN32
4491 static void termsig_handler(int signal)
4493 qemu_system_shutdown_request();
4496 static void sigchld_handler(int signal)
4498 waitpid(-1, NULL, WNOHANG);
4501 static void sighandler_setup(void)
4503 struct sigaction act;
4505 memset(&act, 0, sizeof(act));
4506 act.sa_handler = termsig_handler;
4507 sigaction(SIGINT, &act, NULL);
4508 sigaction(SIGHUP, &act, NULL);
4509 sigaction(SIGTERM, &act, NULL);
4511 act.sa_handler = sigchld_handler;
4512 act.sa_flags = SA_NOCLDSTOP;
4513 sigaction(SIGCHLD, &act, NULL);
4516 #endif
4518 #ifdef _WIN32
4519 /* Look for support files in the same directory as the executable. */
4520 static char *find_datadir(const char *argv0)
4522 char *p;
4523 char buf[MAX_PATH];
4524 DWORD len;
4526 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4527 if (len == 0) {
4528 return NULL;
4531 buf[len] = 0;
4532 p = buf + len - 1;
4533 while (p != buf && *p != '\\')
4534 p--;
4535 *p = 0;
4536 if (access(buf, R_OK) == 0) {
4537 return qemu_strdup(buf);
4539 return NULL;
4541 #else /* !_WIN32 */
4543 /* Find a likely location for support files using the location of the binary.
4544 For installed binaries this will be "$bindir/../share/qemu". When
4545 running from the build tree this will be "$bindir/../pc-bios". */
4546 #define SHARE_SUFFIX "/share/qemu"
4547 #define BUILD_SUFFIX "/pc-bios"
4548 static char *find_datadir(const char *argv0)
4550 char *dir;
4551 char *p = NULL;
4552 char *res;
4553 char buf[PATH_MAX];
4554 size_t max_len;
4556 #if defined(__linux__)
4558 int len;
4559 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4560 if (len > 0) {
4561 buf[len] = 0;
4562 p = buf;
4565 #elif defined(__FreeBSD__)
4567 int len;
4568 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4569 if (len > 0) {
4570 buf[len] = 0;
4571 p = buf;
4574 #endif
4575 /* If we don't have any way of figuring out the actual executable
4576 location then try argv[0]. */
4577 if (!p) {
4578 p = realpath(argv0, buf);
4579 if (!p) {
4580 return NULL;
4583 dir = dirname(p);
4584 dir = dirname(dir);
4586 max_len = strlen(dir) +
4587 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4588 res = qemu_mallocz(max_len);
4589 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4590 if (access(res, R_OK)) {
4591 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4592 if (access(res, R_OK)) {
4593 qemu_free(res);
4594 res = NULL;
4598 return res;
4600 #undef SHARE_SUFFIX
4601 #undef BUILD_SUFFIX
4602 #endif
4604 char *qemu_find_file(int type, const char *name)
4606 int len;
4607 const char *subdir;
4608 char *buf;
4610 /* If name contains path separators then try it as a straight path. */
4611 if ((strchr(name, '/') || strchr(name, '\\'))
4612 && access(name, R_OK) == 0) {
4613 return qemu_strdup(name);
4615 switch (type) {
4616 case QEMU_FILE_TYPE_BIOS:
4617 subdir = "";
4618 break;
4619 case QEMU_FILE_TYPE_KEYMAP:
4620 subdir = "keymaps/";
4621 break;
4622 default:
4623 abort();
4625 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4626 buf = qemu_mallocz(len);
4627 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4628 if (access(buf, R_OK)) {
4629 qemu_free(buf);
4630 return NULL;
4632 return buf;
4635 static int device_init_func(QemuOpts *opts, void *opaque)
4637 DeviceState *dev;
4639 dev = qdev_device_add(opts);
4640 if (!dev)
4641 return -1;
4642 return 0;
4645 struct device_config {
4646 enum {
4647 DEV_USB, /* -usbdevice */
4648 DEV_BT, /* -bt */
4649 } type;
4650 const char *cmdline;
4651 QTAILQ_ENTRY(device_config) next;
4653 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4655 static void add_device_config(int type, const char *cmdline)
4657 struct device_config *conf;
4659 conf = qemu_mallocz(sizeof(*conf));
4660 conf->type = type;
4661 conf->cmdline = cmdline;
4662 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4665 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4667 struct device_config *conf;
4668 int rc;
4670 QTAILQ_FOREACH(conf, &device_configs, next) {
4671 if (conf->type != type)
4672 continue;
4673 rc = func(conf->cmdline);
4674 if (0 != rc)
4675 return rc;
4677 return 0;
4680 int main(int argc, char **argv, char **envp)
4682 const char *gdbstub_dev = NULL;
4683 uint32_t boot_devices_bitmap = 0;
4684 int i;
4685 int snapshot, linux_boot, net_boot;
4686 const char *initrd_filename;
4687 const char *kernel_filename, *kernel_cmdline;
4688 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4689 DisplayState *ds;
4690 DisplayChangeListener *dcl;
4691 int cyls, heads, secs, translation;
4692 QemuOpts *hda_opts = NULL, *opts;
4693 int optind;
4694 const char *r, *optarg;
4695 CharDriverState *monitor_hds[MAX_MONITOR_DEVICES];
4696 const char *monitor_devices[MAX_MONITOR_DEVICES];
4697 int monitor_device_index;
4698 const char *serial_devices[MAX_SERIAL_PORTS];
4699 int serial_device_index;
4700 const char *parallel_devices[MAX_PARALLEL_PORTS];
4701 int parallel_device_index;
4702 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4703 int virtio_console_index;
4704 const char *loadvm = NULL;
4705 QEMUMachine *machine;
4706 const char *cpu_model;
4707 #ifndef _WIN32
4708 int fds[2];
4709 #endif
4710 int tb_size;
4711 const char *pid_file = NULL;
4712 const char *incoming = NULL;
4713 #ifndef _WIN32
4714 int fd = 0;
4715 struct passwd *pwd = NULL;
4716 const char *chroot_dir = NULL;
4717 const char *run_as = NULL;
4718 #endif
4719 CPUState *env;
4720 int show_vnc_port = 0;
4722 init_clocks();
4724 qemu_errors_to_file(stderr);
4725 qemu_cache_utils_init(envp);
4727 QLIST_INIT (&vm_change_state_head);
4728 #ifndef _WIN32
4730 struct sigaction act;
4731 sigfillset(&act.sa_mask);
4732 act.sa_flags = 0;
4733 act.sa_handler = SIG_IGN;
4734 sigaction(SIGPIPE, &act, NULL);
4736 #else
4737 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4738 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4739 QEMU to run on a single CPU */
4741 HANDLE h;
4742 DWORD mask, smask;
4743 int i;
4744 h = GetCurrentProcess();
4745 if (GetProcessAffinityMask(h, &mask, &smask)) {
4746 for(i = 0; i < 32; i++) {
4747 if (mask & (1 << i))
4748 break;
4750 if (i != 32) {
4751 mask = 1 << i;
4752 SetProcessAffinityMask(h, mask);
4756 #endif
4758 module_call_init(MODULE_INIT_MACHINE);
4759 machine = find_default_machine();
4760 cpu_model = NULL;
4761 initrd_filename = NULL;
4762 ram_size = 0;
4763 snapshot = 0;
4764 kernel_filename = NULL;
4765 kernel_cmdline = "";
4766 cyls = heads = secs = 0;
4767 translation = BIOS_ATA_TRANSLATION_AUTO;
4769 serial_devices[0] = "vc:80Cx24C";
4770 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4771 serial_devices[i] = NULL;
4772 serial_device_index = 0;
4774 parallel_devices[0] = "vc:80Cx24C";
4775 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4776 parallel_devices[i] = NULL;
4777 parallel_device_index = 0;
4779 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4780 virtio_consoles[i] = NULL;
4781 virtio_console_index = 0;
4783 monitor_devices[0] = "vc:80Cx24C";
4784 for (i = 1; i < MAX_MONITOR_DEVICES; i++) {
4785 monitor_devices[i] = NULL;
4787 monitor_device_index = 0;
4789 for (i = 0; i < MAX_NODES; i++) {
4790 node_mem[i] = 0;
4791 node_cpumask[i] = 0;
4794 assigned_devices_index = 0;
4796 nb_numa_nodes = 0;
4797 nb_nics = 0;
4799 tb_size = 0;
4800 autostart= 1;
4802 optind = 1;
4803 for(;;) {
4804 if (optind >= argc)
4805 break;
4806 r = argv[optind];
4807 if (r[0] != '-') {
4808 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4809 } else {
4810 const QEMUOption *popt;
4812 optind++;
4813 /* Treat --foo the same as -foo. */
4814 if (r[1] == '-')
4815 r++;
4816 popt = qemu_options;
4817 for(;;) {
4818 if (!popt->name) {
4819 fprintf(stderr, "%s: invalid option -- '%s'\n",
4820 argv[0], r);
4821 exit(1);
4823 if (!strcmp(popt->name, r + 1))
4824 break;
4825 popt++;
4827 if (popt->flags & HAS_ARG) {
4828 if (optind >= argc) {
4829 fprintf(stderr, "%s: option '%s' requires an argument\n",
4830 argv[0], r);
4831 exit(1);
4833 optarg = argv[optind++];
4834 } else {
4835 optarg = NULL;
4838 switch(popt->index) {
4839 case QEMU_OPTION_M:
4840 machine = find_machine(optarg);
4841 if (!machine) {
4842 QEMUMachine *m;
4843 printf("Supported machines are:\n");
4844 for(m = first_machine; m != NULL; m = m->next) {
4845 if (m->alias)
4846 printf("%-10s %s (alias of %s)\n",
4847 m->alias, m->desc, m->name);
4848 printf("%-10s %s%s\n",
4849 m->name, m->desc,
4850 m->is_default ? " (default)" : "");
4852 exit(*optarg != '?');
4854 break;
4855 case QEMU_OPTION_cpu:
4856 /* hw initialization will check this */
4857 if (*optarg == '?') {
4858 /* XXX: implement xxx_cpu_list for targets that still miss it */
4859 #if defined(cpu_list)
4860 cpu_list(stdout, &fprintf);
4861 #endif
4862 exit(0);
4863 } else {
4864 cpu_model = optarg;
4866 break;
4867 case QEMU_OPTION_initrd:
4868 initrd_filename = optarg;
4869 break;
4870 case QEMU_OPTION_hda:
4871 if (cyls == 0)
4872 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4873 else
4874 hda_opts = drive_add(optarg, HD_ALIAS
4875 ",cyls=%d,heads=%d,secs=%d%s",
4876 0, cyls, heads, secs,
4877 translation == BIOS_ATA_TRANSLATION_LBA ?
4878 ",trans=lba" :
4879 translation == BIOS_ATA_TRANSLATION_NONE ?
4880 ",trans=none" : "");
4881 break;
4882 case QEMU_OPTION_hdb:
4883 case QEMU_OPTION_hdc:
4884 case QEMU_OPTION_hdd:
4885 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4886 break;
4887 case QEMU_OPTION_drive:
4888 drive_add(NULL, "%s", optarg);
4889 break;
4890 case QEMU_OPTION_set:
4891 if (qemu_set_option(optarg) != 0)
4892 exit(1);
4893 break;
4894 case QEMU_OPTION_mtdblock:
4895 drive_add(optarg, MTD_ALIAS);
4896 break;
4897 case QEMU_OPTION_sd:
4898 drive_add(optarg, SD_ALIAS);
4899 break;
4900 case QEMU_OPTION_pflash:
4901 drive_add(optarg, PFLASH_ALIAS);
4902 break;
4903 case QEMU_OPTION_snapshot:
4904 snapshot = 1;
4905 break;
4906 case QEMU_OPTION_hdachs:
4908 const char *p;
4909 p = optarg;
4910 cyls = strtol(p, (char **)&p, 0);
4911 if (cyls < 1 || cyls > 16383)
4912 goto chs_fail;
4913 if (*p != ',')
4914 goto chs_fail;
4915 p++;
4916 heads = strtol(p, (char **)&p, 0);
4917 if (heads < 1 || heads > 16)
4918 goto chs_fail;
4919 if (*p != ',')
4920 goto chs_fail;
4921 p++;
4922 secs = strtol(p, (char **)&p, 0);
4923 if (secs < 1 || secs > 63)
4924 goto chs_fail;
4925 if (*p == ',') {
4926 p++;
4927 if (!strcmp(p, "none"))
4928 translation = BIOS_ATA_TRANSLATION_NONE;
4929 else if (!strcmp(p, "lba"))
4930 translation = BIOS_ATA_TRANSLATION_LBA;
4931 else if (!strcmp(p, "auto"))
4932 translation = BIOS_ATA_TRANSLATION_AUTO;
4933 else
4934 goto chs_fail;
4935 } else if (*p != '\0') {
4936 chs_fail:
4937 fprintf(stderr, "qemu: invalid physical CHS format\n");
4938 exit(1);
4940 if (hda_opts != NULL) {
4941 char num[16];
4942 snprintf(num, sizeof(num), "%d", cyls);
4943 qemu_opt_set(hda_opts, "cyls", num);
4944 snprintf(num, sizeof(num), "%d", heads);
4945 qemu_opt_set(hda_opts, "heads", num);
4946 snprintf(num, sizeof(num), "%d", secs);
4947 qemu_opt_set(hda_opts, "secs", num);
4948 if (translation == BIOS_ATA_TRANSLATION_LBA)
4949 qemu_opt_set(hda_opts, "trans", "lba");
4950 if (translation == BIOS_ATA_TRANSLATION_NONE)
4951 qemu_opt_set(hda_opts, "trans", "none");
4954 break;
4955 case QEMU_OPTION_numa:
4956 if (nb_numa_nodes >= MAX_NODES) {
4957 fprintf(stderr, "qemu: too many NUMA nodes\n");
4958 exit(1);
4960 numa_add(optarg);
4961 break;
4962 case QEMU_OPTION_nographic:
4963 display_type = DT_NOGRAPHIC;
4964 break;
4965 #ifdef CONFIG_CURSES
4966 case QEMU_OPTION_curses:
4967 display_type = DT_CURSES;
4968 break;
4969 #endif
4970 case QEMU_OPTION_portrait:
4971 graphic_rotate = 1;
4972 break;
4973 case QEMU_OPTION_kernel:
4974 kernel_filename = optarg;
4975 break;
4976 case QEMU_OPTION_append:
4977 kernel_cmdline = optarg;
4978 break;
4979 case QEMU_OPTION_cdrom:
4980 drive_add(optarg, CDROM_ALIAS);
4981 break;
4982 case QEMU_OPTION_boot:
4984 static const char * const params[] = {
4985 "order", "once", "menu", NULL
4987 char buf[sizeof(boot_devices)];
4988 char *standard_boot_devices;
4989 int legacy = 0;
4991 if (!strchr(optarg, '=')) {
4992 legacy = 1;
4993 pstrcpy(buf, sizeof(buf), optarg);
4994 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4995 fprintf(stderr,
4996 "qemu: unknown boot parameter '%s' in '%s'\n",
4997 buf, optarg);
4998 exit(1);
5001 if (legacy ||
5002 get_param_value(buf, sizeof(buf), "order", optarg)) {
5003 boot_devices_bitmap = parse_bootdevices(buf);
5004 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5006 if (!legacy) {
5007 if (get_param_value(buf, sizeof(buf),
5008 "once", optarg)) {
5009 boot_devices_bitmap |= parse_bootdevices(buf);
5010 standard_boot_devices = qemu_strdup(boot_devices);
5011 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5012 qemu_register_reset(restore_boot_devices,
5013 standard_boot_devices);
5015 if (get_param_value(buf, sizeof(buf),
5016 "menu", optarg)) {
5017 if (!strcmp(buf, "on")) {
5018 boot_menu = 1;
5019 } else if (!strcmp(buf, "off")) {
5020 boot_menu = 0;
5021 } else {
5022 fprintf(stderr,
5023 "qemu: invalid option value '%s'\n",
5024 buf);
5025 exit(1);
5030 break;
5031 case QEMU_OPTION_fda:
5032 case QEMU_OPTION_fdb:
5033 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5034 break;
5035 #ifdef TARGET_I386
5036 case QEMU_OPTION_no_fd_bootchk:
5037 fd_bootchk = 0;
5038 break;
5039 #endif
5040 case QEMU_OPTION_netdev:
5041 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5042 exit(1);
5044 break;
5045 case QEMU_OPTION_net:
5046 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5047 exit(1);
5049 break;
5050 #ifdef CONFIG_SLIRP
5051 case QEMU_OPTION_tftp:
5052 legacy_tftp_prefix = optarg;
5053 break;
5054 case QEMU_OPTION_bootp:
5055 legacy_bootp_filename = optarg;
5056 break;
5057 #ifndef _WIN32
5058 case QEMU_OPTION_smb:
5059 if (net_slirp_smb(optarg) < 0)
5060 exit(1);
5061 break;
5062 #endif
5063 case QEMU_OPTION_redir:
5064 if (net_slirp_redir(optarg) < 0)
5065 exit(1);
5066 break;
5067 #endif
5068 case QEMU_OPTION_bt:
5069 add_device_config(DEV_BT, optarg);
5070 break;
5071 #ifdef HAS_AUDIO
5072 case QEMU_OPTION_audio_help:
5073 AUD_help ();
5074 exit (0);
5075 break;
5076 case QEMU_OPTION_soundhw:
5077 select_soundhw (optarg);
5078 break;
5079 #endif
5080 case QEMU_OPTION_h:
5081 help(0);
5082 break;
5083 case QEMU_OPTION_version:
5084 version();
5085 exit(0);
5086 break;
5087 case QEMU_OPTION_m: {
5088 uint64_t value;
5089 char *ptr;
5091 value = strtoul(optarg, &ptr, 10);
5092 switch (*ptr) {
5093 case 0: case 'M': case 'm':
5094 value <<= 20;
5095 break;
5096 case 'G': case 'g':
5097 value <<= 30;
5098 break;
5099 default:
5100 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5101 exit(1);
5104 /* On 32-bit hosts, QEMU is limited by virtual address space */
5105 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5106 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5107 exit(1);
5109 if (value != (uint64_t)(ram_addr_t)value) {
5110 fprintf(stderr, "qemu: ram size too large\n");
5111 exit(1);
5113 ram_size = value;
5114 break;
5116 case QEMU_OPTION_d:
5118 int mask;
5119 const CPULogItem *item;
5121 mask = cpu_str_to_log_mask(optarg);
5122 if (!mask) {
5123 printf("Log items (comma separated):\n");
5124 for(item = cpu_log_items; item->mask != 0; item++) {
5125 printf("%-10s %s\n", item->name, item->help);
5127 exit(1);
5129 cpu_set_log(mask);
5131 break;
5132 case QEMU_OPTION_s:
5133 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5134 break;
5135 case QEMU_OPTION_gdb:
5136 gdbstub_dev = optarg;
5137 break;
5138 case QEMU_OPTION_L:
5139 data_dir = optarg;
5140 break;
5141 case QEMU_OPTION_bios:
5142 bios_name = optarg;
5143 break;
5144 case QEMU_OPTION_singlestep:
5145 singlestep = 1;
5146 break;
5147 case QEMU_OPTION_S:
5148 autostart = 0;
5149 break;
5150 #ifndef _WIN32
5151 case QEMU_OPTION_k:
5152 keyboard_layout = optarg;
5153 break;
5154 #endif
5155 case QEMU_OPTION_localtime:
5156 rtc_utc = 0;
5157 break;
5158 case QEMU_OPTION_vga:
5159 select_vgahw (optarg);
5160 break;
5161 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5162 case QEMU_OPTION_g:
5164 const char *p;
5165 int w, h, depth;
5166 p = optarg;
5167 w = strtol(p, (char **)&p, 10);
5168 if (w <= 0) {
5169 graphic_error:
5170 fprintf(stderr, "qemu: invalid resolution or depth\n");
5171 exit(1);
5173 if (*p != 'x')
5174 goto graphic_error;
5175 p++;
5176 h = strtol(p, (char **)&p, 10);
5177 if (h <= 0)
5178 goto graphic_error;
5179 if (*p == 'x') {
5180 p++;
5181 depth = strtol(p, (char **)&p, 10);
5182 if (depth != 8 && depth != 15 && depth != 16 &&
5183 depth != 24 && depth != 32)
5184 goto graphic_error;
5185 } else if (*p == '\0') {
5186 depth = graphic_depth;
5187 } else {
5188 goto graphic_error;
5191 graphic_width = w;
5192 graphic_height = h;
5193 graphic_depth = depth;
5195 break;
5196 #endif
5197 case QEMU_OPTION_echr:
5199 char *r;
5200 term_escape_char = strtol(optarg, &r, 0);
5201 if (r == optarg)
5202 printf("Bad argument to echr\n");
5203 break;
5205 case QEMU_OPTION_monitor:
5206 if (monitor_device_index >= MAX_MONITOR_DEVICES) {
5207 fprintf(stderr, "qemu: too many monitor devices\n");
5208 exit(1);
5210 monitor_devices[monitor_device_index] = optarg;
5211 monitor_device_index++;
5212 break;
5213 case QEMU_OPTION_chardev:
5214 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5215 if (!opts) {
5216 fprintf(stderr, "parse error: %s\n", optarg);
5217 exit(1);
5219 if (qemu_chr_open_opts(opts, NULL) == NULL) {
5220 exit(1);
5222 break;
5223 case QEMU_OPTION_serial:
5224 if (serial_device_index >= MAX_SERIAL_PORTS) {
5225 fprintf(stderr, "qemu: too many serial ports\n");
5226 exit(1);
5228 serial_devices[serial_device_index] = optarg;
5229 serial_device_index++;
5230 break;
5231 case QEMU_OPTION_watchdog:
5232 if (watchdog) {
5233 fprintf(stderr,
5234 "qemu: only one watchdog option may be given\n");
5235 return 1;
5237 watchdog = optarg;
5238 break;
5239 case QEMU_OPTION_watchdog_action:
5240 if (select_watchdog_action(optarg) == -1) {
5241 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5242 exit(1);
5244 break;
5245 case QEMU_OPTION_virtiocon:
5246 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5247 fprintf(stderr, "qemu: too many virtio consoles\n");
5248 exit(1);
5250 virtio_consoles[virtio_console_index] = optarg;
5251 virtio_console_index++;
5252 break;
5253 case QEMU_OPTION_parallel:
5254 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5255 fprintf(stderr, "qemu: too many parallel ports\n");
5256 exit(1);
5258 parallel_devices[parallel_device_index] = optarg;
5259 parallel_device_index++;
5260 break;
5261 case QEMU_OPTION_loadvm:
5262 loadvm = optarg;
5263 break;
5264 case QEMU_OPTION_full_screen:
5265 full_screen = 1;
5266 break;
5267 #ifdef CONFIG_SDL
5268 case QEMU_OPTION_no_frame:
5269 no_frame = 1;
5270 break;
5271 case QEMU_OPTION_alt_grab:
5272 alt_grab = 1;
5273 break;
5274 case QEMU_OPTION_ctrl_grab:
5275 ctrl_grab = 1;
5276 break;
5277 case QEMU_OPTION_no_quit:
5278 no_quit = 1;
5279 break;
5280 case QEMU_OPTION_sdl:
5281 display_type = DT_SDL;
5282 break;
5283 #endif
5284 case QEMU_OPTION_pidfile:
5285 pid_file = optarg;
5286 break;
5287 #ifdef TARGET_I386
5288 case QEMU_OPTION_win2k_hack:
5289 win2k_install_hack = 1;
5290 break;
5291 case QEMU_OPTION_rtc_td_hack:
5292 rtc_td_hack = 1;
5293 break;
5294 case QEMU_OPTION_acpitable:
5295 if(acpi_table_add(optarg) < 0) {
5296 fprintf(stderr, "Wrong acpi table provided\n");
5297 exit(1);
5299 break;
5300 case QEMU_OPTION_smbios:
5301 if(smbios_entry_add(optarg) < 0) {
5302 fprintf(stderr, "Wrong smbios provided\n");
5303 exit(1);
5305 break;
5306 #endif
5307 #ifdef CONFIG_KVM
5308 #ifdef KVM_UPSTREAM
5309 case QEMU_OPTION_enable_kvm:
5310 kvm_allowed = 1;
5311 #endif
5312 break;
5313 case QEMU_OPTION_no_kvm:
5314 kvm_allowed = 0;
5315 break;
5316 case QEMU_OPTION_no_kvm_irqchip: {
5317 kvm_irqchip = 0;
5318 kvm_pit = 0;
5319 break;
5321 case QEMU_OPTION_no_kvm_pit: {
5322 kvm_pit = 0;
5323 break;
5325 case QEMU_OPTION_no_kvm_pit_reinjection: {
5326 kvm_pit_reinject = 0;
5327 break;
5329 case QEMU_OPTION_enable_nesting: {
5330 kvm_nested = 1;
5331 break;
5333 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5334 case QEMU_OPTION_pcidevice:
5335 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5336 fprintf(stderr, "Too many assigned devices\n");
5337 exit(1);
5339 assigned_devices[assigned_devices_index] = optarg;
5340 assigned_devices_index++;
5341 break;
5342 #endif
5343 #endif
5344 case QEMU_OPTION_usb:
5345 usb_enabled = 1;
5346 break;
5347 case QEMU_OPTION_usbdevice:
5348 usb_enabled = 1;
5349 add_device_config(DEV_USB, optarg);
5350 break;
5351 case QEMU_OPTION_device:
5352 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5353 exit(1);
5355 break;
5356 case QEMU_OPTION_smp:
5357 smp_parse(optarg);
5358 if (smp_cpus < 1) {
5359 fprintf(stderr, "Invalid number of CPUs\n");
5360 exit(1);
5362 if (max_cpus < smp_cpus) {
5363 fprintf(stderr, "maxcpus must be equal to or greater than "
5364 "smp\n");
5365 exit(1);
5367 if (max_cpus > 255) {
5368 fprintf(stderr, "Unsupported number of maxcpus\n");
5369 exit(1);
5371 break;
5372 case QEMU_OPTION_vnc:
5373 display_type = DT_VNC;
5374 vnc_display = optarg;
5375 break;
5376 #ifdef TARGET_I386
5377 case QEMU_OPTION_no_acpi:
5378 acpi_enabled = 0;
5379 break;
5380 case QEMU_OPTION_no_hpet:
5381 no_hpet = 1;
5382 break;
5383 case QEMU_OPTION_balloon:
5384 if (balloon_parse(optarg) < 0) {
5385 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5386 exit(1);
5388 break;
5389 #endif
5390 case QEMU_OPTION_no_reboot:
5391 no_reboot = 1;
5392 break;
5393 case QEMU_OPTION_no_shutdown:
5394 no_shutdown = 1;
5395 break;
5396 case QEMU_OPTION_show_cursor:
5397 cursor_hide = 0;
5398 break;
5399 case QEMU_OPTION_uuid:
5400 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5401 fprintf(stderr, "Fail to parse UUID string."
5402 " Wrong format.\n");
5403 exit(1);
5405 break;
5406 #ifndef _WIN32
5407 case QEMU_OPTION_daemonize:
5408 daemonize = 1;
5409 break;
5410 #endif
5411 case QEMU_OPTION_option_rom:
5412 if (nb_option_roms >= MAX_OPTION_ROMS) {
5413 fprintf(stderr, "Too many option ROMs\n");
5414 exit(1);
5416 option_rom[nb_option_roms] = optarg;
5417 nb_option_roms++;
5418 break;
5419 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5420 case QEMU_OPTION_semihosting:
5421 semihosting_enabled = 1;
5422 break;
5423 #endif
5424 case QEMU_OPTION_tdf:
5425 time_drift_fix = 1;
5426 break;
5427 case QEMU_OPTION_kvm_shadow_memory:
5428 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5429 break;
5430 case QEMU_OPTION_mempath:
5431 mem_path = optarg;
5432 break;
5433 #ifdef MAP_POPULATE
5434 case QEMU_OPTION_mem_prealloc:
5435 mem_prealloc = !mem_prealloc;
5436 break;
5437 #endif
5438 case QEMU_OPTION_name:
5439 qemu_name = qemu_strdup(optarg);
5441 char *p = strchr(qemu_name, ',');
5442 if (p != NULL) {
5443 *p++ = 0;
5444 if (strncmp(p, "process=", 8)) {
5445 fprintf(stderr, "Unknown subargument %s to -name", p);
5446 exit(1);
5448 p += 8;
5449 set_proc_name(p);
5452 break;
5453 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5454 case QEMU_OPTION_prom_env:
5455 if (nb_prom_envs >= MAX_PROM_ENVS) {
5456 fprintf(stderr, "Too many prom variables\n");
5457 exit(1);
5459 prom_envs[nb_prom_envs] = optarg;
5460 nb_prom_envs++;
5461 break;
5462 #endif
5463 #ifdef TARGET_ARM
5464 case QEMU_OPTION_old_param:
5465 old_param = 1;
5466 break;
5467 #endif
5468 case QEMU_OPTION_clock:
5469 configure_alarms(optarg);
5470 break;
5471 case QEMU_OPTION_startdate:
5472 configure_rtc_date_offset(optarg, 1);
5473 break;
5474 case QEMU_OPTION_rtc:
5475 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5476 if (!opts) {
5477 fprintf(stderr, "parse error: %s\n", optarg);
5478 exit(1);
5480 configure_rtc(opts);
5481 break;
5482 case QEMU_OPTION_tb_size:
5483 tb_size = strtol(optarg, NULL, 0);
5484 if (tb_size < 0)
5485 tb_size = 0;
5486 break;
5487 case QEMU_OPTION_icount:
5488 use_icount = 1;
5489 if (strcmp(optarg, "auto") == 0) {
5490 icount_time_shift = -1;
5491 } else {
5492 icount_time_shift = strtol(optarg, NULL, 0);
5494 break;
5495 case QEMU_OPTION_incoming:
5496 incoming = optarg;
5497 break;
5498 #ifndef _WIN32
5499 case QEMU_OPTION_chroot:
5500 chroot_dir = optarg;
5501 break;
5502 case QEMU_OPTION_runas:
5503 run_as = optarg;
5504 break;
5505 case QEMU_OPTION_nvram:
5506 nvram = optarg;
5507 break;
5508 #endif
5509 #ifdef CONFIG_XEN
5510 case QEMU_OPTION_xen_domid:
5511 xen_domid = atoi(optarg);
5512 break;
5513 case QEMU_OPTION_xen_create:
5514 xen_mode = XEN_CREATE;
5515 break;
5516 case QEMU_OPTION_xen_attach:
5517 xen_mode = XEN_ATTACH;
5518 break;
5519 #endif
5524 /* If no data_dir is specified then try to find it relative to the
5525 executable path. */
5526 if (!data_dir) {
5527 data_dir = find_datadir(argv[0]);
5529 /* If all else fails use the install patch specified when building. */
5530 if (!data_dir) {
5531 data_dir = CONFIG_QEMU_SHAREDIR;
5535 * Default to max_cpus = smp_cpus, in case the user doesn't
5536 * specify a max_cpus value.
5538 if (!max_cpus)
5539 max_cpus = smp_cpus;
5541 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5542 if (smp_cpus > machine->max_cpus) {
5543 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5544 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5545 machine->max_cpus);
5546 exit(1);
5549 if (display_type == DT_NOGRAPHIC) {
5550 if (serial_device_index == 0)
5551 serial_devices[0] = "stdio";
5552 if (parallel_device_index == 0)
5553 parallel_devices[0] = "null";
5554 if (strncmp(monitor_devices[0], "vc", 2) == 0) {
5555 monitor_devices[0] = "stdio";
5559 #ifndef _WIN32
5560 if (daemonize) {
5561 pid_t pid;
5563 if (pipe(fds) == -1)
5564 exit(1);
5566 pid = fork();
5567 if (pid > 0) {
5568 uint8_t status;
5569 ssize_t len;
5571 close(fds[1]);
5573 again:
5574 len = read(fds[0], &status, 1);
5575 if (len == -1 && (errno == EINTR))
5576 goto again;
5578 if (len != 1)
5579 exit(1);
5580 else if (status == 1) {
5581 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5582 exit(1);
5583 } else
5584 exit(0);
5585 } else if (pid < 0)
5586 exit(1);
5588 setsid();
5590 pid = fork();
5591 if (pid > 0)
5592 exit(0);
5593 else if (pid < 0)
5594 exit(1);
5596 umask(027);
5598 signal(SIGTSTP, SIG_IGN);
5599 signal(SIGTTOU, SIG_IGN);
5600 signal(SIGTTIN, SIG_IGN);
5603 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5604 if (daemonize) {
5605 uint8_t status = 1;
5606 write(fds[1], &status, 1);
5607 } else
5608 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5609 exit(1);
5611 #endif
5613 if (kvm_enabled()) {
5614 int ret;
5616 ret = kvm_init(smp_cpus);
5617 if (ret < 0) {
5618 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5619 fprintf(stderr, "failed to initialize KVM\n");
5620 exit(1);
5621 #endif
5622 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5623 kvm_allowed = 0;
5627 if (qemu_init_main_loop()) {
5628 fprintf(stderr, "qemu_init_main_loop failed\n");
5629 exit(1);
5631 linux_boot = (kernel_filename != NULL);
5633 if (!linux_boot && *kernel_cmdline != '\0') {
5634 fprintf(stderr, "-append only allowed with -kernel option\n");
5635 exit(1);
5638 if (!linux_boot && initrd_filename != NULL) {
5639 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5640 exit(1);
5643 #ifndef _WIN32
5644 /* Win32 doesn't support line-buffering and requires size >= 2 */
5645 setvbuf(stdout, NULL, _IOLBF, 0);
5646 #endif
5648 if (init_timer_alarm() < 0) {
5649 fprintf(stderr, "could not initialize alarm timer\n");
5650 exit(1);
5652 if (use_icount && icount_time_shift < 0) {
5653 use_icount = 2;
5654 /* 125MIPS seems a reasonable initial guess at the guest speed.
5655 It will be corrected fairly quickly anyway. */
5656 icount_time_shift = 3;
5657 init_icount_adjust();
5660 #ifdef _WIN32
5661 socket_init();
5662 #endif
5664 if (net_init_clients() < 0) {
5665 exit(1);
5668 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5669 net_set_boot_mask(net_boot);
5671 /* init the bluetooth world */
5672 if (foreach_device_config(DEV_BT, bt_parse))
5673 exit(1);
5675 /* init the memory */
5676 if (ram_size == 0)
5677 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5679 /* init the dynamic translator */
5680 cpu_exec_init_all(tb_size * 1024 * 1024);
5682 bdrv_init();
5684 /* we always create the cdrom drive, even if no disk is there */
5685 drive_add(NULL, CDROM_ALIAS);
5687 /* we always create at least one floppy */
5688 drive_add(NULL, FD_ALIAS, 0);
5690 /* we always create one sd slot, even if no card is in it */
5691 drive_add(NULL, SD_ALIAS);
5693 /* open the virtual block devices */
5694 if (snapshot)
5695 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5696 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5697 exit(1);
5699 vmstate_register(0, &vmstate_timers ,&timers_state);
5700 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5702 /* Maintain compatibility with multiple stdio monitors */
5703 if (!strcmp(monitor_devices[0],"stdio")) {
5704 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5705 const char *devname = serial_devices[i];
5706 if (devname && !strcmp(devname,"mon:stdio")) {
5707 monitor_devices[0] = NULL;
5708 break;
5709 } else if (devname && !strcmp(devname,"stdio")) {
5710 monitor_devices[0] = NULL;
5711 serial_devices[i] = "mon:stdio";
5712 break;
5717 if (nb_numa_nodes > 0) {
5718 int i;
5720 if (nb_numa_nodes > smp_cpus) {
5721 nb_numa_nodes = smp_cpus;
5724 /* If no memory size if given for any node, assume the default case
5725 * and distribute the available memory equally across all nodes
5727 for (i = 0; i < nb_numa_nodes; i++) {
5728 if (node_mem[i] != 0)
5729 break;
5731 if (i == nb_numa_nodes) {
5732 uint64_t usedmem = 0;
5734 /* On Linux, the each node's border has to be 8MB aligned,
5735 * the final node gets the rest.
5737 for (i = 0; i < nb_numa_nodes - 1; i++) {
5738 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5739 usedmem += node_mem[i];
5741 node_mem[i] = ram_size - usedmem;
5744 for (i = 0; i < nb_numa_nodes; i++) {
5745 if (node_cpumask[i] != 0)
5746 break;
5748 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5749 * must cope with this anyway, because there are BIOSes out there in
5750 * real machines which also use this scheme.
5752 if (i == nb_numa_nodes) {
5753 for (i = 0; i < smp_cpus; i++) {
5754 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5759 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5760 const char *devname = monitor_devices[i];
5761 if (devname && strcmp(devname, "none")) {
5762 char label[32];
5763 if (i == 0) {
5764 snprintf(label, sizeof(label), "monitor");
5765 } else {
5766 snprintf(label, sizeof(label), "monitor%d", i);
5768 monitor_hds[i] = qemu_chr_open(label, devname, NULL);
5769 if (!monitor_hds[i]) {
5770 fprintf(stderr, "qemu: could not open monitor device '%s'\n",
5771 devname);
5772 exit(1);
5777 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5778 const char *devname = serial_devices[i];
5779 if (devname && strcmp(devname, "none")) {
5780 char label[32];
5781 snprintf(label, sizeof(label), "serial%d", i);
5782 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5783 if (!serial_hds[i]) {
5784 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
5785 devname, strerror(errno));
5786 exit(1);
5791 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5792 const char *devname = parallel_devices[i];
5793 if (devname && strcmp(devname, "none")) {
5794 char label[32];
5795 snprintf(label, sizeof(label), "parallel%d", i);
5796 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5797 if (!parallel_hds[i]) {
5798 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
5799 devname, strerror(errno));
5800 exit(1);
5805 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5806 const char *devname = virtio_consoles[i];
5807 if (devname && strcmp(devname, "none")) {
5808 char label[32];
5809 snprintf(label, sizeof(label), "virtcon%d", i);
5810 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5811 if (!virtcon_hds[i]) {
5812 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
5813 devname, strerror(errno));
5814 exit(1);
5819 module_call_init(MODULE_INIT_DEVICE);
5821 if (watchdog) {
5822 i = select_watchdog(watchdog);
5823 if (i > 0)
5824 exit (i == 1 ? 1 : 0);
5827 if (machine->compat_props) {
5828 qdev_prop_register_compat(machine->compat_props);
5830 machine->init(ram_size, boot_devices,
5831 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5834 #ifndef _WIN32
5835 /* must be after terminal init, SDL library changes signal handlers */
5836 sighandler_setup();
5837 #endif
5839 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5840 for (i = 0; i < nb_numa_nodes; i++) {
5841 if (node_cpumask[i] & (1 << env->cpu_index)) {
5842 env->numa_node = i;
5847 current_machine = machine;
5849 /* init USB devices */
5850 if (usb_enabled) {
5851 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5852 exit(1);
5855 /* init generic devices */
5856 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5857 exit(1);
5859 if (!display_state)
5860 dumb_display_init();
5861 /* just use the first displaystate for the moment */
5862 ds = display_state;
5864 if (display_type == DT_DEFAULT) {
5865 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5866 display_type = DT_SDL;
5867 #else
5868 display_type = DT_VNC;
5869 vnc_display = "localhost:0,to=99";
5870 show_vnc_port = 1;
5871 #endif
5875 switch (display_type) {
5876 case DT_NOGRAPHIC:
5877 break;
5878 #if defined(CONFIG_CURSES)
5879 case DT_CURSES:
5880 curses_display_init(ds, full_screen);
5881 break;
5882 #endif
5883 #if defined(CONFIG_SDL)
5884 case DT_SDL:
5885 sdl_display_init(ds, full_screen, no_frame);
5886 break;
5887 #elif defined(CONFIG_COCOA)
5888 case DT_SDL:
5889 cocoa_display_init(ds, full_screen);
5890 break;
5891 #endif
5892 case DT_VNC:
5893 vnc_display_init(ds);
5894 if (vnc_display_open(ds, vnc_display) < 0)
5895 exit(1);
5897 if (show_vnc_port) {
5898 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5900 break;
5901 default:
5902 break;
5904 dpy_resize(ds);
5906 dcl = ds->listeners;
5907 while (dcl != NULL) {
5908 if (dcl->dpy_refresh != NULL) {
5909 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5910 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5912 dcl = dcl->next;
5915 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5916 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5917 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5920 text_consoles_set_display(display_state);
5921 qemu_chr_initial_reset();
5923 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5924 if (monitor_devices[i] && monitor_hds[i]) {
5925 monitor_init(monitor_hds[i],
5926 MONITOR_USE_READLINE |
5927 ((i == 0) ? MONITOR_IS_DEFAULT : 0));
5931 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5932 const char *devname = serial_devices[i];
5933 if (devname && strcmp(devname, "none")) {
5934 if (strstart(devname, "vc", 0))
5935 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5939 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5940 const char *devname = parallel_devices[i];
5941 if (devname && strcmp(devname, "none")) {
5942 if (strstart(devname, "vc", 0))
5943 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5947 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5948 const char *devname = virtio_consoles[i];
5949 if (virtcon_hds[i] && devname) {
5950 if (strstart(devname, "vc", 0))
5951 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5955 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5956 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5957 gdbstub_dev);
5958 exit(1);
5961 qdev_machine_creation_done();
5963 rom_load_all();
5965 if (loadvm) {
5966 if (load_vmstate(cur_mon, loadvm) < 0) {
5967 autostart = 0;
5971 if (incoming) {
5972 qemu_start_incoming_migration(incoming);
5973 } else if (autostart) {
5974 vm_start();
5977 #ifndef _WIN32
5978 if (daemonize) {
5979 uint8_t status = 0;
5980 ssize_t len;
5982 again1:
5983 len = write(fds[1], &status, 1);
5984 if (len == -1 && (errno == EINTR))
5985 goto again1;
5987 if (len != 1)
5988 exit(1);
5990 chdir("/");
5991 TFR(fd = open("/dev/null", O_RDWR));
5992 if (fd == -1)
5993 exit(1);
5996 if (run_as) {
5997 pwd = getpwnam(run_as);
5998 if (!pwd) {
5999 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6000 exit(1);
6004 if (chroot_dir) {
6005 if (chroot(chroot_dir) < 0) {
6006 fprintf(stderr, "chroot failed\n");
6007 exit(1);
6009 chdir("/");
6012 if (run_as) {
6013 if (setgid(pwd->pw_gid) < 0) {
6014 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6015 exit(1);
6017 if (setuid(pwd->pw_uid) < 0) {
6018 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6019 exit(1);
6021 if (setuid(0) != -1) {
6022 fprintf(stderr, "Dropping privileges failed\n");
6023 exit(1);
6027 if (daemonize) {
6028 dup2(fd, 0);
6029 dup2(fd, 1);
6030 dup2(fd, 2);
6032 close(fd);
6034 #endif
6036 main_loop();
6037 quit_timers();
6038 net_cleanup();
6040 return 0;