Merge commit '3a3fb96d0d9e3331e3beb672108ec18a6d3d8c1c' into upstream-merge
[qemu/qemu-dev-zwu.git] / vl.c
blob7be5512d6315896dfdef37caf4635b763e88972d
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 "block_int.h"
152 #include "block-migration.h"
153 #include "dma.h"
154 #include "audio/audio.h"
155 #include "migration.h"
156 #include "kvm.h"
157 #include "balloon.h"
158 #include "qemu-option.h"
159 #include "qemu-config.h"
160 #include "qemu-kvm.h"
161 #include "hw/device-assignment.h"
163 #include "disas.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #include "slirp/libslirp.h"
171 #include "qemu-queue.h"
173 //#define DEBUG_NET
174 //#define DEBUG_SLIRP
176 #define DEFAULT_RAM_SIZE 128
178 /* Maximum number of monitor devices */
179 #define MAX_MONITOR_DEVICES 10
181 static const char *data_dir;
182 const char *bios_name = NULL;
183 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
184 to store the VM snapshots */
185 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
186 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
187 DriveInfo *extboot_drive = NULL;
188 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
189 static DisplayState *display_state;
190 DisplayType display_type = DT_DEFAULT;
191 const char* keyboard_layout = NULL;
192 ram_addr_t ram_size;
193 int nb_nics;
194 NICInfo nd_table[MAX_NICS];
195 int vm_running;
196 int autostart;
197 static int rtc_utc = 1;
198 static int rtc_date_offset = -1; /* -1 means no change */
199 QEMUClock *rtc_clock;
200 int vga_interface_type = VGA_CIRRUS;
201 #ifdef TARGET_SPARC
202 int graphic_width = 1024;
203 int graphic_height = 768;
204 int graphic_depth = 8;
205 #else
206 int graphic_width = 800;
207 int graphic_height = 600;
208 int graphic_depth = 15;
209 #endif
210 static int full_screen = 0;
211 #ifdef CONFIG_SDL
212 static int no_frame = 0;
213 #endif
214 int no_quit = 0;
215 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
216 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
217 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
218 #ifdef TARGET_I386
219 int win2k_install_hack = 0;
220 int rtc_td_hack = 0;
221 #endif
222 int usb_enabled = 0;
223 int singlestep = 0;
224 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
225 int assigned_devices_index;
226 int smp_cpus = 1;
227 int max_cpus = 0;
228 int smp_cores = 1;
229 int smp_threads = 1;
230 const char *vnc_display;
231 int acpi_enabled = 1;
232 #ifdef TARGET_I386
233 int no_hpet = 0;
234 #endif
235 int fd_bootchk = 1;
236 int no_reboot = 0;
237 int no_shutdown = 0;
238 int cursor_hide = 1;
239 int graphic_rotate = 0;
240 uint8_t irq0override = 1;
241 #ifndef _WIN32
242 int daemonize = 0;
243 #endif
244 const char *watchdog;
245 const char *option_rom[MAX_OPTION_ROMS];
246 int nb_option_roms;
247 int semihosting_enabled = 0;
248 int time_drift_fix = 0;
249 unsigned int kvm_shadow_memory = 0;
250 const char *mem_path = NULL;
251 #ifdef MAP_POPULATE
252 int mem_prealloc = 1; /* force preallocation of physical target memory */
253 #endif
254 #ifdef TARGET_ARM
255 int old_param = 0;
256 #endif
257 const char *qemu_name;
258 int alt_grab = 0;
259 int ctrl_grab = 0;
260 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
261 unsigned int nb_prom_envs = 0;
262 const char *prom_envs[MAX_PROM_ENVS];
263 #endif
264 const char *nvram = NULL;
265 int boot_menu;
267 int nb_numa_nodes;
268 uint64_t node_mem[MAX_NODES];
269 uint64_t node_cpumask[MAX_NODES];
271 static CPUState *cur_cpu;
272 static CPUState *next_cpu;
273 static int timer_alarm_pending = 1;
274 /* Conversion factor from emulated instructions to virtual clock ticks. */
275 static int icount_time_shift;
276 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
277 #define MAX_ICOUNT_SHIFT 10
278 /* Compensate for varying guest execution speed. */
279 static int64_t qemu_icount_bias;
280 static QEMUTimer *icount_rt_timer;
281 static QEMUTimer *icount_vm_timer;
282 static QEMUTimer *nographic_timer;
284 uint8_t qemu_uuid[16];
286 static QEMUBootSetHandler *boot_set_handler;
287 static void *boot_set_opaque;
289 /***********************************************************/
290 /* x86 ISA bus support */
292 target_phys_addr_t isa_mem_base = 0;
293 PicState2 *isa_pic;
295 /***********************************************************/
296 void hw_error(const char *fmt, ...)
298 va_list ap;
299 CPUState *env;
301 va_start(ap, fmt);
302 fprintf(stderr, "qemu: hardware error: ");
303 vfprintf(stderr, fmt, ap);
304 fprintf(stderr, "\n");
305 for(env = first_cpu; env != NULL; env = env->next_cpu) {
306 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
307 #ifdef TARGET_I386
308 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
309 #else
310 cpu_dump_state(env, stderr, fprintf, 0);
311 #endif
313 va_end(ap);
314 abort();
317 static void set_proc_name(const char *s)
319 #if defined(__linux__) && defined(PR_SET_NAME)
320 char name[16];
321 if (!s)
322 return;
323 name[sizeof(name) - 1] = 0;
324 strncpy(name, s, sizeof(name));
325 /* Could rewrite argv[0] too, but that's a bit more complicated.
326 This simple way is enough for `top'. */
327 prctl(PR_SET_NAME, name);
328 #endif
331 /***************/
332 /* ballooning */
334 static QEMUBalloonEvent *qemu_balloon_event;
335 void *qemu_balloon_event_opaque;
337 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
339 qemu_balloon_event = func;
340 qemu_balloon_event_opaque = opaque;
343 void qemu_balloon(ram_addr_t target)
345 if (qemu_balloon_event)
346 qemu_balloon_event(qemu_balloon_event_opaque, target);
349 ram_addr_t qemu_balloon_status(void)
351 if (qemu_balloon_event)
352 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
353 return 0;
356 /***********************************************************/
357 /* keyboard/mouse */
359 static QEMUPutKBDEvent *qemu_put_kbd_event;
360 static void *qemu_put_kbd_event_opaque;
361 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
362 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
364 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
366 qemu_put_kbd_event_opaque = opaque;
367 qemu_put_kbd_event = func;
370 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
371 void *opaque, int absolute,
372 const char *name)
374 QEMUPutMouseEntry *s, *cursor;
376 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
378 s->qemu_put_mouse_event = func;
379 s->qemu_put_mouse_event_opaque = opaque;
380 s->qemu_put_mouse_event_absolute = absolute;
381 s->qemu_put_mouse_event_name = qemu_strdup(name);
382 s->next = NULL;
384 if (!qemu_put_mouse_event_head) {
385 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
386 return s;
389 cursor = qemu_put_mouse_event_head;
390 while (cursor->next != NULL)
391 cursor = cursor->next;
393 cursor->next = s;
394 qemu_put_mouse_event_current = s;
396 return s;
399 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
401 QEMUPutMouseEntry *prev = NULL, *cursor;
403 if (!qemu_put_mouse_event_head || entry == NULL)
404 return;
406 cursor = qemu_put_mouse_event_head;
407 while (cursor != NULL && cursor != entry) {
408 prev = cursor;
409 cursor = cursor->next;
412 if (cursor == NULL) // does not exist or list empty
413 return;
414 else if (prev == NULL) { // entry is head
415 qemu_put_mouse_event_head = cursor->next;
416 if (qemu_put_mouse_event_current == entry)
417 qemu_put_mouse_event_current = cursor->next;
418 qemu_free(entry->qemu_put_mouse_event_name);
419 qemu_free(entry);
420 return;
423 prev->next = entry->next;
425 if (qemu_put_mouse_event_current == entry)
426 qemu_put_mouse_event_current = prev;
428 qemu_free(entry->qemu_put_mouse_event_name);
429 qemu_free(entry);
432 void kbd_put_keycode(int keycode)
434 if (qemu_put_kbd_event) {
435 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
439 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
441 QEMUPutMouseEvent *mouse_event;
442 void *mouse_event_opaque;
443 int width;
445 if (!qemu_put_mouse_event_current) {
446 return;
449 mouse_event =
450 qemu_put_mouse_event_current->qemu_put_mouse_event;
451 mouse_event_opaque =
452 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
454 if (mouse_event) {
455 if (graphic_rotate) {
456 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
457 width = 0x7fff;
458 else
459 width = graphic_width - 1;
460 mouse_event(mouse_event_opaque,
461 width - dy, dx, dz, buttons_state);
462 } else
463 mouse_event(mouse_event_opaque,
464 dx, dy, dz, buttons_state);
468 int kbd_mouse_is_absolute(void)
470 if (!qemu_put_mouse_event_current)
471 return 0;
473 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
476 void do_info_mice(Monitor *mon)
478 QEMUPutMouseEntry *cursor;
479 int index = 0;
481 if (!qemu_put_mouse_event_head) {
482 monitor_printf(mon, "No mouse devices connected\n");
483 return;
486 monitor_printf(mon, "Mouse devices available:\n");
487 cursor = qemu_put_mouse_event_head;
488 while (cursor != NULL) {
489 monitor_printf(mon, "%c Mouse #%d: %s\n",
490 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
491 index, cursor->qemu_put_mouse_event_name);
492 index++;
493 cursor = cursor->next;
497 void do_mouse_set(Monitor *mon, const QDict *qdict)
499 QEMUPutMouseEntry *cursor;
500 int i = 0;
501 int index = qdict_get_int(qdict, "index");
503 if (!qemu_put_mouse_event_head) {
504 monitor_printf(mon, "No mouse devices connected\n");
505 return;
508 cursor = qemu_put_mouse_event_head;
509 while (cursor != NULL && index != i) {
510 i++;
511 cursor = cursor->next;
514 if (cursor != NULL)
515 qemu_put_mouse_event_current = cursor;
516 else
517 monitor_printf(mon, "Mouse at given index not found\n");
520 /* compute with 96 bit intermediate result: (a*b)/c */
521 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
523 union {
524 uint64_t ll;
525 struct {
526 #ifdef HOST_WORDS_BIGENDIAN
527 uint32_t high, low;
528 #else
529 uint32_t low, high;
530 #endif
531 } l;
532 } u, res;
533 uint64_t rl, rh;
535 u.ll = a;
536 rl = (uint64_t)u.l.low * (uint64_t)b;
537 rh = (uint64_t)u.l.high * (uint64_t)b;
538 rh += (rl >> 32);
539 res.l.high = rh / c;
540 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
541 return res.ll;
544 /***********************************************************/
545 /* real time host monotonic timer */
547 static int64_t get_clock_realtime(void)
549 struct timeval tv;
551 gettimeofday(&tv, NULL);
552 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
555 #ifdef WIN32
557 static int64_t clock_freq;
559 static void init_get_clock(void)
561 LARGE_INTEGER freq;
562 int ret;
563 ret = QueryPerformanceFrequency(&freq);
564 if (ret == 0) {
565 fprintf(stderr, "Could not calibrate ticks\n");
566 exit(1);
568 clock_freq = freq.QuadPart;
571 static int64_t get_clock(void)
573 LARGE_INTEGER ti;
574 QueryPerformanceCounter(&ti);
575 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
578 #else
580 static int use_rt_clock;
582 static void init_get_clock(void)
584 use_rt_clock = 0;
585 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
586 || defined(__DragonFly__)
588 struct timespec ts;
589 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
590 use_rt_clock = 1;
593 #endif
596 static int64_t get_clock(void)
598 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
599 || defined(__DragonFly__)
600 if (use_rt_clock) {
601 struct timespec ts;
602 clock_gettime(CLOCK_MONOTONIC, &ts);
603 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
604 } else
605 #endif
607 /* XXX: using gettimeofday leads to problems if the date
608 changes, so it should be avoided. */
609 return get_clock_realtime();
612 #endif
614 /* Return the virtual CPU time, based on the instruction counter. */
615 static int64_t cpu_get_icount(void)
617 int64_t icount;
618 CPUState *env = cpu_single_env;;
619 icount = qemu_icount;
620 if (env) {
621 if (!can_do_io(env))
622 fprintf(stderr, "Bad clock read\n");
623 icount -= (env->icount_decr.u16.low + env->icount_extra);
625 return qemu_icount_bias + (icount << icount_time_shift);
628 /***********************************************************/
629 /* guest cycle counter */
631 typedef struct TimersState {
632 int64_t cpu_ticks_prev;
633 int64_t cpu_ticks_offset;
634 int64_t cpu_clock_offset;
635 int32_t cpu_ticks_enabled;
636 int64_t dummy;
637 } TimersState;
639 TimersState timers_state;
641 /* return the host CPU cycle counter and handle stop/restart */
642 int64_t cpu_get_ticks(void)
644 if (use_icount) {
645 return cpu_get_icount();
647 if (!timers_state.cpu_ticks_enabled) {
648 return timers_state.cpu_ticks_offset;
649 } else {
650 int64_t ticks;
651 ticks = cpu_get_real_ticks();
652 if (timers_state.cpu_ticks_prev > ticks) {
653 /* Note: non increasing ticks may happen if the host uses
654 software suspend */
655 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
657 timers_state.cpu_ticks_prev = ticks;
658 return ticks + timers_state.cpu_ticks_offset;
662 /* return the host CPU monotonic timer and handle stop/restart */
663 static int64_t cpu_get_clock(void)
665 int64_t ti;
666 if (!timers_state.cpu_ticks_enabled) {
667 return timers_state.cpu_clock_offset;
668 } else {
669 ti = get_clock();
670 return ti + timers_state.cpu_clock_offset;
674 /* enable cpu_get_ticks() */
675 void cpu_enable_ticks(void)
677 if (!timers_state.cpu_ticks_enabled) {
678 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
679 timers_state.cpu_clock_offset -= get_clock();
680 timers_state.cpu_ticks_enabled = 1;
684 /* disable cpu_get_ticks() : the clock is stopped. You must not call
685 cpu_get_ticks() after that. */
686 void cpu_disable_ticks(void)
688 if (timers_state.cpu_ticks_enabled) {
689 timers_state.cpu_ticks_offset = cpu_get_ticks();
690 timers_state.cpu_clock_offset = cpu_get_clock();
691 timers_state.cpu_ticks_enabled = 0;
695 /***********************************************************/
696 /* timers */
698 #define QEMU_CLOCK_REALTIME 0
699 #define QEMU_CLOCK_VIRTUAL 1
700 #define QEMU_CLOCK_HOST 2
702 struct QEMUClock {
703 int type;
704 /* XXX: add frequency */
707 struct QEMUTimer {
708 QEMUClock *clock;
709 int64_t expire_time;
710 QEMUTimerCB *cb;
711 void *opaque;
712 struct QEMUTimer *next;
715 struct qemu_alarm_timer {
716 char const *name;
717 unsigned int flags;
719 int (*start)(struct qemu_alarm_timer *t);
720 void (*stop)(struct qemu_alarm_timer *t);
721 void (*rearm)(struct qemu_alarm_timer *t);
722 void *priv;
725 #define ALARM_FLAG_DYNTICKS 0x1
726 #define ALARM_FLAG_EXPIRED 0x2
728 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
730 return t && (t->flags & ALARM_FLAG_DYNTICKS);
733 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
735 if (!alarm_has_dynticks(t))
736 return;
738 t->rearm(t);
741 /* TODO: MIN_TIMER_REARM_US should be optimized */
742 #define MIN_TIMER_REARM_US 250
744 static struct qemu_alarm_timer *alarm_timer;
746 #ifdef _WIN32
748 struct qemu_alarm_win32 {
749 MMRESULT timerId;
750 unsigned int period;
751 } alarm_win32_data = {0, -1};
753 static int win32_start_timer(struct qemu_alarm_timer *t);
754 static void win32_stop_timer(struct qemu_alarm_timer *t);
755 static void win32_rearm_timer(struct qemu_alarm_timer *t);
757 #else
759 static int unix_start_timer(struct qemu_alarm_timer *t);
760 static void unix_stop_timer(struct qemu_alarm_timer *t);
762 #ifdef __linux__
764 static int dynticks_start_timer(struct qemu_alarm_timer *t);
765 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
766 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
768 static int hpet_start_timer(struct qemu_alarm_timer *t);
769 static void hpet_stop_timer(struct qemu_alarm_timer *t);
771 static int rtc_start_timer(struct qemu_alarm_timer *t);
772 static void rtc_stop_timer(struct qemu_alarm_timer *t);
774 #endif /* __linux__ */
776 #endif /* _WIN32 */
778 /* Correlation between real and virtual time is always going to be
779 fairly approximate, so ignore small variation.
780 When the guest is idle real and virtual time will be aligned in
781 the IO wait loop. */
782 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
784 static void icount_adjust(void)
786 int64_t cur_time;
787 int64_t cur_icount;
788 int64_t delta;
789 static int64_t last_delta;
790 /* If the VM is not running, then do nothing. */
791 if (!vm_running)
792 return;
794 cur_time = cpu_get_clock();
795 cur_icount = qemu_get_clock(vm_clock);
796 delta = cur_icount - cur_time;
797 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
798 if (delta > 0
799 && last_delta + ICOUNT_WOBBLE < delta * 2
800 && icount_time_shift > 0) {
801 /* The guest is getting too far ahead. Slow time down. */
802 icount_time_shift--;
804 if (delta < 0
805 && last_delta - ICOUNT_WOBBLE > delta * 2
806 && icount_time_shift < MAX_ICOUNT_SHIFT) {
807 /* The guest is getting too far behind. Speed time up. */
808 icount_time_shift++;
810 last_delta = delta;
811 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
814 static void icount_adjust_rt(void * opaque)
816 qemu_mod_timer(icount_rt_timer,
817 qemu_get_clock(rt_clock) + 1000);
818 icount_adjust();
821 static void icount_adjust_vm(void * opaque)
823 qemu_mod_timer(icount_vm_timer,
824 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
825 icount_adjust();
828 static void init_icount_adjust(void)
830 /* Have both realtime and virtual time triggers for speed adjustment.
831 The realtime trigger catches emulated time passing too slowly,
832 the virtual time trigger catches emulated time passing too fast.
833 Realtime triggers occur even when idle, so use them less frequently
834 than VM triggers. */
835 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
836 qemu_mod_timer(icount_rt_timer,
837 qemu_get_clock(rt_clock) + 1000);
838 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
839 qemu_mod_timer(icount_vm_timer,
840 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
843 static struct qemu_alarm_timer alarm_timers[] = {
844 #ifndef _WIN32
845 #ifdef __linux__
846 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
847 dynticks_stop_timer, dynticks_rearm_timer, NULL},
848 /* HPET - if available - is preferred */
849 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
850 /* ...otherwise try RTC */
851 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
852 #endif
853 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
854 #else
855 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
856 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
857 {"win32", 0, win32_start_timer,
858 win32_stop_timer, NULL, &alarm_win32_data},
859 #endif
860 {NULL, }
863 static void show_available_alarms(void)
865 int i;
867 printf("Available alarm timers, in order of precedence:\n");
868 for (i = 0; alarm_timers[i].name; i++)
869 printf("%s\n", alarm_timers[i].name);
872 static void configure_alarms(char const *opt)
874 int i;
875 int cur = 0;
876 int count = ARRAY_SIZE(alarm_timers) - 1;
877 char *arg;
878 char *name;
879 struct qemu_alarm_timer tmp;
881 if (!strcmp(opt, "?")) {
882 show_available_alarms();
883 exit(0);
886 arg = qemu_strdup(opt);
888 /* Reorder the array */
889 name = strtok(arg, ",");
890 while (name) {
891 for (i = 0; i < count && alarm_timers[i].name; i++) {
892 if (!strcmp(alarm_timers[i].name, name))
893 break;
896 if (i == count) {
897 fprintf(stderr, "Unknown clock %s\n", name);
898 goto next;
901 if (i < cur)
902 /* Ignore */
903 goto next;
905 /* Swap */
906 tmp = alarm_timers[i];
907 alarm_timers[i] = alarm_timers[cur];
908 alarm_timers[cur] = tmp;
910 cur++;
911 next:
912 name = strtok(NULL, ",");
915 qemu_free(arg);
917 if (cur) {
918 /* Disable remaining timers */
919 for (i = cur; i < count; i++)
920 alarm_timers[i].name = NULL;
921 } else {
922 show_available_alarms();
923 exit(1);
927 #define QEMU_NUM_CLOCKS 3
929 QEMUClock *rt_clock;
930 QEMUClock *vm_clock;
931 QEMUClock *host_clock;
933 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
935 static QEMUClock *qemu_new_clock(int type)
937 QEMUClock *clock;
938 clock = qemu_mallocz(sizeof(QEMUClock));
939 clock->type = type;
940 return clock;
943 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
945 QEMUTimer *ts;
947 ts = qemu_mallocz(sizeof(QEMUTimer));
948 ts->clock = clock;
949 ts->cb = cb;
950 ts->opaque = opaque;
951 return ts;
954 void qemu_free_timer(QEMUTimer *ts)
956 qemu_free(ts);
959 /* stop a timer, but do not dealloc it */
960 void qemu_del_timer(QEMUTimer *ts)
962 QEMUTimer **pt, *t;
964 /* NOTE: this code must be signal safe because
965 qemu_timer_expired() can be called from a signal. */
966 pt = &active_timers[ts->clock->type];
967 for(;;) {
968 t = *pt;
969 if (!t)
970 break;
971 if (t == ts) {
972 *pt = t->next;
973 break;
975 pt = &t->next;
979 /* modify the current timer so that it will be fired when current_time
980 >= expire_time. The corresponding callback will be called. */
981 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
983 QEMUTimer **pt, *t;
985 qemu_del_timer(ts);
987 /* add the timer in the sorted list */
988 /* NOTE: this code must be signal safe because
989 qemu_timer_expired() can be called from a signal. */
990 pt = &active_timers[ts->clock->type];
991 for(;;) {
992 t = *pt;
993 if (!t)
994 break;
995 if (t->expire_time > expire_time)
996 break;
997 pt = &t->next;
999 ts->expire_time = expire_time;
1000 ts->next = *pt;
1001 *pt = ts;
1003 /* Rearm if necessary */
1004 if (pt == &active_timers[ts->clock->type]) {
1005 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1006 qemu_rearm_alarm_timer(alarm_timer);
1008 /* Interrupt execution to force deadline recalculation. */
1009 if (use_icount)
1010 qemu_notify_event();
1014 int qemu_timer_pending(QEMUTimer *ts)
1016 QEMUTimer *t;
1017 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1018 if (t == ts)
1019 return 1;
1021 return 0;
1024 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1026 if (!timer_head)
1027 return 0;
1028 return (timer_head->expire_time <= current_time);
1031 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1033 QEMUTimer *ts;
1035 for(;;) {
1036 ts = *ptimer_head;
1037 if (!ts || ts->expire_time > current_time)
1038 break;
1039 /* remove timer from the list before calling the callback */
1040 *ptimer_head = ts->next;
1041 ts->next = NULL;
1043 /* run the callback (the timer list can be modified) */
1044 ts->cb(ts->opaque);
1048 int64_t qemu_get_clock(QEMUClock *clock)
1050 switch(clock->type) {
1051 case QEMU_CLOCK_REALTIME:
1052 return get_clock() / 1000000;
1053 default:
1054 case QEMU_CLOCK_VIRTUAL:
1055 if (use_icount) {
1056 return cpu_get_icount();
1057 } else {
1058 return cpu_get_clock();
1060 case QEMU_CLOCK_HOST:
1061 return get_clock_realtime();
1065 static void init_clocks(void)
1067 init_get_clock();
1068 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
1069 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
1070 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
1072 rtc_clock = host_clock;
1075 /* save a timer */
1076 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1078 uint64_t expire_time;
1080 if (qemu_timer_pending(ts)) {
1081 expire_time = ts->expire_time;
1082 } else {
1083 expire_time = -1;
1085 qemu_put_be64(f, expire_time);
1088 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1090 uint64_t expire_time;
1092 expire_time = qemu_get_be64(f);
1093 if (expire_time != -1) {
1094 qemu_mod_timer(ts, expire_time);
1095 } else {
1096 qemu_del_timer(ts);
1100 static const VMStateDescription vmstate_timers = {
1101 .name = "timer",
1102 .version_id = 2,
1103 .minimum_version_id = 1,
1104 .minimum_version_id_old = 1,
1105 .fields = (VMStateField []) {
1106 VMSTATE_INT64(cpu_ticks_offset, TimersState),
1107 VMSTATE_INT64(dummy, TimersState),
1108 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1109 VMSTATE_END_OF_LIST()
1113 static void qemu_event_increment(void);
1115 #ifdef _WIN32
1116 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1117 DWORD_PTR dwUser, DWORD_PTR dw1,
1118 DWORD_PTR dw2)
1119 #else
1120 static void host_alarm_handler(int host_signum)
1121 #endif
1123 #if 0
1124 #define DISP_FREQ 1000
1126 static int64_t delta_min = INT64_MAX;
1127 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1128 static int count;
1129 ti = qemu_get_clock(vm_clock);
1130 if (last_clock != 0) {
1131 delta = ti - last_clock;
1132 if (delta < delta_min)
1133 delta_min = delta;
1134 if (delta > delta_max)
1135 delta_max = delta;
1136 delta_cum += delta;
1137 if (++count == DISP_FREQ) {
1138 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1139 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1140 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1141 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1142 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1143 count = 0;
1144 delta_min = INT64_MAX;
1145 delta_max = 0;
1146 delta_cum = 0;
1149 last_clock = ti;
1151 #endif
1152 if (alarm_has_dynticks(alarm_timer) ||
1153 (!use_icount &&
1154 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1155 qemu_get_clock(vm_clock))) ||
1156 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1157 qemu_get_clock(rt_clock)) ||
1158 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1159 qemu_get_clock(host_clock))) {
1160 qemu_event_increment();
1161 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1163 #ifndef CONFIG_IOTHREAD
1164 if (next_cpu) {
1165 /* stop the currently executing cpu because a timer occured */
1166 cpu_exit(next_cpu);
1168 #endif
1169 timer_alarm_pending = 1;
1170 qemu_notify_event();
1174 static int64_t qemu_next_deadline(void)
1176 /* To avoid problems with overflow limit this to 2^32. */
1177 int64_t delta = INT32_MAX;
1179 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1180 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1181 qemu_get_clock(vm_clock);
1183 if (active_timers[QEMU_CLOCK_HOST]) {
1184 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1185 qemu_get_clock(host_clock);
1186 if (hdelta < delta)
1187 delta = hdelta;
1190 if (delta < 0)
1191 delta = 0;
1193 return delta;
1196 #if defined(__linux__)
1197 static uint64_t qemu_next_deadline_dyntick(void)
1199 int64_t delta;
1200 int64_t rtdelta;
1202 if (use_icount)
1203 delta = INT32_MAX;
1204 else
1205 delta = (qemu_next_deadline() + 999) / 1000;
1207 if (active_timers[QEMU_CLOCK_REALTIME]) {
1208 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1209 qemu_get_clock(rt_clock))*1000;
1210 if (rtdelta < delta)
1211 delta = rtdelta;
1214 if (delta < MIN_TIMER_REARM_US)
1215 delta = MIN_TIMER_REARM_US;
1217 return delta;
1219 #endif
1221 #ifndef _WIN32
1223 /* Sets a specific flag */
1224 static int fcntl_setfl(int fd, int flag)
1226 int flags;
1228 flags = fcntl(fd, F_GETFL);
1229 if (flags == -1)
1230 return -errno;
1232 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1233 return -errno;
1235 return 0;
1238 #if defined(__linux__)
1240 #define RTC_FREQ 1024
1242 static void enable_sigio_timer(int fd)
1244 struct sigaction act;
1246 /* timer signal */
1247 sigfillset(&act.sa_mask);
1248 act.sa_flags = 0;
1249 act.sa_handler = host_alarm_handler;
1251 sigaction(SIGIO, &act, NULL);
1252 fcntl_setfl(fd, O_ASYNC);
1253 fcntl(fd, F_SETOWN, getpid());
1256 static int hpet_start_timer(struct qemu_alarm_timer *t)
1258 struct hpet_info info;
1259 int r, fd;
1261 fd = open("/dev/hpet", O_RDONLY);
1262 if (fd < 0)
1263 return -1;
1265 /* Set frequency */
1266 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1267 if (r < 0) {
1268 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1269 "error, but for better emulation accuracy type:\n"
1270 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1271 goto fail;
1274 /* Check capabilities */
1275 r = ioctl(fd, HPET_INFO, &info);
1276 if (r < 0)
1277 goto fail;
1279 /* Enable periodic mode */
1280 r = ioctl(fd, HPET_EPI, 0);
1281 if (info.hi_flags && (r < 0))
1282 goto fail;
1284 /* Enable interrupt */
1285 r = ioctl(fd, HPET_IE_ON, 0);
1286 if (r < 0)
1287 goto fail;
1289 enable_sigio_timer(fd);
1290 t->priv = (void *)(long)fd;
1292 return 0;
1293 fail:
1294 close(fd);
1295 return -1;
1298 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1300 int fd = (long)t->priv;
1302 close(fd);
1305 static int rtc_start_timer(struct qemu_alarm_timer *t)
1307 int rtc_fd;
1308 unsigned long current_rtc_freq = 0;
1310 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1311 if (rtc_fd < 0)
1312 return -1;
1313 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1314 if (current_rtc_freq != RTC_FREQ &&
1315 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1316 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1317 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1318 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1319 goto fail;
1321 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1322 fail:
1323 close(rtc_fd);
1324 return -1;
1327 enable_sigio_timer(rtc_fd);
1329 t->priv = (void *)(long)rtc_fd;
1331 return 0;
1334 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1336 int rtc_fd = (long)t->priv;
1338 close(rtc_fd);
1341 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1343 struct sigevent ev;
1344 timer_t host_timer;
1345 struct sigaction act;
1347 sigfillset(&act.sa_mask);
1348 act.sa_flags = 0;
1349 act.sa_handler = host_alarm_handler;
1351 sigaction(SIGALRM, &act, NULL);
1354 * Initialize ev struct to 0 to avoid valgrind complaining
1355 * about uninitialized data in timer_create call
1357 memset(&ev, 0, sizeof(ev));
1358 ev.sigev_value.sival_int = 0;
1359 ev.sigev_notify = SIGEV_SIGNAL;
1360 ev.sigev_signo = SIGALRM;
1362 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1363 perror("timer_create");
1365 /* disable dynticks */
1366 fprintf(stderr, "Dynamic Ticks disabled\n");
1368 return -1;
1371 t->priv = (void *)(long)host_timer;
1373 return 0;
1376 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1378 timer_t host_timer = (timer_t)(long)t->priv;
1380 timer_delete(host_timer);
1383 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1385 timer_t host_timer = (timer_t)(long)t->priv;
1386 struct itimerspec timeout;
1387 int64_t nearest_delta_us = INT64_MAX;
1388 int64_t current_us;
1390 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1391 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1392 !active_timers[QEMU_CLOCK_HOST])
1393 return;
1395 nearest_delta_us = qemu_next_deadline_dyntick();
1397 /* check whether a timer is already running */
1398 if (timer_gettime(host_timer, &timeout)) {
1399 perror("gettime");
1400 fprintf(stderr, "Internal timer error: aborting\n");
1401 exit(1);
1403 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1404 if (current_us && current_us <= nearest_delta_us)
1405 return;
1407 timeout.it_interval.tv_sec = 0;
1408 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1409 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1410 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1411 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1412 perror("settime");
1413 fprintf(stderr, "Internal timer error: aborting\n");
1414 exit(1);
1418 #endif /* defined(__linux__) */
1420 static int unix_start_timer(struct qemu_alarm_timer *t)
1422 struct sigaction act;
1423 struct itimerval itv;
1424 int err;
1426 /* timer signal */
1427 sigfillset(&act.sa_mask);
1428 act.sa_flags = 0;
1429 act.sa_handler = host_alarm_handler;
1431 sigaction(SIGALRM, &act, NULL);
1433 itv.it_interval.tv_sec = 0;
1434 /* for i386 kernel 2.6 to get 1 ms */
1435 itv.it_interval.tv_usec = 999;
1436 itv.it_value.tv_sec = 0;
1437 itv.it_value.tv_usec = 10 * 1000;
1439 err = setitimer(ITIMER_REAL, &itv, NULL);
1440 if (err)
1441 return -1;
1443 return 0;
1446 static void unix_stop_timer(struct qemu_alarm_timer *t)
1448 struct itimerval itv;
1450 memset(&itv, 0, sizeof(itv));
1451 setitimer(ITIMER_REAL, &itv, NULL);
1454 #endif /* !defined(_WIN32) */
1457 #ifdef _WIN32
1459 static int win32_start_timer(struct qemu_alarm_timer *t)
1461 TIMECAPS tc;
1462 struct qemu_alarm_win32 *data = t->priv;
1463 UINT flags;
1465 memset(&tc, 0, sizeof(tc));
1466 timeGetDevCaps(&tc, sizeof(tc));
1468 if (data->period < tc.wPeriodMin)
1469 data->period = tc.wPeriodMin;
1471 timeBeginPeriod(data->period);
1473 flags = TIME_CALLBACK_FUNCTION;
1474 if (alarm_has_dynticks(t))
1475 flags |= TIME_ONESHOT;
1476 else
1477 flags |= TIME_PERIODIC;
1479 data->timerId = timeSetEvent(1, // interval (ms)
1480 data->period, // resolution
1481 host_alarm_handler, // function
1482 (DWORD)t, // parameter
1483 flags);
1485 if (!data->timerId) {
1486 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1487 GetLastError());
1488 timeEndPeriod(data->period);
1489 return -1;
1492 return 0;
1495 static void win32_stop_timer(struct qemu_alarm_timer *t)
1497 struct qemu_alarm_win32 *data = t->priv;
1499 timeKillEvent(data->timerId);
1500 timeEndPeriod(data->period);
1503 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1505 struct qemu_alarm_win32 *data = t->priv;
1507 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1508 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1509 !active_timers[QEMU_CLOCK_HOST])
1510 return;
1512 timeKillEvent(data->timerId);
1514 data->timerId = timeSetEvent(1,
1515 data->period,
1516 host_alarm_handler,
1517 (DWORD)t,
1518 TIME_ONESHOT | TIME_PERIODIC);
1520 if (!data->timerId) {
1521 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1522 GetLastError());
1524 timeEndPeriod(data->period);
1525 exit(1);
1529 #endif /* _WIN32 */
1531 static int init_timer_alarm(void)
1533 struct qemu_alarm_timer *t = NULL;
1534 int i, err = -1;
1536 for (i = 0; alarm_timers[i].name; i++) {
1537 t = &alarm_timers[i];
1539 err = t->start(t);
1540 if (!err)
1541 break;
1544 if (err) {
1545 err = -ENOENT;
1546 goto fail;
1549 alarm_timer = t;
1551 return 0;
1553 fail:
1554 return err;
1557 static void quit_timers(void)
1559 alarm_timer->stop(alarm_timer);
1560 alarm_timer = NULL;
1563 /***********************************************************/
1564 /* host time/date access */
1565 void qemu_get_timedate(struct tm *tm, int offset)
1567 time_t ti;
1568 struct tm *ret;
1570 time(&ti);
1571 ti += offset;
1572 if (rtc_date_offset == -1) {
1573 if (rtc_utc)
1574 ret = gmtime(&ti);
1575 else
1576 ret = localtime(&ti);
1577 } else {
1578 ti -= rtc_date_offset;
1579 ret = gmtime(&ti);
1582 memcpy(tm, ret, sizeof(struct tm));
1585 int qemu_timedate_diff(struct tm *tm)
1587 time_t seconds;
1589 if (rtc_date_offset == -1)
1590 if (rtc_utc)
1591 seconds = mktimegm(tm);
1592 else
1593 seconds = mktime(tm);
1594 else
1595 seconds = mktimegm(tm) + rtc_date_offset;
1597 return seconds - time(NULL);
1600 static void configure_rtc_date_offset(const char *startdate, int legacy)
1602 time_t rtc_start_date;
1603 struct tm tm;
1605 if (!strcmp(startdate, "now") && legacy) {
1606 rtc_date_offset = -1;
1607 } else {
1608 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1609 &tm.tm_year,
1610 &tm.tm_mon,
1611 &tm.tm_mday,
1612 &tm.tm_hour,
1613 &tm.tm_min,
1614 &tm.tm_sec) == 6) {
1615 /* OK */
1616 } else if (sscanf(startdate, "%d-%d-%d",
1617 &tm.tm_year,
1618 &tm.tm_mon,
1619 &tm.tm_mday) == 3) {
1620 tm.tm_hour = 0;
1621 tm.tm_min = 0;
1622 tm.tm_sec = 0;
1623 } else {
1624 goto date_fail;
1626 tm.tm_year -= 1900;
1627 tm.tm_mon--;
1628 rtc_start_date = mktimegm(&tm);
1629 if (rtc_start_date == -1) {
1630 date_fail:
1631 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1632 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1633 exit(1);
1635 rtc_date_offset = time(NULL) - rtc_start_date;
1639 static void configure_rtc(QemuOpts *opts)
1641 const char *value;
1643 value = qemu_opt_get(opts, "base");
1644 if (value) {
1645 if (!strcmp(value, "utc")) {
1646 rtc_utc = 1;
1647 } else if (!strcmp(value, "localtime")) {
1648 rtc_utc = 0;
1649 } else {
1650 configure_rtc_date_offset(value, 0);
1653 value = qemu_opt_get(opts, "clock");
1654 if (value) {
1655 if (!strcmp(value, "host")) {
1656 rtc_clock = host_clock;
1657 } else if (!strcmp(value, "vm")) {
1658 rtc_clock = vm_clock;
1659 } else {
1660 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1661 exit(1);
1664 #ifdef CONFIG_TARGET_I386
1665 value = qemu_opt_get(opts, "driftfix");
1666 if (value) {
1667 if (!strcmp(buf, "slew")) {
1668 rtc_td_hack = 1;
1669 } else if (!strcmp(buf, "none")) {
1670 rtc_td_hack = 0;
1671 } else {
1672 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1673 exit(1);
1676 #endif
1679 #ifdef _WIN32
1680 static void socket_cleanup(void)
1682 WSACleanup();
1685 static int socket_init(void)
1687 WSADATA Data;
1688 int ret, err;
1690 ret = WSAStartup(MAKEWORD(2,2), &Data);
1691 if (ret != 0) {
1692 err = WSAGetLastError();
1693 fprintf(stderr, "WSAStartup: %d\n", err);
1694 return -1;
1696 atexit(socket_cleanup);
1697 return 0;
1699 #endif
1701 /***********************************************************/
1702 /* Bluetooth support */
1703 static int nb_hcis;
1704 static int cur_hci;
1705 static struct HCIInfo *hci_table[MAX_NICS];
1707 static struct bt_vlan_s {
1708 struct bt_scatternet_s net;
1709 int id;
1710 struct bt_vlan_s *next;
1711 } *first_bt_vlan;
1713 /* find or alloc a new bluetooth "VLAN" */
1714 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1716 struct bt_vlan_s **pvlan, *vlan;
1717 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1718 if (vlan->id == id)
1719 return &vlan->net;
1721 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1722 vlan->id = id;
1723 pvlan = &first_bt_vlan;
1724 while (*pvlan != NULL)
1725 pvlan = &(*pvlan)->next;
1726 *pvlan = vlan;
1727 return &vlan->net;
1730 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1734 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1736 return -ENOTSUP;
1739 static struct HCIInfo null_hci = {
1740 .cmd_send = null_hci_send,
1741 .sco_send = null_hci_send,
1742 .acl_send = null_hci_send,
1743 .bdaddr_set = null_hci_addr_set,
1746 struct HCIInfo *qemu_next_hci(void)
1748 if (cur_hci == nb_hcis)
1749 return &null_hci;
1751 return hci_table[cur_hci++];
1754 static struct HCIInfo *hci_init(const char *str)
1756 char *endp;
1757 struct bt_scatternet_s *vlan = 0;
1759 if (!strcmp(str, "null"))
1760 /* null */
1761 return &null_hci;
1762 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1763 /* host[:hciN] */
1764 return bt_host_hci(str[4] ? str + 5 : "hci0");
1765 else if (!strncmp(str, "hci", 3)) {
1766 /* hci[,vlan=n] */
1767 if (str[3]) {
1768 if (!strncmp(str + 3, ",vlan=", 6)) {
1769 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1770 if (*endp)
1771 vlan = 0;
1773 } else
1774 vlan = qemu_find_bt_vlan(0);
1775 if (vlan)
1776 return bt_new_hci(vlan);
1779 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1781 return 0;
1784 static int bt_hci_parse(const char *str)
1786 struct HCIInfo *hci;
1787 bdaddr_t bdaddr;
1789 if (nb_hcis >= MAX_NICS) {
1790 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1791 return -1;
1794 hci = hci_init(str);
1795 if (!hci)
1796 return -1;
1798 bdaddr.b[0] = 0x52;
1799 bdaddr.b[1] = 0x54;
1800 bdaddr.b[2] = 0x00;
1801 bdaddr.b[3] = 0x12;
1802 bdaddr.b[4] = 0x34;
1803 bdaddr.b[5] = 0x56 + nb_hcis;
1804 hci->bdaddr_set(hci, bdaddr.b);
1806 hci_table[nb_hcis++] = hci;
1808 return 0;
1811 static void bt_vhci_add(int vlan_id)
1813 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1815 if (!vlan->slave)
1816 fprintf(stderr, "qemu: warning: adding a VHCI to "
1817 "an empty scatternet %i\n", vlan_id);
1819 bt_vhci_init(bt_new_hci(vlan));
1822 static struct bt_device_s *bt_device_add(const char *opt)
1824 struct bt_scatternet_s *vlan;
1825 int vlan_id = 0;
1826 char *endp = strstr(opt, ",vlan=");
1827 int len = (endp ? endp - opt : strlen(opt)) + 1;
1828 char devname[10];
1830 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1832 if (endp) {
1833 vlan_id = strtol(endp + 6, &endp, 0);
1834 if (*endp) {
1835 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1836 return 0;
1840 vlan = qemu_find_bt_vlan(vlan_id);
1842 if (!vlan->slave)
1843 fprintf(stderr, "qemu: warning: adding a slave device to "
1844 "an empty scatternet %i\n", vlan_id);
1846 if (!strcmp(devname, "keyboard"))
1847 return bt_keyboard_init(vlan);
1849 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1850 return 0;
1853 static int bt_parse(const char *opt)
1855 const char *endp, *p;
1856 int vlan;
1858 if (strstart(opt, "hci", &endp)) {
1859 if (!*endp || *endp == ',') {
1860 if (*endp)
1861 if (!strstart(endp, ",vlan=", 0))
1862 opt = endp + 1;
1864 return bt_hci_parse(opt);
1866 } else if (strstart(opt, "vhci", &endp)) {
1867 if (!*endp || *endp == ',') {
1868 if (*endp) {
1869 if (strstart(endp, ",vlan=", &p)) {
1870 vlan = strtol(p, (char **) &endp, 0);
1871 if (*endp) {
1872 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1873 return 1;
1875 } else {
1876 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1877 return 1;
1879 } else
1880 vlan = 0;
1882 bt_vhci_add(vlan);
1883 return 0;
1885 } else if (strstart(opt, "device:", &endp))
1886 return !bt_device_add(endp);
1888 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1889 return 1;
1892 /***********************************************************/
1893 /* QEMU Block devices */
1895 #define HD_ALIAS "index=%d,media=disk"
1896 #define CDROM_ALIAS "index=2,media=cdrom"
1897 #define FD_ALIAS "index=%d,if=floppy"
1898 #define PFLASH_ALIAS "if=pflash"
1899 #define MTD_ALIAS "if=mtd"
1900 #define SD_ALIAS "index=0,if=sd"
1902 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1904 va_list ap;
1905 char optstr[1024];
1906 QemuOpts *opts;
1908 va_start(ap, fmt);
1909 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1910 va_end(ap);
1912 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1913 if (!opts) {
1914 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1915 __FUNCTION__, optstr);
1916 return NULL;
1918 if (file)
1919 qemu_opt_set(opts, "file", file);
1920 return opts;
1923 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1925 DriveInfo *dinfo;
1927 /* seek interface, bus and unit */
1929 QTAILQ_FOREACH(dinfo, &drives, next) {
1930 if (dinfo->type == type &&
1931 dinfo->bus == bus &&
1932 dinfo->unit == unit)
1933 return dinfo;
1936 return NULL;
1939 DriveInfo *drive_get_by_id(const char *id)
1941 DriveInfo *dinfo;
1943 QTAILQ_FOREACH(dinfo, &drives, next) {
1944 if (strcmp(id, dinfo->id))
1945 continue;
1946 return dinfo;
1948 return NULL;
1951 int drive_get_max_bus(BlockInterfaceType type)
1953 int max_bus;
1954 DriveInfo *dinfo;
1956 max_bus = -1;
1957 QTAILQ_FOREACH(dinfo, &drives, next) {
1958 if(dinfo->type == type &&
1959 dinfo->bus > max_bus)
1960 max_bus = dinfo->bus;
1962 return max_bus;
1965 const char *drive_get_serial(BlockDriverState *bdrv)
1967 DriveInfo *dinfo;
1969 QTAILQ_FOREACH(dinfo, &drives, next) {
1970 if (dinfo->bdrv == bdrv)
1971 return dinfo->serial;
1974 return "\0";
1977 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1979 DriveInfo *dinfo;
1981 QTAILQ_FOREACH(dinfo, &drives, next) {
1982 if (dinfo->bdrv == bdrv)
1983 return dinfo->onerror;
1986 return BLOCK_ERR_STOP_ENOSPC;
1989 static void bdrv_format_print(void *opaque, const char *name)
1991 fprintf(stderr, " %s", name);
1994 void drive_uninit(DriveInfo *dinfo)
1996 qemu_opts_del(dinfo->opts);
1997 bdrv_delete(dinfo->bdrv);
1998 QTAILQ_REMOVE(&drives, dinfo, next);
1999 qemu_free(dinfo);
2002 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
2003 int *fatal_error)
2005 const char *buf;
2006 const char *file = NULL;
2007 char devname[128];
2008 const char *serial;
2009 const char *mediastr = "";
2010 BlockInterfaceType type;
2011 enum { MEDIA_DISK, MEDIA_CDROM } media;
2012 int bus_id, unit_id;
2013 int cyls, heads, secs, translation;
2014 BlockDriver *drv = NULL;
2015 QEMUMachine *machine = opaque;
2016 int max_devs;
2017 int index;
2018 int cache;
2019 int aio = 0;
2020 int ro = 0;
2021 int bdrv_flags, onerror;
2022 const char *devaddr;
2023 DriveInfo *dinfo;
2024 int is_extboot = 0;
2025 int snapshot = 0;
2027 *fatal_error = 1;
2029 translation = BIOS_ATA_TRANSLATION_AUTO;
2030 cache = 1;
2032 if (machine && machine->use_scsi) {
2033 type = IF_SCSI;
2034 max_devs = MAX_SCSI_DEVS;
2035 pstrcpy(devname, sizeof(devname), "scsi");
2036 } else {
2037 type = IF_IDE;
2038 max_devs = MAX_IDE_DEVS;
2039 pstrcpy(devname, sizeof(devname), "ide");
2041 media = MEDIA_DISK;
2043 /* extract parameters */
2044 bus_id = qemu_opt_get_number(opts, "bus", 0);
2045 unit_id = qemu_opt_get_number(opts, "unit", -1);
2046 index = qemu_opt_get_number(opts, "index", -1);
2048 cyls = qemu_opt_get_number(opts, "cyls", 0);
2049 heads = qemu_opt_get_number(opts, "heads", 0);
2050 secs = qemu_opt_get_number(opts, "secs", 0);
2052 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2053 ro = qemu_opt_get_bool(opts, "readonly", 0);
2055 file = qemu_opt_get(opts, "file");
2056 serial = qemu_opt_get(opts, "serial");
2058 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2059 pstrcpy(devname, sizeof(devname), buf);
2060 if (!strcmp(buf, "ide")) {
2061 type = IF_IDE;
2062 max_devs = MAX_IDE_DEVS;
2063 } else if (!strcmp(buf, "scsi")) {
2064 type = IF_SCSI;
2065 max_devs = MAX_SCSI_DEVS;
2066 } else if (!strcmp(buf, "floppy")) {
2067 type = IF_FLOPPY;
2068 max_devs = 0;
2069 } else if (!strcmp(buf, "pflash")) {
2070 type = IF_PFLASH;
2071 max_devs = 0;
2072 } else if (!strcmp(buf, "mtd")) {
2073 type = IF_MTD;
2074 max_devs = 0;
2075 } else if (!strcmp(buf, "sd")) {
2076 type = IF_SD;
2077 max_devs = 0;
2078 } else if (!strcmp(buf, "virtio")) {
2079 type = IF_VIRTIO;
2080 max_devs = 0;
2081 } else if (!strcmp(buf, "xen")) {
2082 type = IF_XEN;
2083 max_devs = 0;
2084 } else if (!strcmp(buf, "none")) {
2085 type = IF_NONE;
2086 max_devs = 0;
2087 } else {
2088 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2089 return NULL;
2093 if (cyls || heads || secs) {
2094 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2095 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2096 return NULL;
2098 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2099 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2100 return NULL;
2102 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2103 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2104 return NULL;
2108 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2109 if (!cyls) {
2110 fprintf(stderr,
2111 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2112 buf);
2113 return NULL;
2115 if (!strcmp(buf, "none"))
2116 translation = BIOS_ATA_TRANSLATION_NONE;
2117 else if (!strcmp(buf, "lba"))
2118 translation = BIOS_ATA_TRANSLATION_LBA;
2119 else if (!strcmp(buf, "auto"))
2120 translation = BIOS_ATA_TRANSLATION_AUTO;
2121 else {
2122 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2123 return NULL;
2127 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2128 if (!strcmp(buf, "disk")) {
2129 media = MEDIA_DISK;
2130 } else if (!strcmp(buf, "cdrom")) {
2131 if (cyls || secs || heads) {
2132 fprintf(stderr,
2133 "qemu: '%s' invalid physical CHS format\n", buf);
2134 return NULL;
2136 media = MEDIA_CDROM;
2137 } else {
2138 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2139 return NULL;
2143 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2144 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2145 cache = 0;
2146 else if (!strcmp(buf, "writethrough"))
2147 cache = 1;
2148 else if (!strcmp(buf, "writeback"))
2149 cache = 2;
2150 else {
2151 fprintf(stderr, "qemu: invalid cache option\n");
2152 return NULL;
2156 #ifdef CONFIG_LINUX_AIO
2157 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2158 if (!strcmp(buf, "threads"))
2159 aio = 0;
2160 else if (!strcmp(buf, "native"))
2161 aio = 1;
2162 else {
2163 fprintf(stderr, "qemu: invalid aio option\n");
2164 return NULL;
2167 #endif
2169 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2170 if (strcmp(buf, "?") == 0) {
2171 fprintf(stderr, "qemu: Supported formats:");
2172 bdrv_iterate_format(bdrv_format_print, NULL);
2173 fprintf(stderr, "\n");
2174 return NULL;
2176 drv = bdrv_find_whitelisted_format(buf);
2177 if (!drv) {
2178 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2179 return NULL;
2183 is_extboot = qemu_opt_get_bool(opts, "boot", 0);
2184 if (is_extboot && extboot_drive) {
2185 fprintf(stderr, "qemu: two bootable drives specified\n");
2186 return NULL;
2189 onerror = BLOCK_ERR_STOP_ENOSPC;
2190 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2191 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2192 fprintf(stderr, "werror is no supported by this format\n");
2193 return NULL;
2195 if (!strcmp(buf, "ignore"))
2196 onerror = BLOCK_ERR_IGNORE;
2197 else if (!strcmp(buf, "enospc"))
2198 onerror = BLOCK_ERR_STOP_ENOSPC;
2199 else if (!strcmp(buf, "stop"))
2200 onerror = BLOCK_ERR_STOP_ANY;
2201 else if (!strcmp(buf, "report"))
2202 onerror = BLOCK_ERR_REPORT;
2203 else {
2204 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2205 return NULL;
2209 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2210 if (type != IF_VIRTIO) {
2211 fprintf(stderr, "addr is not supported\n");
2212 return NULL;
2216 /* compute bus and unit according index */
2218 if (index != -1) {
2219 if (bus_id != 0 || unit_id != -1) {
2220 fprintf(stderr,
2221 "qemu: index cannot be used with bus and unit\n");
2222 return NULL;
2224 if (max_devs == 0)
2226 unit_id = index;
2227 bus_id = 0;
2228 } else {
2229 unit_id = index % max_devs;
2230 bus_id = index / max_devs;
2234 /* if user doesn't specify a unit_id,
2235 * try to find the first free
2238 if (unit_id == -1) {
2239 unit_id = 0;
2240 while (drive_get(type, bus_id, unit_id) != NULL) {
2241 unit_id++;
2242 if (max_devs && unit_id >= max_devs) {
2243 unit_id -= max_devs;
2244 bus_id++;
2249 /* check unit id */
2251 if (max_devs && unit_id >= max_devs) {
2252 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2253 unit_id, max_devs - 1);
2254 return NULL;
2258 * ignore multiple definitions
2261 if (drive_get(type, bus_id, unit_id) != NULL) {
2262 *fatal_error = 0;
2263 return NULL;
2266 /* init */
2268 dinfo = qemu_mallocz(sizeof(*dinfo));
2269 if ((buf = qemu_opts_id(opts)) != NULL) {
2270 dinfo->id = qemu_strdup(buf);
2271 } else {
2272 /* no id supplied -> create one */
2273 dinfo->id = qemu_mallocz(32);
2274 if (type == IF_IDE || type == IF_SCSI)
2275 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2276 if (max_devs)
2277 snprintf(dinfo->id, 32, "%s%i%s%i",
2278 devname, bus_id, mediastr, unit_id);
2279 else
2280 snprintf(dinfo->id, 32, "%s%s%i",
2281 devname, mediastr, unit_id);
2283 dinfo->bdrv = bdrv_new(dinfo->id);
2284 dinfo->devaddr = devaddr;
2285 dinfo->type = type;
2286 dinfo->bus = bus_id;
2287 dinfo->unit = unit_id;
2288 dinfo->onerror = onerror;
2289 dinfo->opts = opts;
2290 if (serial)
2291 strncpy(dinfo->serial, serial, sizeof(serial));
2292 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2293 if (is_extboot) {
2294 extboot_drive = dinfo;
2297 switch(type) {
2298 case IF_IDE:
2299 case IF_SCSI:
2300 case IF_XEN:
2301 case IF_NONE:
2302 switch(media) {
2303 case MEDIA_DISK:
2304 if (cyls != 0) {
2305 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2306 bdrv_set_translation_hint(dinfo->bdrv, translation);
2308 break;
2309 case MEDIA_CDROM:
2310 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2311 break;
2313 break;
2314 case IF_SD:
2315 /* FIXME: This isn't really a floppy, but it's a reasonable
2316 approximation. */
2317 case IF_FLOPPY:
2318 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2319 break;
2320 case IF_PFLASH:
2321 case IF_MTD:
2322 break;
2323 case IF_VIRTIO:
2324 /* add virtio block device */
2325 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2326 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2327 qemu_opt_set(opts, "drive", dinfo->id);
2328 if (devaddr)
2329 qemu_opt_set(opts, "addr", devaddr);
2330 break;
2331 case IF_COUNT:
2332 abort();
2334 if (!file) {
2335 *fatal_error = 0;
2336 return NULL;
2338 bdrv_flags = 0;
2339 if (snapshot) {
2340 bdrv_flags |= BDRV_O_SNAPSHOT;
2341 cache = 2; /* always use write-back with snapshot */
2343 if (cache == 0) /* no caching */
2344 bdrv_flags |= BDRV_O_NOCACHE;
2345 else if (cache == 2) /* write-back */
2346 bdrv_flags |= BDRV_O_CACHE_WB;
2348 if (aio == 1) {
2349 bdrv_flags |= BDRV_O_NATIVE_AIO;
2350 } else {
2351 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2354 if (ro == 1) {
2355 if (type == IF_IDE) {
2356 fprintf(stderr, "qemu: readonly flag not supported for drive with ide interface\n");
2357 return NULL;
2359 (void)bdrv_set_read_only(dinfo->bdrv, 1);
2362 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2363 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2364 file, strerror(errno));
2365 return NULL;
2368 if (bdrv_key_required(dinfo->bdrv))
2369 autostart = 0;
2370 *fatal_error = 0;
2371 return dinfo;
2374 static int drive_init_func(QemuOpts *opts, void *opaque)
2376 QEMUMachine *machine = opaque;
2377 int fatal_error = 0;
2379 if (drive_init(opts, machine, &fatal_error) == NULL) {
2380 if (fatal_error)
2381 return 1;
2383 return 0;
2386 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2388 if (NULL == qemu_opt_get(opts, "snapshot")) {
2389 qemu_opt_set(opts, "snapshot", "on");
2391 return 0;
2394 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2396 boot_set_handler = func;
2397 boot_set_opaque = opaque;
2400 int qemu_boot_set(const char *boot_devices)
2402 if (!boot_set_handler) {
2403 return -EINVAL;
2405 return boot_set_handler(boot_set_opaque, boot_devices);
2408 static int parse_bootdevices(char *devices)
2410 /* We just do some generic consistency checks */
2411 const char *p;
2412 int bitmap = 0;
2414 for (p = devices; *p != '\0'; p++) {
2415 /* Allowed boot devices are:
2416 * a-b: floppy disk drives
2417 * c-f: IDE disk drives
2418 * g-m: machine implementation dependant drives
2419 * n-p: network devices
2420 * It's up to each machine implementation to check if the given boot
2421 * devices match the actual hardware implementation and firmware
2422 * features.
2424 if (*p < 'a' || *p > 'p') {
2425 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2426 exit(1);
2428 if (bitmap & (1 << (*p - 'a'))) {
2429 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2430 exit(1);
2432 bitmap |= 1 << (*p - 'a');
2434 return bitmap;
2437 static void restore_boot_devices(void *opaque)
2439 char *standard_boot_devices = opaque;
2441 qemu_boot_set(standard_boot_devices);
2443 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2444 qemu_free(standard_boot_devices);
2447 static void numa_add(const char *optarg)
2449 char option[128];
2450 char *endptr;
2451 unsigned long long value, endvalue;
2452 int nodenr;
2454 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2455 if (!strcmp(option, "node")) {
2456 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2457 nodenr = nb_numa_nodes;
2458 } else {
2459 nodenr = strtoull(option, NULL, 10);
2462 if (get_param_value(option, 128, "mem", optarg) == 0) {
2463 node_mem[nodenr] = 0;
2464 } else {
2465 value = strtoull(option, &endptr, 0);
2466 switch (*endptr) {
2467 case 0: case 'M': case 'm':
2468 value <<= 20;
2469 break;
2470 case 'G': case 'g':
2471 value <<= 30;
2472 break;
2474 node_mem[nodenr] = value;
2476 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2477 node_cpumask[nodenr] = 0;
2478 } else {
2479 value = strtoull(option, &endptr, 10);
2480 if (value >= 64) {
2481 value = 63;
2482 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2483 } else {
2484 if (*endptr == '-') {
2485 endvalue = strtoull(endptr+1, &endptr, 10);
2486 if (endvalue >= 63) {
2487 endvalue = 62;
2488 fprintf(stderr,
2489 "only 63 CPUs in NUMA mode supported.\n");
2491 value = (1 << (endvalue + 1)) - (1 << value);
2492 } else {
2493 value = 1 << value;
2496 node_cpumask[nodenr] = value;
2498 nb_numa_nodes++;
2500 return;
2503 static void smp_parse(const char *optarg)
2505 int smp, sockets = 0, threads = 0, cores = 0;
2506 char *endptr;
2507 char option[128];
2509 smp = strtoul(optarg, &endptr, 10);
2510 if (endptr != optarg) {
2511 if (*endptr == ',') {
2512 endptr++;
2515 if (get_param_value(option, 128, "sockets", endptr) != 0)
2516 sockets = strtoull(option, NULL, 10);
2517 if (get_param_value(option, 128, "cores", endptr) != 0)
2518 cores = strtoull(option, NULL, 10);
2519 if (get_param_value(option, 128, "threads", endptr) != 0)
2520 threads = strtoull(option, NULL, 10);
2521 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2522 max_cpus = strtoull(option, NULL, 10);
2524 /* compute missing values, prefer sockets over cores over threads */
2525 if (smp == 0 || sockets == 0) {
2526 sockets = sockets > 0 ? sockets : 1;
2527 cores = cores > 0 ? cores : 1;
2528 threads = threads > 0 ? threads : 1;
2529 if (smp == 0) {
2530 smp = cores * threads * sockets;
2531 } else {
2532 sockets = smp / (cores * threads);
2534 } else {
2535 if (cores == 0) {
2536 threads = threads > 0 ? threads : 1;
2537 cores = smp / (sockets * threads);
2538 } else {
2539 if (sockets == 0) {
2540 sockets = smp / (cores * threads);
2541 } else {
2542 threads = smp / (cores * sockets);
2546 smp_cpus = smp;
2547 smp_cores = cores > 0 ? cores : 1;
2548 smp_threads = threads > 0 ? threads : 1;
2549 if (max_cpus == 0)
2550 max_cpus = smp_cpus;
2553 /***********************************************************/
2554 /* USB devices */
2556 static int usb_device_add(const char *devname, int is_hotplug)
2558 const char *p;
2559 USBDevice *dev = NULL;
2561 if (!usb_enabled)
2562 return -1;
2564 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2565 dev = usbdevice_create(devname);
2566 if (dev)
2567 goto done;
2569 /* the other ones */
2570 if (strstart(devname, "host:", &p)) {
2571 dev = usb_host_device_open(p);
2572 } else if (strstart(devname, "net:", &p)) {
2573 QemuOpts *opts;
2574 int idx;
2576 opts = qemu_opts_parse(&qemu_net_opts, p, NULL);
2577 if (!opts) {
2578 return -1;
2581 qemu_opt_set(opts, "type", "nic");
2582 qemu_opt_set(opts, "model", "usb");
2584 idx = net_client_init(NULL, opts, 0);
2585 if (idx == -1) {
2586 return -1;
2589 dev = usb_net_init(&nd_table[idx]);
2590 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2591 dev = usb_bt_init(devname[2] ? hci_init(p) :
2592 bt_new_hci(qemu_find_bt_vlan(0)));
2593 } else {
2594 return -1;
2596 if (!dev)
2597 return -1;
2599 done:
2600 return 0;
2603 static int usb_device_del(const char *devname)
2605 int bus_num, addr;
2606 const char *p;
2608 if (strstart(devname, "host:", &p))
2609 return usb_host_device_close(p);
2611 if (!usb_enabled)
2612 return -1;
2614 p = strchr(devname, '.');
2615 if (!p)
2616 return -1;
2617 bus_num = strtoul(devname, NULL, 0);
2618 addr = strtoul(p + 1, NULL, 0);
2620 return usb_device_delete_addr(bus_num, addr);
2623 static int usb_parse(const char *cmdline)
2625 return usb_device_add(cmdline, 0);
2628 void do_usb_add(Monitor *mon, const QDict *qdict)
2630 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2633 void do_usb_del(Monitor *mon, const QDict *qdict)
2635 usb_device_del(qdict_get_str(qdict, "devname"));
2638 /***********************************************************/
2639 /* PCMCIA/Cardbus */
2641 static struct pcmcia_socket_entry_s {
2642 PCMCIASocket *socket;
2643 struct pcmcia_socket_entry_s *next;
2644 } *pcmcia_sockets = 0;
2646 void pcmcia_socket_register(PCMCIASocket *socket)
2648 struct pcmcia_socket_entry_s *entry;
2650 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2651 entry->socket = socket;
2652 entry->next = pcmcia_sockets;
2653 pcmcia_sockets = entry;
2656 void pcmcia_socket_unregister(PCMCIASocket *socket)
2658 struct pcmcia_socket_entry_s *entry, **ptr;
2660 ptr = &pcmcia_sockets;
2661 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2662 if (entry->socket == socket) {
2663 *ptr = entry->next;
2664 qemu_free(entry);
2668 void pcmcia_info(Monitor *mon)
2670 struct pcmcia_socket_entry_s *iter;
2672 if (!pcmcia_sockets)
2673 monitor_printf(mon, "No PCMCIA sockets\n");
2675 for (iter = pcmcia_sockets; iter; iter = iter->next)
2676 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2677 iter->socket->attached ? iter->socket->card_string :
2678 "Empty");
2681 /***********************************************************/
2682 /* register display */
2684 struct DisplayAllocator default_allocator = {
2685 defaultallocator_create_displaysurface,
2686 defaultallocator_resize_displaysurface,
2687 defaultallocator_free_displaysurface
2690 void register_displaystate(DisplayState *ds)
2692 DisplayState **s;
2693 s = &display_state;
2694 while (*s != NULL)
2695 s = &(*s)->next;
2696 ds->next = NULL;
2697 *s = ds;
2700 DisplayState *get_displaystate(void)
2702 return display_state;
2705 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2707 if(ds->allocator == &default_allocator) ds->allocator = da;
2708 return ds->allocator;
2711 /* dumb display */
2713 static void dumb_display_init(void)
2715 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2716 ds->allocator = &default_allocator;
2717 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2718 register_displaystate(ds);
2721 /***********************************************************/
2722 /* I/O handling */
2724 typedef struct IOHandlerRecord {
2725 int fd;
2726 IOCanRWHandler *fd_read_poll;
2727 IOHandler *fd_read;
2728 IOHandler *fd_write;
2729 int deleted;
2730 void *opaque;
2731 /* temporary data */
2732 struct pollfd *ufd;
2733 struct IOHandlerRecord *next;
2734 } IOHandlerRecord;
2736 static IOHandlerRecord *first_io_handler;
2738 /* XXX: fd_read_poll should be suppressed, but an API change is
2739 necessary in the character devices to suppress fd_can_read(). */
2740 int qemu_set_fd_handler2(int fd,
2741 IOCanRWHandler *fd_read_poll,
2742 IOHandler *fd_read,
2743 IOHandler *fd_write,
2744 void *opaque)
2746 IOHandlerRecord **pioh, *ioh;
2748 if (!fd_read && !fd_write) {
2749 pioh = &first_io_handler;
2750 for(;;) {
2751 ioh = *pioh;
2752 if (ioh == NULL)
2753 break;
2754 if (ioh->fd == fd) {
2755 ioh->deleted = 1;
2756 break;
2758 pioh = &ioh->next;
2760 } else {
2761 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2762 if (ioh->fd == fd)
2763 goto found;
2765 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2766 ioh->next = first_io_handler;
2767 first_io_handler = ioh;
2768 found:
2769 ioh->fd = fd;
2770 ioh->fd_read_poll = fd_read_poll;
2771 ioh->fd_read = fd_read;
2772 ioh->fd_write = fd_write;
2773 ioh->opaque = opaque;
2774 ioh->deleted = 0;
2776 qemu_notify_event();
2777 return 0;
2780 int qemu_set_fd_handler(int fd,
2781 IOHandler *fd_read,
2782 IOHandler *fd_write,
2783 void *opaque)
2785 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2788 #ifdef _WIN32
2789 /***********************************************************/
2790 /* Polling handling */
2792 typedef struct PollingEntry {
2793 PollingFunc *func;
2794 void *opaque;
2795 struct PollingEntry *next;
2796 } PollingEntry;
2798 static PollingEntry *first_polling_entry;
2800 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2802 PollingEntry **ppe, *pe;
2803 pe = qemu_mallocz(sizeof(PollingEntry));
2804 pe->func = func;
2805 pe->opaque = opaque;
2806 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2807 *ppe = pe;
2808 return 0;
2811 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2813 PollingEntry **ppe, *pe;
2814 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2815 pe = *ppe;
2816 if (pe->func == func && pe->opaque == opaque) {
2817 *ppe = pe->next;
2818 qemu_free(pe);
2819 break;
2824 /***********************************************************/
2825 /* Wait objects support */
2826 typedef struct WaitObjects {
2827 int num;
2828 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2829 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2830 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2831 } WaitObjects;
2833 static WaitObjects wait_objects = {0};
2835 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2837 WaitObjects *w = &wait_objects;
2839 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2840 return -1;
2841 w->events[w->num] = handle;
2842 w->func[w->num] = func;
2843 w->opaque[w->num] = opaque;
2844 w->num++;
2845 return 0;
2848 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2850 int i, found;
2851 WaitObjects *w = &wait_objects;
2853 found = 0;
2854 for (i = 0; i < w->num; i++) {
2855 if (w->events[i] == handle)
2856 found = 1;
2857 if (found) {
2858 w->events[i] = w->events[i + 1];
2859 w->func[i] = w->func[i + 1];
2860 w->opaque[i] = w->opaque[i + 1];
2863 if (found)
2864 w->num--;
2866 #endif
2868 /***********************************************************/
2869 /* ram save/restore */
2871 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2872 #define RAM_SAVE_FLAG_COMPRESS 0x02
2873 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2874 #define RAM_SAVE_FLAG_PAGE 0x08
2875 #define RAM_SAVE_FLAG_EOS 0x10
2877 static int is_dup_page(uint8_t *page, uint8_t ch)
2879 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2880 uint32_t *array = (uint32_t *)page;
2881 int i;
2883 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2884 if (array[i] != val)
2885 return 0;
2888 return 1;
2891 static int ram_save_block(QEMUFile *f)
2893 static ram_addr_t current_addr = 0;
2894 ram_addr_t saved_addr = current_addr;
2895 ram_addr_t addr = 0;
2896 int found = 0;
2898 while (addr < last_ram_offset) {
2899 if (kvm_enabled() && current_addr == 0) {
2900 int r;
2901 r = kvm_update_dirty_pages_log();
2902 if (r) {
2903 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
2904 qemu_file_set_error(f);
2905 return 0;
2908 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2909 uint8_t *p;
2911 cpu_physical_memory_reset_dirty(current_addr,
2912 current_addr + TARGET_PAGE_SIZE,
2913 MIGRATION_DIRTY_FLAG);
2915 p = qemu_get_ram_ptr(current_addr);
2917 if (is_dup_page(p, *p)) {
2918 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2919 qemu_put_byte(f, *p);
2920 } else {
2921 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2922 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2925 found = 1;
2926 break;
2928 addr += TARGET_PAGE_SIZE;
2929 current_addr = (saved_addr + addr) % last_ram_offset;
2932 return found;
2935 static uint64_t bytes_transferred = 0;
2937 static ram_addr_t ram_save_remaining(void)
2939 ram_addr_t addr;
2940 ram_addr_t count = 0;
2942 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2943 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2944 count++;
2947 return count;
2950 uint64_t ram_bytes_remaining(void)
2952 return ram_save_remaining() * TARGET_PAGE_SIZE;
2955 uint64_t ram_bytes_transferred(void)
2957 return bytes_transferred;
2960 uint64_t ram_bytes_total(void)
2962 return last_ram_offset;
2965 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
2967 ram_addr_t addr;
2968 uint64_t bytes_transferred_last;
2969 double bwidth = 0;
2970 uint64_t expected_time = 0;
2972 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2973 qemu_file_set_error(f);
2974 return 0;
2977 if (stage == 1) {
2978 /* Make sure all dirty bits are set */
2979 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2980 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2981 cpu_physical_memory_set_dirty(addr);
2984 /* Enable dirty memory tracking */
2985 cpu_physical_memory_set_dirty_tracking(1);
2987 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2990 bytes_transferred_last = bytes_transferred;
2991 bwidth = get_clock();
2993 while (!qemu_file_rate_limit(f)) {
2994 int ret;
2996 ret = ram_save_block(f);
2997 bytes_transferred += ret * TARGET_PAGE_SIZE;
2998 if (ret == 0) /* no more blocks */
2999 break;
3002 bwidth = get_clock() - bwidth;
3003 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3005 /* if we haven't transferred anything this round, force expected_time to a
3006 * a very high value, but without crashing */
3007 if (bwidth == 0)
3008 bwidth = 0.000001;
3010 /* try transferring iterative blocks of memory */
3011 if (stage == 3) {
3012 /* flush all remaining blocks regardless of rate limiting */
3013 while (ram_save_block(f) != 0) {
3014 bytes_transferred += TARGET_PAGE_SIZE;
3016 cpu_physical_memory_set_dirty_tracking(0);
3019 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3021 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3023 return (stage == 2) && (expected_time <= migrate_max_downtime());
3026 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3028 ram_addr_t addr;
3029 int flags;
3031 if (version_id != 3)
3032 return -EINVAL;
3034 do {
3035 addr = qemu_get_be64(f);
3037 flags = addr & ~TARGET_PAGE_MASK;
3038 addr &= TARGET_PAGE_MASK;
3040 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3041 if (addr != last_ram_offset)
3042 return -EINVAL;
3045 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3046 uint8_t ch = qemu_get_byte(f);
3047 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3048 #ifndef _WIN32
3049 if (ch == 0 &&
3050 (!kvm_enabled() || kvm_has_sync_mmu())) {
3051 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3053 #endif
3054 } else if (flags & RAM_SAVE_FLAG_PAGE)
3055 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3056 } while (!(flags & RAM_SAVE_FLAG_EOS));
3058 return 0;
3061 void qemu_service_io(void)
3063 qemu_notify_event();
3066 /***********************************************************/
3067 /* machine registration */
3069 static QEMUMachine *first_machine = NULL;
3070 QEMUMachine *current_machine = NULL;
3072 int qemu_register_machine(QEMUMachine *m)
3074 QEMUMachine **pm;
3075 pm = &first_machine;
3076 while (*pm != NULL)
3077 pm = &(*pm)->next;
3078 m->next = NULL;
3079 *pm = m;
3080 return 0;
3083 static QEMUMachine *find_machine(const char *name)
3085 QEMUMachine *m;
3087 for(m = first_machine; m != NULL; m = m->next) {
3088 if (!strcmp(m->name, name))
3089 return m;
3090 if (m->alias && !strcmp(m->alias, name))
3091 return m;
3093 return NULL;
3096 static QEMUMachine *find_default_machine(void)
3098 QEMUMachine *m;
3100 for(m = first_machine; m != NULL; m = m->next) {
3101 if (m->is_default) {
3102 return m;
3105 return NULL;
3108 /***********************************************************/
3109 /* main execution loop */
3111 static void gui_update(void *opaque)
3113 uint64_t interval = GUI_REFRESH_INTERVAL;
3114 DisplayState *ds = opaque;
3115 DisplayChangeListener *dcl = ds->listeners;
3117 dpy_refresh(ds);
3119 while (dcl != NULL) {
3120 if (dcl->gui_timer_interval &&
3121 dcl->gui_timer_interval < interval)
3122 interval = dcl->gui_timer_interval;
3123 dcl = dcl->next;
3125 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3128 static void nographic_update(void *opaque)
3130 uint64_t interval = GUI_REFRESH_INTERVAL;
3132 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3135 struct vm_change_state_entry {
3136 VMChangeStateHandler *cb;
3137 void *opaque;
3138 QLIST_ENTRY (vm_change_state_entry) entries;
3141 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3143 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3144 void *opaque)
3146 VMChangeStateEntry *e;
3148 e = qemu_mallocz(sizeof (*e));
3150 e->cb = cb;
3151 e->opaque = opaque;
3152 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3153 return e;
3156 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3158 QLIST_REMOVE (e, entries);
3159 qemu_free (e);
3162 static void vm_state_notify(int running, int reason)
3164 VMChangeStateEntry *e;
3166 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3167 e->cb(e->opaque, running, reason);
3171 static void resume_all_vcpus(void);
3172 static void pause_all_vcpus(void);
3174 void vm_start(void)
3176 if (!vm_running) {
3177 cpu_enable_ticks();
3178 vm_running = 1;
3179 vm_state_notify(1, 0);
3180 qemu_rearm_alarm_timer(alarm_timer);
3181 resume_all_vcpus();
3185 /* reset/shutdown handler */
3187 typedef struct QEMUResetEntry {
3188 QTAILQ_ENTRY(QEMUResetEntry) entry;
3189 QEMUResetHandler *func;
3190 void *opaque;
3191 } QEMUResetEntry;
3193 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3194 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3195 static int reset_requested;
3196 static int shutdown_requested;
3197 static int powerdown_requested;
3198 static int debug_requested;
3199 static int vmstop_requested;
3201 int qemu_no_shutdown(void)
3203 int r = no_shutdown;
3204 no_shutdown = 0;
3205 return r;
3208 int qemu_shutdown_requested(void)
3210 int r = shutdown_requested;
3211 shutdown_requested = 0;
3212 return r;
3215 int qemu_reset_requested(void)
3217 int r = reset_requested;
3218 reset_requested = 0;
3219 return r;
3222 int qemu_powerdown_requested(void)
3224 int r = powerdown_requested;
3225 powerdown_requested = 0;
3226 return r;
3229 static int qemu_debug_requested(void)
3231 int r = debug_requested;
3232 debug_requested = 0;
3233 return r;
3236 static int qemu_vmstop_requested(void)
3238 int r = vmstop_requested;
3239 vmstop_requested = 0;
3240 return r;
3243 static void do_vm_stop(int reason)
3245 if (vm_running) {
3246 cpu_disable_ticks();
3247 vm_running = 0;
3248 pause_all_vcpus();
3249 vm_state_notify(0, reason);
3253 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3255 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3257 re->func = func;
3258 re->opaque = opaque;
3259 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3262 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3264 QEMUResetEntry *re;
3266 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3267 if (re->func == func && re->opaque == opaque) {
3268 QTAILQ_REMOVE(&reset_handlers, re, entry);
3269 qemu_free(re);
3270 return;
3275 void qemu_system_reset(void)
3277 QEMUResetEntry *re, *nre;
3279 /* reset all devices */
3280 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3281 re->func(re->opaque);
3285 void qemu_system_reset_request(void)
3287 if (no_reboot) {
3288 shutdown_requested = 1;
3289 } else {
3290 reset_requested = 1;
3292 if (cpu_single_env) {
3293 cpu_single_env->stopped = 1;
3295 qemu_notify_event();
3298 void qemu_system_shutdown_request(void)
3300 shutdown_requested = 1;
3301 qemu_notify_event();
3304 void qemu_system_powerdown_request(void)
3306 powerdown_requested = 1;
3307 qemu_notify_event();
3310 #ifdef CONFIG_IOTHREAD
3311 static void qemu_system_vmstop_request(int reason)
3313 vmstop_requested = reason;
3314 qemu_notify_event();
3316 #endif
3318 #ifndef _WIN32
3319 static int io_thread_fd = -1;
3321 static void qemu_event_increment(void)
3323 static const char byte = 0;
3325 if (io_thread_fd == -1)
3326 return;
3328 write(io_thread_fd, &byte, sizeof(byte));
3331 static void qemu_event_read(void *opaque)
3333 int fd = (unsigned long)opaque;
3334 ssize_t len;
3336 /* Drain the notify pipe */
3337 do {
3338 char buffer[512];
3339 len = read(fd, buffer, sizeof(buffer));
3340 } while ((len == -1 && errno == EINTR) || len > 0);
3343 static int qemu_event_init(void)
3345 int err;
3346 int fds[2];
3348 err = pipe(fds);
3349 if (err == -1)
3350 return -errno;
3352 err = fcntl_setfl(fds[0], O_NONBLOCK);
3353 if (err < 0)
3354 goto fail;
3356 err = fcntl_setfl(fds[1], O_NONBLOCK);
3357 if (err < 0)
3358 goto fail;
3360 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3361 (void *)(unsigned long)fds[0]);
3363 io_thread_fd = fds[1];
3364 return 0;
3366 fail:
3367 close(fds[0]);
3368 close(fds[1]);
3369 return err;
3371 #else
3372 HANDLE qemu_event_handle;
3374 static void dummy_event_handler(void *opaque)
3378 static int qemu_event_init(void)
3380 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3381 if (!qemu_event_handle) {
3382 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3383 return -1;
3385 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3386 return 0;
3389 static void qemu_event_increment(void)
3391 if (!SetEvent(qemu_event_handle)) {
3392 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3393 GetLastError());
3394 exit (1);
3397 #endif
3399 static int cpu_can_run(CPUState *env)
3401 if (env->stop)
3402 return 0;
3403 if (env->stopped)
3404 return 0;
3405 return 1;
3408 #ifndef CONFIG_IOTHREAD
3409 static int qemu_init_main_loop(void)
3411 return qemu_event_init();
3414 void qemu_init_vcpu(void *_env)
3416 CPUState *env = _env;
3418 if (kvm_enabled())
3419 kvm_init_vcpu(env);
3420 env->nr_cores = smp_cores;
3421 env->nr_threads = smp_threads;
3422 return;
3425 int qemu_cpu_self(void *env)
3427 return 1;
3430 static void resume_all_vcpus(void)
3434 static void pause_all_vcpus(void)
3438 void qemu_cpu_kick(void *env)
3440 return;
3443 void qemu_notify_event(void)
3445 CPUState *env = cpu_single_env;
3447 if (kvm_enabled()) {
3448 qemu_kvm_notify_work();
3449 return;
3451 if (env) {
3452 cpu_exit(env);
3456 #if defined(KVM_UPSTREAM) || !defined(CONFIG_KVM)
3457 void qemu_mutex_lock_iothread(void) {}
3458 void qemu_mutex_unlock_iothread(void) {}
3459 #endif
3461 void vm_stop(int reason)
3463 do_vm_stop(reason);
3466 #else /* CONFIG_IOTHREAD */
3468 #include "qemu-thread.h"
3470 QemuMutex qemu_global_mutex;
3471 static QemuMutex qemu_fair_mutex;
3473 static QemuThread io_thread;
3475 static QemuThread *tcg_cpu_thread;
3476 static QemuCond *tcg_halt_cond;
3478 static int qemu_system_ready;
3479 /* cpu creation */
3480 static QemuCond qemu_cpu_cond;
3481 /* system init */
3482 static QemuCond qemu_system_cond;
3483 static QemuCond qemu_pause_cond;
3485 static void block_io_signals(void);
3486 static void unblock_io_signals(void);
3487 static int tcg_has_work(void);
3489 static int qemu_init_main_loop(void)
3491 int ret;
3493 ret = qemu_event_init();
3494 if (ret)
3495 return ret;
3497 qemu_cond_init(&qemu_pause_cond);
3498 qemu_mutex_init(&qemu_fair_mutex);
3499 qemu_mutex_init(&qemu_global_mutex);
3500 qemu_mutex_lock(&qemu_global_mutex);
3502 unblock_io_signals();
3503 qemu_thread_self(&io_thread);
3505 return 0;
3508 static void qemu_wait_io_event(CPUState *env)
3510 while (!tcg_has_work())
3511 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3513 qemu_mutex_unlock(&qemu_global_mutex);
3516 * Users of qemu_global_mutex can be starved, having no chance
3517 * to acquire it since this path will get to it first.
3518 * So use another lock to provide fairness.
3520 qemu_mutex_lock(&qemu_fair_mutex);
3521 qemu_mutex_unlock(&qemu_fair_mutex);
3523 qemu_mutex_lock(&qemu_global_mutex);
3524 if (env->stop) {
3525 env->stop = 0;
3526 env->stopped = 1;
3527 qemu_cond_signal(&qemu_pause_cond);
3531 static int qemu_cpu_exec(CPUState *env);
3533 static void *kvm_cpu_thread_fn(void *arg)
3535 CPUState *env = arg;
3537 block_io_signals();
3538 qemu_thread_self(env->thread);
3539 if (kvm_enabled())
3540 kvm_init_vcpu(env);
3542 /* signal CPU creation */
3543 qemu_mutex_lock(&qemu_global_mutex);
3544 env->created = 1;
3545 qemu_cond_signal(&qemu_cpu_cond);
3547 /* and wait for machine initialization */
3548 while (!qemu_system_ready)
3549 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3551 while (1) {
3552 if (cpu_can_run(env))
3553 qemu_cpu_exec(env);
3554 qemu_wait_io_event(env);
3557 return NULL;
3560 static void tcg_cpu_exec(void);
3562 static void *tcg_cpu_thread_fn(void *arg)
3564 CPUState *env = arg;
3566 block_io_signals();
3567 qemu_thread_self(env->thread);
3569 /* signal CPU creation */
3570 qemu_mutex_lock(&qemu_global_mutex);
3571 for (env = first_cpu; env != NULL; env = env->next_cpu)
3572 env->created = 1;
3573 qemu_cond_signal(&qemu_cpu_cond);
3575 /* and wait for machine initialization */
3576 while (!qemu_system_ready)
3577 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3579 while (1) {
3580 tcg_cpu_exec();
3581 qemu_wait_io_event(cur_cpu);
3584 return NULL;
3587 void qemu_cpu_kick(void *_env)
3589 CPUState *env = _env;
3590 qemu_cond_broadcast(env->halt_cond);
3591 if (kvm_enabled())
3592 qemu_thread_signal(env->thread, SIGUSR1);
3595 int qemu_cpu_self(void *_env)
3597 CPUState *env = _env;
3598 QemuThread this;
3600 qemu_thread_self(&this);
3602 return qemu_thread_equal(&this, env->thread);
3605 static void cpu_signal(int sig)
3607 if (cpu_single_env)
3608 cpu_exit(cpu_single_env);
3611 static void block_io_signals(void)
3613 sigset_t set;
3614 struct sigaction sigact;
3616 sigemptyset(&set);
3617 sigaddset(&set, SIGUSR2);
3618 sigaddset(&set, SIGIO);
3619 sigaddset(&set, SIGALRM);
3620 pthread_sigmask(SIG_BLOCK, &set, NULL);
3622 sigemptyset(&set);
3623 sigaddset(&set, SIGUSR1);
3624 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3626 memset(&sigact, 0, sizeof(sigact));
3627 sigact.sa_handler = cpu_signal;
3628 sigaction(SIGUSR1, &sigact, NULL);
3631 static void unblock_io_signals(void)
3633 sigset_t set;
3635 sigemptyset(&set);
3636 sigaddset(&set, SIGUSR2);
3637 sigaddset(&set, SIGIO);
3638 sigaddset(&set, SIGALRM);
3639 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3641 sigemptyset(&set);
3642 sigaddset(&set, SIGUSR1);
3643 pthread_sigmask(SIG_BLOCK, &set, NULL);
3646 static void qemu_signal_lock(unsigned int msecs)
3648 qemu_mutex_lock(&qemu_fair_mutex);
3650 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3651 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3652 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3653 break;
3655 qemu_mutex_unlock(&qemu_fair_mutex);
3658 void qemu_mutex_lock_iothread(void)
3660 if (kvm_enabled()) {
3661 qemu_mutex_lock(&qemu_fair_mutex);
3662 qemu_mutex_lock(&qemu_global_mutex);
3663 qemu_mutex_unlock(&qemu_fair_mutex);
3664 } else
3665 qemu_signal_lock(100);
3668 void qemu_mutex_unlock_iothread(void)
3670 qemu_mutex_unlock(&qemu_global_mutex);
3673 static int all_vcpus_paused(void)
3675 CPUState *penv = first_cpu;
3677 while (penv) {
3678 if (!penv->stopped)
3679 return 0;
3680 penv = (CPUState *)penv->next_cpu;
3683 return 1;
3686 static void pause_all_vcpus(void)
3688 CPUState *penv = first_cpu;
3690 while (penv) {
3691 penv->stop = 1;
3692 qemu_thread_signal(penv->thread, SIGUSR1);
3693 qemu_cpu_kick(penv);
3694 penv = (CPUState *)penv->next_cpu;
3697 while (!all_vcpus_paused()) {
3698 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3699 penv = first_cpu;
3700 while (penv) {
3701 qemu_thread_signal(penv->thread, SIGUSR1);
3702 penv = (CPUState *)penv->next_cpu;
3707 static void resume_all_vcpus(void)
3709 CPUState *penv = first_cpu;
3711 while (penv) {
3712 penv->stop = 0;
3713 penv->stopped = 0;
3714 qemu_thread_signal(penv->thread, SIGUSR1);
3715 qemu_cpu_kick(penv);
3716 penv = (CPUState *)penv->next_cpu;
3720 static void tcg_init_vcpu(void *_env)
3722 CPUState *env = _env;
3723 /* share a single thread for all cpus with TCG */
3724 if (!tcg_cpu_thread) {
3725 env->thread = qemu_mallocz(sizeof(QemuThread));
3726 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3727 qemu_cond_init(env->halt_cond);
3728 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3729 while (env->created == 0)
3730 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3731 tcg_cpu_thread = env->thread;
3732 tcg_halt_cond = env->halt_cond;
3733 } else {
3734 env->thread = tcg_cpu_thread;
3735 env->halt_cond = tcg_halt_cond;
3739 static void kvm_start_vcpu(CPUState *env)
3741 env->thread = qemu_mallocz(sizeof(QemuThread));
3742 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3743 qemu_cond_init(env->halt_cond);
3744 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3745 while (env->created == 0)
3746 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3749 void qemu_init_vcpu(void *_env)
3751 CPUState *env = _env;
3753 if (kvm_enabled())
3754 kvm_start_vcpu(env);
3755 else
3756 tcg_init_vcpu(env);
3757 env->nr_cores = smp_cores;
3758 env->nr_threads = smp_threads;
3761 void qemu_notify_event(void)
3763 qemu_event_increment();
3766 void vm_stop(int reason)
3768 QemuThread me;
3769 qemu_thread_self(&me);
3771 if (!qemu_thread_equal(&me, &io_thread)) {
3772 qemu_system_vmstop_request(reason);
3774 * FIXME: should not return to device code in case
3775 * vm_stop() has been requested.
3777 if (cpu_single_env) {
3778 cpu_exit(cpu_single_env);
3779 cpu_single_env->stop = 1;
3781 return;
3783 do_vm_stop(reason);
3786 #endif
3789 #ifdef _WIN32
3790 static void host_main_loop_wait(int *timeout)
3792 int ret, ret2, i;
3793 PollingEntry *pe;
3796 /* XXX: need to suppress polling by better using win32 events */
3797 ret = 0;
3798 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3799 ret |= pe->func(pe->opaque);
3801 if (ret == 0) {
3802 int err;
3803 WaitObjects *w = &wait_objects;
3805 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3806 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3807 if (w->func[ret - WAIT_OBJECT_0])
3808 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3810 /* Check for additional signaled events */
3811 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3813 /* Check if event is signaled */
3814 ret2 = WaitForSingleObject(w->events[i], 0);
3815 if(ret2 == WAIT_OBJECT_0) {
3816 if (w->func[i])
3817 w->func[i](w->opaque[i]);
3818 } else if (ret2 == WAIT_TIMEOUT) {
3819 } else {
3820 err = GetLastError();
3821 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3824 } else if (ret == WAIT_TIMEOUT) {
3825 } else {
3826 err = GetLastError();
3827 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3831 *timeout = 0;
3833 #else
3834 static void host_main_loop_wait(int *timeout)
3837 #endif
3839 void main_loop_wait(int timeout)
3841 IOHandlerRecord *ioh;
3842 fd_set rfds, wfds, xfds;
3843 int ret, nfds;
3844 struct timeval tv;
3846 qemu_bh_update_timeout(&timeout);
3848 host_main_loop_wait(&timeout);
3850 /* poll any events */
3851 /* XXX: separate device handlers from system ones */
3852 nfds = -1;
3853 FD_ZERO(&rfds);
3854 FD_ZERO(&wfds);
3855 FD_ZERO(&xfds);
3856 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3857 if (ioh->deleted)
3858 continue;
3859 if (ioh->fd_read &&
3860 (!ioh->fd_read_poll ||
3861 ioh->fd_read_poll(ioh->opaque) != 0)) {
3862 FD_SET(ioh->fd, &rfds);
3863 if (ioh->fd > nfds)
3864 nfds = ioh->fd;
3866 if (ioh->fd_write) {
3867 FD_SET(ioh->fd, &wfds);
3868 if (ioh->fd > nfds)
3869 nfds = ioh->fd;
3873 tv.tv_sec = timeout / 1000;
3874 tv.tv_usec = (timeout % 1000) * 1000;
3876 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3878 qemu_mutex_unlock_iothread();
3879 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3880 qemu_mutex_lock_iothread();
3881 if (ret > 0) {
3882 IOHandlerRecord **pioh;
3884 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3885 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3886 ioh->fd_read(ioh->opaque);
3887 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3888 FD_CLR(ioh->fd, &rfds);
3890 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3891 ioh->fd_write(ioh->opaque);
3895 /* remove deleted IO handlers */
3896 pioh = &first_io_handler;
3897 while (*pioh) {
3898 ioh = *pioh;
3899 if (ioh->deleted) {
3900 *pioh = ioh->next;
3901 qemu_free(ioh);
3902 } else
3903 pioh = &ioh->next;
3907 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3909 /* rearm timer, if not periodic */
3910 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3911 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3912 qemu_rearm_alarm_timer(alarm_timer);
3915 /* vm time timers */
3916 if (vm_running) {
3917 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3918 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3919 qemu_get_clock(vm_clock));
3922 /* real time timers */
3923 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3924 qemu_get_clock(rt_clock));
3926 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3927 qemu_get_clock(host_clock));
3929 /* Check bottom-halves last in case any of the earlier events triggered
3930 them. */
3931 qemu_bh_poll();
3935 static int qemu_cpu_exec(CPUState *env)
3937 int ret;
3938 #ifdef CONFIG_PROFILER
3939 int64_t ti;
3940 #endif
3942 #ifdef CONFIG_PROFILER
3943 ti = profile_getclock();
3944 #endif
3945 if (use_icount) {
3946 int64_t count;
3947 int decr;
3948 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3949 env->icount_decr.u16.low = 0;
3950 env->icount_extra = 0;
3951 count = qemu_next_deadline();
3952 count = (count + (1 << icount_time_shift) - 1)
3953 >> icount_time_shift;
3954 qemu_icount += count;
3955 decr = (count > 0xffff) ? 0xffff : count;
3956 count -= decr;
3957 env->icount_decr.u16.low = decr;
3958 env->icount_extra = count;
3960 ret = cpu_exec(env);
3961 #ifdef CONFIG_PROFILER
3962 qemu_time += profile_getclock() - ti;
3963 #endif
3964 if (use_icount) {
3965 /* Fold pending instructions back into the
3966 instruction counter, and clear the interrupt flag. */
3967 qemu_icount -= (env->icount_decr.u16.low
3968 + env->icount_extra);
3969 env->icount_decr.u32 = 0;
3970 env->icount_extra = 0;
3972 return ret;
3975 static void tcg_cpu_exec(void)
3977 int ret = 0;
3979 if (next_cpu == NULL)
3980 next_cpu = first_cpu;
3981 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3982 CPUState *env = cur_cpu = next_cpu;
3984 if (!vm_running)
3985 break;
3986 if (timer_alarm_pending) {
3987 timer_alarm_pending = 0;
3988 break;
3990 if (cpu_can_run(env))
3991 ret = qemu_cpu_exec(env);
3992 if (ret == EXCP_DEBUG) {
3993 gdb_set_stop_cpu(env);
3994 debug_requested = 1;
3995 break;
4000 static int cpu_has_work(CPUState *env)
4002 if (env->stop)
4003 return 1;
4004 if (env->stopped)
4005 return 0;
4006 if (!env->halted)
4007 return 1;
4008 if (qemu_cpu_has_work(env))
4009 return 1;
4010 return 0;
4013 static int tcg_has_work(void)
4015 CPUState *env;
4017 for (env = first_cpu; env != NULL; env = env->next_cpu)
4018 if (cpu_has_work(env))
4019 return 1;
4020 return 0;
4023 static int qemu_calculate_timeout(void)
4025 #ifndef CONFIG_IOTHREAD
4026 int timeout;
4028 if (!vm_running)
4029 timeout = 5000;
4030 else if (tcg_has_work())
4031 timeout = 0;
4032 else if (!use_icount)
4033 timeout = 5000;
4034 else {
4035 /* XXX: use timeout computed from timers */
4036 int64_t add;
4037 int64_t delta;
4038 /* Advance virtual time to the next event. */
4039 if (use_icount == 1) {
4040 /* When not using an adaptive execution frequency
4041 we tend to get badly out of sync with real time,
4042 so just delay for a reasonable amount of time. */
4043 delta = 0;
4044 } else {
4045 delta = cpu_get_icount() - cpu_get_clock();
4047 if (delta > 0) {
4048 /* If virtual time is ahead of real time then just
4049 wait for IO. */
4050 timeout = (delta / 1000000) + 1;
4051 } else {
4052 /* Wait for either IO to occur or the next
4053 timer event. */
4054 add = qemu_next_deadline();
4055 /* We advance the timer before checking for IO.
4056 Limit the amount we advance so that early IO
4057 activity won't get the guest too far ahead. */
4058 if (add > 10000000)
4059 add = 10000000;
4060 delta += add;
4061 add = (add + (1 << icount_time_shift) - 1)
4062 >> icount_time_shift;
4063 qemu_icount += add;
4064 timeout = delta / 1000000;
4065 if (timeout < 0)
4066 timeout = 0;
4070 return timeout;
4071 #else /* CONFIG_IOTHREAD */
4072 return 1000;
4073 #endif
4076 static int vm_can_run(void)
4078 if (powerdown_requested)
4079 return 0;
4080 if (reset_requested)
4081 return 0;
4082 if (shutdown_requested)
4083 return 0;
4084 if (debug_requested)
4085 return 0;
4086 return 1;
4089 qemu_irq qemu_system_powerdown;
4091 static void main_loop(void)
4093 int r;
4095 if (kvm_enabled()) {
4096 kvm_main_loop();
4097 cpu_disable_ticks();
4098 return;
4101 #ifdef CONFIG_IOTHREAD
4102 qemu_system_ready = 1;
4103 qemu_cond_broadcast(&qemu_system_cond);
4104 #endif
4106 for (;;) {
4107 do {
4108 #ifdef CONFIG_PROFILER
4109 int64_t ti;
4110 #endif
4111 #ifndef CONFIG_IOTHREAD
4112 tcg_cpu_exec();
4113 #endif
4114 #ifdef CONFIG_PROFILER
4115 ti = profile_getclock();
4116 #endif
4117 main_loop_wait(qemu_calculate_timeout());
4118 #ifdef CONFIG_PROFILER
4119 dev_time += profile_getclock() - ti;
4120 #endif
4121 } while (vm_can_run());
4123 if (qemu_debug_requested())
4124 vm_stop(EXCP_DEBUG);
4125 if (qemu_shutdown_requested()) {
4126 if (no_shutdown) {
4127 vm_stop(0);
4128 no_shutdown = 0;
4129 } else
4130 break;
4132 if (qemu_reset_requested()) {
4133 pause_all_vcpus();
4134 qemu_system_reset();
4135 resume_all_vcpus();
4137 if (qemu_powerdown_requested()) {
4138 qemu_irq_raise(qemu_system_powerdown);
4140 if ((r = qemu_vmstop_requested()))
4141 vm_stop(r);
4143 pause_all_vcpus();
4146 static void version(void)
4148 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4151 static void help(int exitcode)
4153 version();
4154 printf("usage: %s [options] [disk_image]\n"
4155 "\n"
4156 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4157 "\n"
4158 #define DEF(option, opt_arg, opt_enum, opt_help) \
4159 opt_help
4160 #define DEFHEADING(text) stringify(text) "\n"
4161 #include "qemu-options.h"
4162 #undef DEF
4163 #undef DEFHEADING
4164 #undef GEN_DOCS
4165 "\n"
4166 "During emulation, the following keys are useful:\n"
4167 "ctrl-alt-f toggle full screen\n"
4168 "ctrl-alt-n switch to virtual console 'n'\n"
4169 "ctrl-alt toggle mouse and keyboard grab\n"
4170 "\n"
4171 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4173 "qemu",
4174 DEFAULT_RAM_SIZE,
4175 #ifndef _WIN32
4176 DEFAULT_NETWORK_SCRIPT,
4177 DEFAULT_NETWORK_DOWN_SCRIPT,
4178 #endif
4179 DEFAULT_GDBSTUB_PORT,
4180 "/tmp/qemu.log");
4181 exit(exitcode);
4184 #define HAS_ARG 0x0001
4186 enum {
4187 #define DEF(option, opt_arg, opt_enum, opt_help) \
4188 opt_enum,
4189 #define DEFHEADING(text)
4190 #include "qemu-options.h"
4191 #undef DEF
4192 #undef DEFHEADING
4193 #undef GEN_DOCS
4196 typedef struct QEMUOption {
4197 const char *name;
4198 int flags;
4199 int index;
4200 } QEMUOption;
4202 static const QEMUOption qemu_options[] = {
4203 { "h", 0, QEMU_OPTION_h },
4204 #define DEF(option, opt_arg, opt_enum, opt_help) \
4205 { option, opt_arg, opt_enum },
4206 #define DEFHEADING(text)
4207 #include "qemu-options.h"
4208 #undef DEF
4209 #undef DEFHEADING
4210 #undef GEN_DOCS
4211 { NULL },
4214 #ifdef HAS_AUDIO
4215 struct soundhw soundhw[] = {
4216 #ifdef HAS_AUDIO_CHOICE
4217 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4219 "pcspk",
4220 "PC speaker",
4223 { .init_isa = pcspk_audio_init }
4225 #endif
4227 #ifdef CONFIG_SB16
4229 "sb16",
4230 "Creative Sound Blaster 16",
4233 { .init_isa = SB16_init }
4235 #endif
4237 #ifdef CONFIG_CS4231A
4239 "cs4231a",
4240 "CS4231A",
4243 { .init_isa = cs4231a_init }
4245 #endif
4247 #ifdef CONFIG_ADLIB
4249 "adlib",
4250 #ifdef HAS_YMF262
4251 "Yamaha YMF262 (OPL3)",
4252 #else
4253 "Yamaha YM3812 (OPL2)",
4254 #endif
4257 { .init_isa = Adlib_init }
4259 #endif
4261 #ifdef CONFIG_GUS
4263 "gus",
4264 "Gravis Ultrasound GF1",
4267 { .init_isa = GUS_init }
4269 #endif
4271 #ifdef CONFIG_AC97
4273 "ac97",
4274 "Intel 82801AA AC97 Audio",
4277 { .init_pci = ac97_init }
4279 #endif
4281 #ifdef CONFIG_ES1370
4283 "es1370",
4284 "ENSONIQ AudioPCI ES1370",
4287 { .init_pci = es1370_init }
4289 #endif
4291 #endif /* HAS_AUDIO_CHOICE */
4293 { NULL, NULL, 0, 0, { NULL } }
4296 static void select_soundhw (const char *optarg)
4298 struct soundhw *c;
4300 if (*optarg == '?') {
4301 show_valid_cards:
4303 printf ("Valid sound card names (comma separated):\n");
4304 for (c = soundhw; c->name; ++c) {
4305 printf ("%-11s %s\n", c->name, c->descr);
4307 printf ("\n-soundhw all will enable all of the above\n");
4308 exit (*optarg != '?');
4310 else {
4311 size_t l;
4312 const char *p;
4313 char *e;
4314 int bad_card = 0;
4316 if (!strcmp (optarg, "all")) {
4317 for (c = soundhw; c->name; ++c) {
4318 c->enabled = 1;
4320 return;
4323 p = optarg;
4324 while (*p) {
4325 e = strchr (p, ',');
4326 l = !e ? strlen (p) : (size_t) (e - p);
4328 for (c = soundhw; c->name; ++c) {
4329 if (!strncmp (c->name, p, l) && !c->name[l]) {
4330 c->enabled = 1;
4331 break;
4335 if (!c->name) {
4336 if (l > 80) {
4337 fprintf (stderr,
4338 "Unknown sound card name (too big to show)\n");
4340 else {
4341 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4342 (int) l, p);
4344 bad_card = 1;
4346 p += l + (e != NULL);
4349 if (bad_card)
4350 goto show_valid_cards;
4353 #endif
4355 static void select_vgahw (const char *p)
4357 const char *opts;
4359 vga_interface_type = VGA_NONE;
4360 if (strstart(p, "std", &opts)) {
4361 vga_interface_type = VGA_STD;
4362 } else if (strstart(p, "cirrus", &opts)) {
4363 vga_interface_type = VGA_CIRRUS;
4364 } else if (strstart(p, "vmware", &opts)) {
4365 vga_interface_type = VGA_VMWARE;
4366 } else if (strstart(p, "xenfb", &opts)) {
4367 vga_interface_type = VGA_XENFB;
4368 } else if (!strstart(p, "none", &opts)) {
4369 invalid_vga:
4370 fprintf(stderr, "Unknown vga type: %s\n", p);
4371 exit(1);
4373 while (*opts) {
4374 const char *nextopt;
4376 if (strstart(opts, ",retrace=", &nextopt)) {
4377 opts = nextopt;
4378 if (strstart(opts, "dumb", &nextopt))
4379 vga_retrace_method = VGA_RETRACE_DUMB;
4380 else if (strstart(opts, "precise", &nextopt))
4381 vga_retrace_method = VGA_RETRACE_PRECISE;
4382 else goto invalid_vga;
4383 } else goto invalid_vga;
4384 opts = nextopt;
4388 #ifdef TARGET_I386
4389 static int balloon_parse(const char *arg)
4391 QemuOpts *opts;
4393 if (strcmp(arg, "none") == 0) {
4394 return 0;
4397 if (!strncmp(arg, "virtio", 6)) {
4398 if (arg[6] == ',') {
4399 /* have params -> parse them */
4400 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4401 if (!opts)
4402 return -1;
4403 } else {
4404 /* create empty opts */
4405 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4407 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4408 return 0;
4411 return -1;
4413 #endif
4415 #ifdef _WIN32
4416 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4418 exit(STATUS_CONTROL_C_EXIT);
4419 return TRUE;
4421 #endif
4423 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4425 int ret;
4427 if(strlen(str) != 36)
4428 return -1;
4430 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4431 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4432 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4434 if(ret != 16)
4435 return -1;
4437 #ifdef TARGET_I386
4438 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4439 #endif
4441 return 0;
4444 #ifndef _WIN32
4446 static void termsig_handler(int signal)
4448 qemu_system_shutdown_request();
4451 static void sigchld_handler(int signal)
4453 waitpid(-1, NULL, WNOHANG);
4456 static void sighandler_setup(void)
4458 struct sigaction act;
4460 memset(&act, 0, sizeof(act));
4461 act.sa_handler = termsig_handler;
4462 sigaction(SIGINT, &act, NULL);
4463 sigaction(SIGHUP, &act, NULL);
4464 sigaction(SIGTERM, &act, NULL);
4466 act.sa_handler = sigchld_handler;
4467 act.sa_flags = SA_NOCLDSTOP;
4468 sigaction(SIGCHLD, &act, NULL);
4471 #endif
4473 #ifdef _WIN32
4474 /* Look for support files in the same directory as the executable. */
4475 static char *find_datadir(const char *argv0)
4477 char *p;
4478 char buf[MAX_PATH];
4479 DWORD len;
4481 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4482 if (len == 0) {
4483 return NULL;
4486 buf[len] = 0;
4487 p = buf + len - 1;
4488 while (p != buf && *p != '\\')
4489 p--;
4490 *p = 0;
4491 if (access(buf, R_OK) == 0) {
4492 return qemu_strdup(buf);
4494 return NULL;
4496 #else /* !_WIN32 */
4498 /* Find a likely location for support files using the location of the binary.
4499 For installed binaries this will be "$bindir/../share/qemu". When
4500 running from the build tree this will be "$bindir/../pc-bios". */
4501 #define SHARE_SUFFIX "/share/qemu"
4502 #define BUILD_SUFFIX "/pc-bios"
4503 static char *find_datadir(const char *argv0)
4505 char *dir;
4506 char *p = NULL;
4507 char *res;
4508 char buf[PATH_MAX];
4509 size_t max_len;
4511 #if defined(__linux__)
4513 int len;
4514 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4515 if (len > 0) {
4516 buf[len] = 0;
4517 p = buf;
4520 #elif defined(__FreeBSD__)
4522 int len;
4523 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4524 if (len > 0) {
4525 buf[len] = 0;
4526 p = buf;
4529 #endif
4530 /* If we don't have any way of figuring out the actual executable
4531 location then try argv[0]. */
4532 if (!p) {
4533 p = realpath(argv0, buf);
4534 if (!p) {
4535 return NULL;
4538 dir = dirname(p);
4539 dir = dirname(dir);
4541 max_len = strlen(dir) +
4542 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4543 res = qemu_mallocz(max_len);
4544 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4545 if (access(res, R_OK)) {
4546 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4547 if (access(res, R_OK)) {
4548 qemu_free(res);
4549 res = NULL;
4553 return res;
4555 #undef SHARE_SUFFIX
4556 #undef BUILD_SUFFIX
4557 #endif
4559 char *qemu_find_file(int type, const char *name)
4561 int len;
4562 const char *subdir;
4563 char *buf;
4565 /* If name contains path separators then try it as a straight path. */
4566 if ((strchr(name, '/') || strchr(name, '\\'))
4567 && access(name, R_OK) == 0) {
4568 return qemu_strdup(name);
4570 switch (type) {
4571 case QEMU_FILE_TYPE_BIOS:
4572 subdir = "";
4573 break;
4574 case QEMU_FILE_TYPE_KEYMAP:
4575 subdir = "keymaps/";
4576 break;
4577 default:
4578 abort();
4580 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4581 buf = qemu_mallocz(len);
4582 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4583 if (access(buf, R_OK)) {
4584 qemu_free(buf);
4585 return NULL;
4587 return buf;
4590 static int device_init_func(QemuOpts *opts, void *opaque)
4592 DeviceState *dev;
4594 dev = qdev_device_add(opts);
4595 if (!dev)
4596 return -1;
4597 return 0;
4600 struct device_config {
4601 enum {
4602 DEV_USB, /* -usbdevice */
4603 DEV_BT, /* -bt */
4604 } type;
4605 const char *cmdline;
4606 QTAILQ_ENTRY(device_config) next;
4608 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4610 static void add_device_config(int type, const char *cmdline)
4612 struct device_config *conf;
4614 conf = qemu_mallocz(sizeof(*conf));
4615 conf->type = type;
4616 conf->cmdline = cmdline;
4617 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4620 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4622 struct device_config *conf;
4623 int rc;
4625 QTAILQ_FOREACH(conf, &device_configs, next) {
4626 if (conf->type != type)
4627 continue;
4628 rc = func(conf->cmdline);
4629 if (0 != rc)
4630 return rc;
4632 return 0;
4635 int main(int argc, char **argv, char **envp)
4637 const char *gdbstub_dev = NULL;
4638 uint32_t boot_devices_bitmap = 0;
4639 int i;
4640 int snapshot, linux_boot, net_boot;
4641 const char *initrd_filename;
4642 const char *kernel_filename, *kernel_cmdline;
4643 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4644 DisplayState *ds;
4645 DisplayChangeListener *dcl;
4646 int cyls, heads, secs, translation;
4647 QemuOpts *hda_opts = NULL, *opts;
4648 int optind;
4649 const char *r, *optarg;
4650 CharDriverState *monitor_hds[MAX_MONITOR_DEVICES];
4651 const char *monitor_devices[MAX_MONITOR_DEVICES];
4652 int monitor_device_index;
4653 const char *serial_devices[MAX_SERIAL_PORTS];
4654 int serial_device_index;
4655 const char *parallel_devices[MAX_PARALLEL_PORTS];
4656 int parallel_device_index;
4657 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4658 int virtio_console_index;
4659 const char *loadvm = NULL;
4660 QEMUMachine *machine;
4661 const char *cpu_model;
4662 #ifndef _WIN32
4663 int fds[2];
4664 #endif
4665 int tb_size;
4666 const char *pid_file = NULL;
4667 const char *incoming = NULL;
4668 #ifndef _WIN32
4669 int fd = 0;
4670 struct passwd *pwd = NULL;
4671 const char *chroot_dir = NULL;
4672 const char *run_as = NULL;
4673 #endif
4674 CPUState *env;
4675 int show_vnc_port = 0;
4677 init_clocks();
4679 qemu_errors_to_file(stderr);
4680 qemu_cache_utils_init(envp);
4682 QLIST_INIT (&vm_change_state_head);
4683 #ifndef _WIN32
4685 struct sigaction act;
4686 sigfillset(&act.sa_mask);
4687 act.sa_flags = 0;
4688 act.sa_handler = SIG_IGN;
4689 sigaction(SIGPIPE, &act, NULL);
4691 #else
4692 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4693 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4694 QEMU to run on a single CPU */
4696 HANDLE h;
4697 DWORD mask, smask;
4698 int i;
4699 h = GetCurrentProcess();
4700 if (GetProcessAffinityMask(h, &mask, &smask)) {
4701 for(i = 0; i < 32; i++) {
4702 if (mask & (1 << i))
4703 break;
4705 if (i != 32) {
4706 mask = 1 << i;
4707 SetProcessAffinityMask(h, mask);
4711 #endif
4713 module_call_init(MODULE_INIT_MACHINE);
4714 machine = find_default_machine();
4715 cpu_model = NULL;
4716 initrd_filename = NULL;
4717 ram_size = 0;
4718 snapshot = 0;
4719 kernel_filename = NULL;
4720 kernel_cmdline = "";
4721 cyls = heads = secs = 0;
4722 translation = BIOS_ATA_TRANSLATION_AUTO;
4724 serial_devices[0] = "vc:80Cx24C";
4725 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4726 serial_devices[i] = NULL;
4727 serial_device_index = 0;
4729 parallel_devices[0] = "vc:80Cx24C";
4730 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4731 parallel_devices[i] = NULL;
4732 parallel_device_index = 0;
4734 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4735 virtio_consoles[i] = NULL;
4736 virtio_console_index = 0;
4738 monitor_devices[0] = "vc:80Cx24C";
4739 for (i = 1; i < MAX_MONITOR_DEVICES; i++) {
4740 monitor_devices[i] = NULL;
4742 monitor_device_index = 0;
4744 for (i = 0; i < MAX_NODES; i++) {
4745 node_mem[i] = 0;
4746 node_cpumask[i] = 0;
4749 assigned_devices_index = 0;
4751 nb_numa_nodes = 0;
4752 nb_nics = 0;
4754 tb_size = 0;
4755 autostart= 1;
4757 optind = 1;
4758 for(;;) {
4759 if (optind >= argc)
4760 break;
4761 r = argv[optind];
4762 if (r[0] != '-') {
4763 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4764 } else {
4765 const QEMUOption *popt;
4767 optind++;
4768 /* Treat --foo the same as -foo. */
4769 if (r[1] == '-')
4770 r++;
4771 popt = qemu_options;
4772 for(;;) {
4773 if (!popt->name) {
4774 fprintf(stderr, "%s: invalid option -- '%s'\n",
4775 argv[0], r);
4776 exit(1);
4778 if (!strcmp(popt->name, r + 1))
4779 break;
4780 popt++;
4782 if (popt->flags & HAS_ARG) {
4783 if (optind >= argc) {
4784 fprintf(stderr, "%s: option '%s' requires an argument\n",
4785 argv[0], r);
4786 exit(1);
4788 optarg = argv[optind++];
4789 } else {
4790 optarg = NULL;
4793 switch(popt->index) {
4794 case QEMU_OPTION_M:
4795 machine = find_machine(optarg);
4796 if (!machine) {
4797 QEMUMachine *m;
4798 printf("Supported machines are:\n");
4799 for(m = first_machine; m != NULL; m = m->next) {
4800 if (m->alias)
4801 printf("%-10s %s (alias of %s)\n",
4802 m->alias, m->desc, m->name);
4803 printf("%-10s %s%s\n",
4804 m->name, m->desc,
4805 m->is_default ? " (default)" : "");
4807 exit(*optarg != '?');
4809 break;
4810 case QEMU_OPTION_cpu:
4811 /* hw initialization will check this */
4812 if (*optarg == '?') {
4813 /* XXX: implement xxx_cpu_list for targets that still miss it */
4814 #if defined(cpu_list)
4815 cpu_list(stdout, &fprintf);
4816 #endif
4817 exit(0);
4818 } else {
4819 cpu_model = optarg;
4821 break;
4822 case QEMU_OPTION_initrd:
4823 initrd_filename = optarg;
4824 break;
4825 case QEMU_OPTION_hda:
4826 if (cyls == 0)
4827 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4828 else
4829 hda_opts = drive_add(optarg, HD_ALIAS
4830 ",cyls=%d,heads=%d,secs=%d%s",
4831 0, cyls, heads, secs,
4832 translation == BIOS_ATA_TRANSLATION_LBA ?
4833 ",trans=lba" :
4834 translation == BIOS_ATA_TRANSLATION_NONE ?
4835 ",trans=none" : "");
4836 break;
4837 case QEMU_OPTION_hdb:
4838 case QEMU_OPTION_hdc:
4839 case QEMU_OPTION_hdd:
4840 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4841 break;
4842 case QEMU_OPTION_drive:
4843 drive_add(NULL, "%s", optarg);
4844 break;
4845 case QEMU_OPTION_set:
4846 if (qemu_set_option(optarg) != 0)
4847 exit(1);
4848 break;
4849 case QEMU_OPTION_mtdblock:
4850 drive_add(optarg, MTD_ALIAS);
4851 break;
4852 case QEMU_OPTION_sd:
4853 drive_add(optarg, SD_ALIAS);
4854 break;
4855 case QEMU_OPTION_pflash:
4856 drive_add(optarg, PFLASH_ALIAS);
4857 break;
4858 case QEMU_OPTION_snapshot:
4859 snapshot = 1;
4860 break;
4861 case QEMU_OPTION_hdachs:
4863 const char *p;
4864 p = optarg;
4865 cyls = strtol(p, (char **)&p, 0);
4866 if (cyls < 1 || cyls > 16383)
4867 goto chs_fail;
4868 if (*p != ',')
4869 goto chs_fail;
4870 p++;
4871 heads = strtol(p, (char **)&p, 0);
4872 if (heads < 1 || heads > 16)
4873 goto chs_fail;
4874 if (*p != ',')
4875 goto chs_fail;
4876 p++;
4877 secs = strtol(p, (char **)&p, 0);
4878 if (secs < 1 || secs > 63)
4879 goto chs_fail;
4880 if (*p == ',') {
4881 p++;
4882 if (!strcmp(p, "none"))
4883 translation = BIOS_ATA_TRANSLATION_NONE;
4884 else if (!strcmp(p, "lba"))
4885 translation = BIOS_ATA_TRANSLATION_LBA;
4886 else if (!strcmp(p, "auto"))
4887 translation = BIOS_ATA_TRANSLATION_AUTO;
4888 else
4889 goto chs_fail;
4890 } else if (*p != '\0') {
4891 chs_fail:
4892 fprintf(stderr, "qemu: invalid physical CHS format\n");
4893 exit(1);
4895 if (hda_opts != NULL) {
4896 char num[16];
4897 snprintf(num, sizeof(num), "%d", cyls);
4898 qemu_opt_set(hda_opts, "cyls", num);
4899 snprintf(num, sizeof(num), "%d", heads);
4900 qemu_opt_set(hda_opts, "heads", num);
4901 snprintf(num, sizeof(num), "%d", secs);
4902 qemu_opt_set(hda_opts, "secs", num);
4903 if (translation == BIOS_ATA_TRANSLATION_LBA)
4904 qemu_opt_set(hda_opts, "trans", "lba");
4905 if (translation == BIOS_ATA_TRANSLATION_NONE)
4906 qemu_opt_set(hda_opts, "trans", "none");
4909 break;
4910 case QEMU_OPTION_numa:
4911 if (nb_numa_nodes >= MAX_NODES) {
4912 fprintf(stderr, "qemu: too many NUMA nodes\n");
4913 exit(1);
4915 numa_add(optarg);
4916 break;
4917 case QEMU_OPTION_nographic:
4918 display_type = DT_NOGRAPHIC;
4919 break;
4920 #ifdef CONFIG_CURSES
4921 case QEMU_OPTION_curses:
4922 display_type = DT_CURSES;
4923 break;
4924 #endif
4925 case QEMU_OPTION_portrait:
4926 graphic_rotate = 1;
4927 break;
4928 case QEMU_OPTION_kernel:
4929 kernel_filename = optarg;
4930 break;
4931 case QEMU_OPTION_append:
4932 kernel_cmdline = optarg;
4933 break;
4934 case QEMU_OPTION_cdrom:
4935 drive_add(optarg, CDROM_ALIAS);
4936 break;
4937 case QEMU_OPTION_boot:
4939 static const char * const params[] = {
4940 "order", "once", "menu", NULL
4942 char buf[sizeof(boot_devices)];
4943 char *standard_boot_devices;
4944 int legacy = 0;
4946 if (!strchr(optarg, '=')) {
4947 legacy = 1;
4948 pstrcpy(buf, sizeof(buf), optarg);
4949 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4950 fprintf(stderr,
4951 "qemu: unknown boot parameter '%s' in '%s'\n",
4952 buf, optarg);
4953 exit(1);
4956 if (legacy ||
4957 get_param_value(buf, sizeof(buf), "order", optarg)) {
4958 boot_devices_bitmap = parse_bootdevices(buf);
4959 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4961 if (!legacy) {
4962 if (get_param_value(buf, sizeof(buf),
4963 "once", optarg)) {
4964 boot_devices_bitmap |= parse_bootdevices(buf);
4965 standard_boot_devices = qemu_strdup(boot_devices);
4966 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4967 qemu_register_reset(restore_boot_devices,
4968 standard_boot_devices);
4970 if (get_param_value(buf, sizeof(buf),
4971 "menu", optarg)) {
4972 if (!strcmp(buf, "on")) {
4973 boot_menu = 1;
4974 } else if (!strcmp(buf, "off")) {
4975 boot_menu = 0;
4976 } else {
4977 fprintf(stderr,
4978 "qemu: invalid option value '%s'\n",
4979 buf);
4980 exit(1);
4985 break;
4986 case QEMU_OPTION_fda:
4987 case QEMU_OPTION_fdb:
4988 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4989 break;
4990 #ifdef TARGET_I386
4991 case QEMU_OPTION_no_fd_bootchk:
4992 fd_bootchk = 0;
4993 break;
4994 #endif
4995 case QEMU_OPTION_netdev:
4996 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4997 exit(1);
4999 break;
5000 case QEMU_OPTION_net:
5001 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5002 exit(1);
5004 break;
5005 #ifdef CONFIG_SLIRP
5006 case QEMU_OPTION_tftp:
5007 legacy_tftp_prefix = optarg;
5008 break;
5009 case QEMU_OPTION_bootp:
5010 legacy_bootp_filename = optarg;
5011 break;
5012 #ifndef _WIN32
5013 case QEMU_OPTION_smb:
5014 if (net_slirp_smb(optarg) < 0)
5015 exit(1);
5016 break;
5017 #endif
5018 case QEMU_OPTION_redir:
5019 if (net_slirp_redir(optarg) < 0)
5020 exit(1);
5021 break;
5022 #endif
5023 case QEMU_OPTION_bt:
5024 add_device_config(DEV_BT, optarg);
5025 break;
5026 #ifdef HAS_AUDIO
5027 case QEMU_OPTION_audio_help:
5028 AUD_help ();
5029 exit (0);
5030 break;
5031 case QEMU_OPTION_soundhw:
5032 select_soundhw (optarg);
5033 break;
5034 #endif
5035 case QEMU_OPTION_h:
5036 help(0);
5037 break;
5038 case QEMU_OPTION_version:
5039 version();
5040 exit(0);
5041 break;
5042 case QEMU_OPTION_m: {
5043 uint64_t value;
5044 char *ptr;
5046 value = strtoul(optarg, &ptr, 10);
5047 switch (*ptr) {
5048 case 0: case 'M': case 'm':
5049 value <<= 20;
5050 break;
5051 case 'G': case 'g':
5052 value <<= 30;
5053 break;
5054 default:
5055 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5056 exit(1);
5059 /* On 32-bit hosts, QEMU is limited by virtual address space */
5060 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5061 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5062 exit(1);
5064 if (value != (uint64_t)(ram_addr_t)value) {
5065 fprintf(stderr, "qemu: ram size too large\n");
5066 exit(1);
5068 ram_size = value;
5069 break;
5071 case QEMU_OPTION_d:
5073 int mask;
5074 const CPULogItem *item;
5076 mask = cpu_str_to_log_mask(optarg);
5077 if (!mask) {
5078 printf("Log items (comma separated):\n");
5079 for(item = cpu_log_items; item->mask != 0; item++) {
5080 printf("%-10s %s\n", item->name, item->help);
5082 exit(1);
5084 cpu_set_log(mask);
5086 break;
5087 case QEMU_OPTION_s:
5088 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5089 break;
5090 case QEMU_OPTION_gdb:
5091 gdbstub_dev = optarg;
5092 break;
5093 case QEMU_OPTION_L:
5094 data_dir = optarg;
5095 break;
5096 case QEMU_OPTION_bios:
5097 bios_name = optarg;
5098 break;
5099 case QEMU_OPTION_singlestep:
5100 singlestep = 1;
5101 break;
5102 case QEMU_OPTION_S:
5103 autostart = 0;
5104 break;
5105 #ifndef _WIN32
5106 case QEMU_OPTION_k:
5107 keyboard_layout = optarg;
5108 break;
5109 #endif
5110 case QEMU_OPTION_localtime:
5111 rtc_utc = 0;
5112 break;
5113 case QEMU_OPTION_vga:
5114 select_vgahw (optarg);
5115 break;
5116 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5117 case QEMU_OPTION_g:
5119 const char *p;
5120 int w, h, depth;
5121 p = optarg;
5122 w = strtol(p, (char **)&p, 10);
5123 if (w <= 0) {
5124 graphic_error:
5125 fprintf(stderr, "qemu: invalid resolution or depth\n");
5126 exit(1);
5128 if (*p != 'x')
5129 goto graphic_error;
5130 p++;
5131 h = strtol(p, (char **)&p, 10);
5132 if (h <= 0)
5133 goto graphic_error;
5134 if (*p == 'x') {
5135 p++;
5136 depth = strtol(p, (char **)&p, 10);
5137 if (depth != 8 && depth != 15 && depth != 16 &&
5138 depth != 24 && depth != 32)
5139 goto graphic_error;
5140 } else if (*p == '\0') {
5141 depth = graphic_depth;
5142 } else {
5143 goto graphic_error;
5146 graphic_width = w;
5147 graphic_height = h;
5148 graphic_depth = depth;
5150 break;
5151 #endif
5152 case QEMU_OPTION_echr:
5154 char *r;
5155 term_escape_char = strtol(optarg, &r, 0);
5156 if (r == optarg)
5157 printf("Bad argument to echr\n");
5158 break;
5160 case QEMU_OPTION_monitor:
5161 if (monitor_device_index >= MAX_MONITOR_DEVICES) {
5162 fprintf(stderr, "qemu: too many monitor devices\n");
5163 exit(1);
5165 monitor_devices[monitor_device_index] = optarg;
5166 monitor_device_index++;
5167 break;
5168 case QEMU_OPTION_chardev:
5169 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5170 if (!opts) {
5171 fprintf(stderr, "parse error: %s\n", optarg);
5172 exit(1);
5174 if (qemu_chr_open_opts(opts, NULL) == NULL) {
5175 exit(1);
5177 break;
5178 case QEMU_OPTION_serial:
5179 if (serial_device_index >= MAX_SERIAL_PORTS) {
5180 fprintf(stderr, "qemu: too many serial ports\n");
5181 exit(1);
5183 serial_devices[serial_device_index] = optarg;
5184 serial_device_index++;
5185 break;
5186 case QEMU_OPTION_watchdog:
5187 if (watchdog) {
5188 fprintf(stderr,
5189 "qemu: only one watchdog option may be given\n");
5190 return 1;
5192 watchdog = optarg;
5193 break;
5194 case QEMU_OPTION_watchdog_action:
5195 if (select_watchdog_action(optarg) == -1) {
5196 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5197 exit(1);
5199 break;
5200 case QEMU_OPTION_virtiocon:
5201 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5202 fprintf(stderr, "qemu: too many virtio consoles\n");
5203 exit(1);
5205 virtio_consoles[virtio_console_index] = optarg;
5206 virtio_console_index++;
5207 break;
5208 case QEMU_OPTION_parallel:
5209 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5210 fprintf(stderr, "qemu: too many parallel ports\n");
5211 exit(1);
5213 parallel_devices[parallel_device_index] = optarg;
5214 parallel_device_index++;
5215 break;
5216 case QEMU_OPTION_loadvm:
5217 loadvm = optarg;
5218 break;
5219 case QEMU_OPTION_full_screen:
5220 full_screen = 1;
5221 break;
5222 #ifdef CONFIG_SDL
5223 case QEMU_OPTION_no_frame:
5224 no_frame = 1;
5225 break;
5226 case QEMU_OPTION_alt_grab:
5227 alt_grab = 1;
5228 break;
5229 case QEMU_OPTION_ctrl_grab:
5230 ctrl_grab = 1;
5231 break;
5232 case QEMU_OPTION_no_quit:
5233 no_quit = 1;
5234 break;
5235 case QEMU_OPTION_sdl:
5236 display_type = DT_SDL;
5237 break;
5238 #endif
5239 case QEMU_OPTION_pidfile:
5240 pid_file = optarg;
5241 break;
5242 #ifdef TARGET_I386
5243 case QEMU_OPTION_win2k_hack:
5244 win2k_install_hack = 1;
5245 break;
5246 case QEMU_OPTION_rtc_td_hack:
5247 rtc_td_hack = 1;
5248 break;
5249 case QEMU_OPTION_acpitable:
5250 if(acpi_table_add(optarg) < 0) {
5251 fprintf(stderr, "Wrong acpi table provided\n");
5252 exit(1);
5254 break;
5255 case QEMU_OPTION_smbios:
5256 if(smbios_entry_add(optarg) < 0) {
5257 fprintf(stderr, "Wrong smbios provided\n");
5258 exit(1);
5260 break;
5261 #endif
5262 #ifdef CONFIG_KVM
5263 #ifdef KVM_UPSTREAM
5264 case QEMU_OPTION_enable_kvm:
5265 kvm_allowed = 1;
5266 #endif
5267 break;
5268 case QEMU_OPTION_no_kvm:
5269 kvm_allowed = 0;
5270 break;
5271 case QEMU_OPTION_no_kvm_irqchip: {
5272 kvm_irqchip = 0;
5273 kvm_pit = 0;
5274 break;
5276 case QEMU_OPTION_no_kvm_pit: {
5277 kvm_pit = 0;
5278 break;
5280 case QEMU_OPTION_no_kvm_pit_reinjection: {
5281 kvm_pit_reinject = 0;
5282 break;
5284 case QEMU_OPTION_enable_nesting: {
5285 kvm_nested = 1;
5286 break;
5288 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5289 case QEMU_OPTION_pcidevice:
5290 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5291 fprintf(stderr, "Too many assigned devices\n");
5292 exit(1);
5294 assigned_devices[assigned_devices_index] = optarg;
5295 assigned_devices_index++;
5296 break;
5297 #endif
5298 #endif
5299 case QEMU_OPTION_usb:
5300 usb_enabled = 1;
5301 break;
5302 case QEMU_OPTION_usbdevice:
5303 usb_enabled = 1;
5304 add_device_config(DEV_USB, optarg);
5305 break;
5306 case QEMU_OPTION_device:
5307 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5308 exit(1);
5310 break;
5311 case QEMU_OPTION_smp:
5312 smp_parse(optarg);
5313 if (smp_cpus < 1) {
5314 fprintf(stderr, "Invalid number of CPUs\n");
5315 exit(1);
5317 if (max_cpus < smp_cpus) {
5318 fprintf(stderr, "maxcpus must be equal to or greater than "
5319 "smp\n");
5320 exit(1);
5322 if (max_cpus > 255) {
5323 fprintf(stderr, "Unsupported number of maxcpus\n");
5324 exit(1);
5326 break;
5327 case QEMU_OPTION_vnc:
5328 display_type = DT_VNC;
5329 vnc_display = optarg;
5330 break;
5331 #ifdef TARGET_I386
5332 case QEMU_OPTION_no_acpi:
5333 acpi_enabled = 0;
5334 break;
5335 case QEMU_OPTION_no_hpet:
5336 no_hpet = 1;
5337 break;
5338 case QEMU_OPTION_balloon:
5339 if (balloon_parse(optarg) < 0) {
5340 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5341 exit(1);
5343 break;
5344 #endif
5345 case QEMU_OPTION_no_reboot:
5346 no_reboot = 1;
5347 break;
5348 case QEMU_OPTION_no_shutdown:
5349 no_shutdown = 1;
5350 break;
5351 case QEMU_OPTION_show_cursor:
5352 cursor_hide = 0;
5353 break;
5354 case QEMU_OPTION_uuid:
5355 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5356 fprintf(stderr, "Fail to parse UUID string."
5357 " Wrong format.\n");
5358 exit(1);
5360 break;
5361 #ifndef _WIN32
5362 case QEMU_OPTION_daemonize:
5363 daemonize = 1;
5364 break;
5365 #endif
5366 case QEMU_OPTION_option_rom:
5367 if (nb_option_roms >= MAX_OPTION_ROMS) {
5368 fprintf(stderr, "Too many option ROMs\n");
5369 exit(1);
5371 option_rom[nb_option_roms] = optarg;
5372 nb_option_roms++;
5373 break;
5374 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5375 case QEMU_OPTION_semihosting:
5376 semihosting_enabled = 1;
5377 break;
5378 #endif
5379 case QEMU_OPTION_tdf:
5380 time_drift_fix = 1;
5381 break;
5382 case QEMU_OPTION_kvm_shadow_memory:
5383 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5384 break;
5385 case QEMU_OPTION_mempath:
5386 mem_path = optarg;
5387 break;
5388 #ifdef MAP_POPULATE
5389 case QEMU_OPTION_mem_prealloc:
5390 mem_prealloc = !mem_prealloc;
5391 break;
5392 #endif
5393 case QEMU_OPTION_name:
5394 qemu_name = qemu_strdup(optarg);
5396 char *p = strchr(qemu_name, ',');
5397 if (p != NULL) {
5398 *p++ = 0;
5399 if (strncmp(p, "process=", 8)) {
5400 fprintf(stderr, "Unknown subargument %s to -name", p);
5401 exit(1);
5403 p += 8;
5404 set_proc_name(p);
5407 break;
5408 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5409 case QEMU_OPTION_prom_env:
5410 if (nb_prom_envs >= MAX_PROM_ENVS) {
5411 fprintf(stderr, "Too many prom variables\n");
5412 exit(1);
5414 prom_envs[nb_prom_envs] = optarg;
5415 nb_prom_envs++;
5416 break;
5417 #endif
5418 #ifdef TARGET_ARM
5419 case QEMU_OPTION_old_param:
5420 old_param = 1;
5421 break;
5422 #endif
5423 case QEMU_OPTION_clock:
5424 configure_alarms(optarg);
5425 break;
5426 case QEMU_OPTION_startdate:
5427 configure_rtc_date_offset(optarg, 1);
5428 break;
5429 case QEMU_OPTION_rtc:
5430 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5431 if (!opts) {
5432 fprintf(stderr, "parse error: %s\n", optarg);
5433 exit(1);
5435 configure_rtc(opts);
5436 break;
5437 case QEMU_OPTION_tb_size:
5438 tb_size = strtol(optarg, NULL, 0);
5439 if (tb_size < 0)
5440 tb_size = 0;
5441 break;
5442 case QEMU_OPTION_icount:
5443 use_icount = 1;
5444 if (strcmp(optarg, "auto") == 0) {
5445 icount_time_shift = -1;
5446 } else {
5447 icount_time_shift = strtol(optarg, NULL, 0);
5449 break;
5450 case QEMU_OPTION_incoming:
5451 incoming = optarg;
5452 break;
5453 #ifndef _WIN32
5454 case QEMU_OPTION_chroot:
5455 chroot_dir = optarg;
5456 break;
5457 case QEMU_OPTION_runas:
5458 run_as = optarg;
5459 break;
5460 case QEMU_OPTION_nvram:
5461 nvram = optarg;
5462 break;
5463 #endif
5464 #ifdef CONFIG_XEN
5465 case QEMU_OPTION_xen_domid:
5466 xen_domid = atoi(optarg);
5467 break;
5468 case QEMU_OPTION_xen_create:
5469 xen_mode = XEN_CREATE;
5470 break;
5471 case QEMU_OPTION_xen_attach:
5472 xen_mode = XEN_ATTACH;
5473 break;
5474 #endif
5475 case QEMU_OPTION_readconfig:
5477 FILE *fp;
5478 fp = fopen(optarg, "r");
5479 if (fp == NULL) {
5480 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5481 exit(1);
5483 if (qemu_config_parse(fp) != 0) {
5484 exit(1);
5486 fclose(fp);
5487 break;
5489 case QEMU_OPTION_writeconfig:
5491 FILE *fp;
5492 if (strcmp(optarg, "-") == 0) {
5493 fp = stdout;
5494 } else {
5495 fp = fopen(optarg, "w");
5496 if (fp == NULL) {
5497 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5498 exit(1);
5501 qemu_config_write(fp);
5502 fclose(fp);
5503 break;
5509 /* If no data_dir is specified then try to find it relative to the
5510 executable path. */
5511 if (!data_dir) {
5512 data_dir = find_datadir(argv[0]);
5514 /* If all else fails use the install patch specified when building. */
5515 if (!data_dir) {
5516 data_dir = CONFIG_QEMU_SHAREDIR;
5520 * Default to max_cpus = smp_cpus, in case the user doesn't
5521 * specify a max_cpus value.
5523 if (!max_cpus)
5524 max_cpus = smp_cpus;
5526 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5527 if (smp_cpus > machine->max_cpus) {
5528 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5529 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5530 machine->max_cpus);
5531 exit(1);
5534 if (display_type == DT_NOGRAPHIC) {
5535 if (serial_device_index == 0)
5536 serial_devices[0] = "stdio";
5537 if (parallel_device_index == 0)
5538 parallel_devices[0] = "null";
5539 if (strncmp(monitor_devices[0], "vc", 2) == 0) {
5540 monitor_devices[0] = "stdio";
5544 #ifndef _WIN32
5545 if (daemonize) {
5546 pid_t pid;
5548 if (pipe(fds) == -1)
5549 exit(1);
5551 pid = fork();
5552 if (pid > 0) {
5553 uint8_t status;
5554 ssize_t len;
5556 close(fds[1]);
5558 again:
5559 len = read(fds[0], &status, 1);
5560 if (len == -1 && (errno == EINTR))
5561 goto again;
5563 if (len != 1)
5564 exit(1);
5565 else if (status == 1) {
5566 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5567 exit(1);
5568 } else
5569 exit(0);
5570 } else if (pid < 0)
5571 exit(1);
5573 setsid();
5575 pid = fork();
5576 if (pid > 0)
5577 exit(0);
5578 else if (pid < 0)
5579 exit(1);
5581 umask(027);
5583 signal(SIGTSTP, SIG_IGN);
5584 signal(SIGTTOU, SIG_IGN);
5585 signal(SIGTTIN, SIG_IGN);
5588 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5589 if (daemonize) {
5590 uint8_t status = 1;
5591 write(fds[1], &status, 1);
5592 } else
5593 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5594 exit(1);
5596 #endif
5598 if (kvm_enabled()) {
5599 int ret;
5601 ret = kvm_init(smp_cpus);
5602 if (ret < 0) {
5603 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5604 fprintf(stderr, "failed to initialize KVM\n");
5605 exit(1);
5606 #endif
5607 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5608 kvm_allowed = 0;
5612 if (qemu_init_main_loop()) {
5613 fprintf(stderr, "qemu_init_main_loop failed\n");
5614 exit(1);
5616 linux_boot = (kernel_filename != NULL);
5618 if (!linux_boot && *kernel_cmdline != '\0') {
5619 fprintf(stderr, "-append only allowed with -kernel option\n");
5620 exit(1);
5623 if (!linux_boot && initrd_filename != NULL) {
5624 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5625 exit(1);
5628 #ifndef _WIN32
5629 /* Win32 doesn't support line-buffering and requires size >= 2 */
5630 setvbuf(stdout, NULL, _IOLBF, 0);
5631 #endif
5633 if (init_timer_alarm() < 0) {
5634 fprintf(stderr, "could not initialize alarm timer\n");
5635 exit(1);
5637 if (use_icount && icount_time_shift < 0) {
5638 use_icount = 2;
5639 /* 125MIPS seems a reasonable initial guess at the guest speed.
5640 It will be corrected fairly quickly anyway. */
5641 icount_time_shift = 3;
5642 init_icount_adjust();
5645 #ifdef _WIN32
5646 socket_init();
5647 #endif
5649 if (net_init_clients() < 0) {
5650 exit(1);
5653 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5654 net_set_boot_mask(net_boot);
5656 /* init the bluetooth world */
5657 if (foreach_device_config(DEV_BT, bt_parse))
5658 exit(1);
5660 /* init the memory */
5661 if (ram_size == 0)
5662 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5664 /* init the dynamic translator */
5665 cpu_exec_init_all(tb_size * 1024 * 1024);
5667 bdrv_init_with_whitelist();
5669 blk_mig_init();
5671 /* we always create the cdrom drive, even if no disk is there */
5672 drive_add(NULL, CDROM_ALIAS);
5674 /* we always create at least one floppy */
5675 drive_add(NULL, FD_ALIAS, 0);
5677 /* we always create one sd slot, even if no card is in it */
5678 drive_add(NULL, SD_ALIAS);
5680 /* open the virtual block devices */
5681 if (snapshot)
5682 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5683 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5684 exit(1);
5686 vmstate_register(0, &vmstate_timers ,&timers_state);
5687 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5688 ram_load, NULL);
5690 /* Maintain compatibility with multiple stdio monitors */
5691 if (!strcmp(monitor_devices[0],"stdio")) {
5692 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5693 const char *devname = serial_devices[i];
5694 if (devname && !strcmp(devname,"mon:stdio")) {
5695 monitor_devices[0] = NULL;
5696 break;
5697 } else if (devname && !strcmp(devname,"stdio")) {
5698 monitor_devices[0] = NULL;
5699 serial_devices[i] = "mon:stdio";
5700 break;
5705 if (nb_numa_nodes > 0) {
5706 int i;
5708 if (nb_numa_nodes > smp_cpus) {
5709 nb_numa_nodes = smp_cpus;
5712 /* If no memory size if given for any node, assume the default case
5713 * and distribute the available memory equally across all nodes
5715 for (i = 0; i < nb_numa_nodes; i++) {
5716 if (node_mem[i] != 0)
5717 break;
5719 if (i == nb_numa_nodes) {
5720 uint64_t usedmem = 0;
5722 /* On Linux, the each node's border has to be 8MB aligned,
5723 * the final node gets the rest.
5725 for (i = 0; i < nb_numa_nodes - 1; i++) {
5726 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5727 usedmem += node_mem[i];
5729 node_mem[i] = ram_size - usedmem;
5732 for (i = 0; i < nb_numa_nodes; i++) {
5733 if (node_cpumask[i] != 0)
5734 break;
5736 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5737 * must cope with this anyway, because there are BIOSes out there in
5738 * real machines which also use this scheme.
5740 if (i == nb_numa_nodes) {
5741 for (i = 0; i < smp_cpus; i++) {
5742 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5747 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5748 const char *devname = monitor_devices[i];
5749 if (devname && strcmp(devname, "none")) {
5750 char label[32];
5751 if (i == 0) {
5752 snprintf(label, sizeof(label), "monitor");
5753 } else {
5754 snprintf(label, sizeof(label), "monitor%d", i);
5756 monitor_hds[i] = qemu_chr_open(label, devname, NULL);
5757 if (!monitor_hds[i]) {
5758 fprintf(stderr, "qemu: could not open monitor device '%s'\n",
5759 devname);
5760 exit(1);
5765 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5766 const char *devname = serial_devices[i];
5767 if (devname && strcmp(devname, "none")) {
5768 char label[32];
5769 snprintf(label, sizeof(label), "serial%d", i);
5770 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5771 if (!serial_hds[i]) {
5772 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
5773 devname, strerror(errno));
5774 exit(1);
5779 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5780 const char *devname = parallel_devices[i];
5781 if (devname && strcmp(devname, "none")) {
5782 char label[32];
5783 snprintf(label, sizeof(label), "parallel%d", i);
5784 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5785 if (!parallel_hds[i]) {
5786 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
5787 devname, strerror(errno));
5788 exit(1);
5793 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5794 const char *devname = virtio_consoles[i];
5795 if (devname && strcmp(devname, "none")) {
5796 char label[32];
5797 snprintf(label, sizeof(label), "virtcon%d", i);
5798 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5799 if (!virtcon_hds[i]) {
5800 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
5801 devname, strerror(errno));
5802 exit(1);
5807 module_call_init(MODULE_INIT_DEVICE);
5809 if (watchdog) {
5810 i = select_watchdog(watchdog);
5811 if (i > 0)
5812 exit (i == 1 ? 1 : 0);
5815 if (machine->compat_props) {
5816 qdev_prop_register_compat(machine->compat_props);
5818 machine->init(ram_size, boot_devices,
5819 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5822 #ifndef _WIN32
5823 /* must be after terminal init, SDL library changes signal handlers */
5824 sighandler_setup();
5825 #endif
5827 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5828 for (i = 0; i < nb_numa_nodes; i++) {
5829 if (node_cpumask[i] & (1 << env->cpu_index)) {
5830 env->numa_node = i;
5835 current_machine = machine;
5837 /* init USB devices */
5838 if (usb_enabled) {
5839 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5840 exit(1);
5843 /* init generic devices */
5844 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5845 exit(1);
5847 if (!display_state)
5848 dumb_display_init();
5849 /* just use the first displaystate for the moment */
5850 ds = display_state;
5852 if (display_type == DT_DEFAULT) {
5853 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5854 display_type = DT_SDL;
5855 #else
5856 display_type = DT_VNC;
5857 vnc_display = "localhost:0,to=99";
5858 show_vnc_port = 1;
5859 #endif
5863 switch (display_type) {
5864 case DT_NOGRAPHIC:
5865 break;
5866 #if defined(CONFIG_CURSES)
5867 case DT_CURSES:
5868 curses_display_init(ds, full_screen);
5869 break;
5870 #endif
5871 #if defined(CONFIG_SDL)
5872 case DT_SDL:
5873 sdl_display_init(ds, full_screen, no_frame);
5874 break;
5875 #elif defined(CONFIG_COCOA)
5876 case DT_SDL:
5877 cocoa_display_init(ds, full_screen);
5878 break;
5879 #endif
5880 case DT_VNC:
5881 vnc_display_init(ds);
5882 if (vnc_display_open(ds, vnc_display) < 0)
5883 exit(1);
5885 if (show_vnc_port) {
5886 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5888 break;
5889 default:
5890 break;
5892 dpy_resize(ds);
5894 dcl = ds->listeners;
5895 while (dcl != NULL) {
5896 if (dcl->dpy_refresh != NULL) {
5897 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5898 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5900 dcl = dcl->next;
5903 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5904 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5905 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5908 text_consoles_set_display(display_state);
5910 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5911 if (monitor_devices[i] && monitor_hds[i]) {
5912 monitor_init(monitor_hds[i],
5913 MONITOR_USE_READLINE |
5914 ((i == 0) ? MONITOR_IS_DEFAULT : 0));
5918 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5919 const char *devname = serial_devices[i];
5920 if (devname && strcmp(devname, "none")) {
5921 if (strstart(devname, "vc", 0))
5922 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5926 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5927 const char *devname = parallel_devices[i];
5928 if (devname && strcmp(devname, "none")) {
5929 if (strstart(devname, "vc", 0))
5930 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5934 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5935 const char *devname = virtio_consoles[i];
5936 if (virtcon_hds[i] && devname) {
5937 if (strstart(devname, "vc", 0))
5938 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5942 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5943 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5944 gdbstub_dev);
5945 exit(1);
5948 qdev_machine_creation_done();
5950 rom_load_all();
5952 qemu_system_reset();
5953 if (loadvm) {
5954 if (load_vmstate(cur_mon, loadvm) < 0) {
5955 autostart = 0;
5959 if (incoming) {
5960 qemu_start_incoming_migration(incoming);
5961 } else if (autostart) {
5962 vm_start();
5965 #ifndef _WIN32
5966 if (daemonize) {
5967 uint8_t status = 0;
5968 ssize_t len;
5970 again1:
5971 len = write(fds[1], &status, 1);
5972 if (len == -1 && (errno == EINTR))
5973 goto again1;
5975 if (len != 1)
5976 exit(1);
5978 chdir("/");
5979 TFR(fd = open("/dev/null", O_RDWR));
5980 if (fd == -1)
5981 exit(1);
5984 if (run_as) {
5985 pwd = getpwnam(run_as);
5986 if (!pwd) {
5987 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5988 exit(1);
5992 if (chroot_dir) {
5993 if (chroot(chroot_dir) < 0) {
5994 fprintf(stderr, "chroot failed\n");
5995 exit(1);
5997 chdir("/");
6000 if (run_as) {
6001 if (setgid(pwd->pw_gid) < 0) {
6002 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6003 exit(1);
6005 if (setuid(pwd->pw_uid) < 0) {
6006 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6007 exit(1);
6009 if (setuid(0) != -1) {
6010 fprintf(stderr, "Dropping privileges failed\n");
6011 exit(1);
6015 if (daemonize) {
6016 dup2(fd, 0);
6017 dup2(fd, 1);
6018 dup2(fd, 2);
6020 close(fd);
6022 #endif
6024 main_loop();
6025 quit_timers();
6026 net_cleanup();
6028 return 0;