Use bios from upstream (seabios binary)
[qemu/qemu-dev-zwu.git] / vl.c
blob594ca342bb2045c3e74f614ed830791b0c1c79a4
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 int usb_device_add(const char *devname, int is_hotplug)
2546 const char *p;
2547 USBDevice *dev = NULL;
2549 if (!usb_enabled)
2550 return -1;
2552 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2553 dev = usbdevice_create(devname);
2554 if (dev)
2555 goto done;
2557 /* the other ones */
2558 if (strstart(devname, "host:", &p)) {
2559 dev = usb_host_device_open(p);
2560 } else if (strstart(devname, "net:", &p)) {
2561 QemuOpts *opts;
2562 int idx;
2564 opts = qemu_opts_parse(&qemu_net_opts, p, NULL);
2565 if (!opts) {
2566 return -1;
2569 qemu_opt_set(opts, "type", "nic");
2570 qemu_opt_set(opts, "model", "usb");
2572 idx = net_client_init(NULL, opts, 0);
2573 if (idx == -1) {
2574 return -1;
2577 dev = usb_net_init(&nd_table[idx]);
2578 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2579 dev = usb_bt_init(devname[2] ? hci_init(p) :
2580 bt_new_hci(qemu_find_bt_vlan(0)));
2581 } else {
2582 return -1;
2584 if (!dev)
2585 return -1;
2587 done:
2588 return 0;
2591 static int usb_device_del(const char *devname)
2593 int bus_num, addr;
2594 const char *p;
2596 if (strstart(devname, "host:", &p))
2597 return usb_host_device_close(p);
2599 if (!usb_enabled)
2600 return -1;
2602 p = strchr(devname, '.');
2603 if (!p)
2604 return -1;
2605 bus_num = strtoul(devname, NULL, 0);
2606 addr = strtoul(p + 1, NULL, 0);
2608 return usb_device_delete_addr(bus_num, addr);
2611 static int usb_parse(const char *cmdline)
2613 return usb_device_add(cmdline, 0);
2616 void do_usb_add(Monitor *mon, const QDict *qdict)
2618 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2621 void do_usb_del(Monitor *mon, const QDict *qdict)
2623 usb_device_del(qdict_get_str(qdict, "devname"));
2626 /***********************************************************/
2627 /* PCMCIA/Cardbus */
2629 static struct pcmcia_socket_entry_s {
2630 PCMCIASocket *socket;
2631 struct pcmcia_socket_entry_s *next;
2632 } *pcmcia_sockets = 0;
2634 void pcmcia_socket_register(PCMCIASocket *socket)
2636 struct pcmcia_socket_entry_s *entry;
2638 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2639 entry->socket = socket;
2640 entry->next = pcmcia_sockets;
2641 pcmcia_sockets = entry;
2644 void pcmcia_socket_unregister(PCMCIASocket *socket)
2646 struct pcmcia_socket_entry_s *entry, **ptr;
2648 ptr = &pcmcia_sockets;
2649 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2650 if (entry->socket == socket) {
2651 *ptr = entry->next;
2652 qemu_free(entry);
2656 void pcmcia_info(Monitor *mon)
2658 struct pcmcia_socket_entry_s *iter;
2660 if (!pcmcia_sockets)
2661 monitor_printf(mon, "No PCMCIA sockets\n");
2663 for (iter = pcmcia_sockets; iter; iter = iter->next)
2664 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2665 iter->socket->attached ? iter->socket->card_string :
2666 "Empty");
2669 /***********************************************************/
2670 /* register display */
2672 struct DisplayAllocator default_allocator = {
2673 defaultallocator_create_displaysurface,
2674 defaultallocator_resize_displaysurface,
2675 defaultallocator_free_displaysurface
2678 void register_displaystate(DisplayState *ds)
2680 DisplayState **s;
2681 s = &display_state;
2682 while (*s != NULL)
2683 s = &(*s)->next;
2684 ds->next = NULL;
2685 *s = ds;
2688 DisplayState *get_displaystate(void)
2690 return display_state;
2693 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2695 if(ds->allocator == &default_allocator) ds->allocator = da;
2696 return ds->allocator;
2699 /* dumb display */
2701 static void dumb_display_init(void)
2703 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2704 ds->allocator = &default_allocator;
2705 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2706 register_displaystate(ds);
2709 /***********************************************************/
2710 /* I/O handling */
2712 typedef struct IOHandlerRecord {
2713 int fd;
2714 IOCanRWHandler *fd_read_poll;
2715 IOHandler *fd_read;
2716 IOHandler *fd_write;
2717 int deleted;
2718 void *opaque;
2719 /* temporary data */
2720 struct pollfd *ufd;
2721 struct IOHandlerRecord *next;
2722 } IOHandlerRecord;
2724 static IOHandlerRecord *first_io_handler;
2726 /* XXX: fd_read_poll should be suppressed, but an API change is
2727 necessary in the character devices to suppress fd_can_read(). */
2728 int qemu_set_fd_handler2(int fd,
2729 IOCanRWHandler *fd_read_poll,
2730 IOHandler *fd_read,
2731 IOHandler *fd_write,
2732 void *opaque)
2734 IOHandlerRecord **pioh, *ioh;
2736 if (!fd_read && !fd_write) {
2737 pioh = &first_io_handler;
2738 for(;;) {
2739 ioh = *pioh;
2740 if (ioh == NULL)
2741 break;
2742 if (ioh->fd == fd) {
2743 ioh->deleted = 1;
2744 break;
2746 pioh = &ioh->next;
2748 } else {
2749 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2750 if (ioh->fd == fd)
2751 goto found;
2753 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2754 ioh->next = first_io_handler;
2755 first_io_handler = ioh;
2756 found:
2757 ioh->fd = fd;
2758 ioh->fd_read_poll = fd_read_poll;
2759 ioh->fd_read = fd_read;
2760 ioh->fd_write = fd_write;
2761 ioh->opaque = opaque;
2762 ioh->deleted = 0;
2764 qemu_notify_event();
2765 return 0;
2768 int qemu_set_fd_handler(int fd,
2769 IOHandler *fd_read,
2770 IOHandler *fd_write,
2771 void *opaque)
2773 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2776 #ifdef _WIN32
2777 /***********************************************************/
2778 /* Polling handling */
2780 typedef struct PollingEntry {
2781 PollingFunc *func;
2782 void *opaque;
2783 struct PollingEntry *next;
2784 } PollingEntry;
2786 static PollingEntry *first_polling_entry;
2788 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2790 PollingEntry **ppe, *pe;
2791 pe = qemu_mallocz(sizeof(PollingEntry));
2792 pe->func = func;
2793 pe->opaque = opaque;
2794 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2795 *ppe = pe;
2796 return 0;
2799 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2801 PollingEntry **ppe, *pe;
2802 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2803 pe = *ppe;
2804 if (pe->func == func && pe->opaque == opaque) {
2805 *ppe = pe->next;
2806 qemu_free(pe);
2807 break;
2812 /***********************************************************/
2813 /* Wait objects support */
2814 typedef struct WaitObjects {
2815 int num;
2816 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2817 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2818 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2819 } WaitObjects;
2821 static WaitObjects wait_objects = {0};
2823 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2825 WaitObjects *w = &wait_objects;
2827 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2828 return -1;
2829 w->events[w->num] = handle;
2830 w->func[w->num] = func;
2831 w->opaque[w->num] = opaque;
2832 w->num++;
2833 return 0;
2836 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2838 int i, found;
2839 WaitObjects *w = &wait_objects;
2841 found = 0;
2842 for (i = 0; i < w->num; i++) {
2843 if (w->events[i] == handle)
2844 found = 1;
2845 if (found) {
2846 w->events[i] = w->events[i + 1];
2847 w->func[i] = w->func[i + 1];
2848 w->opaque[i] = w->opaque[i + 1];
2851 if (found)
2852 w->num--;
2854 #endif
2856 /***********************************************************/
2857 /* ram save/restore */
2859 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2860 #define RAM_SAVE_FLAG_COMPRESS 0x02
2861 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2862 #define RAM_SAVE_FLAG_PAGE 0x08
2863 #define RAM_SAVE_FLAG_EOS 0x10
2865 static int is_dup_page(uint8_t *page, uint8_t ch)
2867 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2868 uint32_t *array = (uint32_t *)page;
2869 int i;
2871 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2872 if (array[i] != val)
2873 return 0;
2876 return 1;
2879 static int ram_save_block(QEMUFile *f)
2881 static ram_addr_t current_addr = 0;
2882 ram_addr_t saved_addr = current_addr;
2883 ram_addr_t addr = 0;
2884 int found = 0;
2886 while (addr < last_ram_offset) {
2887 if (kvm_enabled() && current_addr == 0) {
2888 int r;
2889 r = kvm_update_dirty_pages_log();
2890 if (r) {
2891 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
2892 qemu_file_set_error(f);
2893 return 0;
2896 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2897 uint8_t *p;
2899 cpu_physical_memory_reset_dirty(current_addr,
2900 current_addr + TARGET_PAGE_SIZE,
2901 MIGRATION_DIRTY_FLAG);
2903 p = qemu_get_ram_ptr(current_addr);
2905 if (is_dup_page(p, *p)) {
2906 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2907 qemu_put_byte(f, *p);
2908 } else {
2909 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2910 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2913 found = 1;
2914 break;
2916 addr += TARGET_PAGE_SIZE;
2917 current_addr = (saved_addr + addr) % last_ram_offset;
2920 return found;
2923 static uint64_t bytes_transferred = 0;
2925 static ram_addr_t ram_save_remaining(void)
2927 ram_addr_t addr;
2928 ram_addr_t count = 0;
2930 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2931 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2932 count++;
2935 return count;
2938 uint64_t ram_bytes_remaining(void)
2940 return ram_save_remaining() * TARGET_PAGE_SIZE;
2943 uint64_t ram_bytes_transferred(void)
2945 return bytes_transferred;
2948 uint64_t ram_bytes_total(void)
2950 return last_ram_offset;
2953 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
2955 ram_addr_t addr;
2956 uint64_t bytes_transferred_last;
2957 double bwidth = 0;
2958 uint64_t expected_time = 0;
2960 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2961 qemu_file_set_error(f);
2962 return 0;
2965 if (stage == 1) {
2966 /* Make sure all dirty bits are set */
2967 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2968 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2969 cpu_physical_memory_set_dirty(addr);
2972 /* Enable dirty memory tracking */
2973 cpu_physical_memory_set_dirty_tracking(1);
2975 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2978 bytes_transferred_last = bytes_transferred;
2979 bwidth = get_clock();
2981 while (!qemu_file_rate_limit(f)) {
2982 int ret;
2984 ret = ram_save_block(f);
2985 bytes_transferred += ret * TARGET_PAGE_SIZE;
2986 if (ret == 0) /* no more blocks */
2987 break;
2990 bwidth = get_clock() - bwidth;
2991 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2993 /* if we haven't transferred anything this round, force expected_time to a
2994 * a very high value, but without crashing */
2995 if (bwidth == 0)
2996 bwidth = 0.000001;
2998 /* try transferring iterative blocks of memory */
3000 if (stage == 3) {
3002 /* flush all remaining blocks regardless of rate limiting */
3003 while (ram_save_block(f) != 0) {
3004 bytes_transferred += TARGET_PAGE_SIZE;
3006 cpu_physical_memory_set_dirty_tracking(0);
3009 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3011 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3013 return (stage == 2) && (expected_time <= migrate_max_downtime());
3016 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3018 ram_addr_t addr;
3019 int flags;
3021 if (version_id != 3)
3022 return -EINVAL;
3024 do {
3025 addr = qemu_get_be64(f);
3027 flags = addr & ~TARGET_PAGE_MASK;
3028 addr &= TARGET_PAGE_MASK;
3030 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3031 if (addr != last_ram_offset)
3032 return -EINVAL;
3035 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3036 uint8_t ch = qemu_get_byte(f);
3037 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3038 #ifndef _WIN32
3039 if (ch == 0 &&
3040 (!kvm_enabled() || kvm_has_sync_mmu())) {
3041 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3043 #endif
3044 } else if (flags & RAM_SAVE_FLAG_PAGE)
3045 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3046 } while (!(flags & RAM_SAVE_FLAG_EOS));
3048 return 0;
3051 void qemu_service_io(void)
3053 qemu_notify_event();
3056 /***********************************************************/
3057 /* machine registration */
3059 static QEMUMachine *first_machine = NULL;
3060 QEMUMachine *current_machine = NULL;
3062 int qemu_register_machine(QEMUMachine *m)
3064 QEMUMachine **pm;
3065 pm = &first_machine;
3066 while (*pm != NULL)
3067 pm = &(*pm)->next;
3068 m->next = NULL;
3069 *pm = m;
3070 return 0;
3073 static QEMUMachine *find_machine(const char *name)
3075 QEMUMachine *m;
3077 for(m = first_machine; m != NULL; m = m->next) {
3078 if (!strcmp(m->name, name))
3079 return m;
3080 if (m->alias && !strcmp(m->alias, name))
3081 return m;
3083 return NULL;
3086 static QEMUMachine *find_default_machine(void)
3088 QEMUMachine *m;
3090 for(m = first_machine; m != NULL; m = m->next) {
3091 if (m->is_default) {
3092 return m;
3095 return NULL;
3098 /***********************************************************/
3099 /* main execution loop */
3101 static void gui_update(void *opaque)
3103 uint64_t interval = GUI_REFRESH_INTERVAL;
3104 DisplayState *ds = opaque;
3105 DisplayChangeListener *dcl = ds->listeners;
3107 dpy_refresh(ds);
3109 while (dcl != NULL) {
3110 if (dcl->gui_timer_interval &&
3111 dcl->gui_timer_interval < interval)
3112 interval = dcl->gui_timer_interval;
3113 dcl = dcl->next;
3115 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3118 static void nographic_update(void *opaque)
3120 uint64_t interval = GUI_REFRESH_INTERVAL;
3122 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3125 struct vm_change_state_entry {
3126 VMChangeStateHandler *cb;
3127 void *opaque;
3128 QLIST_ENTRY (vm_change_state_entry) entries;
3131 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3133 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3134 void *opaque)
3136 VMChangeStateEntry *e;
3138 e = qemu_mallocz(sizeof (*e));
3140 e->cb = cb;
3141 e->opaque = opaque;
3142 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3143 return e;
3146 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3148 QLIST_REMOVE (e, entries);
3149 qemu_free (e);
3152 static void vm_state_notify(int running, int reason)
3154 VMChangeStateEntry *e;
3156 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3157 e->cb(e->opaque, running, reason);
3161 static void resume_all_vcpus(void);
3162 static void pause_all_vcpus(void);
3164 void vm_start(void)
3166 if (!vm_running) {
3167 cpu_enable_ticks();
3168 vm_running = 1;
3169 vm_state_notify(1, 0);
3170 qemu_rearm_alarm_timer(alarm_timer);
3171 resume_all_vcpus();
3175 /* reset/shutdown handler */
3177 typedef struct QEMUResetEntry {
3178 QTAILQ_ENTRY(QEMUResetEntry) entry;
3179 QEMUResetHandler *func;
3180 void *opaque;
3181 } QEMUResetEntry;
3183 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3184 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3185 static int reset_requested;
3186 static int shutdown_requested;
3187 static int powerdown_requested;
3188 static int debug_requested;
3189 static int vmstop_requested;
3191 int qemu_no_shutdown(void)
3193 int r = no_shutdown;
3194 no_shutdown = 0;
3195 return r;
3198 int qemu_shutdown_requested(void)
3200 int r = shutdown_requested;
3201 shutdown_requested = 0;
3202 return r;
3205 int qemu_reset_requested(void)
3207 int r = reset_requested;
3208 reset_requested = 0;
3209 return r;
3212 int qemu_powerdown_requested(void)
3214 int r = powerdown_requested;
3215 powerdown_requested = 0;
3216 return r;
3219 static int qemu_debug_requested(void)
3221 int r = debug_requested;
3222 debug_requested = 0;
3223 return r;
3226 static int qemu_vmstop_requested(void)
3228 int r = vmstop_requested;
3229 vmstop_requested = 0;
3230 return r;
3233 static void do_vm_stop(int reason)
3235 if (vm_running) {
3236 cpu_disable_ticks();
3237 vm_running = 0;
3238 pause_all_vcpus();
3239 vm_state_notify(0, reason);
3243 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3245 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3247 re->func = func;
3248 re->opaque = opaque;
3249 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3252 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3254 QEMUResetEntry *re;
3256 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3257 if (re->func == func && re->opaque == opaque) {
3258 QTAILQ_REMOVE(&reset_handlers, re, entry);
3259 qemu_free(re);
3260 return;
3265 void qemu_system_reset(void)
3267 QEMUResetEntry *re, *nre;
3269 /* reset all devices */
3270 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3271 re->func(re->opaque);
3275 void qemu_system_reset_request(void)
3277 if (no_reboot) {
3278 shutdown_requested = 1;
3279 } else {
3280 reset_requested = 1;
3282 if (cpu_single_env) {
3283 cpu_single_env->stopped = 1;
3285 qemu_notify_event();
3288 void qemu_system_shutdown_request(void)
3290 shutdown_requested = 1;
3291 qemu_notify_event();
3294 void qemu_system_powerdown_request(void)
3296 powerdown_requested = 1;
3297 qemu_notify_event();
3300 #ifdef CONFIG_IOTHREAD
3301 static void qemu_system_vmstop_request(int reason)
3303 vmstop_requested = reason;
3304 qemu_notify_event();
3306 #endif
3308 #ifndef _WIN32
3309 static int io_thread_fd = -1;
3311 static void qemu_event_increment(void)
3313 static const char byte = 0;
3315 if (io_thread_fd == -1)
3316 return;
3318 write(io_thread_fd, &byte, sizeof(byte));
3321 static void qemu_event_read(void *opaque)
3323 int fd = (unsigned long)opaque;
3324 ssize_t len;
3326 /* Drain the notify pipe */
3327 do {
3328 char buffer[512];
3329 len = read(fd, buffer, sizeof(buffer));
3330 } while ((len == -1 && errno == EINTR) || len > 0);
3333 static int qemu_event_init(void)
3335 int err;
3336 int fds[2];
3338 err = pipe(fds);
3339 if (err == -1)
3340 return -errno;
3342 err = fcntl_setfl(fds[0], O_NONBLOCK);
3343 if (err < 0)
3344 goto fail;
3346 err = fcntl_setfl(fds[1], O_NONBLOCK);
3347 if (err < 0)
3348 goto fail;
3350 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3351 (void *)(unsigned long)fds[0]);
3353 io_thread_fd = fds[1];
3354 return 0;
3356 fail:
3357 close(fds[0]);
3358 close(fds[1]);
3359 return err;
3361 #else
3362 HANDLE qemu_event_handle;
3364 static void dummy_event_handler(void *opaque)
3368 static int qemu_event_init(void)
3370 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3371 if (!qemu_event_handle) {
3372 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3373 return -1;
3375 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3376 return 0;
3379 static void qemu_event_increment(void)
3381 if (!SetEvent(qemu_event_handle)) {
3382 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3383 GetLastError());
3384 exit (1);
3387 #endif
3389 static int cpu_can_run(CPUState *env)
3391 if (env->stop)
3392 return 0;
3393 if (env->stopped)
3394 return 0;
3395 return 1;
3398 #ifndef CONFIG_IOTHREAD
3399 static int qemu_init_main_loop(void)
3401 return qemu_event_init();
3404 void qemu_init_vcpu(void *_env)
3406 CPUState *env = _env;
3408 if (kvm_enabled())
3409 kvm_init_vcpu(env);
3410 env->nr_cores = smp_cores;
3411 env->nr_threads = smp_threads;
3412 return;
3415 int qemu_cpu_self(void *env)
3417 return 1;
3420 static void resume_all_vcpus(void)
3424 static void pause_all_vcpus(void)
3428 void qemu_cpu_kick(void *env)
3430 return;
3433 void qemu_notify_event(void)
3435 CPUState *env = cpu_single_env;
3437 if (kvm_enabled()) {
3438 qemu_kvm_notify_work();
3439 return;
3441 if (env) {
3442 cpu_exit(env);
3446 #ifdef KVM_UPSTREAM
3447 void qemu_mutex_lock_iothread(void) {}
3448 void qemu_mutex_unlock_iothread(void) {}
3449 #endif
3451 void vm_stop(int reason)
3453 do_vm_stop(reason);
3456 #else /* CONFIG_IOTHREAD */
3458 #include "qemu-thread.h"
3460 QemuMutex qemu_global_mutex;
3461 static QemuMutex qemu_fair_mutex;
3463 static QemuThread io_thread;
3465 static QemuThread *tcg_cpu_thread;
3466 static QemuCond *tcg_halt_cond;
3468 static int qemu_system_ready;
3469 /* cpu creation */
3470 static QemuCond qemu_cpu_cond;
3471 /* system init */
3472 static QemuCond qemu_system_cond;
3473 static QemuCond qemu_pause_cond;
3475 static void block_io_signals(void);
3476 static void unblock_io_signals(void);
3477 static int tcg_has_work(void);
3479 static int qemu_init_main_loop(void)
3481 int ret;
3483 ret = qemu_event_init();
3484 if (ret)
3485 return ret;
3487 qemu_cond_init(&qemu_pause_cond);
3488 qemu_mutex_init(&qemu_fair_mutex);
3489 qemu_mutex_init(&qemu_global_mutex);
3490 qemu_mutex_lock(&qemu_global_mutex);
3492 unblock_io_signals();
3493 qemu_thread_self(&io_thread);
3495 return 0;
3498 static void qemu_wait_io_event(CPUState *env)
3500 while (!tcg_has_work())
3501 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3503 qemu_mutex_unlock(&qemu_global_mutex);
3506 * Users of qemu_global_mutex can be starved, having no chance
3507 * to acquire it since this path will get to it first.
3508 * So use another lock to provide fairness.
3510 qemu_mutex_lock(&qemu_fair_mutex);
3511 qemu_mutex_unlock(&qemu_fair_mutex);
3513 qemu_mutex_lock(&qemu_global_mutex);
3514 if (env->stop) {
3515 env->stop = 0;
3516 env->stopped = 1;
3517 qemu_cond_signal(&qemu_pause_cond);
3521 static int qemu_cpu_exec(CPUState *env);
3523 static void *kvm_cpu_thread_fn(void *arg)
3525 CPUState *env = arg;
3527 block_io_signals();
3528 qemu_thread_self(env->thread);
3529 if (kvm_enabled())
3530 kvm_init_vcpu(env);
3532 /* signal CPU creation */
3533 qemu_mutex_lock(&qemu_global_mutex);
3534 env->created = 1;
3535 qemu_cond_signal(&qemu_cpu_cond);
3537 /* and wait for machine initialization */
3538 while (!qemu_system_ready)
3539 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3541 while (1) {
3542 if (cpu_can_run(env))
3543 qemu_cpu_exec(env);
3544 qemu_wait_io_event(env);
3547 return NULL;
3550 static void tcg_cpu_exec(void);
3552 static void *tcg_cpu_thread_fn(void *arg)
3554 CPUState *env = arg;
3556 block_io_signals();
3557 qemu_thread_self(env->thread);
3559 /* signal CPU creation */
3560 qemu_mutex_lock(&qemu_global_mutex);
3561 for (env = first_cpu; env != NULL; env = env->next_cpu)
3562 env->created = 1;
3563 qemu_cond_signal(&qemu_cpu_cond);
3565 /* and wait for machine initialization */
3566 while (!qemu_system_ready)
3567 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3569 while (1) {
3570 tcg_cpu_exec();
3571 qemu_wait_io_event(cur_cpu);
3574 return NULL;
3577 void qemu_cpu_kick(void *_env)
3579 CPUState *env = _env;
3580 qemu_cond_broadcast(env->halt_cond);
3581 if (kvm_enabled())
3582 qemu_thread_signal(env->thread, SIGUSR1);
3585 int qemu_cpu_self(void *_env)
3587 CPUState *env = _env;
3588 QemuThread this;
3590 qemu_thread_self(&this);
3592 return qemu_thread_equal(&this, env->thread);
3595 static void cpu_signal(int sig)
3597 if (cpu_single_env)
3598 cpu_exit(cpu_single_env);
3601 static void block_io_signals(void)
3603 sigset_t set;
3604 struct sigaction sigact;
3606 sigemptyset(&set);
3607 sigaddset(&set, SIGUSR2);
3608 sigaddset(&set, SIGIO);
3609 sigaddset(&set, SIGALRM);
3610 pthread_sigmask(SIG_BLOCK, &set, NULL);
3612 sigemptyset(&set);
3613 sigaddset(&set, SIGUSR1);
3614 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3616 memset(&sigact, 0, sizeof(sigact));
3617 sigact.sa_handler = cpu_signal;
3618 sigaction(SIGUSR1, &sigact, NULL);
3621 static void unblock_io_signals(void)
3623 sigset_t set;
3625 sigemptyset(&set);
3626 sigaddset(&set, SIGUSR2);
3627 sigaddset(&set, SIGIO);
3628 sigaddset(&set, SIGALRM);
3629 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3631 sigemptyset(&set);
3632 sigaddset(&set, SIGUSR1);
3633 pthread_sigmask(SIG_BLOCK, &set, NULL);
3636 static void qemu_signal_lock(unsigned int msecs)
3638 qemu_mutex_lock(&qemu_fair_mutex);
3640 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3641 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3642 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3643 break;
3645 qemu_mutex_unlock(&qemu_fair_mutex);
3648 void qemu_mutex_lock_iothread(void)
3650 if (kvm_enabled()) {
3651 qemu_mutex_lock(&qemu_fair_mutex);
3652 qemu_mutex_lock(&qemu_global_mutex);
3653 qemu_mutex_unlock(&qemu_fair_mutex);
3654 } else
3655 qemu_signal_lock(100);
3658 void qemu_mutex_unlock_iothread(void)
3660 qemu_mutex_unlock(&qemu_global_mutex);
3663 static int all_vcpus_paused(void)
3665 CPUState *penv = first_cpu;
3667 while (penv) {
3668 if (!penv->stopped)
3669 return 0;
3670 penv = (CPUState *)penv->next_cpu;
3673 return 1;
3676 static void pause_all_vcpus(void)
3678 CPUState *penv = first_cpu;
3680 while (penv) {
3681 penv->stop = 1;
3682 qemu_thread_signal(penv->thread, SIGUSR1);
3683 qemu_cpu_kick(penv);
3684 penv = (CPUState *)penv->next_cpu;
3687 while (!all_vcpus_paused()) {
3688 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3689 penv = first_cpu;
3690 while (penv) {
3691 qemu_thread_signal(penv->thread, SIGUSR1);
3692 penv = (CPUState *)penv->next_cpu;
3697 static void resume_all_vcpus(void)
3699 CPUState *penv = first_cpu;
3701 while (penv) {
3702 penv->stop = 0;
3703 penv->stopped = 0;
3704 qemu_thread_signal(penv->thread, SIGUSR1);
3705 qemu_cpu_kick(penv);
3706 penv = (CPUState *)penv->next_cpu;
3710 static void tcg_init_vcpu(void *_env)
3712 CPUState *env = _env;
3713 /* share a single thread for all cpus with TCG */
3714 if (!tcg_cpu_thread) {
3715 env->thread = qemu_mallocz(sizeof(QemuThread));
3716 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3717 qemu_cond_init(env->halt_cond);
3718 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3719 while (env->created == 0)
3720 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3721 tcg_cpu_thread = env->thread;
3722 tcg_halt_cond = env->halt_cond;
3723 } else {
3724 env->thread = tcg_cpu_thread;
3725 env->halt_cond = tcg_halt_cond;
3729 static void kvm_start_vcpu(CPUState *env)
3731 env->thread = qemu_mallocz(sizeof(QemuThread));
3732 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3733 qemu_cond_init(env->halt_cond);
3734 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3735 while (env->created == 0)
3736 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3739 void qemu_init_vcpu(void *_env)
3741 CPUState *env = _env;
3743 if (kvm_enabled())
3744 kvm_start_vcpu(env);
3745 else
3746 tcg_init_vcpu(env);
3747 env->nr_cores = smp_cores;
3748 env->nr_threads = smp_threads;
3751 void qemu_notify_event(void)
3753 qemu_event_increment();
3756 void vm_stop(int reason)
3758 QemuThread me;
3759 qemu_thread_self(&me);
3761 if (!qemu_thread_equal(&me, &io_thread)) {
3762 qemu_system_vmstop_request(reason);
3764 * FIXME: should not return to device code in case
3765 * vm_stop() has been requested.
3767 if (cpu_single_env) {
3768 cpu_exit(cpu_single_env);
3769 cpu_single_env->stop = 1;
3771 return;
3773 do_vm_stop(reason);
3776 #endif
3779 #ifdef _WIN32
3780 static void host_main_loop_wait(int *timeout)
3782 int ret, ret2, i;
3783 PollingEntry *pe;
3786 /* XXX: need to suppress polling by better using win32 events */
3787 ret = 0;
3788 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3789 ret |= pe->func(pe->opaque);
3791 if (ret == 0) {
3792 int err;
3793 WaitObjects *w = &wait_objects;
3795 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3796 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3797 if (w->func[ret - WAIT_OBJECT_0])
3798 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3800 /* Check for additional signaled events */
3801 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3803 /* Check if event is signaled */
3804 ret2 = WaitForSingleObject(w->events[i], 0);
3805 if(ret2 == WAIT_OBJECT_0) {
3806 if (w->func[i])
3807 w->func[i](w->opaque[i]);
3808 } else if (ret2 == WAIT_TIMEOUT) {
3809 } else {
3810 err = GetLastError();
3811 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3814 } else if (ret == WAIT_TIMEOUT) {
3815 } else {
3816 err = GetLastError();
3817 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3821 *timeout = 0;
3823 #else
3824 static void host_main_loop_wait(int *timeout)
3827 #endif
3829 void main_loop_wait(int timeout)
3831 IOHandlerRecord *ioh;
3832 fd_set rfds, wfds, xfds;
3833 int ret, nfds;
3834 struct timeval tv;
3836 qemu_bh_update_timeout(&timeout);
3838 host_main_loop_wait(&timeout);
3840 /* poll any events */
3841 /* XXX: separate device handlers from system ones */
3842 nfds = -1;
3843 FD_ZERO(&rfds);
3844 FD_ZERO(&wfds);
3845 FD_ZERO(&xfds);
3846 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3847 if (ioh->deleted)
3848 continue;
3849 if (ioh->fd_read &&
3850 (!ioh->fd_read_poll ||
3851 ioh->fd_read_poll(ioh->opaque) != 0)) {
3852 FD_SET(ioh->fd, &rfds);
3853 if (ioh->fd > nfds)
3854 nfds = ioh->fd;
3856 if (ioh->fd_write) {
3857 FD_SET(ioh->fd, &wfds);
3858 if (ioh->fd > nfds)
3859 nfds = ioh->fd;
3863 tv.tv_sec = timeout / 1000;
3864 tv.tv_usec = (timeout % 1000) * 1000;
3866 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3868 qemu_mutex_unlock_iothread();
3869 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3870 qemu_mutex_lock_iothread();
3871 if (ret > 0) {
3872 IOHandlerRecord **pioh;
3874 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3875 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3876 ioh->fd_read(ioh->opaque);
3877 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3878 FD_CLR(ioh->fd, &rfds);
3880 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3881 ioh->fd_write(ioh->opaque);
3885 /* remove deleted IO handlers */
3886 pioh = &first_io_handler;
3887 while (*pioh) {
3888 ioh = *pioh;
3889 if (ioh->deleted) {
3890 *pioh = ioh->next;
3891 qemu_free(ioh);
3892 } else
3893 pioh = &ioh->next;
3897 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3899 /* rearm timer, if not periodic */
3900 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3901 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3902 qemu_rearm_alarm_timer(alarm_timer);
3905 /* vm time timers */
3906 if (vm_running) {
3907 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3908 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3909 qemu_get_clock(vm_clock));
3912 /* real time timers */
3913 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3914 qemu_get_clock(rt_clock));
3916 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3917 qemu_get_clock(host_clock));
3919 /* Check bottom-halves last in case any of the earlier events triggered
3920 them. */
3921 qemu_bh_poll();
3925 static int qemu_cpu_exec(CPUState *env)
3927 int ret;
3928 #ifdef CONFIG_PROFILER
3929 int64_t ti;
3930 #endif
3932 #ifdef CONFIG_PROFILER
3933 ti = profile_getclock();
3934 #endif
3935 if (use_icount) {
3936 int64_t count;
3937 int decr;
3938 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3939 env->icount_decr.u16.low = 0;
3940 env->icount_extra = 0;
3941 count = qemu_next_deadline();
3942 count = (count + (1 << icount_time_shift) - 1)
3943 >> icount_time_shift;
3944 qemu_icount += count;
3945 decr = (count > 0xffff) ? 0xffff : count;
3946 count -= decr;
3947 env->icount_decr.u16.low = decr;
3948 env->icount_extra = count;
3950 ret = cpu_exec(env);
3951 #ifdef CONFIG_PROFILER
3952 qemu_time += profile_getclock() - ti;
3953 #endif
3954 if (use_icount) {
3955 /* Fold pending instructions back into the
3956 instruction counter, and clear the interrupt flag. */
3957 qemu_icount -= (env->icount_decr.u16.low
3958 + env->icount_extra);
3959 env->icount_decr.u32 = 0;
3960 env->icount_extra = 0;
3962 return ret;
3965 static void tcg_cpu_exec(void)
3967 int ret = 0;
3969 if (next_cpu == NULL)
3970 next_cpu = first_cpu;
3971 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3972 CPUState *env = cur_cpu = next_cpu;
3974 if (!vm_running)
3975 break;
3976 if (timer_alarm_pending) {
3977 timer_alarm_pending = 0;
3978 break;
3980 if (cpu_can_run(env))
3981 ret = qemu_cpu_exec(env);
3982 if (ret == EXCP_DEBUG) {
3983 gdb_set_stop_cpu(env);
3984 debug_requested = 1;
3985 break;
3990 static int cpu_has_work(CPUState *env)
3992 if (env->stop)
3993 return 1;
3994 if (env->stopped)
3995 return 0;
3996 if (!env->halted)
3997 return 1;
3998 if (qemu_cpu_has_work(env))
3999 return 1;
4000 return 0;
4003 static int tcg_has_work(void)
4005 CPUState *env;
4007 for (env = first_cpu; env != NULL; env = env->next_cpu)
4008 if (cpu_has_work(env))
4009 return 1;
4010 return 0;
4013 static int qemu_calculate_timeout(void)
4015 #ifndef CONFIG_IOTHREAD
4016 int timeout;
4018 if (!vm_running)
4019 timeout = 5000;
4020 else if (tcg_has_work())
4021 timeout = 0;
4022 else if (!use_icount)
4023 timeout = 5000;
4024 else {
4025 /* XXX: use timeout computed from timers */
4026 int64_t add;
4027 int64_t delta;
4028 /* Advance virtual time to the next event. */
4029 if (use_icount == 1) {
4030 /* When not using an adaptive execution frequency
4031 we tend to get badly out of sync with real time,
4032 so just delay for a reasonable amount of time. */
4033 delta = 0;
4034 } else {
4035 delta = cpu_get_icount() - cpu_get_clock();
4037 if (delta > 0) {
4038 /* If virtual time is ahead of real time then just
4039 wait for IO. */
4040 timeout = (delta / 1000000) + 1;
4041 } else {
4042 /* Wait for either IO to occur or the next
4043 timer event. */
4044 add = qemu_next_deadline();
4045 /* We advance the timer before checking for IO.
4046 Limit the amount we advance so that early IO
4047 activity won't get the guest too far ahead. */
4048 if (add > 10000000)
4049 add = 10000000;
4050 delta += add;
4051 add = (add + (1 << icount_time_shift) - 1)
4052 >> icount_time_shift;
4053 qemu_icount += add;
4054 timeout = delta / 1000000;
4055 if (timeout < 0)
4056 timeout = 0;
4060 return timeout;
4061 #else /* CONFIG_IOTHREAD */
4062 return 1000;
4063 #endif
4066 static int vm_can_run(void)
4068 if (powerdown_requested)
4069 return 0;
4070 if (reset_requested)
4071 return 0;
4072 if (shutdown_requested)
4073 return 0;
4074 if (debug_requested)
4075 return 0;
4076 return 1;
4079 qemu_irq qemu_system_powerdown;
4081 static void main_loop(void)
4083 int r;
4085 if (kvm_enabled()) {
4086 kvm_main_loop();
4087 cpu_disable_ticks();
4088 return;
4091 #ifdef CONFIG_IOTHREAD
4092 qemu_system_ready = 1;
4093 qemu_cond_broadcast(&qemu_system_cond);
4094 #endif
4096 for (;;) {
4097 do {
4098 #ifdef CONFIG_PROFILER
4099 int64_t ti;
4100 #endif
4101 #ifndef CONFIG_IOTHREAD
4102 tcg_cpu_exec();
4103 #endif
4104 #ifdef CONFIG_PROFILER
4105 ti = profile_getclock();
4106 #endif
4107 main_loop_wait(qemu_calculate_timeout());
4108 #ifdef CONFIG_PROFILER
4109 dev_time += profile_getclock() - ti;
4110 #endif
4111 } while (vm_can_run());
4113 if (qemu_debug_requested())
4114 vm_stop(EXCP_DEBUG);
4115 if (qemu_shutdown_requested()) {
4116 if (no_shutdown) {
4117 vm_stop(0);
4118 no_shutdown = 0;
4119 } else
4120 break;
4122 if (qemu_reset_requested()) {
4123 pause_all_vcpus();
4124 qemu_system_reset();
4125 resume_all_vcpus();
4127 if (qemu_powerdown_requested()) {
4128 qemu_irq_raise(qemu_system_powerdown);
4130 if ((r = qemu_vmstop_requested()))
4131 vm_stop(r);
4133 pause_all_vcpus();
4136 static void version(void)
4138 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4141 static void help(int exitcode)
4143 version();
4144 printf("usage: %s [options] [disk_image]\n"
4145 "\n"
4146 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4147 "\n"
4148 #define DEF(option, opt_arg, opt_enum, opt_help) \
4149 opt_help
4150 #define DEFHEADING(text) stringify(text) "\n"
4151 #include "qemu-options.h"
4152 #undef DEF
4153 #undef DEFHEADING
4154 #undef GEN_DOCS
4155 "\n"
4156 "During emulation, the following keys are useful:\n"
4157 "ctrl-alt-f toggle full screen\n"
4158 "ctrl-alt-n switch to virtual console 'n'\n"
4159 "ctrl-alt toggle mouse and keyboard grab\n"
4160 "\n"
4161 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4163 "qemu",
4164 DEFAULT_RAM_SIZE,
4165 #ifndef _WIN32
4166 DEFAULT_NETWORK_SCRIPT,
4167 DEFAULT_NETWORK_DOWN_SCRIPT,
4168 #endif
4169 DEFAULT_GDBSTUB_PORT,
4170 "/tmp/qemu.log");
4171 exit(exitcode);
4174 #define HAS_ARG 0x0001
4176 enum {
4177 #define DEF(option, opt_arg, opt_enum, opt_help) \
4178 opt_enum,
4179 #define DEFHEADING(text)
4180 #include "qemu-options.h"
4181 #undef DEF
4182 #undef DEFHEADING
4183 #undef GEN_DOCS
4186 typedef struct QEMUOption {
4187 const char *name;
4188 int flags;
4189 int index;
4190 } QEMUOption;
4192 static const QEMUOption qemu_options[] = {
4193 { "h", 0, QEMU_OPTION_h },
4194 #define DEF(option, opt_arg, opt_enum, opt_help) \
4195 { option, opt_arg, opt_enum },
4196 #define DEFHEADING(text)
4197 #include "qemu-options.h"
4198 #undef DEF
4199 #undef DEFHEADING
4200 #undef GEN_DOCS
4201 { NULL },
4204 #ifdef HAS_AUDIO
4205 struct soundhw soundhw[] = {
4206 #ifdef HAS_AUDIO_CHOICE
4207 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4209 "pcspk",
4210 "PC speaker",
4213 { .init_isa = pcspk_audio_init }
4215 #endif
4217 #ifdef CONFIG_SB16
4219 "sb16",
4220 "Creative Sound Blaster 16",
4223 { .init_isa = SB16_init }
4225 #endif
4227 #ifdef CONFIG_CS4231A
4229 "cs4231a",
4230 "CS4231A",
4233 { .init_isa = cs4231a_init }
4235 #endif
4237 #ifdef CONFIG_ADLIB
4239 "adlib",
4240 #ifdef HAS_YMF262
4241 "Yamaha YMF262 (OPL3)",
4242 #else
4243 "Yamaha YM3812 (OPL2)",
4244 #endif
4247 { .init_isa = Adlib_init }
4249 #endif
4251 #ifdef CONFIG_GUS
4253 "gus",
4254 "Gravis Ultrasound GF1",
4257 { .init_isa = GUS_init }
4259 #endif
4261 #ifdef CONFIG_AC97
4263 "ac97",
4264 "Intel 82801AA AC97 Audio",
4267 { .init_pci = ac97_init }
4269 #endif
4271 #ifdef CONFIG_ES1370
4273 "es1370",
4274 "ENSONIQ AudioPCI ES1370",
4277 { .init_pci = es1370_init }
4279 #endif
4281 #endif /* HAS_AUDIO_CHOICE */
4283 { NULL, NULL, 0, 0, { NULL } }
4286 static void select_soundhw (const char *optarg)
4288 struct soundhw *c;
4290 if (*optarg == '?') {
4291 show_valid_cards:
4293 printf ("Valid sound card names (comma separated):\n");
4294 for (c = soundhw; c->name; ++c) {
4295 printf ("%-11s %s\n", c->name, c->descr);
4297 printf ("\n-soundhw all will enable all of the above\n");
4298 exit (*optarg != '?');
4300 else {
4301 size_t l;
4302 const char *p;
4303 char *e;
4304 int bad_card = 0;
4306 if (!strcmp (optarg, "all")) {
4307 for (c = soundhw; c->name; ++c) {
4308 c->enabled = 1;
4310 return;
4313 p = optarg;
4314 while (*p) {
4315 e = strchr (p, ',');
4316 l = !e ? strlen (p) : (size_t) (e - p);
4318 for (c = soundhw; c->name; ++c) {
4319 if (!strncmp (c->name, p, l) && !c->name[l]) {
4320 c->enabled = 1;
4321 break;
4325 if (!c->name) {
4326 if (l > 80) {
4327 fprintf (stderr,
4328 "Unknown sound card name (too big to show)\n");
4330 else {
4331 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4332 (int) l, p);
4334 bad_card = 1;
4336 p += l + (e != NULL);
4339 if (bad_card)
4340 goto show_valid_cards;
4343 #endif
4345 static void select_vgahw (const char *p)
4347 const char *opts;
4349 vga_interface_type = VGA_NONE;
4350 if (strstart(p, "std", &opts)) {
4351 vga_interface_type = VGA_STD;
4352 } else if (strstart(p, "cirrus", &opts)) {
4353 vga_interface_type = VGA_CIRRUS;
4354 } else if (strstart(p, "vmware", &opts)) {
4355 vga_interface_type = VGA_VMWARE;
4356 } else if (strstart(p, "xenfb", &opts)) {
4357 vga_interface_type = VGA_XENFB;
4358 } else if (!strstart(p, "none", &opts)) {
4359 invalid_vga:
4360 fprintf(stderr, "Unknown vga type: %s\n", p);
4361 exit(1);
4363 while (*opts) {
4364 const char *nextopt;
4366 if (strstart(opts, ",retrace=", &nextopt)) {
4367 opts = nextopt;
4368 if (strstart(opts, "dumb", &nextopt))
4369 vga_retrace_method = VGA_RETRACE_DUMB;
4370 else if (strstart(opts, "precise", &nextopt))
4371 vga_retrace_method = VGA_RETRACE_PRECISE;
4372 else goto invalid_vga;
4373 } else goto invalid_vga;
4374 opts = nextopt;
4378 #ifdef TARGET_I386
4379 static int balloon_parse(const char *arg)
4381 QemuOpts *opts;
4383 if (strcmp(arg, "none") == 0) {
4384 return 0;
4387 if (!strncmp(arg, "virtio", 6)) {
4388 if (arg[6] == ',') {
4389 /* have params -> parse them */
4390 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4391 if (!opts)
4392 return -1;
4393 } else {
4394 /* create empty opts */
4395 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4397 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4398 return 0;
4401 return -1;
4403 #endif
4405 #ifdef _WIN32
4406 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4408 exit(STATUS_CONTROL_C_EXIT);
4409 return TRUE;
4411 #endif
4413 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4415 int ret;
4417 if(strlen(str) != 36)
4418 return -1;
4420 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4421 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4422 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4424 if(ret != 16)
4425 return -1;
4427 #ifdef TARGET_I386
4428 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4429 #endif
4431 return 0;
4434 #ifndef _WIN32
4436 static void termsig_handler(int signal)
4438 qemu_system_shutdown_request();
4441 static void sigchld_handler(int signal)
4443 waitpid(-1, NULL, WNOHANG);
4446 static void sighandler_setup(void)
4448 struct sigaction act;
4450 memset(&act, 0, sizeof(act));
4451 act.sa_handler = termsig_handler;
4452 sigaction(SIGINT, &act, NULL);
4453 sigaction(SIGHUP, &act, NULL);
4454 sigaction(SIGTERM, &act, NULL);
4456 act.sa_handler = sigchld_handler;
4457 act.sa_flags = SA_NOCLDSTOP;
4458 sigaction(SIGCHLD, &act, NULL);
4461 #endif
4463 #ifdef _WIN32
4464 /* Look for support files in the same directory as the executable. */
4465 static char *find_datadir(const char *argv0)
4467 char *p;
4468 char buf[MAX_PATH];
4469 DWORD len;
4471 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4472 if (len == 0) {
4473 return NULL;
4476 buf[len] = 0;
4477 p = buf + len - 1;
4478 while (p != buf && *p != '\\')
4479 p--;
4480 *p = 0;
4481 if (access(buf, R_OK) == 0) {
4482 return qemu_strdup(buf);
4484 return NULL;
4486 #else /* !_WIN32 */
4488 /* Find a likely location for support files using the location of the binary.
4489 For installed binaries this will be "$bindir/../share/qemu". When
4490 running from the build tree this will be "$bindir/../pc-bios". */
4491 #define SHARE_SUFFIX "/share/qemu"
4492 #define BUILD_SUFFIX "/pc-bios"
4493 static char *find_datadir(const char *argv0)
4495 char *dir;
4496 char *p = NULL;
4497 char *res;
4498 char buf[PATH_MAX];
4499 size_t max_len;
4501 #if defined(__linux__)
4503 int len;
4504 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4505 if (len > 0) {
4506 buf[len] = 0;
4507 p = buf;
4510 #elif defined(__FreeBSD__)
4512 int len;
4513 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4514 if (len > 0) {
4515 buf[len] = 0;
4516 p = buf;
4519 #endif
4520 /* If we don't have any way of figuring out the actual executable
4521 location then try argv[0]. */
4522 if (!p) {
4523 p = realpath(argv0, buf);
4524 if (!p) {
4525 return NULL;
4528 dir = dirname(p);
4529 dir = dirname(dir);
4531 max_len = strlen(dir) +
4532 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4533 res = qemu_mallocz(max_len);
4534 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4535 if (access(res, R_OK)) {
4536 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4537 if (access(res, R_OK)) {
4538 qemu_free(res);
4539 res = NULL;
4543 return res;
4545 #undef SHARE_SUFFIX
4546 #undef BUILD_SUFFIX
4547 #endif
4549 char *qemu_find_file(int type, const char *name)
4551 int len;
4552 const char *subdir;
4553 char *buf;
4555 /* If name contains path separators then try it as a straight path. */
4556 if ((strchr(name, '/') || strchr(name, '\\'))
4557 && access(name, R_OK) == 0) {
4558 return qemu_strdup(name);
4560 switch (type) {
4561 case QEMU_FILE_TYPE_BIOS:
4562 subdir = "";
4563 break;
4564 case QEMU_FILE_TYPE_KEYMAP:
4565 subdir = "keymaps/";
4566 break;
4567 default:
4568 abort();
4570 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4571 buf = qemu_mallocz(len);
4572 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4573 if (access(buf, R_OK)) {
4574 qemu_free(buf);
4575 return NULL;
4577 return buf;
4580 static int device_init_func(QemuOpts *opts, void *opaque)
4582 DeviceState *dev;
4584 dev = qdev_device_add(opts);
4585 if (!dev)
4586 return -1;
4587 return 0;
4590 struct device_config {
4591 enum {
4592 DEV_USB, /* -usbdevice */
4593 DEV_BT, /* -bt */
4594 } type;
4595 const char *cmdline;
4596 QTAILQ_ENTRY(device_config) next;
4598 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4600 static void add_device_config(int type, const char *cmdline)
4602 struct device_config *conf;
4604 conf = qemu_mallocz(sizeof(*conf));
4605 conf->type = type;
4606 conf->cmdline = cmdline;
4607 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4610 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4612 struct device_config *conf;
4613 int rc;
4615 QTAILQ_FOREACH(conf, &device_configs, next) {
4616 if (conf->type != type)
4617 continue;
4618 rc = func(conf->cmdline);
4619 if (0 != rc)
4620 return rc;
4622 return 0;
4625 int main(int argc, char **argv, char **envp)
4627 const char *gdbstub_dev = NULL;
4628 uint32_t boot_devices_bitmap = 0;
4629 int i;
4630 int snapshot, linux_boot, net_boot;
4631 const char *initrd_filename;
4632 const char *kernel_filename, *kernel_cmdline;
4633 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4634 DisplayState *ds;
4635 DisplayChangeListener *dcl;
4636 int cyls, heads, secs, translation;
4637 QemuOpts *hda_opts = NULL, *opts;
4638 int optind;
4639 const char *r, *optarg;
4640 CharDriverState *monitor_hds[MAX_MONITOR_DEVICES];
4641 const char *monitor_devices[MAX_MONITOR_DEVICES];
4642 int monitor_device_index;
4643 const char *serial_devices[MAX_SERIAL_PORTS];
4644 int serial_device_index;
4645 const char *parallel_devices[MAX_PARALLEL_PORTS];
4646 int parallel_device_index;
4647 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4648 int virtio_console_index;
4649 const char *loadvm = NULL;
4650 QEMUMachine *machine;
4651 const char *cpu_model;
4652 #ifndef _WIN32
4653 int fds[2];
4654 #endif
4655 int tb_size;
4656 const char *pid_file = NULL;
4657 const char *incoming = NULL;
4658 #ifndef _WIN32
4659 int fd = 0;
4660 struct passwd *pwd = NULL;
4661 const char *chroot_dir = NULL;
4662 const char *run_as = NULL;
4663 #endif
4664 CPUState *env;
4665 int show_vnc_port = 0;
4667 init_clocks();
4669 qemu_errors_to_file(stderr);
4670 qemu_cache_utils_init(envp);
4672 QLIST_INIT (&vm_change_state_head);
4673 #ifndef _WIN32
4675 struct sigaction act;
4676 sigfillset(&act.sa_mask);
4677 act.sa_flags = 0;
4678 act.sa_handler = SIG_IGN;
4679 sigaction(SIGPIPE, &act, NULL);
4681 #else
4682 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4683 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4684 QEMU to run on a single CPU */
4686 HANDLE h;
4687 DWORD mask, smask;
4688 int i;
4689 h = GetCurrentProcess();
4690 if (GetProcessAffinityMask(h, &mask, &smask)) {
4691 for(i = 0; i < 32; i++) {
4692 if (mask & (1 << i))
4693 break;
4695 if (i != 32) {
4696 mask = 1 << i;
4697 SetProcessAffinityMask(h, mask);
4701 #endif
4703 module_call_init(MODULE_INIT_MACHINE);
4704 machine = find_default_machine();
4705 cpu_model = NULL;
4706 initrd_filename = NULL;
4707 ram_size = 0;
4708 snapshot = 0;
4709 kernel_filename = NULL;
4710 kernel_cmdline = "";
4711 cyls = heads = secs = 0;
4712 translation = BIOS_ATA_TRANSLATION_AUTO;
4714 serial_devices[0] = "vc:80Cx24C";
4715 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4716 serial_devices[i] = NULL;
4717 serial_device_index = 0;
4719 parallel_devices[0] = "vc:80Cx24C";
4720 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4721 parallel_devices[i] = NULL;
4722 parallel_device_index = 0;
4724 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4725 virtio_consoles[i] = NULL;
4726 virtio_console_index = 0;
4728 monitor_devices[0] = "vc:80Cx24C";
4729 for (i = 1; i < MAX_MONITOR_DEVICES; i++) {
4730 monitor_devices[i] = NULL;
4732 monitor_device_index = 0;
4734 for (i = 0; i < MAX_NODES; i++) {
4735 node_mem[i] = 0;
4736 node_cpumask[i] = 0;
4739 assigned_devices_index = 0;
4741 nb_numa_nodes = 0;
4742 nb_nics = 0;
4744 tb_size = 0;
4745 autostart= 1;
4747 optind = 1;
4748 for(;;) {
4749 if (optind >= argc)
4750 break;
4751 r = argv[optind];
4752 if (r[0] != '-') {
4753 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4754 } else {
4755 const QEMUOption *popt;
4757 optind++;
4758 /* Treat --foo the same as -foo. */
4759 if (r[1] == '-')
4760 r++;
4761 popt = qemu_options;
4762 for(;;) {
4763 if (!popt->name) {
4764 fprintf(stderr, "%s: invalid option -- '%s'\n",
4765 argv[0], r);
4766 exit(1);
4768 if (!strcmp(popt->name, r + 1))
4769 break;
4770 popt++;
4772 if (popt->flags & HAS_ARG) {
4773 if (optind >= argc) {
4774 fprintf(stderr, "%s: option '%s' requires an argument\n",
4775 argv[0], r);
4776 exit(1);
4778 optarg = argv[optind++];
4779 } else {
4780 optarg = NULL;
4783 switch(popt->index) {
4784 case QEMU_OPTION_M:
4785 machine = find_machine(optarg);
4786 if (!machine) {
4787 QEMUMachine *m;
4788 printf("Supported machines are:\n");
4789 for(m = first_machine; m != NULL; m = m->next) {
4790 if (m->alias)
4791 printf("%-10s %s (alias of %s)\n",
4792 m->alias, m->desc, m->name);
4793 printf("%-10s %s%s\n",
4794 m->name, m->desc,
4795 m->is_default ? " (default)" : "");
4797 exit(*optarg != '?');
4799 break;
4800 case QEMU_OPTION_cpu:
4801 /* hw initialization will check this */
4802 if (*optarg == '?') {
4803 /* XXX: implement xxx_cpu_list for targets that still miss it */
4804 #if defined(cpu_list)
4805 cpu_list(stdout, &fprintf);
4806 #endif
4807 exit(0);
4808 } else {
4809 cpu_model = optarg;
4811 break;
4812 case QEMU_OPTION_initrd:
4813 initrd_filename = optarg;
4814 break;
4815 case QEMU_OPTION_hda:
4816 if (cyls == 0)
4817 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4818 else
4819 hda_opts = drive_add(optarg, HD_ALIAS
4820 ",cyls=%d,heads=%d,secs=%d%s",
4821 0, cyls, heads, secs,
4822 translation == BIOS_ATA_TRANSLATION_LBA ?
4823 ",trans=lba" :
4824 translation == BIOS_ATA_TRANSLATION_NONE ?
4825 ",trans=none" : "");
4826 break;
4827 case QEMU_OPTION_hdb:
4828 case QEMU_OPTION_hdc:
4829 case QEMU_OPTION_hdd:
4830 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4831 break;
4832 case QEMU_OPTION_drive:
4833 drive_add(NULL, "%s", optarg);
4834 break;
4835 case QEMU_OPTION_set:
4836 if (qemu_set_option(optarg) != 0)
4837 exit(1);
4838 break;
4839 case QEMU_OPTION_mtdblock:
4840 drive_add(optarg, MTD_ALIAS);
4841 break;
4842 case QEMU_OPTION_sd:
4843 drive_add(optarg, SD_ALIAS);
4844 break;
4845 case QEMU_OPTION_pflash:
4846 drive_add(optarg, PFLASH_ALIAS);
4847 break;
4848 case QEMU_OPTION_snapshot:
4849 snapshot = 1;
4850 break;
4851 case QEMU_OPTION_hdachs:
4853 const char *p;
4854 p = optarg;
4855 cyls = strtol(p, (char **)&p, 0);
4856 if (cyls < 1 || cyls > 16383)
4857 goto chs_fail;
4858 if (*p != ',')
4859 goto chs_fail;
4860 p++;
4861 heads = strtol(p, (char **)&p, 0);
4862 if (heads < 1 || heads > 16)
4863 goto chs_fail;
4864 if (*p != ',')
4865 goto chs_fail;
4866 p++;
4867 secs = strtol(p, (char **)&p, 0);
4868 if (secs < 1 || secs > 63)
4869 goto chs_fail;
4870 if (*p == ',') {
4871 p++;
4872 if (!strcmp(p, "none"))
4873 translation = BIOS_ATA_TRANSLATION_NONE;
4874 else if (!strcmp(p, "lba"))
4875 translation = BIOS_ATA_TRANSLATION_LBA;
4876 else if (!strcmp(p, "auto"))
4877 translation = BIOS_ATA_TRANSLATION_AUTO;
4878 else
4879 goto chs_fail;
4880 } else if (*p != '\0') {
4881 chs_fail:
4882 fprintf(stderr, "qemu: invalid physical CHS format\n");
4883 exit(1);
4885 if (hda_opts != NULL) {
4886 char num[16];
4887 snprintf(num, sizeof(num), "%d", cyls);
4888 qemu_opt_set(hda_opts, "cyls", num);
4889 snprintf(num, sizeof(num), "%d", heads);
4890 qemu_opt_set(hda_opts, "heads", num);
4891 snprintf(num, sizeof(num), "%d", secs);
4892 qemu_opt_set(hda_opts, "secs", num);
4893 if (translation == BIOS_ATA_TRANSLATION_LBA)
4894 qemu_opt_set(hda_opts, "trans", "lba");
4895 if (translation == BIOS_ATA_TRANSLATION_NONE)
4896 qemu_opt_set(hda_opts, "trans", "none");
4899 break;
4900 case QEMU_OPTION_numa:
4901 if (nb_numa_nodes >= MAX_NODES) {
4902 fprintf(stderr, "qemu: too many NUMA nodes\n");
4903 exit(1);
4905 numa_add(optarg);
4906 break;
4907 case QEMU_OPTION_nographic:
4908 display_type = DT_NOGRAPHIC;
4909 break;
4910 #ifdef CONFIG_CURSES
4911 case QEMU_OPTION_curses:
4912 display_type = DT_CURSES;
4913 break;
4914 #endif
4915 case QEMU_OPTION_portrait:
4916 graphic_rotate = 1;
4917 break;
4918 case QEMU_OPTION_kernel:
4919 kernel_filename = optarg;
4920 break;
4921 case QEMU_OPTION_append:
4922 kernel_cmdline = optarg;
4923 break;
4924 case QEMU_OPTION_cdrom:
4925 drive_add(optarg, CDROM_ALIAS);
4926 break;
4927 case QEMU_OPTION_boot:
4929 static const char * const params[] = {
4930 "order", "once", "menu", NULL
4932 char buf[sizeof(boot_devices)];
4933 char *standard_boot_devices;
4934 int legacy = 0;
4936 if (!strchr(optarg, '=')) {
4937 legacy = 1;
4938 pstrcpy(buf, sizeof(buf), optarg);
4939 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4940 fprintf(stderr,
4941 "qemu: unknown boot parameter '%s' in '%s'\n",
4942 buf, optarg);
4943 exit(1);
4946 if (legacy ||
4947 get_param_value(buf, sizeof(buf), "order", optarg)) {
4948 boot_devices_bitmap = parse_bootdevices(buf);
4949 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4951 if (!legacy) {
4952 if (get_param_value(buf, sizeof(buf),
4953 "once", optarg)) {
4954 boot_devices_bitmap |= parse_bootdevices(buf);
4955 standard_boot_devices = qemu_strdup(boot_devices);
4956 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4957 qemu_register_reset(restore_boot_devices,
4958 standard_boot_devices);
4960 if (get_param_value(buf, sizeof(buf),
4961 "menu", optarg)) {
4962 if (!strcmp(buf, "on")) {
4963 boot_menu = 1;
4964 } else if (!strcmp(buf, "off")) {
4965 boot_menu = 0;
4966 } else {
4967 fprintf(stderr,
4968 "qemu: invalid option value '%s'\n",
4969 buf);
4970 exit(1);
4975 break;
4976 case QEMU_OPTION_fda:
4977 case QEMU_OPTION_fdb:
4978 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4979 break;
4980 #ifdef TARGET_I386
4981 case QEMU_OPTION_no_fd_bootchk:
4982 fd_bootchk = 0;
4983 break;
4984 #endif
4985 case QEMU_OPTION_netdev:
4986 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4987 exit(1);
4989 break;
4990 case QEMU_OPTION_net:
4991 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
4992 exit(1);
4994 break;
4995 #ifdef CONFIG_SLIRP
4996 case QEMU_OPTION_tftp:
4997 legacy_tftp_prefix = optarg;
4998 break;
4999 case QEMU_OPTION_bootp:
5000 legacy_bootp_filename = optarg;
5001 break;
5002 #ifndef _WIN32
5003 case QEMU_OPTION_smb:
5004 if (net_slirp_smb(optarg) < 0)
5005 exit(1);
5006 break;
5007 #endif
5008 case QEMU_OPTION_redir:
5009 if (net_slirp_redir(optarg) < 0)
5010 exit(1);
5011 break;
5012 #endif
5013 case QEMU_OPTION_bt:
5014 add_device_config(DEV_BT, optarg);
5015 break;
5016 #ifdef HAS_AUDIO
5017 case QEMU_OPTION_audio_help:
5018 AUD_help ();
5019 exit (0);
5020 break;
5021 case QEMU_OPTION_soundhw:
5022 select_soundhw (optarg);
5023 break;
5024 #endif
5025 case QEMU_OPTION_h:
5026 help(0);
5027 break;
5028 case QEMU_OPTION_version:
5029 version();
5030 exit(0);
5031 break;
5032 case QEMU_OPTION_m: {
5033 uint64_t value;
5034 char *ptr;
5036 value = strtoul(optarg, &ptr, 10);
5037 switch (*ptr) {
5038 case 0: case 'M': case 'm':
5039 value <<= 20;
5040 break;
5041 case 'G': case 'g':
5042 value <<= 30;
5043 break;
5044 default:
5045 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5046 exit(1);
5049 /* On 32-bit hosts, QEMU is limited by virtual address space */
5050 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5051 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5052 exit(1);
5054 if (value != (uint64_t)(ram_addr_t)value) {
5055 fprintf(stderr, "qemu: ram size too large\n");
5056 exit(1);
5058 ram_size = value;
5059 break;
5061 case QEMU_OPTION_d:
5063 int mask;
5064 const CPULogItem *item;
5066 mask = cpu_str_to_log_mask(optarg);
5067 if (!mask) {
5068 printf("Log items (comma separated):\n");
5069 for(item = cpu_log_items; item->mask != 0; item++) {
5070 printf("%-10s %s\n", item->name, item->help);
5072 exit(1);
5074 cpu_set_log(mask);
5076 break;
5077 case QEMU_OPTION_s:
5078 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5079 break;
5080 case QEMU_OPTION_gdb:
5081 gdbstub_dev = optarg;
5082 break;
5083 case QEMU_OPTION_L:
5084 data_dir = optarg;
5085 break;
5086 case QEMU_OPTION_bios:
5087 bios_name = optarg;
5088 break;
5089 case QEMU_OPTION_singlestep:
5090 singlestep = 1;
5091 break;
5092 case QEMU_OPTION_S:
5093 autostart = 0;
5094 break;
5095 #ifndef _WIN32
5096 case QEMU_OPTION_k:
5097 keyboard_layout = optarg;
5098 break;
5099 #endif
5100 case QEMU_OPTION_localtime:
5101 rtc_utc = 0;
5102 break;
5103 case QEMU_OPTION_vga:
5104 select_vgahw (optarg);
5105 break;
5106 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5107 case QEMU_OPTION_g:
5109 const char *p;
5110 int w, h, depth;
5111 p = optarg;
5112 w = strtol(p, (char **)&p, 10);
5113 if (w <= 0) {
5114 graphic_error:
5115 fprintf(stderr, "qemu: invalid resolution or depth\n");
5116 exit(1);
5118 if (*p != 'x')
5119 goto graphic_error;
5120 p++;
5121 h = strtol(p, (char **)&p, 10);
5122 if (h <= 0)
5123 goto graphic_error;
5124 if (*p == 'x') {
5125 p++;
5126 depth = strtol(p, (char **)&p, 10);
5127 if (depth != 8 && depth != 15 && depth != 16 &&
5128 depth != 24 && depth != 32)
5129 goto graphic_error;
5130 } else if (*p == '\0') {
5131 depth = graphic_depth;
5132 } else {
5133 goto graphic_error;
5136 graphic_width = w;
5137 graphic_height = h;
5138 graphic_depth = depth;
5140 break;
5141 #endif
5142 case QEMU_OPTION_echr:
5144 char *r;
5145 term_escape_char = strtol(optarg, &r, 0);
5146 if (r == optarg)
5147 printf("Bad argument to echr\n");
5148 break;
5150 case QEMU_OPTION_monitor:
5151 if (monitor_device_index >= MAX_MONITOR_DEVICES) {
5152 fprintf(stderr, "qemu: too many monitor devices\n");
5153 exit(1);
5155 monitor_devices[monitor_device_index] = optarg;
5156 monitor_device_index++;
5157 break;
5158 case QEMU_OPTION_chardev:
5159 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5160 if (!opts) {
5161 fprintf(stderr, "parse error: %s\n", optarg);
5162 exit(1);
5164 if (qemu_chr_open_opts(opts, NULL) == NULL) {
5165 exit(1);
5167 break;
5168 case QEMU_OPTION_serial:
5169 if (serial_device_index >= MAX_SERIAL_PORTS) {
5170 fprintf(stderr, "qemu: too many serial ports\n");
5171 exit(1);
5173 serial_devices[serial_device_index] = optarg;
5174 serial_device_index++;
5175 break;
5176 case QEMU_OPTION_watchdog:
5177 if (watchdog) {
5178 fprintf(stderr,
5179 "qemu: only one watchdog option may be given\n");
5180 return 1;
5182 watchdog = optarg;
5183 break;
5184 case QEMU_OPTION_watchdog_action:
5185 if (select_watchdog_action(optarg) == -1) {
5186 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5187 exit(1);
5189 break;
5190 case QEMU_OPTION_virtiocon:
5191 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5192 fprintf(stderr, "qemu: too many virtio consoles\n");
5193 exit(1);
5195 virtio_consoles[virtio_console_index] = optarg;
5196 virtio_console_index++;
5197 break;
5198 case QEMU_OPTION_parallel:
5199 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5200 fprintf(stderr, "qemu: too many parallel ports\n");
5201 exit(1);
5203 parallel_devices[parallel_device_index] = optarg;
5204 parallel_device_index++;
5205 break;
5206 case QEMU_OPTION_loadvm:
5207 loadvm = optarg;
5208 break;
5209 case QEMU_OPTION_full_screen:
5210 full_screen = 1;
5211 break;
5212 #ifdef CONFIG_SDL
5213 case QEMU_OPTION_no_frame:
5214 no_frame = 1;
5215 break;
5216 case QEMU_OPTION_alt_grab:
5217 alt_grab = 1;
5218 break;
5219 case QEMU_OPTION_ctrl_grab:
5220 ctrl_grab = 1;
5221 break;
5222 case QEMU_OPTION_no_quit:
5223 no_quit = 1;
5224 break;
5225 case QEMU_OPTION_sdl:
5226 display_type = DT_SDL;
5227 break;
5228 #endif
5229 case QEMU_OPTION_pidfile:
5230 pid_file = optarg;
5231 break;
5232 #ifdef TARGET_I386
5233 case QEMU_OPTION_win2k_hack:
5234 win2k_install_hack = 1;
5235 break;
5236 case QEMU_OPTION_rtc_td_hack:
5237 rtc_td_hack = 1;
5238 break;
5239 case QEMU_OPTION_acpitable:
5240 if(acpi_table_add(optarg) < 0) {
5241 fprintf(stderr, "Wrong acpi table provided\n");
5242 exit(1);
5244 break;
5245 case QEMU_OPTION_smbios:
5246 if(smbios_entry_add(optarg) < 0) {
5247 fprintf(stderr, "Wrong smbios provided\n");
5248 exit(1);
5250 break;
5251 #endif
5252 #ifdef CONFIG_KVM
5253 #ifdef KVM_UPSTREAM
5254 case QEMU_OPTION_enable_kvm:
5255 kvm_allowed = 1;
5256 #endif
5257 break;
5258 case QEMU_OPTION_no_kvm:
5259 kvm_allowed = 0;
5260 break;
5261 case QEMU_OPTION_no_kvm_irqchip: {
5262 kvm_irqchip = 0;
5263 kvm_pit = 0;
5264 break;
5266 case QEMU_OPTION_no_kvm_pit: {
5267 kvm_pit = 0;
5268 break;
5270 case QEMU_OPTION_no_kvm_pit_reinjection: {
5271 kvm_pit_reinject = 0;
5272 break;
5274 case QEMU_OPTION_enable_nesting: {
5275 kvm_nested = 1;
5276 break;
5278 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5279 case QEMU_OPTION_pcidevice:
5280 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5281 fprintf(stderr, "Too many assigned devices\n");
5282 exit(1);
5284 assigned_devices[assigned_devices_index] = optarg;
5285 assigned_devices_index++;
5286 break;
5287 #endif
5288 #endif
5289 case QEMU_OPTION_usb:
5290 usb_enabled = 1;
5291 break;
5292 case QEMU_OPTION_usbdevice:
5293 usb_enabled = 1;
5294 add_device_config(DEV_USB, optarg);
5295 break;
5296 case QEMU_OPTION_device:
5297 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5298 exit(1);
5300 break;
5301 case QEMU_OPTION_smp:
5302 smp_parse(optarg);
5303 if (smp_cpus < 1) {
5304 fprintf(stderr, "Invalid number of CPUs\n");
5305 exit(1);
5307 if (max_cpus < smp_cpus) {
5308 fprintf(stderr, "maxcpus must be equal to or greater than "
5309 "smp\n");
5310 exit(1);
5312 if (max_cpus > 255) {
5313 fprintf(stderr, "Unsupported number of maxcpus\n");
5314 exit(1);
5316 break;
5317 case QEMU_OPTION_vnc:
5318 display_type = DT_VNC;
5319 vnc_display = optarg;
5320 break;
5321 #ifdef TARGET_I386
5322 case QEMU_OPTION_no_acpi:
5323 acpi_enabled = 0;
5324 break;
5325 case QEMU_OPTION_no_hpet:
5326 no_hpet = 1;
5327 break;
5328 case QEMU_OPTION_balloon:
5329 if (balloon_parse(optarg) < 0) {
5330 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5331 exit(1);
5333 break;
5334 #endif
5335 case QEMU_OPTION_no_reboot:
5336 no_reboot = 1;
5337 break;
5338 case QEMU_OPTION_no_shutdown:
5339 no_shutdown = 1;
5340 break;
5341 case QEMU_OPTION_show_cursor:
5342 cursor_hide = 0;
5343 break;
5344 case QEMU_OPTION_uuid:
5345 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5346 fprintf(stderr, "Fail to parse UUID string."
5347 " Wrong format.\n");
5348 exit(1);
5350 break;
5351 #ifndef _WIN32
5352 case QEMU_OPTION_daemonize:
5353 daemonize = 1;
5354 break;
5355 #endif
5356 case QEMU_OPTION_option_rom:
5357 if (nb_option_roms >= MAX_OPTION_ROMS) {
5358 fprintf(stderr, "Too many option ROMs\n");
5359 exit(1);
5361 option_rom[nb_option_roms] = optarg;
5362 nb_option_roms++;
5363 break;
5364 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5365 case QEMU_OPTION_semihosting:
5366 semihosting_enabled = 1;
5367 break;
5368 #endif
5369 case QEMU_OPTION_tdf:
5370 time_drift_fix = 1;
5371 break;
5372 case QEMU_OPTION_kvm_shadow_memory:
5373 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5374 break;
5375 case QEMU_OPTION_mempath:
5376 mem_path = optarg;
5377 break;
5378 #ifdef MAP_POPULATE
5379 case QEMU_OPTION_mem_prealloc:
5380 mem_prealloc = !mem_prealloc;
5381 break;
5382 #endif
5383 case QEMU_OPTION_name:
5384 qemu_name = qemu_strdup(optarg);
5386 char *p = strchr(qemu_name, ',');
5387 if (p != NULL) {
5388 *p++ = 0;
5389 if (strncmp(p, "process=", 8)) {
5390 fprintf(stderr, "Unknown subargument %s to -name", p);
5391 exit(1);
5393 p += 8;
5394 set_proc_name(p);
5397 break;
5398 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5399 case QEMU_OPTION_prom_env:
5400 if (nb_prom_envs >= MAX_PROM_ENVS) {
5401 fprintf(stderr, "Too many prom variables\n");
5402 exit(1);
5404 prom_envs[nb_prom_envs] = optarg;
5405 nb_prom_envs++;
5406 break;
5407 #endif
5408 #ifdef TARGET_ARM
5409 case QEMU_OPTION_old_param:
5410 old_param = 1;
5411 break;
5412 #endif
5413 case QEMU_OPTION_clock:
5414 configure_alarms(optarg);
5415 break;
5416 case QEMU_OPTION_startdate:
5417 configure_rtc_date_offset(optarg, 1);
5418 break;
5419 case QEMU_OPTION_rtc:
5420 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5421 if (!opts) {
5422 fprintf(stderr, "parse error: %s\n", optarg);
5423 exit(1);
5425 configure_rtc(opts);
5426 break;
5427 case QEMU_OPTION_tb_size:
5428 tb_size = strtol(optarg, NULL, 0);
5429 if (tb_size < 0)
5430 tb_size = 0;
5431 break;
5432 case QEMU_OPTION_icount:
5433 use_icount = 1;
5434 if (strcmp(optarg, "auto") == 0) {
5435 icount_time_shift = -1;
5436 } else {
5437 icount_time_shift = strtol(optarg, NULL, 0);
5439 break;
5440 case QEMU_OPTION_incoming:
5441 incoming = optarg;
5442 break;
5443 #ifndef _WIN32
5444 case QEMU_OPTION_chroot:
5445 chroot_dir = optarg;
5446 break;
5447 case QEMU_OPTION_runas:
5448 run_as = optarg;
5449 break;
5450 case QEMU_OPTION_nvram:
5451 nvram = optarg;
5452 break;
5453 #endif
5454 #ifdef CONFIG_XEN
5455 case QEMU_OPTION_xen_domid:
5456 xen_domid = atoi(optarg);
5457 break;
5458 case QEMU_OPTION_xen_create:
5459 xen_mode = XEN_CREATE;
5460 break;
5461 case QEMU_OPTION_xen_attach:
5462 xen_mode = XEN_ATTACH;
5463 break;
5464 #endif
5469 /* If no data_dir is specified then try to find it relative to the
5470 executable path. */
5471 if (!data_dir) {
5472 data_dir = find_datadir(argv[0]);
5474 /* If all else fails use the install patch specified when building. */
5475 if (!data_dir) {
5476 data_dir = CONFIG_QEMU_SHAREDIR;
5480 * Default to max_cpus = smp_cpus, in case the user doesn't
5481 * specify a max_cpus value.
5483 if (!max_cpus)
5484 max_cpus = smp_cpus;
5486 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5487 if (smp_cpus > machine->max_cpus) {
5488 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5489 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5490 machine->max_cpus);
5491 exit(1);
5494 if (display_type == DT_NOGRAPHIC) {
5495 if (serial_device_index == 0)
5496 serial_devices[0] = "stdio";
5497 if (parallel_device_index == 0)
5498 parallel_devices[0] = "null";
5499 if (strncmp(monitor_devices[0], "vc", 2) == 0) {
5500 monitor_devices[0] = "stdio";
5504 #ifndef _WIN32
5505 if (daemonize) {
5506 pid_t pid;
5508 if (pipe(fds) == -1)
5509 exit(1);
5511 pid = fork();
5512 if (pid > 0) {
5513 uint8_t status;
5514 ssize_t len;
5516 close(fds[1]);
5518 again:
5519 len = read(fds[0], &status, 1);
5520 if (len == -1 && (errno == EINTR))
5521 goto again;
5523 if (len != 1)
5524 exit(1);
5525 else if (status == 1) {
5526 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5527 exit(1);
5528 } else
5529 exit(0);
5530 } else if (pid < 0)
5531 exit(1);
5533 setsid();
5535 pid = fork();
5536 if (pid > 0)
5537 exit(0);
5538 else if (pid < 0)
5539 exit(1);
5541 umask(027);
5543 signal(SIGTSTP, SIG_IGN);
5544 signal(SIGTTOU, SIG_IGN);
5545 signal(SIGTTIN, SIG_IGN);
5548 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5549 if (daemonize) {
5550 uint8_t status = 1;
5551 write(fds[1], &status, 1);
5552 } else
5553 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5554 exit(1);
5556 #endif
5558 if (kvm_enabled()) {
5559 int ret;
5561 ret = kvm_init(smp_cpus);
5562 if (ret < 0) {
5563 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5564 fprintf(stderr, "failed to initialize KVM\n");
5565 exit(1);
5566 #endif
5567 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5568 kvm_allowed = 0;
5572 if (qemu_init_main_loop()) {
5573 fprintf(stderr, "qemu_init_main_loop failed\n");
5574 exit(1);
5576 linux_boot = (kernel_filename != NULL);
5578 if (!linux_boot && *kernel_cmdline != '\0') {
5579 fprintf(stderr, "-append only allowed with -kernel option\n");
5580 exit(1);
5583 if (!linux_boot && initrd_filename != NULL) {
5584 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5585 exit(1);
5588 #ifndef _WIN32
5589 /* Win32 doesn't support line-buffering and requires size >= 2 */
5590 setvbuf(stdout, NULL, _IOLBF, 0);
5591 #endif
5593 if (init_timer_alarm() < 0) {
5594 fprintf(stderr, "could not initialize alarm timer\n");
5595 exit(1);
5597 if (use_icount && icount_time_shift < 0) {
5598 use_icount = 2;
5599 /* 125MIPS seems a reasonable initial guess at the guest speed.
5600 It will be corrected fairly quickly anyway. */
5601 icount_time_shift = 3;
5602 init_icount_adjust();
5605 #ifdef _WIN32
5606 socket_init();
5607 #endif
5609 if (net_init_clients() < 0) {
5610 exit(1);
5613 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5614 net_set_boot_mask(net_boot);
5616 /* init the bluetooth world */
5617 if (foreach_device_config(DEV_BT, bt_parse))
5618 exit(1);
5620 /* init the memory */
5621 if (ram_size == 0)
5622 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5624 /* init the dynamic translator */
5625 cpu_exec_init_all(tb_size * 1024 * 1024);
5627 bdrv_init();
5629 /* we always create the cdrom drive, even if no disk is there */
5630 drive_add(NULL, CDROM_ALIAS);
5632 /* we always create at least one floppy */
5633 drive_add(NULL, FD_ALIAS, 0);
5635 /* we always create one sd slot, even if no card is in it */
5636 drive_add(NULL, SD_ALIAS);
5638 /* open the virtual block devices */
5639 if (snapshot)
5640 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5641 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5642 exit(1);
5644 vmstate_register(0, &vmstate_timers ,&timers_state);
5645 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5647 /* Maintain compatibility with multiple stdio monitors */
5648 if (!strcmp(monitor_devices[0],"stdio")) {
5649 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5650 const char *devname = serial_devices[i];
5651 if (devname && !strcmp(devname,"mon:stdio")) {
5652 monitor_devices[0] = NULL;
5653 break;
5654 } else if (devname && !strcmp(devname,"stdio")) {
5655 monitor_devices[0] = NULL;
5656 serial_devices[i] = "mon:stdio";
5657 break;
5662 if (nb_numa_nodes > 0) {
5663 int i;
5665 if (nb_numa_nodes > smp_cpus) {
5666 nb_numa_nodes = smp_cpus;
5669 /* If no memory size if given for any node, assume the default case
5670 * and distribute the available memory equally across all nodes
5672 for (i = 0; i < nb_numa_nodes; i++) {
5673 if (node_mem[i] != 0)
5674 break;
5676 if (i == nb_numa_nodes) {
5677 uint64_t usedmem = 0;
5679 /* On Linux, the each node's border has to be 8MB aligned,
5680 * the final node gets the rest.
5682 for (i = 0; i < nb_numa_nodes - 1; i++) {
5683 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5684 usedmem += node_mem[i];
5686 node_mem[i] = ram_size - usedmem;
5689 for (i = 0; i < nb_numa_nodes; i++) {
5690 if (node_cpumask[i] != 0)
5691 break;
5693 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5694 * must cope with this anyway, because there are BIOSes out there in
5695 * real machines which also use this scheme.
5697 if (i == nb_numa_nodes) {
5698 for (i = 0; i < smp_cpus; i++) {
5699 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5704 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5705 const char *devname = monitor_devices[i];
5706 if (devname && strcmp(devname, "none")) {
5707 char label[32];
5708 if (i == 0) {
5709 snprintf(label, sizeof(label), "monitor");
5710 } else {
5711 snprintf(label, sizeof(label), "monitor%d", i);
5713 monitor_hds[i] = qemu_chr_open(label, devname, NULL);
5714 if (!monitor_hds[i]) {
5715 fprintf(stderr, "qemu: could not open monitor device '%s'\n",
5716 devname);
5717 exit(1);
5722 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5723 const char *devname = serial_devices[i];
5724 if (devname && strcmp(devname, "none")) {
5725 char label[32];
5726 snprintf(label, sizeof(label), "serial%d", i);
5727 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5728 if (!serial_hds[i]) {
5729 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
5730 devname, strerror(errno));
5731 exit(1);
5736 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5737 const char *devname = parallel_devices[i];
5738 if (devname && strcmp(devname, "none")) {
5739 char label[32];
5740 snprintf(label, sizeof(label), "parallel%d", i);
5741 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5742 if (!parallel_hds[i]) {
5743 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
5744 devname, strerror(errno));
5745 exit(1);
5750 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5751 const char *devname = virtio_consoles[i];
5752 if (devname && strcmp(devname, "none")) {
5753 char label[32];
5754 snprintf(label, sizeof(label), "virtcon%d", i);
5755 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5756 if (!virtcon_hds[i]) {
5757 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
5758 devname, strerror(errno));
5759 exit(1);
5764 module_call_init(MODULE_INIT_DEVICE);
5766 if (watchdog) {
5767 i = select_watchdog(watchdog);
5768 if (i > 0)
5769 exit (i == 1 ? 1 : 0);
5772 if (machine->compat_props) {
5773 qdev_prop_register_compat(machine->compat_props);
5775 machine->init(ram_size, boot_devices,
5776 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5779 #ifndef _WIN32
5780 /* must be after terminal init, SDL library changes signal handlers */
5781 sighandler_setup();
5782 #endif
5784 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5785 for (i = 0; i < nb_numa_nodes; i++) {
5786 if (node_cpumask[i] & (1 << env->cpu_index)) {
5787 env->numa_node = i;
5792 current_machine = machine;
5794 /* init USB devices */
5795 if (usb_enabled) {
5796 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5797 exit(1);
5800 /* init generic devices */
5801 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5802 exit(1);
5804 if (!display_state)
5805 dumb_display_init();
5806 /* just use the first displaystate for the moment */
5807 ds = display_state;
5809 if (display_type == DT_DEFAULT) {
5810 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5811 display_type = DT_SDL;
5812 #else
5813 display_type = DT_VNC;
5814 vnc_display = "localhost:0,to=99";
5815 show_vnc_port = 1;
5816 #endif
5820 switch (display_type) {
5821 case DT_NOGRAPHIC:
5822 break;
5823 #if defined(CONFIG_CURSES)
5824 case DT_CURSES:
5825 curses_display_init(ds, full_screen);
5826 break;
5827 #endif
5828 #if defined(CONFIG_SDL)
5829 case DT_SDL:
5830 sdl_display_init(ds, full_screen, no_frame);
5831 break;
5832 #elif defined(CONFIG_COCOA)
5833 case DT_SDL:
5834 cocoa_display_init(ds, full_screen);
5835 break;
5836 #endif
5837 case DT_VNC:
5838 vnc_display_init(ds);
5839 if (vnc_display_open(ds, vnc_display) < 0)
5840 exit(1);
5842 if (show_vnc_port) {
5843 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5845 break;
5846 default:
5847 break;
5849 dpy_resize(ds);
5851 dcl = ds->listeners;
5852 while (dcl != NULL) {
5853 if (dcl->dpy_refresh != NULL) {
5854 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5855 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5857 dcl = dcl->next;
5860 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5861 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5862 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5865 text_consoles_set_display(display_state);
5866 qemu_chr_initial_reset();
5868 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5869 if (monitor_devices[i] && monitor_hds[i]) {
5870 monitor_init(monitor_hds[i],
5871 MONITOR_USE_READLINE |
5872 ((i == 0) ? MONITOR_IS_DEFAULT : 0));
5876 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5877 const char *devname = serial_devices[i];
5878 if (devname && strcmp(devname, "none")) {
5879 if (strstart(devname, "vc", 0))
5880 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5884 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5885 const char *devname = parallel_devices[i];
5886 if (devname && strcmp(devname, "none")) {
5887 if (strstart(devname, "vc", 0))
5888 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5892 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5893 const char *devname = virtio_consoles[i];
5894 if (virtcon_hds[i] && devname) {
5895 if (strstart(devname, "vc", 0))
5896 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5900 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5901 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5902 gdbstub_dev);
5903 exit(1);
5906 qdev_machine_creation_done();
5908 rom_load_all();
5910 if (loadvm) {
5911 if (load_vmstate(cur_mon, loadvm) < 0) {
5912 autostart = 0;
5916 if (incoming) {
5917 qemu_start_incoming_migration(incoming);
5918 } else if (autostart) {
5919 vm_start();
5922 #ifndef _WIN32
5923 if (daemonize) {
5924 uint8_t status = 0;
5925 ssize_t len;
5927 again1:
5928 len = write(fds[1], &status, 1);
5929 if (len == -1 && (errno == EINTR))
5930 goto again1;
5932 if (len != 1)
5933 exit(1);
5935 chdir("/");
5936 TFR(fd = open("/dev/null", O_RDWR));
5937 if (fd == -1)
5938 exit(1);
5941 if (run_as) {
5942 pwd = getpwnam(run_as);
5943 if (!pwd) {
5944 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5945 exit(1);
5949 if (chroot_dir) {
5950 if (chroot(chroot_dir) < 0) {
5951 fprintf(stderr, "chroot failed\n");
5952 exit(1);
5954 chdir("/");
5957 if (run_as) {
5958 if (setgid(pwd->pw_gid) < 0) {
5959 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5960 exit(1);
5962 if (setuid(pwd->pw_uid) < 0) {
5963 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5964 exit(1);
5966 if (setuid(0) != -1) {
5967 fprintf(stderr, "Dropping privileges failed\n");
5968 exit(1);
5972 if (daemonize) {
5973 dup2(fd, 0);
5974 dup2(fd, 1);
5975 dup2(fd, 2);
5977 close(fd);
5979 #endif
5981 main_loop();
5982 quit_timers();
5983 net_cleanup();
5985 return 0;