Merge commit '4c91cd28105485ae04b5cc9e5150e346fddf0874' into upstream-merge
[qemu-kvm/markmc.git] / vl.c
blob5dc7b2b08aef5a4742dbd9b4c60f33ea0be58ed4
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 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
49 #endif
50 #ifdef __linux__
51 #include <linux/if_tun.h>
52 #endif
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef CONFIG_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
60 #include <libutil.h>
61 #else
62 #include <util.h>
63 #endif
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
66 #else
67 #ifdef __linux__
68 #include <pty.h>
69 #include <malloc.h>
70 #include <linux/rtc.h>
71 #include <sys/prctl.h>
73 /* For the benefit of older linux systems which don't supply it,
74 we use a local copy of hpet.h. */
75 /* #include <linux/hpet.h> */
76 #include "hpet.h"
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
80 #endif
81 #ifdef __sun__
82 #include <sys/stat.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
92 #include <net/if.h>
93 #include <syslog.h>
94 #include <stropts.h>
95 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
96 discussion about Solaris header problems */
97 extern int madvise(caddr_t, size_t, int);
98 #endif
99 #endif
100 #endif
102 #if defined(__OpenBSD__)
103 #include <util.h>
104 #endif
106 #if defined(CONFIG_VDE)
107 #include <libvdeplug.h>
108 #endif
110 #ifdef _WIN32
111 #include <windows.h>
112 #include <mmsystem.h>
113 #endif
115 #ifdef CONFIG_SDL
116 #if defined(__APPLE__) || defined(main)
117 #include <SDL.h>
118 int qemu_main(int argc, char **argv, char **envp);
119 int main(int argc, char **argv)
121 return qemu_main(argc, argv, NULL);
123 #undef main
124 #define main qemu_main
125 #endif
126 #endif /* CONFIG_SDL */
128 #ifdef CONFIG_COCOA
129 #undef main
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
133 #include "hw/hw.h"
134 #include "hw/boards.h"
135 #include "hw/usb.h"
136 #include "hw/pcmcia.h"
137 #include "hw/pc.h"
138 #include "hw/audiodev.h"
139 #include "hw/isa.h"
140 #include "hw/baum.h"
141 #include "hw/bt.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
144 #include "hw/xen.h"
145 #include "hw/qdev.h"
146 #include "hw/loader.h"
147 #include "bt-host.h"
148 #include "net.h"
149 #include "monitor.h"
150 #include "console.h"
151 #include "sysemu.h"
152 #include "gdbstub.h"
153 #include "qemu-timer.h"
154 #include "qemu-char.h"
155 #include "cache-utils.h"
156 #include "block.h"
157 #include "dma.h"
158 #include "audio/audio.h"
159 #include "migration.h"
160 #include "kvm.h"
161 #include "balloon.h"
162 #include "qemu-option.h"
163 #include "qemu-config.h"
164 #include "qemu-kvm.h"
165 #include "hw/device-assignment.h"
167 #include "disas.h"
169 #include "exec-all.h"
171 #include "qemu_socket.h"
173 #include "slirp/libslirp.h"
175 #include "qemu-queue.h"
177 //#define DEBUG_NET
178 //#define DEBUG_SLIRP
180 #define DEFAULT_RAM_SIZE 128
182 /* Maximum number of monitor devices */
183 #define MAX_MONITOR_DEVICES 10
185 static const char *data_dir;
186 const char *bios_name = NULL;
187 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
188 to store the VM snapshots */
189 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
190 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
191 DriveInfo *extboot_drive = NULL;
192 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
193 static DisplayState *display_state;
194 DisplayType display_type = DT_DEFAULT;
195 const char* keyboard_layout = NULL;
196 ram_addr_t ram_size;
197 int nb_nics;
198 NICInfo nd_table[MAX_NICS];
199 int vm_running;
200 int autostart;
201 static int rtc_utc = 1;
202 static int rtc_date_offset = -1; /* -1 means no change */
203 QEMUClock *rtc_clock;
204 int vga_interface_type = VGA_CIRRUS;
205 #ifdef TARGET_SPARC
206 int graphic_width = 1024;
207 int graphic_height = 768;
208 int graphic_depth = 8;
209 #else
210 int graphic_width = 800;
211 int graphic_height = 600;
212 int graphic_depth = 15;
213 #endif
214 static int full_screen = 0;
215 #ifdef CONFIG_SDL
216 static int no_frame = 0;
217 #endif
218 int no_quit = 0;
219 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
220 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
221 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
222 #ifdef TARGET_I386
223 int win2k_install_hack = 0;
224 int rtc_td_hack = 0;
225 #endif
226 int usb_enabled = 0;
227 int singlestep = 0;
228 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
229 int assigned_devices_index;
230 int smp_cpus = 1;
231 int max_cpus = 0;
232 int smp_cores = 1;
233 int smp_threads = 1;
234 const char *vnc_display;
235 int acpi_enabled = 1;
236 #ifdef TARGET_I386
237 int no_hpet = 0;
238 #endif
239 int fd_bootchk = 1;
240 int no_reboot = 0;
241 int no_shutdown = 0;
242 int cursor_hide = 1;
243 int graphic_rotate = 0;
244 uint8_t irq0override = 1;
245 #ifndef _WIN32
246 int daemonize = 0;
247 #endif
248 const char *watchdog;
249 const char *option_rom[MAX_OPTION_ROMS];
250 int nb_option_roms;
251 int semihosting_enabled = 0;
252 int time_drift_fix = 0;
253 unsigned int kvm_shadow_memory = 0;
254 const char *mem_path = NULL;
255 #ifdef MAP_POPULATE
256 int mem_prealloc = 1; /* force preallocation of physical target memory */
257 #endif
258 #ifdef TARGET_ARM
259 int old_param = 0;
260 #endif
261 const char *qemu_name;
262 int alt_grab = 0;
263 int ctrl_grab = 0;
264 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
265 unsigned int nb_prom_envs = 0;
266 const char *prom_envs[MAX_PROM_ENVS];
267 #endif
268 const char *nvram = NULL;
269 int boot_menu;
271 int nb_numa_nodes;
272 uint64_t node_mem[MAX_NODES];
273 uint64_t node_cpumask[MAX_NODES];
275 static CPUState *cur_cpu;
276 static CPUState *next_cpu;
277 static int timer_alarm_pending = 1;
278 /* Conversion factor from emulated instructions to virtual clock ticks. */
279 static int icount_time_shift;
280 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
281 #define MAX_ICOUNT_SHIFT 10
282 /* Compensate for varying guest execution speed. */
283 static int64_t qemu_icount_bias;
284 static QEMUTimer *icount_rt_timer;
285 static QEMUTimer *icount_vm_timer;
286 static QEMUTimer *nographic_timer;
288 uint8_t qemu_uuid[16];
290 static QEMUBootSetHandler *boot_set_handler;
291 static void *boot_set_opaque;
293 /***********************************************************/
294 /* x86 ISA bus support */
296 target_phys_addr_t isa_mem_base = 0;
297 PicState2 *isa_pic;
299 /***********************************************************/
300 void hw_error(const char *fmt, ...)
302 va_list ap;
303 CPUState *env;
305 va_start(ap, fmt);
306 fprintf(stderr, "qemu: hardware error: ");
307 vfprintf(stderr, fmt, ap);
308 fprintf(stderr, "\n");
309 for(env = first_cpu; env != NULL; env = env->next_cpu) {
310 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
311 #ifdef TARGET_I386
312 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
313 #else
314 cpu_dump_state(env, stderr, fprintf, 0);
315 #endif
317 va_end(ap);
318 abort();
321 static void set_proc_name(const char *s)
323 #if defined(__linux__) && defined(PR_SET_NAME)
324 char name[16];
325 if (!s)
326 return;
327 name[sizeof(name) - 1] = 0;
328 strncpy(name, s, sizeof(name));
329 /* Could rewrite argv[0] too, but that's a bit more complicated.
330 This simple way is enough for `top'. */
331 prctl(PR_SET_NAME, name);
332 #endif
335 /***************/
336 /* ballooning */
338 static QEMUBalloonEvent *qemu_balloon_event;
339 void *qemu_balloon_event_opaque;
341 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
343 qemu_balloon_event = func;
344 qemu_balloon_event_opaque = opaque;
347 void qemu_balloon(ram_addr_t target)
349 if (qemu_balloon_event)
350 qemu_balloon_event(qemu_balloon_event_opaque, target);
353 ram_addr_t qemu_balloon_status(void)
355 if (qemu_balloon_event)
356 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
357 return 0;
360 /***********************************************************/
361 /* keyboard/mouse */
363 static QEMUPutKBDEvent *qemu_put_kbd_event;
364 static void *qemu_put_kbd_event_opaque;
365 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
366 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
368 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
370 qemu_put_kbd_event_opaque = opaque;
371 qemu_put_kbd_event = func;
374 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
375 void *opaque, int absolute,
376 const char *name)
378 QEMUPutMouseEntry *s, *cursor;
380 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
382 s->qemu_put_mouse_event = func;
383 s->qemu_put_mouse_event_opaque = opaque;
384 s->qemu_put_mouse_event_absolute = absolute;
385 s->qemu_put_mouse_event_name = qemu_strdup(name);
386 s->next = NULL;
388 if (!qemu_put_mouse_event_head) {
389 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
390 return s;
393 cursor = qemu_put_mouse_event_head;
394 while (cursor->next != NULL)
395 cursor = cursor->next;
397 cursor->next = s;
398 qemu_put_mouse_event_current = s;
400 return s;
403 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
405 QEMUPutMouseEntry *prev = NULL, *cursor;
407 if (!qemu_put_mouse_event_head || entry == NULL)
408 return;
410 cursor = qemu_put_mouse_event_head;
411 while (cursor != NULL && cursor != entry) {
412 prev = cursor;
413 cursor = cursor->next;
416 if (cursor == NULL) // does not exist or list empty
417 return;
418 else if (prev == NULL) { // entry is head
419 qemu_put_mouse_event_head = cursor->next;
420 if (qemu_put_mouse_event_current == entry)
421 qemu_put_mouse_event_current = cursor->next;
422 qemu_free(entry->qemu_put_mouse_event_name);
423 qemu_free(entry);
424 return;
427 prev->next = entry->next;
429 if (qemu_put_mouse_event_current == entry)
430 qemu_put_mouse_event_current = prev;
432 qemu_free(entry->qemu_put_mouse_event_name);
433 qemu_free(entry);
436 void kbd_put_keycode(int keycode)
438 if (qemu_put_kbd_event) {
439 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
443 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
445 QEMUPutMouseEvent *mouse_event;
446 void *mouse_event_opaque;
447 int width;
449 if (!qemu_put_mouse_event_current) {
450 return;
453 mouse_event =
454 qemu_put_mouse_event_current->qemu_put_mouse_event;
455 mouse_event_opaque =
456 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
458 if (mouse_event) {
459 if (graphic_rotate) {
460 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
461 width = 0x7fff;
462 else
463 width = graphic_width - 1;
464 mouse_event(mouse_event_opaque,
465 width - dy, dx, dz, buttons_state);
466 } else
467 mouse_event(mouse_event_opaque,
468 dx, dy, dz, buttons_state);
472 int kbd_mouse_is_absolute(void)
474 if (!qemu_put_mouse_event_current)
475 return 0;
477 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
480 void do_info_mice(Monitor *mon)
482 QEMUPutMouseEntry *cursor;
483 int index = 0;
485 if (!qemu_put_mouse_event_head) {
486 monitor_printf(mon, "No mouse devices connected\n");
487 return;
490 monitor_printf(mon, "Mouse devices available:\n");
491 cursor = qemu_put_mouse_event_head;
492 while (cursor != NULL) {
493 monitor_printf(mon, "%c Mouse #%d: %s\n",
494 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
495 index, cursor->qemu_put_mouse_event_name);
496 index++;
497 cursor = cursor->next;
501 void do_mouse_set(Monitor *mon, const QDict *qdict)
503 QEMUPutMouseEntry *cursor;
504 int i = 0;
505 int index = qdict_get_int(qdict, "index");
507 if (!qemu_put_mouse_event_head) {
508 monitor_printf(mon, "No mouse devices connected\n");
509 return;
512 cursor = qemu_put_mouse_event_head;
513 while (cursor != NULL && index != i) {
514 i++;
515 cursor = cursor->next;
518 if (cursor != NULL)
519 qemu_put_mouse_event_current = cursor;
520 else
521 monitor_printf(mon, "Mouse at given index not found\n");
524 /* compute with 96 bit intermediate result: (a*b)/c */
525 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
527 union {
528 uint64_t ll;
529 struct {
530 #ifdef HOST_WORDS_BIGENDIAN
531 uint32_t high, low;
532 #else
533 uint32_t low, high;
534 #endif
535 } l;
536 } u, res;
537 uint64_t rl, rh;
539 u.ll = a;
540 rl = (uint64_t)u.l.low * (uint64_t)b;
541 rh = (uint64_t)u.l.high * (uint64_t)b;
542 rh += (rl >> 32);
543 res.l.high = rh / c;
544 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
545 return res.ll;
548 /***********************************************************/
549 /* real time host monotonic timer */
551 static int64_t get_clock_realtime(void)
553 struct timeval tv;
555 gettimeofday(&tv, NULL);
556 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
559 #ifdef WIN32
561 static int64_t clock_freq;
563 static void init_get_clock(void)
565 LARGE_INTEGER freq;
566 int ret;
567 ret = QueryPerformanceFrequency(&freq);
568 if (ret == 0) {
569 fprintf(stderr, "Could not calibrate ticks\n");
570 exit(1);
572 clock_freq = freq.QuadPart;
575 static int64_t get_clock(void)
577 LARGE_INTEGER ti;
578 QueryPerformanceCounter(&ti);
579 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
582 #else
584 static int use_rt_clock;
586 static void init_get_clock(void)
588 use_rt_clock = 0;
589 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
590 || defined(__DragonFly__)
592 struct timespec ts;
593 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
594 use_rt_clock = 1;
597 #endif
600 static int64_t get_clock(void)
602 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
603 || defined(__DragonFly__)
604 if (use_rt_clock) {
605 struct timespec ts;
606 clock_gettime(CLOCK_MONOTONIC, &ts);
607 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
608 } else
609 #endif
611 /* XXX: using gettimeofday leads to problems if the date
612 changes, so it should be avoided. */
613 return get_clock_realtime();
616 #endif
618 /* Return the virtual CPU time, based on the instruction counter. */
619 static int64_t cpu_get_icount(void)
621 int64_t icount;
622 CPUState *env = cpu_single_env;;
623 icount = qemu_icount;
624 if (env) {
625 if (!can_do_io(env))
626 fprintf(stderr, "Bad clock read\n");
627 icount -= (env->icount_decr.u16.low + env->icount_extra);
629 return qemu_icount_bias + (icount << icount_time_shift);
632 /***********************************************************/
633 /* guest cycle counter */
635 typedef struct TimersState {
636 int64_t cpu_ticks_prev;
637 int64_t cpu_ticks_offset;
638 int64_t cpu_clock_offset;
639 int32_t cpu_ticks_enabled;
640 int64_t dummy;
641 } TimersState;
643 TimersState timers_state;
645 /* return the host CPU cycle counter and handle stop/restart */
646 int64_t cpu_get_ticks(void)
648 if (use_icount) {
649 return cpu_get_icount();
651 if (!timers_state.cpu_ticks_enabled) {
652 return timers_state.cpu_ticks_offset;
653 } else {
654 int64_t ticks;
655 ticks = cpu_get_real_ticks();
656 if (timers_state.cpu_ticks_prev > ticks) {
657 /* Note: non increasing ticks may happen if the host uses
658 software suspend */
659 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
661 timers_state.cpu_ticks_prev = ticks;
662 return ticks + timers_state.cpu_ticks_offset;
666 /* return the host CPU monotonic timer and handle stop/restart */
667 static int64_t cpu_get_clock(void)
669 int64_t ti;
670 if (!timers_state.cpu_ticks_enabled) {
671 return timers_state.cpu_clock_offset;
672 } else {
673 ti = get_clock();
674 return ti + timers_state.cpu_clock_offset;
678 /* enable cpu_get_ticks() */
679 void cpu_enable_ticks(void)
681 if (!timers_state.cpu_ticks_enabled) {
682 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
683 timers_state.cpu_clock_offset -= get_clock();
684 timers_state.cpu_ticks_enabled = 1;
688 /* disable cpu_get_ticks() : the clock is stopped. You must not call
689 cpu_get_ticks() after that. */
690 void cpu_disable_ticks(void)
692 if (timers_state.cpu_ticks_enabled) {
693 timers_state.cpu_ticks_offset = cpu_get_ticks();
694 timers_state.cpu_clock_offset = cpu_get_clock();
695 timers_state.cpu_ticks_enabled = 0;
699 /***********************************************************/
700 /* timers */
702 #define QEMU_CLOCK_REALTIME 0
703 #define QEMU_CLOCK_VIRTUAL 1
704 #define QEMU_CLOCK_HOST 2
706 struct QEMUClock {
707 int type;
708 /* XXX: add frequency */
711 struct QEMUTimer {
712 QEMUClock *clock;
713 int64_t expire_time;
714 QEMUTimerCB *cb;
715 void *opaque;
716 struct QEMUTimer *next;
719 struct qemu_alarm_timer {
720 char const *name;
721 unsigned int flags;
723 int (*start)(struct qemu_alarm_timer *t);
724 void (*stop)(struct qemu_alarm_timer *t);
725 void (*rearm)(struct qemu_alarm_timer *t);
726 void *priv;
729 #define ALARM_FLAG_DYNTICKS 0x1
730 #define ALARM_FLAG_EXPIRED 0x2
732 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
734 return t && (t->flags & ALARM_FLAG_DYNTICKS);
737 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
739 if (!alarm_has_dynticks(t))
740 return;
742 t->rearm(t);
745 /* TODO: MIN_TIMER_REARM_US should be optimized */
746 #define MIN_TIMER_REARM_US 250
748 static struct qemu_alarm_timer *alarm_timer;
750 #ifdef _WIN32
752 struct qemu_alarm_win32 {
753 MMRESULT timerId;
754 unsigned int period;
755 } alarm_win32_data = {0, -1};
757 static int win32_start_timer(struct qemu_alarm_timer *t);
758 static void win32_stop_timer(struct qemu_alarm_timer *t);
759 static void win32_rearm_timer(struct qemu_alarm_timer *t);
761 #else
763 static int unix_start_timer(struct qemu_alarm_timer *t);
764 static void unix_stop_timer(struct qemu_alarm_timer *t);
766 #ifdef __linux__
768 static int dynticks_start_timer(struct qemu_alarm_timer *t);
769 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
770 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
772 static int hpet_start_timer(struct qemu_alarm_timer *t);
773 static void hpet_stop_timer(struct qemu_alarm_timer *t);
775 static int rtc_start_timer(struct qemu_alarm_timer *t);
776 static void rtc_stop_timer(struct qemu_alarm_timer *t);
778 #endif /* __linux__ */
780 #endif /* _WIN32 */
782 /* Correlation between real and virtual time is always going to be
783 fairly approximate, so ignore small variation.
784 When the guest is idle real and virtual time will be aligned in
785 the IO wait loop. */
786 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
788 static void icount_adjust(void)
790 int64_t cur_time;
791 int64_t cur_icount;
792 int64_t delta;
793 static int64_t last_delta;
794 /* If the VM is not running, then do nothing. */
795 if (!vm_running)
796 return;
798 cur_time = cpu_get_clock();
799 cur_icount = qemu_get_clock(vm_clock);
800 delta = cur_icount - cur_time;
801 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
802 if (delta > 0
803 && last_delta + ICOUNT_WOBBLE < delta * 2
804 && icount_time_shift > 0) {
805 /* The guest is getting too far ahead. Slow time down. */
806 icount_time_shift--;
808 if (delta < 0
809 && last_delta - ICOUNT_WOBBLE > delta * 2
810 && icount_time_shift < MAX_ICOUNT_SHIFT) {
811 /* The guest is getting too far behind. Speed time up. */
812 icount_time_shift++;
814 last_delta = delta;
815 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
818 static void icount_adjust_rt(void * opaque)
820 qemu_mod_timer(icount_rt_timer,
821 qemu_get_clock(rt_clock) + 1000);
822 icount_adjust();
825 static void icount_adjust_vm(void * opaque)
827 qemu_mod_timer(icount_vm_timer,
828 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
829 icount_adjust();
832 static void init_icount_adjust(void)
834 /* Have both realtime and virtual time triggers for speed adjustment.
835 The realtime trigger catches emulated time passing too slowly,
836 the virtual time trigger catches emulated time passing too fast.
837 Realtime triggers occur even when idle, so use them less frequently
838 than VM triggers. */
839 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
840 qemu_mod_timer(icount_rt_timer,
841 qemu_get_clock(rt_clock) + 1000);
842 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
843 qemu_mod_timer(icount_vm_timer,
844 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
847 static struct qemu_alarm_timer alarm_timers[] = {
848 #ifndef _WIN32
849 #ifdef __linux__
850 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
851 dynticks_stop_timer, dynticks_rearm_timer, NULL},
852 /* HPET - if available - is preferred */
853 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
854 /* ...otherwise try RTC */
855 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
856 #endif
857 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
858 #else
859 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
860 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
861 {"win32", 0, win32_start_timer,
862 win32_stop_timer, NULL, &alarm_win32_data},
863 #endif
864 {NULL, }
867 static void show_available_alarms(void)
869 int i;
871 printf("Available alarm timers, in order of precedence:\n");
872 for (i = 0; alarm_timers[i].name; i++)
873 printf("%s\n", alarm_timers[i].name);
876 static void configure_alarms(char const *opt)
878 int i;
879 int cur = 0;
880 int count = ARRAY_SIZE(alarm_timers) - 1;
881 char *arg;
882 char *name;
883 struct qemu_alarm_timer tmp;
885 if (!strcmp(opt, "?")) {
886 show_available_alarms();
887 exit(0);
890 arg = qemu_strdup(opt);
892 /* Reorder the array */
893 name = strtok(arg, ",");
894 while (name) {
895 for (i = 0; i < count && alarm_timers[i].name; i++) {
896 if (!strcmp(alarm_timers[i].name, name))
897 break;
900 if (i == count) {
901 fprintf(stderr, "Unknown clock %s\n", name);
902 goto next;
905 if (i < cur)
906 /* Ignore */
907 goto next;
909 /* Swap */
910 tmp = alarm_timers[i];
911 alarm_timers[i] = alarm_timers[cur];
912 alarm_timers[cur] = tmp;
914 cur++;
915 next:
916 name = strtok(NULL, ",");
919 qemu_free(arg);
921 if (cur) {
922 /* Disable remaining timers */
923 for (i = cur; i < count; i++)
924 alarm_timers[i].name = NULL;
925 } else {
926 show_available_alarms();
927 exit(1);
931 #define QEMU_NUM_CLOCKS 3
933 QEMUClock *rt_clock;
934 QEMUClock *vm_clock;
935 QEMUClock *host_clock;
937 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
939 static QEMUClock *qemu_new_clock(int type)
941 QEMUClock *clock;
942 clock = qemu_mallocz(sizeof(QEMUClock));
943 clock->type = type;
944 return clock;
947 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
949 QEMUTimer *ts;
951 ts = qemu_mallocz(sizeof(QEMUTimer));
952 ts->clock = clock;
953 ts->cb = cb;
954 ts->opaque = opaque;
955 return ts;
958 void qemu_free_timer(QEMUTimer *ts)
960 qemu_free(ts);
963 /* stop a timer, but do not dealloc it */
964 void qemu_del_timer(QEMUTimer *ts)
966 QEMUTimer **pt, *t;
968 /* NOTE: this code must be signal safe because
969 qemu_timer_expired() can be called from a signal. */
970 pt = &active_timers[ts->clock->type];
971 for(;;) {
972 t = *pt;
973 if (!t)
974 break;
975 if (t == ts) {
976 *pt = t->next;
977 break;
979 pt = &t->next;
983 /* modify the current timer so that it will be fired when current_time
984 >= expire_time. The corresponding callback will be called. */
985 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
987 QEMUTimer **pt, *t;
989 qemu_del_timer(ts);
991 /* add the timer in the sorted list */
992 /* NOTE: this code must be signal safe because
993 qemu_timer_expired() can be called from a signal. */
994 pt = &active_timers[ts->clock->type];
995 for(;;) {
996 t = *pt;
997 if (!t)
998 break;
999 if (t->expire_time > expire_time)
1000 break;
1001 pt = &t->next;
1003 ts->expire_time = expire_time;
1004 ts->next = *pt;
1005 *pt = ts;
1007 /* Rearm if necessary */
1008 if (pt == &active_timers[ts->clock->type]) {
1009 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1010 qemu_rearm_alarm_timer(alarm_timer);
1012 /* Interrupt execution to force deadline recalculation. */
1013 if (use_icount)
1014 qemu_notify_event();
1018 int qemu_timer_pending(QEMUTimer *ts)
1020 QEMUTimer *t;
1021 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1022 if (t == ts)
1023 return 1;
1025 return 0;
1028 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1030 if (!timer_head)
1031 return 0;
1032 return (timer_head->expire_time <= current_time);
1035 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1037 QEMUTimer *ts;
1039 for(;;) {
1040 ts = *ptimer_head;
1041 if (!ts || ts->expire_time > current_time)
1042 break;
1043 /* remove timer from the list before calling the callback */
1044 *ptimer_head = ts->next;
1045 ts->next = NULL;
1047 /* run the callback (the timer list can be modified) */
1048 ts->cb(ts->opaque);
1052 int64_t qemu_get_clock(QEMUClock *clock)
1054 switch(clock->type) {
1055 case QEMU_CLOCK_REALTIME:
1056 return get_clock() / 1000000;
1057 default:
1058 case QEMU_CLOCK_VIRTUAL:
1059 if (use_icount) {
1060 return cpu_get_icount();
1061 } else {
1062 return cpu_get_clock();
1064 case QEMU_CLOCK_HOST:
1065 return get_clock_realtime();
1069 static void init_clocks(void)
1071 init_get_clock();
1072 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
1073 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
1074 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
1076 rtc_clock = host_clock;
1079 /* save a timer */
1080 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1082 uint64_t expire_time;
1084 if (qemu_timer_pending(ts)) {
1085 expire_time = ts->expire_time;
1086 } else {
1087 expire_time = -1;
1089 qemu_put_be64(f, expire_time);
1092 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1094 uint64_t expire_time;
1096 expire_time = qemu_get_be64(f);
1097 if (expire_time != -1) {
1098 qemu_mod_timer(ts, expire_time);
1099 } else {
1100 qemu_del_timer(ts);
1104 static const VMStateDescription vmstate_timers = {
1105 .name = "timer",
1106 .version_id = 2,
1107 .minimum_version_id = 1,
1108 .minimum_version_id_old = 1,
1109 .fields = (VMStateField []) {
1110 VMSTATE_INT64(cpu_ticks_offset, TimersState),
1111 VMSTATE_INT64(dummy, TimersState),
1112 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1113 VMSTATE_END_OF_LIST()
1117 static void qemu_event_increment(void);
1119 #ifdef _WIN32
1120 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1121 DWORD_PTR dwUser, DWORD_PTR dw1,
1122 DWORD_PTR dw2)
1123 #else
1124 static void host_alarm_handler(int host_signum)
1125 #endif
1127 #if 0
1128 #define DISP_FREQ 1000
1130 static int64_t delta_min = INT64_MAX;
1131 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1132 static int count;
1133 ti = qemu_get_clock(vm_clock);
1134 if (last_clock != 0) {
1135 delta = ti - last_clock;
1136 if (delta < delta_min)
1137 delta_min = delta;
1138 if (delta > delta_max)
1139 delta_max = delta;
1140 delta_cum += delta;
1141 if (++count == DISP_FREQ) {
1142 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1143 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1144 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1145 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1146 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1147 count = 0;
1148 delta_min = INT64_MAX;
1149 delta_max = 0;
1150 delta_cum = 0;
1153 last_clock = ti;
1155 #endif
1156 if (alarm_has_dynticks(alarm_timer) ||
1157 (!use_icount &&
1158 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1159 qemu_get_clock(vm_clock))) ||
1160 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1161 qemu_get_clock(rt_clock)) ||
1162 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1163 qemu_get_clock(host_clock))) {
1164 qemu_event_increment();
1165 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1167 #ifndef CONFIG_IOTHREAD
1168 if (next_cpu) {
1169 /* stop the currently executing cpu because a timer occured */
1170 cpu_exit(next_cpu);
1172 #endif
1173 timer_alarm_pending = 1;
1174 qemu_notify_event();
1178 static int64_t qemu_next_deadline(void)
1180 /* To avoid problems with overflow limit this to 2^32. */
1181 int64_t delta = INT32_MAX;
1183 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1184 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1185 qemu_get_clock(vm_clock);
1187 if (active_timers[QEMU_CLOCK_HOST]) {
1188 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1189 qemu_get_clock(host_clock);
1190 if (hdelta < delta)
1191 delta = hdelta;
1194 if (delta < 0)
1195 delta = 0;
1197 return delta;
1200 #if defined(__linux__)
1201 static uint64_t qemu_next_deadline_dyntick(void)
1203 int64_t delta;
1204 int64_t rtdelta;
1206 if (use_icount)
1207 delta = INT32_MAX;
1208 else
1209 delta = (qemu_next_deadline() + 999) / 1000;
1211 if (active_timers[QEMU_CLOCK_REALTIME]) {
1212 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1213 qemu_get_clock(rt_clock))*1000;
1214 if (rtdelta < delta)
1215 delta = rtdelta;
1218 if (delta < MIN_TIMER_REARM_US)
1219 delta = MIN_TIMER_REARM_US;
1221 return delta;
1223 #endif
1225 #ifndef _WIN32
1227 /* Sets a specific flag */
1228 static int fcntl_setfl(int fd, int flag)
1230 int flags;
1232 flags = fcntl(fd, F_GETFL);
1233 if (flags == -1)
1234 return -errno;
1236 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1237 return -errno;
1239 return 0;
1242 #if defined(__linux__)
1244 #define RTC_FREQ 1024
1246 static void enable_sigio_timer(int fd)
1248 struct sigaction act;
1250 /* timer signal */
1251 sigfillset(&act.sa_mask);
1252 act.sa_flags = 0;
1253 act.sa_handler = host_alarm_handler;
1255 sigaction(SIGIO, &act, NULL);
1256 fcntl_setfl(fd, O_ASYNC);
1257 fcntl(fd, F_SETOWN, getpid());
1260 static int hpet_start_timer(struct qemu_alarm_timer *t)
1262 struct hpet_info info;
1263 int r, fd;
1265 fd = open("/dev/hpet", O_RDONLY);
1266 if (fd < 0)
1267 return -1;
1269 /* Set frequency */
1270 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1271 if (r < 0) {
1272 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1273 "error, but for better emulation accuracy type:\n"
1274 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1275 goto fail;
1278 /* Check capabilities */
1279 r = ioctl(fd, HPET_INFO, &info);
1280 if (r < 0)
1281 goto fail;
1283 /* Enable periodic mode */
1284 r = ioctl(fd, HPET_EPI, 0);
1285 if (info.hi_flags && (r < 0))
1286 goto fail;
1288 /* Enable interrupt */
1289 r = ioctl(fd, HPET_IE_ON, 0);
1290 if (r < 0)
1291 goto fail;
1293 enable_sigio_timer(fd);
1294 t->priv = (void *)(long)fd;
1296 return 0;
1297 fail:
1298 close(fd);
1299 return -1;
1302 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1304 int fd = (long)t->priv;
1306 close(fd);
1309 static int rtc_start_timer(struct qemu_alarm_timer *t)
1311 int rtc_fd;
1312 unsigned long current_rtc_freq = 0;
1314 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1315 if (rtc_fd < 0)
1316 return -1;
1317 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1318 if (current_rtc_freq != RTC_FREQ &&
1319 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1320 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1321 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1322 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1323 goto fail;
1325 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1326 fail:
1327 close(rtc_fd);
1328 return -1;
1331 enable_sigio_timer(rtc_fd);
1333 t->priv = (void *)(long)rtc_fd;
1335 return 0;
1338 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1340 int rtc_fd = (long)t->priv;
1342 close(rtc_fd);
1345 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1347 struct sigevent ev;
1348 timer_t host_timer;
1349 struct sigaction act;
1351 sigfillset(&act.sa_mask);
1352 act.sa_flags = 0;
1353 act.sa_handler = host_alarm_handler;
1355 sigaction(SIGALRM, &act, NULL);
1358 * Initialize ev struct to 0 to avoid valgrind complaining
1359 * about uninitialized data in timer_create call
1361 memset(&ev, 0, sizeof(ev));
1362 ev.sigev_value.sival_int = 0;
1363 ev.sigev_notify = SIGEV_SIGNAL;
1364 ev.sigev_signo = SIGALRM;
1366 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1367 perror("timer_create");
1369 /* disable dynticks */
1370 fprintf(stderr, "Dynamic Ticks disabled\n");
1372 return -1;
1375 t->priv = (void *)(long)host_timer;
1377 return 0;
1380 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1382 timer_t host_timer = (timer_t)(long)t->priv;
1384 timer_delete(host_timer);
1387 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1389 timer_t host_timer = (timer_t)(long)t->priv;
1390 struct itimerspec timeout;
1391 int64_t nearest_delta_us = INT64_MAX;
1392 int64_t current_us;
1394 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1395 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1396 !active_timers[QEMU_CLOCK_HOST])
1397 return;
1399 nearest_delta_us = qemu_next_deadline_dyntick();
1401 /* check whether a timer is already running */
1402 if (timer_gettime(host_timer, &timeout)) {
1403 perror("gettime");
1404 fprintf(stderr, "Internal timer error: aborting\n");
1405 exit(1);
1407 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1408 if (current_us && current_us <= nearest_delta_us)
1409 return;
1411 timeout.it_interval.tv_sec = 0;
1412 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1413 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1414 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1415 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1416 perror("settime");
1417 fprintf(stderr, "Internal timer error: aborting\n");
1418 exit(1);
1422 #endif /* defined(__linux__) */
1424 static int unix_start_timer(struct qemu_alarm_timer *t)
1426 struct sigaction act;
1427 struct itimerval itv;
1428 int err;
1430 /* timer signal */
1431 sigfillset(&act.sa_mask);
1432 act.sa_flags = 0;
1433 act.sa_handler = host_alarm_handler;
1435 sigaction(SIGALRM, &act, NULL);
1437 itv.it_interval.tv_sec = 0;
1438 /* for i386 kernel 2.6 to get 1 ms */
1439 itv.it_interval.tv_usec = 999;
1440 itv.it_value.tv_sec = 0;
1441 itv.it_value.tv_usec = 10 * 1000;
1443 err = setitimer(ITIMER_REAL, &itv, NULL);
1444 if (err)
1445 return -1;
1447 return 0;
1450 static void unix_stop_timer(struct qemu_alarm_timer *t)
1452 struct itimerval itv;
1454 memset(&itv, 0, sizeof(itv));
1455 setitimer(ITIMER_REAL, &itv, NULL);
1458 #endif /* !defined(_WIN32) */
1461 #ifdef _WIN32
1463 static int win32_start_timer(struct qemu_alarm_timer *t)
1465 TIMECAPS tc;
1466 struct qemu_alarm_win32 *data = t->priv;
1467 UINT flags;
1469 memset(&tc, 0, sizeof(tc));
1470 timeGetDevCaps(&tc, sizeof(tc));
1472 if (data->period < tc.wPeriodMin)
1473 data->period = tc.wPeriodMin;
1475 timeBeginPeriod(data->period);
1477 flags = TIME_CALLBACK_FUNCTION;
1478 if (alarm_has_dynticks(t))
1479 flags |= TIME_ONESHOT;
1480 else
1481 flags |= TIME_PERIODIC;
1483 data->timerId = timeSetEvent(1, // interval (ms)
1484 data->period, // resolution
1485 host_alarm_handler, // function
1486 (DWORD)t, // parameter
1487 flags);
1489 if (!data->timerId) {
1490 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1491 GetLastError());
1492 timeEndPeriod(data->period);
1493 return -1;
1496 return 0;
1499 static void win32_stop_timer(struct qemu_alarm_timer *t)
1501 struct qemu_alarm_win32 *data = t->priv;
1503 timeKillEvent(data->timerId);
1504 timeEndPeriod(data->period);
1507 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1509 struct qemu_alarm_win32 *data = t->priv;
1511 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1512 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1513 !active_timers[QEMU_CLOCK_HOST])
1514 return;
1516 timeKillEvent(data->timerId);
1518 data->timerId = timeSetEvent(1,
1519 data->period,
1520 host_alarm_handler,
1521 (DWORD)t,
1522 TIME_ONESHOT | TIME_PERIODIC);
1524 if (!data->timerId) {
1525 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1526 GetLastError());
1528 timeEndPeriod(data->period);
1529 exit(1);
1533 #endif /* _WIN32 */
1535 static int init_timer_alarm(void)
1537 struct qemu_alarm_timer *t = NULL;
1538 int i, err = -1;
1540 for (i = 0; alarm_timers[i].name; i++) {
1541 t = &alarm_timers[i];
1543 err = t->start(t);
1544 if (!err)
1545 break;
1548 if (err) {
1549 err = -ENOENT;
1550 goto fail;
1553 alarm_timer = t;
1555 return 0;
1557 fail:
1558 return err;
1561 static void quit_timers(void)
1563 alarm_timer->stop(alarm_timer);
1564 alarm_timer = NULL;
1567 /***********************************************************/
1568 /* host time/date access */
1569 void qemu_get_timedate(struct tm *tm, int offset)
1571 time_t ti;
1572 struct tm *ret;
1574 time(&ti);
1575 ti += offset;
1576 if (rtc_date_offset == -1) {
1577 if (rtc_utc)
1578 ret = gmtime(&ti);
1579 else
1580 ret = localtime(&ti);
1581 } else {
1582 ti -= rtc_date_offset;
1583 ret = gmtime(&ti);
1586 memcpy(tm, ret, sizeof(struct tm));
1589 int qemu_timedate_diff(struct tm *tm)
1591 time_t seconds;
1593 if (rtc_date_offset == -1)
1594 if (rtc_utc)
1595 seconds = mktimegm(tm);
1596 else
1597 seconds = mktime(tm);
1598 else
1599 seconds = mktimegm(tm) + rtc_date_offset;
1601 return seconds - time(NULL);
1604 static void configure_rtc_date_offset(const char *startdate, int legacy)
1606 time_t rtc_start_date;
1607 struct tm tm;
1609 if (!strcmp(startdate, "now") && legacy) {
1610 rtc_date_offset = -1;
1611 } else {
1612 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1613 &tm.tm_year,
1614 &tm.tm_mon,
1615 &tm.tm_mday,
1616 &tm.tm_hour,
1617 &tm.tm_min,
1618 &tm.tm_sec) == 6) {
1619 /* OK */
1620 } else if (sscanf(startdate, "%d-%d-%d",
1621 &tm.tm_year,
1622 &tm.tm_mon,
1623 &tm.tm_mday) == 3) {
1624 tm.tm_hour = 0;
1625 tm.tm_min = 0;
1626 tm.tm_sec = 0;
1627 } else {
1628 goto date_fail;
1630 tm.tm_year -= 1900;
1631 tm.tm_mon--;
1632 rtc_start_date = mktimegm(&tm);
1633 if (rtc_start_date == -1) {
1634 date_fail:
1635 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1636 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1637 exit(1);
1639 rtc_date_offset = time(NULL) - rtc_start_date;
1643 static void configure_rtc(QemuOpts *opts)
1645 const char *value;
1647 value = qemu_opt_get(opts, "base");
1648 if (value) {
1649 if (!strcmp(value, "utc")) {
1650 rtc_utc = 1;
1651 } else if (!strcmp(value, "localtime")) {
1652 rtc_utc = 0;
1653 } else {
1654 configure_rtc_date_offset(value, 0);
1657 value = qemu_opt_get(opts, "clock");
1658 if (value) {
1659 if (!strcmp(value, "host")) {
1660 rtc_clock = host_clock;
1661 } else if (!strcmp(value, "vm")) {
1662 rtc_clock = vm_clock;
1663 } else {
1664 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1665 exit(1);
1668 #ifdef CONFIG_TARGET_I386
1669 value = qemu_opt_get(opts, "driftfix");
1670 if (value) {
1671 if (!strcmp(buf, "slew")) {
1672 rtc_td_hack = 1;
1673 } else if (!strcmp(buf, "none")) {
1674 rtc_td_hack = 0;
1675 } else {
1676 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1677 exit(1);
1680 #endif
1683 #ifdef _WIN32
1684 static void socket_cleanup(void)
1686 WSACleanup();
1689 static int socket_init(void)
1691 WSADATA Data;
1692 int ret, err;
1694 ret = WSAStartup(MAKEWORD(2,2), &Data);
1695 if (ret != 0) {
1696 err = WSAGetLastError();
1697 fprintf(stderr, "WSAStartup: %d\n", err);
1698 return -1;
1700 atexit(socket_cleanup);
1701 return 0;
1703 #endif
1705 /***********************************************************/
1706 /* Bluetooth support */
1707 static int nb_hcis;
1708 static int cur_hci;
1709 static struct HCIInfo *hci_table[MAX_NICS];
1711 static struct bt_vlan_s {
1712 struct bt_scatternet_s net;
1713 int id;
1714 struct bt_vlan_s *next;
1715 } *first_bt_vlan;
1717 /* find or alloc a new bluetooth "VLAN" */
1718 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1720 struct bt_vlan_s **pvlan, *vlan;
1721 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1722 if (vlan->id == id)
1723 return &vlan->net;
1725 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1726 vlan->id = id;
1727 pvlan = &first_bt_vlan;
1728 while (*pvlan != NULL)
1729 pvlan = &(*pvlan)->next;
1730 *pvlan = vlan;
1731 return &vlan->net;
1734 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1738 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1740 return -ENOTSUP;
1743 static struct HCIInfo null_hci = {
1744 .cmd_send = null_hci_send,
1745 .sco_send = null_hci_send,
1746 .acl_send = null_hci_send,
1747 .bdaddr_set = null_hci_addr_set,
1750 struct HCIInfo *qemu_next_hci(void)
1752 if (cur_hci == nb_hcis)
1753 return &null_hci;
1755 return hci_table[cur_hci++];
1758 static struct HCIInfo *hci_init(const char *str)
1760 char *endp;
1761 struct bt_scatternet_s *vlan = 0;
1763 if (!strcmp(str, "null"))
1764 /* null */
1765 return &null_hci;
1766 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1767 /* host[:hciN] */
1768 return bt_host_hci(str[4] ? str + 5 : "hci0");
1769 else if (!strncmp(str, "hci", 3)) {
1770 /* hci[,vlan=n] */
1771 if (str[3]) {
1772 if (!strncmp(str + 3, ",vlan=", 6)) {
1773 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1774 if (*endp)
1775 vlan = 0;
1777 } else
1778 vlan = qemu_find_bt_vlan(0);
1779 if (vlan)
1780 return bt_new_hci(vlan);
1783 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1785 return 0;
1788 static int bt_hci_parse(const char *str)
1790 struct HCIInfo *hci;
1791 bdaddr_t bdaddr;
1793 if (nb_hcis >= MAX_NICS) {
1794 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1795 return -1;
1798 hci = hci_init(str);
1799 if (!hci)
1800 return -1;
1802 bdaddr.b[0] = 0x52;
1803 bdaddr.b[1] = 0x54;
1804 bdaddr.b[2] = 0x00;
1805 bdaddr.b[3] = 0x12;
1806 bdaddr.b[4] = 0x34;
1807 bdaddr.b[5] = 0x56 + nb_hcis;
1808 hci->bdaddr_set(hci, bdaddr.b);
1810 hci_table[nb_hcis++] = hci;
1812 return 0;
1815 static void bt_vhci_add(int vlan_id)
1817 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1819 if (!vlan->slave)
1820 fprintf(stderr, "qemu: warning: adding a VHCI to "
1821 "an empty scatternet %i\n", vlan_id);
1823 bt_vhci_init(bt_new_hci(vlan));
1826 static struct bt_device_s *bt_device_add(const char *opt)
1828 struct bt_scatternet_s *vlan;
1829 int vlan_id = 0;
1830 char *endp = strstr(opt, ",vlan=");
1831 int len = (endp ? endp - opt : strlen(opt)) + 1;
1832 char devname[10];
1834 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1836 if (endp) {
1837 vlan_id = strtol(endp + 6, &endp, 0);
1838 if (*endp) {
1839 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1840 return 0;
1844 vlan = qemu_find_bt_vlan(vlan_id);
1846 if (!vlan->slave)
1847 fprintf(stderr, "qemu: warning: adding a slave device to "
1848 "an empty scatternet %i\n", vlan_id);
1850 if (!strcmp(devname, "keyboard"))
1851 return bt_keyboard_init(vlan);
1853 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1854 return 0;
1857 static int bt_parse(const char *opt)
1859 const char *endp, *p;
1860 int vlan;
1862 if (strstart(opt, "hci", &endp)) {
1863 if (!*endp || *endp == ',') {
1864 if (*endp)
1865 if (!strstart(endp, ",vlan=", 0))
1866 opt = endp + 1;
1868 return bt_hci_parse(opt);
1870 } else if (strstart(opt, "vhci", &endp)) {
1871 if (!*endp || *endp == ',') {
1872 if (*endp) {
1873 if (strstart(endp, ",vlan=", &p)) {
1874 vlan = strtol(p, (char **) &endp, 0);
1875 if (*endp) {
1876 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1877 return 1;
1879 } else {
1880 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1881 return 1;
1883 } else
1884 vlan = 0;
1886 bt_vhci_add(vlan);
1887 return 0;
1889 } else if (strstart(opt, "device:", &endp))
1890 return !bt_device_add(endp);
1892 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1893 return 1;
1896 /***********************************************************/
1897 /* QEMU Block devices */
1899 #define HD_ALIAS "index=%d,media=disk"
1900 #define CDROM_ALIAS "index=2,media=cdrom"
1901 #define FD_ALIAS "index=%d,if=floppy"
1902 #define PFLASH_ALIAS "if=pflash"
1903 #define MTD_ALIAS "if=mtd"
1904 #define SD_ALIAS "index=0,if=sd"
1906 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1908 va_list ap;
1909 char optstr[1024];
1910 QemuOpts *opts;
1912 va_start(ap, fmt);
1913 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1914 va_end(ap);
1916 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1917 if (!opts) {
1918 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1919 __FUNCTION__, optstr);
1920 return NULL;
1922 if (file)
1923 qemu_opt_set(opts, "file", file);
1924 return opts;
1927 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1929 DriveInfo *dinfo;
1931 /* seek interface, bus and unit */
1933 QTAILQ_FOREACH(dinfo, &drives, next) {
1934 if (dinfo->type == type &&
1935 dinfo->bus == bus &&
1936 dinfo->unit == unit)
1937 return dinfo;
1940 return NULL;
1943 DriveInfo *drive_get_by_id(const char *id)
1945 DriveInfo *dinfo;
1947 QTAILQ_FOREACH(dinfo, &drives, next) {
1948 if (strcmp(id, dinfo->id))
1949 continue;
1950 return dinfo;
1952 return NULL;
1955 int drive_get_max_bus(BlockInterfaceType type)
1957 int max_bus;
1958 DriveInfo *dinfo;
1960 max_bus = -1;
1961 QTAILQ_FOREACH(dinfo, &drives, next) {
1962 if(dinfo->type == type &&
1963 dinfo->bus > max_bus)
1964 max_bus = dinfo->bus;
1966 return max_bus;
1969 const char *drive_get_serial(BlockDriverState *bdrv)
1971 DriveInfo *dinfo;
1973 QTAILQ_FOREACH(dinfo, &drives, next) {
1974 if (dinfo->bdrv == bdrv)
1975 return dinfo->serial;
1978 return "\0";
1981 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1983 DriveInfo *dinfo;
1985 QTAILQ_FOREACH(dinfo, &drives, next) {
1986 if (dinfo->bdrv == bdrv)
1987 return dinfo->onerror;
1990 return BLOCK_ERR_STOP_ENOSPC;
1993 static void bdrv_format_print(void *opaque, const char *name)
1995 fprintf(stderr, " %s", name);
1998 void drive_uninit(DriveInfo *dinfo)
2000 qemu_opts_del(dinfo->opts);
2001 bdrv_delete(dinfo->bdrv);
2002 QTAILQ_REMOVE(&drives, dinfo, next);
2003 qemu_free(dinfo);
2006 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
2007 int *fatal_error)
2009 const char *buf;
2010 const char *file = NULL;
2011 char devname[128];
2012 const char *serial;
2013 const char *mediastr = "";
2014 BlockInterfaceType type;
2015 enum { MEDIA_DISK, MEDIA_CDROM } media;
2016 int bus_id, unit_id;
2017 int cyls, heads, secs, translation;
2018 BlockDriver *drv = NULL;
2019 QEMUMachine *machine = opaque;
2020 int max_devs;
2021 int index;
2022 int cache;
2023 int aio = 0;
2024 int bdrv_flags, onerror;
2025 const char *devaddr;
2026 DriveInfo *dinfo;
2027 int is_extboot = 0;
2028 int snapshot = 0;
2030 *fatal_error = 1;
2032 translation = BIOS_ATA_TRANSLATION_AUTO;
2033 cache = 1;
2035 if (machine && machine->use_scsi) {
2036 type = IF_SCSI;
2037 max_devs = MAX_SCSI_DEVS;
2038 pstrcpy(devname, sizeof(devname), "scsi");
2039 } else {
2040 type = IF_IDE;
2041 max_devs = MAX_IDE_DEVS;
2042 pstrcpy(devname, sizeof(devname), "ide");
2044 media = MEDIA_DISK;
2046 /* extract parameters */
2047 bus_id = qemu_opt_get_number(opts, "bus", 0);
2048 unit_id = qemu_opt_get_number(opts, "unit", -1);
2049 index = qemu_opt_get_number(opts, "index", -1);
2051 cyls = qemu_opt_get_number(opts, "cyls", 0);
2052 heads = qemu_opt_get_number(opts, "heads", 0);
2053 secs = qemu_opt_get_number(opts, "secs", 0);
2055 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2057 file = qemu_opt_get(opts, "file");
2058 serial = qemu_opt_get(opts, "serial");
2060 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2061 pstrcpy(devname, sizeof(devname), buf);
2062 if (!strcmp(buf, "ide")) {
2063 type = IF_IDE;
2064 max_devs = MAX_IDE_DEVS;
2065 } else if (!strcmp(buf, "scsi")) {
2066 type = IF_SCSI;
2067 max_devs = MAX_SCSI_DEVS;
2068 } else if (!strcmp(buf, "floppy")) {
2069 type = IF_FLOPPY;
2070 max_devs = 0;
2071 } else if (!strcmp(buf, "pflash")) {
2072 type = IF_PFLASH;
2073 max_devs = 0;
2074 } else if (!strcmp(buf, "mtd")) {
2075 type = IF_MTD;
2076 max_devs = 0;
2077 } else if (!strcmp(buf, "sd")) {
2078 type = IF_SD;
2079 max_devs = 0;
2080 } else if (!strcmp(buf, "virtio")) {
2081 type = IF_VIRTIO;
2082 max_devs = 0;
2083 } else if (!strcmp(buf, "xen")) {
2084 type = IF_XEN;
2085 max_devs = 0;
2086 } else if (!strcmp(buf, "none")) {
2087 type = IF_NONE;
2088 max_devs = 0;
2089 } else {
2090 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2091 return NULL;
2095 if (cyls || heads || secs) {
2096 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2097 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2098 return NULL;
2100 if (heads < 1 || (type == IF_IDE && heads > 16)) {
2101 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2102 return NULL;
2104 if (secs < 1 || (type == IF_IDE && secs > 63)) {
2105 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2106 return NULL;
2110 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2111 if (!cyls) {
2112 fprintf(stderr,
2113 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2114 buf);
2115 return NULL;
2117 if (!strcmp(buf, "none"))
2118 translation = BIOS_ATA_TRANSLATION_NONE;
2119 else if (!strcmp(buf, "lba"))
2120 translation = BIOS_ATA_TRANSLATION_LBA;
2121 else if (!strcmp(buf, "auto"))
2122 translation = BIOS_ATA_TRANSLATION_AUTO;
2123 else {
2124 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2125 return NULL;
2129 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2130 if (!strcmp(buf, "disk")) {
2131 media = MEDIA_DISK;
2132 } else if (!strcmp(buf, "cdrom")) {
2133 if (cyls || secs || heads) {
2134 fprintf(stderr,
2135 "qemu: '%s' invalid physical CHS format\n", buf);
2136 return NULL;
2138 media = MEDIA_CDROM;
2139 } else {
2140 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2141 return NULL;
2145 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2146 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2147 cache = 0;
2148 else if (!strcmp(buf, "writethrough"))
2149 cache = 1;
2150 else if (!strcmp(buf, "writeback"))
2151 cache = 2;
2152 else {
2153 fprintf(stderr, "qemu: invalid cache option\n");
2154 return NULL;
2158 #ifdef CONFIG_LINUX_AIO
2159 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2160 if (!strcmp(buf, "threads"))
2161 aio = 0;
2162 else if (!strcmp(buf, "native"))
2163 aio = 1;
2164 else {
2165 fprintf(stderr, "qemu: invalid aio option\n");
2166 return NULL;
2169 #endif
2171 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2172 if (strcmp(buf, "?") == 0) {
2173 fprintf(stderr, "qemu: Supported formats:");
2174 bdrv_iterate_format(bdrv_format_print, NULL);
2175 fprintf(stderr, "\n");
2176 return NULL;
2178 drv = bdrv_find_format(buf);
2179 if (!drv) {
2180 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2181 return NULL;
2185 is_extboot = qemu_opt_get_bool(opts, "boot", 0);
2186 if (is_extboot && extboot_drive) {
2187 fprintf(stderr, "qemu: two bootable drives specified\n");
2188 return NULL;
2191 onerror = BLOCK_ERR_STOP_ENOSPC;
2192 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2193 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2194 fprintf(stderr, "werror is no supported by this format\n");
2195 return NULL;
2197 if (!strcmp(buf, "ignore"))
2198 onerror = BLOCK_ERR_IGNORE;
2199 else if (!strcmp(buf, "enospc"))
2200 onerror = BLOCK_ERR_STOP_ENOSPC;
2201 else if (!strcmp(buf, "stop"))
2202 onerror = BLOCK_ERR_STOP_ANY;
2203 else if (!strcmp(buf, "report"))
2204 onerror = BLOCK_ERR_REPORT;
2205 else {
2206 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2207 return NULL;
2211 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2212 if (type != IF_VIRTIO) {
2213 fprintf(stderr, "addr is not supported\n");
2214 return NULL;
2218 /* compute bus and unit according index */
2220 if (index != -1) {
2221 if (bus_id != 0 || unit_id != -1) {
2222 fprintf(stderr,
2223 "qemu: index cannot be used with bus and unit\n");
2224 return NULL;
2226 if (max_devs == 0)
2228 unit_id = index;
2229 bus_id = 0;
2230 } else {
2231 unit_id = index % max_devs;
2232 bus_id = index / max_devs;
2236 /* if user doesn't specify a unit_id,
2237 * try to find the first free
2240 if (unit_id == -1) {
2241 unit_id = 0;
2242 while (drive_get(type, bus_id, unit_id) != NULL) {
2243 unit_id++;
2244 if (max_devs && unit_id >= max_devs) {
2245 unit_id -= max_devs;
2246 bus_id++;
2251 /* check unit id */
2253 if (max_devs && unit_id >= max_devs) {
2254 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2255 unit_id, max_devs - 1);
2256 return NULL;
2260 * ignore multiple definitions
2263 if (drive_get(type, bus_id, unit_id) != NULL) {
2264 *fatal_error = 0;
2265 return NULL;
2268 /* init */
2270 dinfo = qemu_mallocz(sizeof(*dinfo));
2271 if ((buf = qemu_opts_id(opts)) != NULL) {
2272 dinfo->id = qemu_strdup(buf);
2273 } else {
2274 /* no id supplied -> create one */
2275 dinfo->id = qemu_mallocz(32);
2276 if (type == IF_IDE || type == IF_SCSI)
2277 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2278 if (max_devs)
2279 snprintf(dinfo->id, 32, "%s%i%s%i",
2280 devname, bus_id, mediastr, unit_id);
2281 else
2282 snprintf(dinfo->id, 32, "%s%s%i",
2283 devname, mediastr, unit_id);
2285 dinfo->bdrv = bdrv_new(dinfo->id);
2286 dinfo->devaddr = devaddr;
2287 dinfo->type = type;
2288 dinfo->bus = bus_id;
2289 dinfo->unit = unit_id;
2290 dinfo->onerror = onerror;
2291 dinfo->opts = opts;
2292 if (serial)
2293 strncpy(dinfo->serial, serial, sizeof(serial));
2294 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2295 if (is_extboot) {
2296 extboot_drive = dinfo;
2299 switch(type) {
2300 case IF_IDE:
2301 case IF_SCSI:
2302 case IF_XEN:
2303 case IF_NONE:
2304 switch(media) {
2305 case MEDIA_DISK:
2306 if (cyls != 0) {
2307 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2308 bdrv_set_translation_hint(dinfo->bdrv, translation);
2310 break;
2311 case MEDIA_CDROM:
2312 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2313 break;
2315 break;
2316 case IF_SD:
2317 /* FIXME: This isn't really a floppy, but it's a reasonable
2318 approximation. */
2319 case IF_FLOPPY:
2320 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2321 break;
2322 case IF_PFLASH:
2323 case IF_MTD:
2324 break;
2325 case IF_VIRTIO:
2326 /* add virtio block device */
2327 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2328 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2329 qemu_opt_set(opts, "drive", dinfo->id);
2330 if (devaddr)
2331 qemu_opt_set(opts, "addr", devaddr);
2332 break;
2333 case IF_COUNT:
2334 abort();
2336 if (!file) {
2337 *fatal_error = 0;
2338 return NULL;
2340 bdrv_flags = 0;
2341 if (snapshot) {
2342 bdrv_flags |= BDRV_O_SNAPSHOT;
2343 cache = 2; /* always use write-back with snapshot */
2345 if (cache == 0) /* no caching */
2346 bdrv_flags |= BDRV_O_NOCACHE;
2347 else if (cache == 2) /* write-back */
2348 bdrv_flags |= BDRV_O_CACHE_WB;
2350 if (aio == 1) {
2351 bdrv_flags |= BDRV_O_NATIVE_AIO;
2352 } else {
2353 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2356 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2357 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2358 file, strerror(errno));
2359 return NULL;
2362 if (bdrv_key_required(dinfo->bdrv))
2363 autostart = 0;
2364 *fatal_error = 0;
2365 return dinfo;
2368 static int drive_init_func(QemuOpts *opts, void *opaque)
2370 QEMUMachine *machine = opaque;
2371 int fatal_error = 0;
2373 if (drive_init(opts, machine, &fatal_error) == NULL) {
2374 if (fatal_error)
2375 return 1;
2377 return 0;
2380 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2382 if (NULL == qemu_opt_get(opts, "snapshot")) {
2383 qemu_opt_set(opts, "snapshot", "on");
2385 return 0;
2388 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2390 boot_set_handler = func;
2391 boot_set_opaque = opaque;
2394 int qemu_boot_set(const char *boot_devices)
2396 if (!boot_set_handler) {
2397 return -EINVAL;
2399 return boot_set_handler(boot_set_opaque, boot_devices);
2402 static int parse_bootdevices(char *devices)
2404 /* We just do some generic consistency checks */
2405 const char *p;
2406 int bitmap = 0;
2408 for (p = devices; *p != '\0'; p++) {
2409 /* Allowed boot devices are:
2410 * a-b: floppy disk drives
2411 * c-f: IDE disk drives
2412 * g-m: machine implementation dependant drives
2413 * n-p: network devices
2414 * It's up to each machine implementation to check if the given boot
2415 * devices match the actual hardware implementation and firmware
2416 * features.
2418 if (*p < 'a' || *p > 'p') {
2419 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2420 exit(1);
2422 if (bitmap & (1 << (*p - 'a'))) {
2423 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2424 exit(1);
2426 bitmap |= 1 << (*p - 'a');
2428 return bitmap;
2431 static void restore_boot_devices(void *opaque)
2433 char *standard_boot_devices = opaque;
2435 qemu_boot_set(standard_boot_devices);
2437 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2438 qemu_free(standard_boot_devices);
2441 static void numa_add(const char *optarg)
2443 char option[128];
2444 char *endptr;
2445 unsigned long long value, endvalue;
2446 int nodenr;
2448 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2449 if (!strcmp(option, "node")) {
2450 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2451 nodenr = nb_numa_nodes;
2452 } else {
2453 nodenr = strtoull(option, NULL, 10);
2456 if (get_param_value(option, 128, "mem", optarg) == 0) {
2457 node_mem[nodenr] = 0;
2458 } else {
2459 value = strtoull(option, &endptr, 0);
2460 switch (*endptr) {
2461 case 0: case 'M': case 'm':
2462 value <<= 20;
2463 break;
2464 case 'G': case 'g':
2465 value <<= 30;
2466 break;
2468 node_mem[nodenr] = value;
2470 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2471 node_cpumask[nodenr] = 0;
2472 } else {
2473 value = strtoull(option, &endptr, 10);
2474 if (value >= 64) {
2475 value = 63;
2476 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2477 } else {
2478 if (*endptr == '-') {
2479 endvalue = strtoull(endptr+1, &endptr, 10);
2480 if (endvalue >= 63) {
2481 endvalue = 62;
2482 fprintf(stderr,
2483 "only 63 CPUs in NUMA mode supported.\n");
2485 value = (1 << (endvalue + 1)) - (1 << value);
2486 } else {
2487 value = 1 << value;
2490 node_cpumask[nodenr] = value;
2492 nb_numa_nodes++;
2494 return;
2497 static void smp_parse(const char *optarg)
2499 int smp, sockets = 0, threads = 0, cores = 0;
2500 char *endptr;
2501 char option[128];
2503 smp = strtoul(optarg, &endptr, 10);
2504 if (endptr != optarg) {
2505 if (*endptr == ',') {
2506 endptr++;
2509 if (get_param_value(option, 128, "sockets", endptr) != 0)
2510 sockets = strtoull(option, NULL, 10);
2511 if (get_param_value(option, 128, "cores", endptr) != 0)
2512 cores = strtoull(option, NULL, 10);
2513 if (get_param_value(option, 128, "threads", endptr) != 0)
2514 threads = strtoull(option, NULL, 10);
2515 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2516 max_cpus = strtoull(option, NULL, 10);
2518 /* compute missing values, prefer sockets over cores over threads */
2519 if (smp == 0 || sockets == 0) {
2520 sockets = sockets > 0 ? sockets : 1;
2521 cores = cores > 0 ? cores : 1;
2522 threads = threads > 0 ? threads : 1;
2523 if (smp == 0) {
2524 smp = cores * threads * sockets;
2525 } else {
2526 sockets = smp / (cores * threads);
2528 } else {
2529 if (cores == 0) {
2530 threads = threads > 0 ? threads : 1;
2531 cores = smp / (sockets * threads);
2532 } else {
2533 if (sockets == 0) {
2534 sockets = smp / (cores * threads);
2535 } else {
2536 threads = smp / (cores * sockets);
2540 smp_cpus = smp;
2541 smp_cores = cores > 0 ? cores : 1;
2542 smp_threads = threads > 0 ? threads : 1;
2543 if (max_cpus == 0)
2544 max_cpus = smp_cpus;
2547 /***********************************************************/
2548 /* USB devices */
2550 static void usb_msd_password_cb(void *opaque, int err)
2552 USBDevice *dev = opaque;
2554 if (!err)
2555 usb_device_attach(dev);
2556 else
2557 dev->info->handle_destroy(dev);
2560 static struct {
2561 const char *name;
2562 const char *qdev;
2563 } usbdevs[] = {
2565 .name = "mouse",
2566 .qdev = "QEMU USB Mouse",
2568 .name = "tablet",
2569 .qdev = "QEMU USB Tablet",
2571 .name = "keyboard",
2572 .qdev = "QEMU USB Keyboard",
2574 .name = "wacom-tablet",
2575 .qdev = "QEMU PenPartner Tablet",
2579 static int usb_device_add(const char *devname, int is_hotplug)
2581 const char *p;
2582 USBBus *bus = usb_bus_find(-1 /* any */);
2583 USBDevice *dev = NULL;
2584 int i;
2586 if (!usb_enabled)
2587 return -1;
2589 /* simple devices which don't need extra care */
2590 for (i = 0; i < ARRAY_SIZE(usbdevs); i++) {
2591 if (strcmp(devname, usbdevs[i].name) != 0)
2592 continue;
2593 dev = usb_create_simple(bus, usbdevs[i].qdev);
2594 goto done;
2597 /* the other ones */
2598 if (strstart(devname, "host:", &p)) {
2599 dev = usb_host_device_open(p);
2600 } else if (strstart(devname, "disk:", &p)) {
2601 BlockDriverState *bs;
2603 dev = usb_msd_init(p);
2604 if (!dev)
2605 return -1;
2606 bs = usb_msd_get_bdrv(dev);
2607 if (bdrv_key_required(bs)) {
2608 autostart = 0;
2609 if (is_hotplug) {
2610 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2611 dev);
2612 return 0;
2615 } else if (strstart(devname, "serial:", &p)) {
2616 dev = usb_serial_init(p);
2617 #ifdef CONFIG_BRLAPI
2618 } else if (!strcmp(devname, "braille")) {
2619 dev = usb_baum_init();
2620 #endif
2621 } else if (strstart(devname, "net:", &p)) {
2622 QemuOpts *opts;
2623 int idx;
2625 opts = qemu_opts_parse(&qemu_net_opts, p, NULL);
2626 if (!opts) {
2627 return -1;
2630 qemu_opt_set(opts, "type", "nic");
2631 qemu_opt_set(opts, "model", "usb");
2633 idx = net_client_init(NULL, opts, 0);
2634 if (idx == -1) {
2635 return -1;
2638 dev = usb_net_init(&nd_table[idx]);
2639 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2640 dev = usb_bt_init(devname[2] ? hci_init(p) :
2641 bt_new_hci(qemu_find_bt_vlan(0)));
2642 } else {
2643 return -1;
2645 if (!dev)
2646 return -1;
2648 done:
2649 return 0;
2652 static int usb_device_del(const char *devname)
2654 int bus_num, addr;
2655 const char *p;
2657 if (strstart(devname, "host:", &p))
2658 return usb_host_device_close(p);
2660 if (!usb_enabled)
2661 return -1;
2663 p = strchr(devname, '.');
2664 if (!p)
2665 return -1;
2666 bus_num = strtoul(devname, NULL, 0);
2667 addr = strtoul(p + 1, NULL, 0);
2669 return usb_device_delete_addr(bus_num, addr);
2672 static int usb_parse(const char *cmdline)
2674 return usb_device_add(cmdline, 0);
2677 void do_usb_add(Monitor *mon, const QDict *qdict)
2679 usb_device_add(qdict_get_str(qdict, "devname"), 1);
2682 void do_usb_del(Monitor *mon, const QDict *qdict)
2684 usb_device_del(qdict_get_str(qdict, "devname"));
2687 /***********************************************************/
2688 /* PCMCIA/Cardbus */
2690 static struct pcmcia_socket_entry_s {
2691 PCMCIASocket *socket;
2692 struct pcmcia_socket_entry_s *next;
2693 } *pcmcia_sockets = 0;
2695 void pcmcia_socket_register(PCMCIASocket *socket)
2697 struct pcmcia_socket_entry_s *entry;
2699 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2700 entry->socket = socket;
2701 entry->next = pcmcia_sockets;
2702 pcmcia_sockets = entry;
2705 void pcmcia_socket_unregister(PCMCIASocket *socket)
2707 struct pcmcia_socket_entry_s *entry, **ptr;
2709 ptr = &pcmcia_sockets;
2710 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2711 if (entry->socket == socket) {
2712 *ptr = entry->next;
2713 qemu_free(entry);
2717 void pcmcia_info(Monitor *mon)
2719 struct pcmcia_socket_entry_s *iter;
2721 if (!pcmcia_sockets)
2722 monitor_printf(mon, "No PCMCIA sockets\n");
2724 for (iter = pcmcia_sockets; iter; iter = iter->next)
2725 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2726 iter->socket->attached ? iter->socket->card_string :
2727 "Empty");
2730 /***********************************************************/
2731 /* register display */
2733 struct DisplayAllocator default_allocator = {
2734 defaultallocator_create_displaysurface,
2735 defaultallocator_resize_displaysurface,
2736 defaultallocator_free_displaysurface
2739 void register_displaystate(DisplayState *ds)
2741 DisplayState **s;
2742 s = &display_state;
2743 while (*s != NULL)
2744 s = &(*s)->next;
2745 ds->next = NULL;
2746 *s = ds;
2749 DisplayState *get_displaystate(void)
2751 return display_state;
2754 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2756 if(ds->allocator == &default_allocator) ds->allocator = da;
2757 return ds->allocator;
2760 /* dumb display */
2762 static void dumb_display_init(void)
2764 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2765 ds->allocator = &default_allocator;
2766 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2767 register_displaystate(ds);
2770 /***********************************************************/
2771 /* I/O handling */
2773 typedef struct IOHandlerRecord {
2774 int fd;
2775 IOCanRWHandler *fd_read_poll;
2776 IOHandler *fd_read;
2777 IOHandler *fd_write;
2778 int deleted;
2779 void *opaque;
2780 /* temporary data */
2781 struct pollfd *ufd;
2782 struct IOHandlerRecord *next;
2783 } IOHandlerRecord;
2785 static IOHandlerRecord *first_io_handler;
2787 /* XXX: fd_read_poll should be suppressed, but an API change is
2788 necessary in the character devices to suppress fd_can_read(). */
2789 int qemu_set_fd_handler2(int fd,
2790 IOCanRWHandler *fd_read_poll,
2791 IOHandler *fd_read,
2792 IOHandler *fd_write,
2793 void *opaque)
2795 IOHandlerRecord **pioh, *ioh;
2797 if (!fd_read && !fd_write) {
2798 pioh = &first_io_handler;
2799 for(;;) {
2800 ioh = *pioh;
2801 if (ioh == NULL)
2802 break;
2803 if (ioh->fd == fd) {
2804 ioh->deleted = 1;
2805 break;
2807 pioh = &ioh->next;
2809 } else {
2810 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2811 if (ioh->fd == fd)
2812 goto found;
2814 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2815 ioh->next = first_io_handler;
2816 first_io_handler = ioh;
2817 found:
2818 ioh->fd = fd;
2819 ioh->fd_read_poll = fd_read_poll;
2820 ioh->fd_read = fd_read;
2821 ioh->fd_write = fd_write;
2822 ioh->opaque = opaque;
2823 ioh->deleted = 0;
2825 qemu_notify_event();
2826 return 0;
2829 int qemu_set_fd_handler(int fd,
2830 IOHandler *fd_read,
2831 IOHandler *fd_write,
2832 void *opaque)
2834 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2837 #ifdef _WIN32
2838 /***********************************************************/
2839 /* Polling handling */
2841 typedef struct PollingEntry {
2842 PollingFunc *func;
2843 void *opaque;
2844 struct PollingEntry *next;
2845 } PollingEntry;
2847 static PollingEntry *first_polling_entry;
2849 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2851 PollingEntry **ppe, *pe;
2852 pe = qemu_mallocz(sizeof(PollingEntry));
2853 pe->func = func;
2854 pe->opaque = opaque;
2855 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2856 *ppe = pe;
2857 return 0;
2860 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2862 PollingEntry **ppe, *pe;
2863 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2864 pe = *ppe;
2865 if (pe->func == func && pe->opaque == opaque) {
2866 *ppe = pe->next;
2867 qemu_free(pe);
2868 break;
2873 /***********************************************************/
2874 /* Wait objects support */
2875 typedef struct WaitObjects {
2876 int num;
2877 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2878 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2879 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2880 } WaitObjects;
2882 static WaitObjects wait_objects = {0};
2884 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2886 WaitObjects *w = &wait_objects;
2888 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2889 return -1;
2890 w->events[w->num] = handle;
2891 w->func[w->num] = func;
2892 w->opaque[w->num] = opaque;
2893 w->num++;
2894 return 0;
2897 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2899 int i, found;
2900 WaitObjects *w = &wait_objects;
2902 found = 0;
2903 for (i = 0; i < w->num; i++) {
2904 if (w->events[i] == handle)
2905 found = 1;
2906 if (found) {
2907 w->events[i] = w->events[i + 1];
2908 w->func[i] = w->func[i + 1];
2909 w->opaque[i] = w->opaque[i + 1];
2912 if (found)
2913 w->num--;
2915 #endif
2917 /***********************************************************/
2918 /* ram save/restore */
2920 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2921 #define RAM_SAVE_FLAG_COMPRESS 0x02
2922 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2923 #define RAM_SAVE_FLAG_PAGE 0x08
2924 #define RAM_SAVE_FLAG_EOS 0x10
2926 static int is_dup_page(uint8_t *page, uint8_t ch)
2928 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2929 uint32_t *array = (uint32_t *)page;
2930 int i;
2932 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2933 if (array[i] != val)
2934 return 0;
2937 return 1;
2940 static int ram_save_block(QEMUFile *f)
2942 static ram_addr_t current_addr = 0;
2943 ram_addr_t saved_addr = current_addr;
2944 ram_addr_t addr = 0;
2945 int found = 0;
2947 while (addr < last_ram_offset) {
2948 if (kvm_enabled() && current_addr == 0) {
2949 int r;
2950 r = kvm_update_dirty_pages_log();
2951 if (r) {
2952 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
2953 qemu_file_set_error(f);
2954 return 0;
2957 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2958 uint8_t *p;
2960 cpu_physical_memory_reset_dirty(current_addr,
2961 current_addr + TARGET_PAGE_SIZE,
2962 MIGRATION_DIRTY_FLAG);
2964 p = qemu_get_ram_ptr(current_addr);
2966 if (is_dup_page(p, *p)) {
2967 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2968 qemu_put_byte(f, *p);
2969 } else {
2970 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2971 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2974 found = 1;
2975 break;
2977 addr += TARGET_PAGE_SIZE;
2978 current_addr = (saved_addr + addr) % last_ram_offset;
2981 return found;
2984 static uint64_t bytes_transferred = 0;
2986 static ram_addr_t ram_save_remaining(void)
2988 ram_addr_t addr;
2989 ram_addr_t count = 0;
2991 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2992 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2993 count++;
2996 return count;
2999 uint64_t ram_bytes_remaining(void)
3001 return ram_save_remaining() * TARGET_PAGE_SIZE;
3004 uint64_t ram_bytes_transferred(void)
3006 return bytes_transferred;
3009 uint64_t ram_bytes_total(void)
3011 return last_ram_offset;
3014 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3016 ram_addr_t addr;
3017 uint64_t bytes_transferred_last;
3018 double bwidth = 0;
3019 uint64_t expected_time = 0;
3021 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3022 qemu_file_set_error(f);
3023 return 0;
3026 if (stage == 1) {
3027 /* Make sure all dirty bits are set */
3028 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3029 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3030 cpu_physical_memory_set_dirty(addr);
3033 /* Enable dirty memory tracking */
3034 cpu_physical_memory_set_dirty_tracking(1);
3036 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3039 bytes_transferred_last = bytes_transferred;
3040 bwidth = get_clock();
3042 while (!qemu_file_rate_limit(f)) {
3043 int ret;
3045 ret = ram_save_block(f);
3046 bytes_transferred += ret * TARGET_PAGE_SIZE;
3047 if (ret == 0) /* no more blocks */
3048 break;
3051 bwidth = get_clock() - bwidth;
3052 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3054 /* if we haven't transferred anything this round, force expected_time to a
3055 * a very high value, but without crashing */
3056 if (bwidth == 0)
3057 bwidth = 0.000001;
3059 /* try transferring iterative blocks of memory */
3061 if (stage == 3) {
3063 /* flush all remaining blocks regardless of rate limiting */
3064 while (ram_save_block(f) != 0) {
3065 bytes_transferred += TARGET_PAGE_SIZE;
3067 cpu_physical_memory_set_dirty_tracking(0);
3070 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3072 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3074 return (stage == 2) && (expected_time <= migrate_max_downtime());
3077 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3079 ram_addr_t addr;
3080 int flags;
3082 if (version_id != 3)
3083 return -EINVAL;
3085 do {
3086 addr = qemu_get_be64(f);
3088 flags = addr & ~TARGET_PAGE_MASK;
3089 addr &= TARGET_PAGE_MASK;
3091 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3092 if (addr != last_ram_offset)
3093 return -EINVAL;
3096 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3097 uint8_t ch = qemu_get_byte(f);
3098 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3099 #ifndef _WIN32
3100 if (ch == 0 &&
3101 (!kvm_enabled() || kvm_has_sync_mmu())) {
3102 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3104 #endif
3105 } else if (flags & RAM_SAVE_FLAG_PAGE)
3106 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3107 } while (!(flags & RAM_SAVE_FLAG_EOS));
3109 return 0;
3112 void qemu_service_io(void)
3114 qemu_notify_event();
3117 /***********************************************************/
3118 /* bottom halves (can be seen as timers which expire ASAP) */
3120 struct QEMUBH {
3121 QEMUBHFunc *cb;
3122 void *opaque;
3123 int scheduled;
3124 int idle;
3125 int deleted;
3126 QEMUBH *next;
3129 static QEMUBH *first_bh = NULL;
3131 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3133 QEMUBH *bh;
3134 bh = qemu_mallocz(sizeof(QEMUBH));
3135 bh->cb = cb;
3136 bh->opaque = opaque;
3137 bh->next = first_bh;
3138 first_bh = bh;
3139 return bh;
3142 int qemu_bh_poll(void)
3144 QEMUBH *bh, **bhp;
3145 int ret;
3147 ret = 0;
3148 for (bh = first_bh; bh; bh = bh->next) {
3149 if (!bh->deleted && bh->scheduled) {
3150 bh->scheduled = 0;
3151 if (!bh->idle)
3152 ret = 1;
3153 bh->idle = 0;
3154 bh->cb(bh->opaque);
3158 /* remove deleted bhs */
3159 bhp = &first_bh;
3160 while (*bhp) {
3161 bh = *bhp;
3162 if (bh->deleted) {
3163 *bhp = bh->next;
3164 qemu_free(bh);
3165 } else
3166 bhp = &bh->next;
3169 return ret;
3172 void qemu_bh_schedule_idle(QEMUBH *bh)
3174 if (bh->scheduled)
3175 return;
3176 bh->scheduled = 1;
3177 bh->idle = 1;
3180 void qemu_bh_schedule(QEMUBH *bh)
3182 if (bh->scheduled)
3183 return;
3184 bh->scheduled = 1;
3185 bh->idle = 0;
3186 /* stop the currently executing CPU to execute the BH ASAP */
3187 qemu_notify_event();
3190 void qemu_bh_cancel(QEMUBH *bh)
3192 bh->scheduled = 0;
3195 void qemu_bh_delete(QEMUBH *bh)
3197 bh->scheduled = 0;
3198 bh->deleted = 1;
3201 static void qemu_bh_update_timeout(int *timeout)
3203 QEMUBH *bh;
3205 for (bh = first_bh; bh; bh = bh->next) {
3206 if (!bh->deleted && bh->scheduled) {
3207 if (bh->idle) {
3208 /* idle bottom halves will be polled at least
3209 * every 10ms */
3210 *timeout = MIN(10, *timeout);
3211 } else {
3212 /* non-idle bottom halves will be executed
3213 * immediately */
3214 *timeout = 0;
3215 break;
3221 /***********************************************************/
3222 /* machine registration */
3224 static QEMUMachine *first_machine = NULL;
3225 QEMUMachine *current_machine = NULL;
3227 int qemu_register_machine(QEMUMachine *m)
3229 QEMUMachine **pm;
3230 pm = &first_machine;
3231 while (*pm != NULL)
3232 pm = &(*pm)->next;
3233 m->next = NULL;
3234 *pm = m;
3235 return 0;
3238 static QEMUMachine *find_machine(const char *name)
3240 QEMUMachine *m;
3242 for(m = first_machine; m != NULL; m = m->next) {
3243 if (!strcmp(m->name, name))
3244 return m;
3245 if (m->alias && !strcmp(m->alias, name))
3246 return m;
3248 return NULL;
3251 static QEMUMachine *find_default_machine(void)
3253 QEMUMachine *m;
3255 for(m = first_machine; m != NULL; m = m->next) {
3256 if (m->is_default) {
3257 return m;
3260 return NULL;
3263 /***********************************************************/
3264 /* main execution loop */
3266 static void gui_update(void *opaque)
3268 uint64_t interval = GUI_REFRESH_INTERVAL;
3269 DisplayState *ds = opaque;
3270 DisplayChangeListener *dcl = ds->listeners;
3272 dpy_refresh(ds);
3274 while (dcl != NULL) {
3275 if (dcl->gui_timer_interval &&
3276 dcl->gui_timer_interval < interval)
3277 interval = dcl->gui_timer_interval;
3278 dcl = dcl->next;
3280 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3283 static void nographic_update(void *opaque)
3285 uint64_t interval = GUI_REFRESH_INTERVAL;
3287 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3290 struct vm_change_state_entry {
3291 VMChangeStateHandler *cb;
3292 void *opaque;
3293 QLIST_ENTRY (vm_change_state_entry) entries;
3296 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3298 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3299 void *opaque)
3301 VMChangeStateEntry *e;
3303 e = qemu_mallocz(sizeof (*e));
3305 e->cb = cb;
3306 e->opaque = opaque;
3307 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3308 return e;
3311 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3313 QLIST_REMOVE (e, entries);
3314 qemu_free (e);
3317 static void vm_state_notify(int running, int reason)
3319 VMChangeStateEntry *e;
3321 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3322 e->cb(e->opaque, running, reason);
3326 static void resume_all_vcpus(void);
3327 static void pause_all_vcpus(void);
3329 void vm_start(void)
3331 if (!vm_running) {
3332 cpu_enable_ticks();
3333 vm_running = 1;
3334 vm_state_notify(1, 0);
3335 qemu_rearm_alarm_timer(alarm_timer);
3336 resume_all_vcpus();
3340 /* reset/shutdown handler */
3342 typedef struct QEMUResetEntry {
3343 QTAILQ_ENTRY(QEMUResetEntry) entry;
3344 QEMUResetHandler *func;
3345 void *opaque;
3346 } QEMUResetEntry;
3348 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3349 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3350 static int reset_requested;
3351 static int shutdown_requested;
3352 static int powerdown_requested;
3353 static int debug_requested;
3354 static int vmstop_requested;
3356 int qemu_no_shutdown(void)
3358 int r = no_shutdown;
3359 no_shutdown = 0;
3360 return r;
3363 int qemu_shutdown_requested(void)
3365 int r = shutdown_requested;
3366 shutdown_requested = 0;
3367 return r;
3370 int qemu_reset_requested(void)
3372 int r = reset_requested;
3373 reset_requested = 0;
3374 return r;
3377 int qemu_powerdown_requested(void)
3379 int r = powerdown_requested;
3380 powerdown_requested = 0;
3381 return r;
3384 static int qemu_debug_requested(void)
3386 int r = debug_requested;
3387 debug_requested = 0;
3388 return r;
3391 static int qemu_vmstop_requested(void)
3393 int r = vmstop_requested;
3394 vmstop_requested = 0;
3395 return r;
3398 static void do_vm_stop(int reason)
3400 if (vm_running) {
3401 cpu_disable_ticks();
3402 vm_running = 0;
3403 pause_all_vcpus();
3404 vm_state_notify(0, reason);
3408 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3410 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3412 re->func = func;
3413 re->opaque = opaque;
3414 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3417 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3419 QEMUResetEntry *re;
3421 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3422 if (re->func == func && re->opaque == opaque) {
3423 QTAILQ_REMOVE(&reset_handlers, re, entry);
3424 qemu_free(re);
3425 return;
3430 void qemu_system_reset(void)
3432 QEMUResetEntry *re, *nre;
3434 /* reset all devices */
3435 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3436 re->func(re->opaque);
3440 void qemu_system_reset_request(void)
3442 if (no_reboot) {
3443 shutdown_requested = 1;
3444 } else {
3445 reset_requested = 1;
3447 if (cpu_single_env) {
3448 cpu_single_env->stopped = 1;
3450 qemu_notify_event();
3453 void qemu_system_shutdown_request(void)
3455 shutdown_requested = 1;
3456 qemu_notify_event();
3459 void qemu_system_powerdown_request(void)
3461 powerdown_requested = 1;
3462 qemu_notify_event();
3465 #ifdef CONFIG_IOTHREAD
3466 static void qemu_system_vmstop_request(int reason)
3468 vmstop_requested = reason;
3469 qemu_notify_event();
3471 #endif
3473 #ifndef _WIN32
3474 static int io_thread_fd = -1;
3476 static void qemu_event_increment(void)
3478 static const char byte = 0;
3480 if (io_thread_fd == -1)
3481 return;
3483 write(io_thread_fd, &byte, sizeof(byte));
3486 static void qemu_event_read(void *opaque)
3488 int fd = (unsigned long)opaque;
3489 ssize_t len;
3491 /* Drain the notify pipe */
3492 do {
3493 char buffer[512];
3494 len = read(fd, buffer, sizeof(buffer));
3495 } while ((len == -1 && errno == EINTR) || len > 0);
3498 static int qemu_event_init(void)
3500 int err;
3501 int fds[2];
3503 err = pipe(fds);
3504 if (err == -1)
3505 return -errno;
3507 err = fcntl_setfl(fds[0], O_NONBLOCK);
3508 if (err < 0)
3509 goto fail;
3511 err = fcntl_setfl(fds[1], O_NONBLOCK);
3512 if (err < 0)
3513 goto fail;
3515 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3516 (void *)(unsigned long)fds[0]);
3518 io_thread_fd = fds[1];
3519 return 0;
3521 fail:
3522 close(fds[0]);
3523 close(fds[1]);
3524 return err;
3526 #else
3527 HANDLE qemu_event_handle;
3529 static void dummy_event_handler(void *opaque)
3533 static int qemu_event_init(void)
3535 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3536 if (!qemu_event_handle) {
3537 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3538 return -1;
3540 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3541 return 0;
3544 static void qemu_event_increment(void)
3546 if (!SetEvent(qemu_event_handle)) {
3547 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3548 GetLastError());
3549 exit (1);
3552 #endif
3554 static int cpu_can_run(CPUState *env)
3556 if (env->stop)
3557 return 0;
3558 if (env->stopped)
3559 return 0;
3560 return 1;
3563 #ifndef CONFIG_IOTHREAD
3564 static int qemu_init_main_loop(void)
3566 return qemu_event_init();
3569 void qemu_init_vcpu(void *_env)
3571 CPUState *env = _env;
3573 if (kvm_enabled())
3574 kvm_init_vcpu(env);
3575 env->nr_cores = smp_cores;
3576 env->nr_threads = smp_threads;
3577 return;
3580 int qemu_cpu_self(void *env)
3582 return 1;
3585 static void resume_all_vcpus(void)
3589 static void pause_all_vcpus(void)
3593 void qemu_cpu_kick(void *env)
3595 return;
3598 void qemu_notify_event(void)
3600 CPUState *env = cpu_single_env;
3602 if (kvm_enabled()) {
3603 qemu_kvm_notify_work();
3604 return;
3606 if (env) {
3607 cpu_exit(env);
3611 #ifdef KVM_UPSTREAM
3612 void qemu_mutex_lock_iothread(void) {}
3613 void qemu_mutex_unlock_iothread(void) {}
3614 #endif
3616 void vm_stop(int reason)
3618 do_vm_stop(reason);
3621 #else /* CONFIG_IOTHREAD */
3623 #include "qemu-thread.h"
3625 QemuMutex qemu_global_mutex;
3626 static QemuMutex qemu_fair_mutex;
3628 static QemuThread io_thread;
3630 static QemuThread *tcg_cpu_thread;
3631 static QemuCond *tcg_halt_cond;
3633 static int qemu_system_ready;
3634 /* cpu creation */
3635 static QemuCond qemu_cpu_cond;
3636 /* system init */
3637 static QemuCond qemu_system_cond;
3638 static QemuCond qemu_pause_cond;
3640 static void block_io_signals(void);
3641 static void unblock_io_signals(void);
3642 static int tcg_has_work(void);
3644 static int qemu_init_main_loop(void)
3646 int ret;
3648 ret = qemu_event_init();
3649 if (ret)
3650 return ret;
3652 qemu_cond_init(&qemu_pause_cond);
3653 qemu_mutex_init(&qemu_fair_mutex);
3654 qemu_mutex_init(&qemu_global_mutex);
3655 qemu_mutex_lock(&qemu_global_mutex);
3657 unblock_io_signals();
3658 qemu_thread_self(&io_thread);
3660 return 0;
3663 static void qemu_wait_io_event(CPUState *env)
3665 while (!tcg_has_work())
3666 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3668 qemu_mutex_unlock(&qemu_global_mutex);
3671 * Users of qemu_global_mutex can be starved, having no chance
3672 * to acquire it since this path will get to it first.
3673 * So use another lock to provide fairness.
3675 qemu_mutex_lock(&qemu_fair_mutex);
3676 qemu_mutex_unlock(&qemu_fair_mutex);
3678 qemu_mutex_lock(&qemu_global_mutex);
3679 if (env->stop) {
3680 env->stop = 0;
3681 env->stopped = 1;
3682 qemu_cond_signal(&qemu_pause_cond);
3686 static int qemu_cpu_exec(CPUState *env);
3688 static void *kvm_cpu_thread_fn(void *arg)
3690 CPUState *env = arg;
3692 block_io_signals();
3693 qemu_thread_self(env->thread);
3694 if (kvm_enabled())
3695 kvm_init_vcpu(env);
3697 /* signal CPU creation */
3698 qemu_mutex_lock(&qemu_global_mutex);
3699 env->created = 1;
3700 qemu_cond_signal(&qemu_cpu_cond);
3702 /* and wait for machine initialization */
3703 while (!qemu_system_ready)
3704 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3706 while (1) {
3707 if (cpu_can_run(env))
3708 qemu_cpu_exec(env);
3709 qemu_wait_io_event(env);
3712 return NULL;
3715 static void tcg_cpu_exec(void);
3717 static void *tcg_cpu_thread_fn(void *arg)
3719 CPUState *env = arg;
3721 block_io_signals();
3722 qemu_thread_self(env->thread);
3724 /* signal CPU creation */
3725 qemu_mutex_lock(&qemu_global_mutex);
3726 for (env = first_cpu; env != NULL; env = env->next_cpu)
3727 env->created = 1;
3728 qemu_cond_signal(&qemu_cpu_cond);
3730 /* and wait for machine initialization */
3731 while (!qemu_system_ready)
3732 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3734 while (1) {
3735 tcg_cpu_exec();
3736 qemu_wait_io_event(cur_cpu);
3739 return NULL;
3742 void qemu_cpu_kick(void *_env)
3744 CPUState *env = _env;
3745 qemu_cond_broadcast(env->halt_cond);
3746 if (kvm_enabled())
3747 qemu_thread_signal(env->thread, SIGUSR1);
3750 int qemu_cpu_self(void *_env)
3752 CPUState *env = _env;
3753 QemuThread this;
3755 qemu_thread_self(&this);
3757 return qemu_thread_equal(&this, env->thread);
3760 static void cpu_signal(int sig)
3762 if (cpu_single_env)
3763 cpu_exit(cpu_single_env);
3766 static void block_io_signals(void)
3768 sigset_t set;
3769 struct sigaction sigact;
3771 sigemptyset(&set);
3772 sigaddset(&set, SIGUSR2);
3773 sigaddset(&set, SIGIO);
3774 sigaddset(&set, SIGALRM);
3775 pthread_sigmask(SIG_BLOCK, &set, NULL);
3777 sigemptyset(&set);
3778 sigaddset(&set, SIGUSR1);
3779 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3781 memset(&sigact, 0, sizeof(sigact));
3782 sigact.sa_handler = cpu_signal;
3783 sigaction(SIGUSR1, &sigact, NULL);
3786 static void unblock_io_signals(void)
3788 sigset_t set;
3790 sigemptyset(&set);
3791 sigaddset(&set, SIGUSR2);
3792 sigaddset(&set, SIGIO);
3793 sigaddset(&set, SIGALRM);
3794 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3796 sigemptyset(&set);
3797 sigaddset(&set, SIGUSR1);
3798 pthread_sigmask(SIG_BLOCK, &set, NULL);
3801 static void qemu_signal_lock(unsigned int msecs)
3803 qemu_mutex_lock(&qemu_fair_mutex);
3805 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3806 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3807 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3808 break;
3810 qemu_mutex_unlock(&qemu_fair_mutex);
3813 void qemu_mutex_lock_iothread(void)
3815 if (kvm_enabled()) {
3816 qemu_mutex_lock(&qemu_fair_mutex);
3817 qemu_mutex_lock(&qemu_global_mutex);
3818 qemu_mutex_unlock(&qemu_fair_mutex);
3819 } else
3820 qemu_signal_lock(100);
3823 void qemu_mutex_unlock_iothread(void)
3825 qemu_mutex_unlock(&qemu_global_mutex);
3828 static int all_vcpus_paused(void)
3830 CPUState *penv = first_cpu;
3832 while (penv) {
3833 if (!penv->stopped)
3834 return 0;
3835 penv = (CPUState *)penv->next_cpu;
3838 return 1;
3841 static void pause_all_vcpus(void)
3843 CPUState *penv = first_cpu;
3845 while (penv) {
3846 penv->stop = 1;
3847 qemu_thread_signal(penv->thread, SIGUSR1);
3848 qemu_cpu_kick(penv);
3849 penv = (CPUState *)penv->next_cpu;
3852 while (!all_vcpus_paused()) {
3853 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3854 penv = first_cpu;
3855 while (penv) {
3856 qemu_thread_signal(penv->thread, SIGUSR1);
3857 penv = (CPUState *)penv->next_cpu;
3862 static void resume_all_vcpus(void)
3864 CPUState *penv = first_cpu;
3866 while (penv) {
3867 penv->stop = 0;
3868 penv->stopped = 0;
3869 qemu_thread_signal(penv->thread, SIGUSR1);
3870 qemu_cpu_kick(penv);
3871 penv = (CPUState *)penv->next_cpu;
3875 static void tcg_init_vcpu(void *_env)
3877 CPUState *env = _env;
3878 /* share a single thread for all cpus with TCG */
3879 if (!tcg_cpu_thread) {
3880 env->thread = qemu_mallocz(sizeof(QemuThread));
3881 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3882 qemu_cond_init(env->halt_cond);
3883 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3884 while (env->created == 0)
3885 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3886 tcg_cpu_thread = env->thread;
3887 tcg_halt_cond = env->halt_cond;
3888 } else {
3889 env->thread = tcg_cpu_thread;
3890 env->halt_cond = tcg_halt_cond;
3894 static void kvm_start_vcpu(CPUState *env)
3896 env->thread = qemu_mallocz(sizeof(QemuThread));
3897 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3898 qemu_cond_init(env->halt_cond);
3899 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3900 while (env->created == 0)
3901 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3904 void qemu_init_vcpu(void *_env)
3906 CPUState *env = _env;
3908 if (kvm_enabled())
3909 kvm_start_vcpu(env);
3910 else
3911 tcg_init_vcpu(env);
3912 env->nr_cores = smp_cores;
3913 env->nr_threads = smp_threads;
3916 void qemu_notify_event(void)
3918 qemu_event_increment();
3921 void vm_stop(int reason)
3923 QemuThread me;
3924 qemu_thread_self(&me);
3926 if (!qemu_thread_equal(&me, &io_thread)) {
3927 qemu_system_vmstop_request(reason);
3929 * FIXME: should not return to device code in case
3930 * vm_stop() has been requested.
3932 if (cpu_single_env) {
3933 cpu_exit(cpu_single_env);
3934 cpu_single_env->stop = 1;
3936 return;
3938 do_vm_stop(reason);
3941 #endif
3944 #ifdef _WIN32
3945 static void host_main_loop_wait(int *timeout)
3947 int ret, ret2, i;
3948 PollingEntry *pe;
3951 /* XXX: need to suppress polling by better using win32 events */
3952 ret = 0;
3953 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3954 ret |= pe->func(pe->opaque);
3956 if (ret == 0) {
3957 int err;
3958 WaitObjects *w = &wait_objects;
3960 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3961 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3962 if (w->func[ret - WAIT_OBJECT_0])
3963 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3965 /* Check for additional signaled events */
3966 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3968 /* Check if event is signaled */
3969 ret2 = WaitForSingleObject(w->events[i], 0);
3970 if(ret2 == WAIT_OBJECT_0) {
3971 if (w->func[i])
3972 w->func[i](w->opaque[i]);
3973 } else if (ret2 == WAIT_TIMEOUT) {
3974 } else {
3975 err = GetLastError();
3976 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3979 } else if (ret == WAIT_TIMEOUT) {
3980 } else {
3981 err = GetLastError();
3982 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3986 *timeout = 0;
3988 #else
3989 static void host_main_loop_wait(int *timeout)
3992 #endif
3994 void main_loop_wait(int timeout)
3996 IOHandlerRecord *ioh;
3997 fd_set rfds, wfds, xfds;
3998 int ret, nfds;
3999 struct timeval tv;
4001 qemu_bh_update_timeout(&timeout);
4003 host_main_loop_wait(&timeout);
4005 /* poll any events */
4006 /* XXX: separate device handlers from system ones */
4007 nfds = -1;
4008 FD_ZERO(&rfds);
4009 FD_ZERO(&wfds);
4010 FD_ZERO(&xfds);
4011 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4012 if (ioh->deleted)
4013 continue;
4014 if (ioh->fd_read &&
4015 (!ioh->fd_read_poll ||
4016 ioh->fd_read_poll(ioh->opaque) != 0)) {
4017 FD_SET(ioh->fd, &rfds);
4018 if (ioh->fd > nfds)
4019 nfds = ioh->fd;
4021 if (ioh->fd_write) {
4022 FD_SET(ioh->fd, &wfds);
4023 if (ioh->fd > nfds)
4024 nfds = ioh->fd;
4028 tv.tv_sec = timeout / 1000;
4029 tv.tv_usec = (timeout % 1000) * 1000;
4031 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4033 qemu_mutex_unlock_iothread();
4034 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4035 qemu_mutex_lock_iothread();
4036 if (ret > 0) {
4037 IOHandlerRecord **pioh;
4039 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4040 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4041 ioh->fd_read(ioh->opaque);
4042 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4043 FD_CLR(ioh->fd, &rfds);
4045 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4046 ioh->fd_write(ioh->opaque);
4050 /* remove deleted IO handlers */
4051 pioh = &first_io_handler;
4052 while (*pioh) {
4053 ioh = *pioh;
4054 if (ioh->deleted) {
4055 *pioh = ioh->next;
4056 qemu_free(ioh);
4057 } else
4058 pioh = &ioh->next;
4062 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4064 /* rearm timer, if not periodic */
4065 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4066 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4067 qemu_rearm_alarm_timer(alarm_timer);
4070 /* vm time timers */
4071 if (vm_running) {
4072 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4073 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
4074 qemu_get_clock(vm_clock));
4077 /* real time timers */
4078 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
4079 qemu_get_clock(rt_clock));
4081 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
4082 qemu_get_clock(host_clock));
4084 /* Check bottom-halves last in case any of the earlier events triggered
4085 them. */
4086 qemu_bh_poll();
4090 static int qemu_cpu_exec(CPUState *env)
4092 int ret;
4093 #ifdef CONFIG_PROFILER
4094 int64_t ti;
4095 #endif
4097 #ifdef CONFIG_PROFILER
4098 ti = profile_getclock();
4099 #endif
4100 if (use_icount) {
4101 int64_t count;
4102 int decr;
4103 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4104 env->icount_decr.u16.low = 0;
4105 env->icount_extra = 0;
4106 count = qemu_next_deadline();
4107 count = (count + (1 << icount_time_shift) - 1)
4108 >> icount_time_shift;
4109 qemu_icount += count;
4110 decr = (count > 0xffff) ? 0xffff : count;
4111 count -= decr;
4112 env->icount_decr.u16.low = decr;
4113 env->icount_extra = count;
4115 ret = cpu_exec(env);
4116 #ifdef CONFIG_PROFILER
4117 qemu_time += profile_getclock() - ti;
4118 #endif
4119 if (use_icount) {
4120 /* Fold pending instructions back into the
4121 instruction counter, and clear the interrupt flag. */
4122 qemu_icount -= (env->icount_decr.u16.low
4123 + env->icount_extra);
4124 env->icount_decr.u32 = 0;
4125 env->icount_extra = 0;
4127 return ret;
4130 static void tcg_cpu_exec(void)
4132 int ret = 0;
4134 if (next_cpu == NULL)
4135 next_cpu = first_cpu;
4136 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4137 CPUState *env = cur_cpu = next_cpu;
4139 if (!vm_running)
4140 break;
4141 if (timer_alarm_pending) {
4142 timer_alarm_pending = 0;
4143 break;
4145 if (cpu_can_run(env))
4146 ret = qemu_cpu_exec(env);
4147 if (ret == EXCP_DEBUG) {
4148 gdb_set_stop_cpu(env);
4149 debug_requested = 1;
4150 break;
4155 static int cpu_has_work(CPUState *env)
4157 if (env->stop)
4158 return 1;
4159 if (env->stopped)
4160 return 0;
4161 if (!env->halted)
4162 return 1;
4163 if (qemu_cpu_has_work(env))
4164 return 1;
4165 return 0;
4168 static int tcg_has_work(void)
4170 CPUState *env;
4172 for (env = first_cpu; env != NULL; env = env->next_cpu)
4173 if (cpu_has_work(env))
4174 return 1;
4175 return 0;
4178 static int qemu_calculate_timeout(void)
4180 #ifndef CONFIG_IOTHREAD
4181 int timeout;
4183 if (!vm_running)
4184 timeout = 5000;
4185 else if (tcg_has_work())
4186 timeout = 0;
4187 else if (!use_icount)
4188 timeout = 5000;
4189 else {
4190 /* XXX: use timeout computed from timers */
4191 int64_t add;
4192 int64_t delta;
4193 /* Advance virtual time to the next event. */
4194 if (use_icount == 1) {
4195 /* When not using an adaptive execution frequency
4196 we tend to get badly out of sync with real time,
4197 so just delay for a reasonable amount of time. */
4198 delta = 0;
4199 } else {
4200 delta = cpu_get_icount() - cpu_get_clock();
4202 if (delta > 0) {
4203 /* If virtual time is ahead of real time then just
4204 wait for IO. */
4205 timeout = (delta / 1000000) + 1;
4206 } else {
4207 /* Wait for either IO to occur or the next
4208 timer event. */
4209 add = qemu_next_deadline();
4210 /* We advance the timer before checking for IO.
4211 Limit the amount we advance so that early IO
4212 activity won't get the guest too far ahead. */
4213 if (add > 10000000)
4214 add = 10000000;
4215 delta += add;
4216 add = (add + (1 << icount_time_shift) - 1)
4217 >> icount_time_shift;
4218 qemu_icount += add;
4219 timeout = delta / 1000000;
4220 if (timeout < 0)
4221 timeout = 0;
4225 return timeout;
4226 #else /* CONFIG_IOTHREAD */
4227 return 1000;
4228 #endif
4231 static int vm_can_run(void)
4233 if (powerdown_requested)
4234 return 0;
4235 if (reset_requested)
4236 return 0;
4237 if (shutdown_requested)
4238 return 0;
4239 if (debug_requested)
4240 return 0;
4241 return 1;
4244 qemu_irq qemu_system_powerdown;
4246 static void main_loop(void)
4248 int r;
4250 if (kvm_enabled()) {
4251 kvm_main_loop();
4252 cpu_disable_ticks();
4253 return;
4256 #ifdef CONFIG_IOTHREAD
4257 qemu_system_ready = 1;
4258 qemu_cond_broadcast(&qemu_system_cond);
4259 #endif
4261 for (;;) {
4262 do {
4263 #ifdef CONFIG_PROFILER
4264 int64_t ti;
4265 #endif
4266 #ifndef CONFIG_IOTHREAD
4267 tcg_cpu_exec();
4268 #endif
4269 #ifdef CONFIG_PROFILER
4270 ti = profile_getclock();
4271 #endif
4272 main_loop_wait(qemu_calculate_timeout());
4273 #ifdef CONFIG_PROFILER
4274 dev_time += profile_getclock() - ti;
4275 #endif
4276 } while (vm_can_run());
4278 if (qemu_debug_requested())
4279 vm_stop(EXCP_DEBUG);
4280 if (qemu_shutdown_requested()) {
4281 if (no_shutdown) {
4282 vm_stop(0);
4283 no_shutdown = 0;
4284 } else
4285 break;
4287 if (qemu_reset_requested()) {
4288 pause_all_vcpus();
4289 qemu_system_reset();
4290 resume_all_vcpus();
4292 if (qemu_powerdown_requested()) {
4293 qemu_irq_raise(qemu_system_powerdown);
4295 if ((r = qemu_vmstop_requested()))
4296 vm_stop(r);
4298 pause_all_vcpus();
4301 static void version(void)
4303 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4306 static void help(int exitcode)
4308 version();
4309 printf("usage: %s [options] [disk_image]\n"
4310 "\n"
4311 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4312 "\n"
4313 #define DEF(option, opt_arg, opt_enum, opt_help) \
4314 opt_help
4315 #define DEFHEADING(text) stringify(text) "\n"
4316 #include "qemu-options.h"
4317 #undef DEF
4318 #undef DEFHEADING
4319 #undef GEN_DOCS
4320 "\n"
4321 "During emulation, the following keys are useful:\n"
4322 "ctrl-alt-f toggle full screen\n"
4323 "ctrl-alt-n switch to virtual console 'n'\n"
4324 "ctrl-alt toggle mouse and keyboard grab\n"
4325 "\n"
4326 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4328 "qemu",
4329 DEFAULT_RAM_SIZE,
4330 #ifndef _WIN32
4331 DEFAULT_NETWORK_SCRIPT,
4332 DEFAULT_NETWORK_DOWN_SCRIPT,
4333 #endif
4334 DEFAULT_GDBSTUB_PORT,
4335 "/tmp/qemu.log");
4336 exit(exitcode);
4339 #define HAS_ARG 0x0001
4341 enum {
4342 #define DEF(option, opt_arg, opt_enum, opt_help) \
4343 opt_enum,
4344 #define DEFHEADING(text)
4345 #include "qemu-options.h"
4346 #undef DEF
4347 #undef DEFHEADING
4348 #undef GEN_DOCS
4351 typedef struct QEMUOption {
4352 const char *name;
4353 int flags;
4354 int index;
4355 } QEMUOption;
4357 static const QEMUOption qemu_options[] = {
4358 { "h", 0, QEMU_OPTION_h },
4359 #define DEF(option, opt_arg, opt_enum, opt_help) \
4360 { option, opt_arg, opt_enum },
4361 #define DEFHEADING(text)
4362 #include "qemu-options.h"
4363 #undef DEF
4364 #undef DEFHEADING
4365 #undef GEN_DOCS
4366 { NULL },
4369 #ifdef HAS_AUDIO
4370 struct soundhw soundhw[] = {
4371 #ifdef HAS_AUDIO_CHOICE
4372 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4374 "pcspk",
4375 "PC speaker",
4378 { .init_isa = pcspk_audio_init }
4380 #endif
4382 #ifdef CONFIG_SB16
4384 "sb16",
4385 "Creative Sound Blaster 16",
4388 { .init_isa = SB16_init }
4390 #endif
4392 #ifdef CONFIG_CS4231A
4394 "cs4231a",
4395 "CS4231A",
4398 { .init_isa = cs4231a_init }
4400 #endif
4402 #ifdef CONFIG_ADLIB
4404 "adlib",
4405 #ifdef HAS_YMF262
4406 "Yamaha YMF262 (OPL3)",
4407 #else
4408 "Yamaha YM3812 (OPL2)",
4409 #endif
4412 { .init_isa = Adlib_init }
4414 #endif
4416 #ifdef CONFIG_GUS
4418 "gus",
4419 "Gravis Ultrasound GF1",
4422 { .init_isa = GUS_init }
4424 #endif
4426 #ifdef CONFIG_AC97
4428 "ac97",
4429 "Intel 82801AA AC97 Audio",
4432 { .init_pci = ac97_init }
4434 #endif
4436 #ifdef CONFIG_ES1370
4438 "es1370",
4439 "ENSONIQ AudioPCI ES1370",
4442 { .init_pci = es1370_init }
4444 #endif
4446 #endif /* HAS_AUDIO_CHOICE */
4448 { NULL, NULL, 0, 0, { NULL } }
4451 static void select_soundhw (const char *optarg)
4453 struct soundhw *c;
4455 if (*optarg == '?') {
4456 show_valid_cards:
4458 printf ("Valid sound card names (comma separated):\n");
4459 for (c = soundhw; c->name; ++c) {
4460 printf ("%-11s %s\n", c->name, c->descr);
4462 printf ("\n-soundhw all will enable all of the above\n");
4463 exit (*optarg != '?');
4465 else {
4466 size_t l;
4467 const char *p;
4468 char *e;
4469 int bad_card = 0;
4471 if (!strcmp (optarg, "all")) {
4472 for (c = soundhw; c->name; ++c) {
4473 c->enabled = 1;
4475 return;
4478 p = optarg;
4479 while (*p) {
4480 e = strchr (p, ',');
4481 l = !e ? strlen (p) : (size_t) (e - p);
4483 for (c = soundhw; c->name; ++c) {
4484 if (!strncmp (c->name, p, l) && !c->name[l]) {
4485 c->enabled = 1;
4486 break;
4490 if (!c->name) {
4491 if (l > 80) {
4492 fprintf (stderr,
4493 "Unknown sound card name (too big to show)\n");
4495 else {
4496 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4497 (int) l, p);
4499 bad_card = 1;
4501 p += l + (e != NULL);
4504 if (bad_card)
4505 goto show_valid_cards;
4508 #endif
4510 static void select_vgahw (const char *p)
4512 const char *opts;
4514 vga_interface_type = VGA_NONE;
4515 if (strstart(p, "std", &opts)) {
4516 vga_interface_type = VGA_STD;
4517 } else if (strstart(p, "cirrus", &opts)) {
4518 vga_interface_type = VGA_CIRRUS;
4519 } else if (strstart(p, "vmware", &opts)) {
4520 vga_interface_type = VGA_VMWARE;
4521 } else if (strstart(p, "xenfb", &opts)) {
4522 vga_interface_type = VGA_XENFB;
4523 } else if (!strstart(p, "none", &opts)) {
4524 invalid_vga:
4525 fprintf(stderr, "Unknown vga type: %s\n", p);
4526 exit(1);
4528 while (*opts) {
4529 const char *nextopt;
4531 if (strstart(opts, ",retrace=", &nextopt)) {
4532 opts = nextopt;
4533 if (strstart(opts, "dumb", &nextopt))
4534 vga_retrace_method = VGA_RETRACE_DUMB;
4535 else if (strstart(opts, "precise", &nextopt))
4536 vga_retrace_method = VGA_RETRACE_PRECISE;
4537 else goto invalid_vga;
4538 } else goto invalid_vga;
4539 opts = nextopt;
4543 #ifdef TARGET_I386
4544 static int balloon_parse(const char *arg)
4546 QemuOpts *opts;
4548 if (strcmp(arg, "none") == 0) {
4549 return 0;
4552 if (!strncmp(arg, "virtio", 6)) {
4553 if (arg[6] == ',') {
4554 /* have params -> parse them */
4555 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4556 if (!opts)
4557 return -1;
4558 } else {
4559 /* create empty opts */
4560 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4562 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4563 return 0;
4566 return -1;
4568 #endif
4570 #ifdef _WIN32
4571 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4573 exit(STATUS_CONTROL_C_EXIT);
4574 return TRUE;
4576 #endif
4578 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4580 int ret;
4582 if(strlen(str) != 36)
4583 return -1;
4585 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4586 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4587 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4589 if(ret != 16)
4590 return -1;
4592 #ifdef TARGET_I386
4593 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4594 #endif
4596 return 0;
4599 #ifndef _WIN32
4601 static void termsig_handler(int signal)
4603 qemu_system_shutdown_request();
4606 static void sigchld_handler(int signal)
4608 waitpid(-1, NULL, WNOHANG);
4611 static void sighandler_setup(void)
4613 struct sigaction act;
4615 memset(&act, 0, sizeof(act));
4616 act.sa_handler = termsig_handler;
4617 sigaction(SIGINT, &act, NULL);
4618 sigaction(SIGHUP, &act, NULL);
4619 sigaction(SIGTERM, &act, NULL);
4621 act.sa_handler = sigchld_handler;
4622 act.sa_flags = SA_NOCLDSTOP;
4623 sigaction(SIGCHLD, &act, NULL);
4626 #endif
4628 #ifdef _WIN32
4629 /* Look for support files in the same directory as the executable. */
4630 static char *find_datadir(const char *argv0)
4632 char *p;
4633 char buf[MAX_PATH];
4634 DWORD len;
4636 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4637 if (len == 0) {
4638 return NULL;
4641 buf[len] = 0;
4642 p = buf + len - 1;
4643 while (p != buf && *p != '\\')
4644 p--;
4645 *p = 0;
4646 if (access(buf, R_OK) == 0) {
4647 return qemu_strdup(buf);
4649 return NULL;
4651 #else /* !_WIN32 */
4653 /* Find a likely location for support files using the location of the binary.
4654 For installed binaries this will be "$bindir/../share/qemu". When
4655 running from the build tree this will be "$bindir/../pc-bios". */
4656 #define SHARE_SUFFIX "/share/qemu"
4657 #define BUILD_SUFFIX "/pc-bios"
4658 static char *find_datadir(const char *argv0)
4660 char *dir;
4661 char *p = NULL;
4662 char *res;
4663 char buf[PATH_MAX];
4664 size_t max_len;
4666 #if defined(__linux__)
4668 int len;
4669 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4670 if (len > 0) {
4671 buf[len] = 0;
4672 p = buf;
4675 #elif defined(__FreeBSD__)
4677 int len;
4678 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4679 if (len > 0) {
4680 buf[len] = 0;
4681 p = buf;
4684 #endif
4685 /* If we don't have any way of figuring out the actual executable
4686 location then try argv[0]. */
4687 if (!p) {
4688 p = realpath(argv0, buf);
4689 if (!p) {
4690 return NULL;
4693 dir = dirname(p);
4694 dir = dirname(dir);
4696 max_len = strlen(dir) +
4697 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4698 res = qemu_mallocz(max_len);
4699 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4700 if (access(res, R_OK)) {
4701 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4702 if (access(res, R_OK)) {
4703 qemu_free(res);
4704 res = NULL;
4708 return res;
4710 #undef SHARE_SUFFIX
4711 #undef BUILD_SUFFIX
4712 #endif
4714 char *qemu_find_file(int type, const char *name)
4716 int len;
4717 const char *subdir;
4718 char *buf;
4720 /* If name contains path separators then try it as a straight path. */
4721 if ((strchr(name, '/') || strchr(name, '\\'))
4722 && access(name, R_OK) == 0) {
4723 return qemu_strdup(name);
4725 switch (type) {
4726 case QEMU_FILE_TYPE_BIOS:
4727 subdir = "";
4728 break;
4729 case QEMU_FILE_TYPE_KEYMAP:
4730 subdir = "keymaps/";
4731 break;
4732 default:
4733 abort();
4735 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4736 buf = qemu_mallocz(len);
4737 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4738 if (access(buf, R_OK)) {
4739 qemu_free(buf);
4740 return NULL;
4742 return buf;
4745 static int device_init_func(QemuOpts *opts, void *opaque)
4747 DeviceState *dev;
4749 dev = qdev_device_add(opts);
4750 if (!dev)
4751 return -1;
4752 return 0;
4755 struct device_config {
4756 enum {
4757 DEV_USB, /* -usbdevice */
4758 DEV_BT, /* -bt */
4759 } type;
4760 const char *cmdline;
4761 QTAILQ_ENTRY(device_config) next;
4763 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4765 static void add_device_config(int type, const char *cmdline)
4767 struct device_config *conf;
4769 conf = qemu_mallocz(sizeof(*conf));
4770 conf->type = type;
4771 conf->cmdline = cmdline;
4772 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4775 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4777 struct device_config *conf;
4778 int rc;
4780 QTAILQ_FOREACH(conf, &device_configs, next) {
4781 if (conf->type != type)
4782 continue;
4783 rc = func(conf->cmdline);
4784 if (0 != rc)
4785 return rc;
4787 return 0;
4790 int main(int argc, char **argv, char **envp)
4792 const char *gdbstub_dev = NULL;
4793 uint32_t boot_devices_bitmap = 0;
4794 int i;
4795 int snapshot, linux_boot, net_boot;
4796 const char *initrd_filename;
4797 const char *kernel_filename, *kernel_cmdline;
4798 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4799 DisplayState *ds;
4800 DisplayChangeListener *dcl;
4801 int cyls, heads, secs, translation;
4802 QemuOpts *hda_opts = NULL, *opts;
4803 int optind;
4804 const char *r, *optarg;
4805 CharDriverState *monitor_hds[MAX_MONITOR_DEVICES];
4806 const char *monitor_devices[MAX_MONITOR_DEVICES];
4807 int monitor_device_index;
4808 const char *serial_devices[MAX_SERIAL_PORTS];
4809 int serial_device_index;
4810 const char *parallel_devices[MAX_PARALLEL_PORTS];
4811 int parallel_device_index;
4812 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4813 int virtio_console_index;
4814 const char *loadvm = NULL;
4815 QEMUMachine *machine;
4816 const char *cpu_model;
4817 #ifndef _WIN32
4818 int fds[2];
4819 #endif
4820 int tb_size;
4821 const char *pid_file = NULL;
4822 const char *incoming = NULL;
4823 #ifndef _WIN32
4824 int fd = 0;
4825 struct passwd *pwd = NULL;
4826 const char *chroot_dir = NULL;
4827 const char *run_as = NULL;
4828 #endif
4829 CPUState *env;
4830 int show_vnc_port = 0;
4832 init_clocks();
4834 qemu_errors_to_file(stderr);
4835 qemu_cache_utils_init(envp);
4837 QLIST_INIT (&vm_change_state_head);
4838 #ifndef _WIN32
4840 struct sigaction act;
4841 sigfillset(&act.sa_mask);
4842 act.sa_flags = 0;
4843 act.sa_handler = SIG_IGN;
4844 sigaction(SIGPIPE, &act, NULL);
4846 #else
4847 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4848 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4849 QEMU to run on a single CPU */
4851 HANDLE h;
4852 DWORD mask, smask;
4853 int i;
4854 h = GetCurrentProcess();
4855 if (GetProcessAffinityMask(h, &mask, &smask)) {
4856 for(i = 0; i < 32; i++) {
4857 if (mask & (1 << i))
4858 break;
4860 if (i != 32) {
4861 mask = 1 << i;
4862 SetProcessAffinityMask(h, mask);
4866 #endif
4868 module_call_init(MODULE_INIT_MACHINE);
4869 machine = find_default_machine();
4870 cpu_model = NULL;
4871 initrd_filename = NULL;
4872 ram_size = 0;
4873 snapshot = 0;
4874 kernel_filename = NULL;
4875 kernel_cmdline = "";
4876 cyls = heads = secs = 0;
4877 translation = BIOS_ATA_TRANSLATION_AUTO;
4879 serial_devices[0] = "vc:80Cx24C";
4880 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4881 serial_devices[i] = NULL;
4882 serial_device_index = 0;
4884 parallel_devices[0] = "vc:80Cx24C";
4885 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4886 parallel_devices[i] = NULL;
4887 parallel_device_index = 0;
4889 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4890 virtio_consoles[i] = NULL;
4891 virtio_console_index = 0;
4893 monitor_devices[0] = "vc:80Cx24C";
4894 for (i = 1; i < MAX_MONITOR_DEVICES; i++) {
4895 monitor_devices[i] = NULL;
4897 monitor_device_index = 0;
4899 for (i = 0; i < MAX_NODES; i++) {
4900 node_mem[i] = 0;
4901 node_cpumask[i] = 0;
4904 assigned_devices_index = 0;
4906 nb_numa_nodes = 0;
4907 nb_nics = 0;
4909 tb_size = 0;
4910 autostart= 1;
4912 optind = 1;
4913 for(;;) {
4914 if (optind >= argc)
4915 break;
4916 r = argv[optind];
4917 if (r[0] != '-') {
4918 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4919 } else {
4920 const QEMUOption *popt;
4922 optind++;
4923 /* Treat --foo the same as -foo. */
4924 if (r[1] == '-')
4925 r++;
4926 popt = qemu_options;
4927 for(;;) {
4928 if (!popt->name) {
4929 fprintf(stderr, "%s: invalid option -- '%s'\n",
4930 argv[0], r);
4931 exit(1);
4933 if (!strcmp(popt->name, r + 1))
4934 break;
4935 popt++;
4937 if (popt->flags & HAS_ARG) {
4938 if (optind >= argc) {
4939 fprintf(stderr, "%s: option '%s' requires an argument\n",
4940 argv[0], r);
4941 exit(1);
4943 optarg = argv[optind++];
4944 } else {
4945 optarg = NULL;
4948 switch(popt->index) {
4949 case QEMU_OPTION_M:
4950 machine = find_machine(optarg);
4951 if (!machine) {
4952 QEMUMachine *m;
4953 printf("Supported machines are:\n");
4954 for(m = first_machine; m != NULL; m = m->next) {
4955 if (m->alias)
4956 printf("%-10s %s (alias of %s)\n",
4957 m->alias, m->desc, m->name);
4958 printf("%-10s %s%s\n",
4959 m->name, m->desc,
4960 m->is_default ? " (default)" : "");
4962 exit(*optarg != '?');
4964 break;
4965 case QEMU_OPTION_cpu:
4966 /* hw initialization will check this */
4967 if (*optarg == '?') {
4968 /* XXX: implement xxx_cpu_list for targets that still miss it */
4969 #if defined(cpu_list)
4970 cpu_list(stdout, &fprintf);
4971 #endif
4972 exit(0);
4973 } else {
4974 cpu_model = optarg;
4976 break;
4977 case QEMU_OPTION_initrd:
4978 initrd_filename = optarg;
4979 break;
4980 case QEMU_OPTION_hda:
4981 if (cyls == 0)
4982 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4983 else
4984 hda_opts = drive_add(optarg, HD_ALIAS
4985 ",cyls=%d,heads=%d,secs=%d%s",
4986 0, cyls, heads, secs,
4987 translation == BIOS_ATA_TRANSLATION_LBA ?
4988 ",trans=lba" :
4989 translation == BIOS_ATA_TRANSLATION_NONE ?
4990 ",trans=none" : "");
4991 break;
4992 case QEMU_OPTION_hdb:
4993 case QEMU_OPTION_hdc:
4994 case QEMU_OPTION_hdd:
4995 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4996 break;
4997 case QEMU_OPTION_drive:
4998 drive_add(NULL, "%s", optarg);
4999 break;
5000 case QEMU_OPTION_set:
5001 if (qemu_set_option(optarg) != 0)
5002 exit(1);
5003 break;
5004 case QEMU_OPTION_mtdblock:
5005 drive_add(optarg, MTD_ALIAS);
5006 break;
5007 case QEMU_OPTION_sd:
5008 drive_add(optarg, SD_ALIAS);
5009 break;
5010 case QEMU_OPTION_pflash:
5011 drive_add(optarg, PFLASH_ALIAS);
5012 break;
5013 case QEMU_OPTION_snapshot:
5014 snapshot = 1;
5015 break;
5016 case QEMU_OPTION_hdachs:
5018 const char *p;
5019 p = optarg;
5020 cyls = strtol(p, (char **)&p, 0);
5021 if (cyls < 1 || cyls > 16383)
5022 goto chs_fail;
5023 if (*p != ',')
5024 goto chs_fail;
5025 p++;
5026 heads = strtol(p, (char **)&p, 0);
5027 if (heads < 1 || heads > 16)
5028 goto chs_fail;
5029 if (*p != ',')
5030 goto chs_fail;
5031 p++;
5032 secs = strtol(p, (char **)&p, 0);
5033 if (secs < 1 || secs > 63)
5034 goto chs_fail;
5035 if (*p == ',') {
5036 p++;
5037 if (!strcmp(p, "none"))
5038 translation = BIOS_ATA_TRANSLATION_NONE;
5039 else if (!strcmp(p, "lba"))
5040 translation = BIOS_ATA_TRANSLATION_LBA;
5041 else if (!strcmp(p, "auto"))
5042 translation = BIOS_ATA_TRANSLATION_AUTO;
5043 else
5044 goto chs_fail;
5045 } else if (*p != '\0') {
5046 chs_fail:
5047 fprintf(stderr, "qemu: invalid physical CHS format\n");
5048 exit(1);
5050 if (hda_opts != NULL) {
5051 char num[16];
5052 snprintf(num, sizeof(num), "%d", cyls);
5053 qemu_opt_set(hda_opts, "cyls", num);
5054 snprintf(num, sizeof(num), "%d", heads);
5055 qemu_opt_set(hda_opts, "heads", num);
5056 snprintf(num, sizeof(num), "%d", secs);
5057 qemu_opt_set(hda_opts, "secs", num);
5058 if (translation == BIOS_ATA_TRANSLATION_LBA)
5059 qemu_opt_set(hda_opts, "trans", "lba");
5060 if (translation == BIOS_ATA_TRANSLATION_NONE)
5061 qemu_opt_set(hda_opts, "trans", "none");
5064 break;
5065 case QEMU_OPTION_numa:
5066 if (nb_numa_nodes >= MAX_NODES) {
5067 fprintf(stderr, "qemu: too many NUMA nodes\n");
5068 exit(1);
5070 numa_add(optarg);
5071 break;
5072 case QEMU_OPTION_nographic:
5073 display_type = DT_NOGRAPHIC;
5074 break;
5075 #ifdef CONFIG_CURSES
5076 case QEMU_OPTION_curses:
5077 display_type = DT_CURSES;
5078 break;
5079 #endif
5080 case QEMU_OPTION_portrait:
5081 graphic_rotate = 1;
5082 break;
5083 case QEMU_OPTION_kernel:
5084 kernel_filename = optarg;
5085 break;
5086 case QEMU_OPTION_append:
5087 kernel_cmdline = optarg;
5088 break;
5089 case QEMU_OPTION_cdrom:
5090 drive_add(optarg, CDROM_ALIAS);
5091 break;
5092 case QEMU_OPTION_boot:
5094 static const char * const params[] = {
5095 "order", "once", "menu", NULL
5097 char buf[sizeof(boot_devices)];
5098 char *standard_boot_devices;
5099 int legacy = 0;
5101 if (!strchr(optarg, '=')) {
5102 legacy = 1;
5103 pstrcpy(buf, sizeof(buf), optarg);
5104 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5105 fprintf(stderr,
5106 "qemu: unknown boot parameter '%s' in '%s'\n",
5107 buf, optarg);
5108 exit(1);
5111 if (legacy ||
5112 get_param_value(buf, sizeof(buf), "order", optarg)) {
5113 boot_devices_bitmap = parse_bootdevices(buf);
5114 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5116 if (!legacy) {
5117 if (get_param_value(buf, sizeof(buf),
5118 "once", optarg)) {
5119 boot_devices_bitmap |= parse_bootdevices(buf);
5120 standard_boot_devices = qemu_strdup(boot_devices);
5121 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5122 qemu_register_reset(restore_boot_devices,
5123 standard_boot_devices);
5125 if (get_param_value(buf, sizeof(buf),
5126 "menu", optarg)) {
5127 if (!strcmp(buf, "on")) {
5128 boot_menu = 1;
5129 } else if (!strcmp(buf, "off")) {
5130 boot_menu = 0;
5131 } else {
5132 fprintf(stderr,
5133 "qemu: invalid option value '%s'\n",
5134 buf);
5135 exit(1);
5140 break;
5141 case QEMU_OPTION_fda:
5142 case QEMU_OPTION_fdb:
5143 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5144 break;
5145 #ifdef TARGET_I386
5146 case QEMU_OPTION_no_fd_bootchk:
5147 fd_bootchk = 0;
5148 break;
5149 #endif
5150 case QEMU_OPTION_netdev:
5151 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5152 exit(1);
5154 break;
5155 case QEMU_OPTION_net:
5156 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5157 exit(1);
5159 break;
5160 #ifdef CONFIG_SLIRP
5161 case QEMU_OPTION_tftp:
5162 legacy_tftp_prefix = optarg;
5163 break;
5164 case QEMU_OPTION_bootp:
5165 legacy_bootp_filename = optarg;
5166 break;
5167 #ifndef _WIN32
5168 case QEMU_OPTION_smb:
5169 if (net_slirp_smb(optarg) < 0)
5170 exit(1);
5171 break;
5172 #endif
5173 case QEMU_OPTION_redir:
5174 if (net_slirp_redir(optarg) < 0)
5175 exit(1);
5176 break;
5177 #endif
5178 case QEMU_OPTION_bt:
5179 add_device_config(DEV_BT, optarg);
5180 break;
5181 #ifdef HAS_AUDIO
5182 case QEMU_OPTION_audio_help:
5183 AUD_help ();
5184 exit (0);
5185 break;
5186 case QEMU_OPTION_soundhw:
5187 select_soundhw (optarg);
5188 break;
5189 #endif
5190 case QEMU_OPTION_h:
5191 help(0);
5192 break;
5193 case QEMU_OPTION_version:
5194 version();
5195 exit(0);
5196 break;
5197 case QEMU_OPTION_m: {
5198 uint64_t value;
5199 char *ptr;
5201 value = strtoul(optarg, &ptr, 10);
5202 switch (*ptr) {
5203 case 0: case 'M': case 'm':
5204 value <<= 20;
5205 break;
5206 case 'G': case 'g':
5207 value <<= 30;
5208 break;
5209 default:
5210 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5211 exit(1);
5214 /* On 32-bit hosts, QEMU is limited by virtual address space */
5215 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5216 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5217 exit(1);
5219 if (value != (uint64_t)(ram_addr_t)value) {
5220 fprintf(stderr, "qemu: ram size too large\n");
5221 exit(1);
5223 ram_size = value;
5224 break;
5226 case QEMU_OPTION_d:
5228 int mask;
5229 const CPULogItem *item;
5231 mask = cpu_str_to_log_mask(optarg);
5232 if (!mask) {
5233 printf("Log items (comma separated):\n");
5234 for(item = cpu_log_items; item->mask != 0; item++) {
5235 printf("%-10s %s\n", item->name, item->help);
5237 exit(1);
5239 cpu_set_log(mask);
5241 break;
5242 case QEMU_OPTION_s:
5243 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5244 break;
5245 case QEMU_OPTION_gdb:
5246 gdbstub_dev = optarg;
5247 break;
5248 case QEMU_OPTION_L:
5249 data_dir = optarg;
5250 break;
5251 case QEMU_OPTION_bios:
5252 bios_name = optarg;
5253 break;
5254 case QEMU_OPTION_singlestep:
5255 singlestep = 1;
5256 break;
5257 case QEMU_OPTION_S:
5258 autostart = 0;
5259 break;
5260 #ifndef _WIN32
5261 case QEMU_OPTION_k:
5262 keyboard_layout = optarg;
5263 break;
5264 #endif
5265 case QEMU_OPTION_localtime:
5266 rtc_utc = 0;
5267 break;
5268 case QEMU_OPTION_vga:
5269 select_vgahw (optarg);
5270 break;
5271 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5272 case QEMU_OPTION_g:
5274 const char *p;
5275 int w, h, depth;
5276 p = optarg;
5277 w = strtol(p, (char **)&p, 10);
5278 if (w <= 0) {
5279 graphic_error:
5280 fprintf(stderr, "qemu: invalid resolution or depth\n");
5281 exit(1);
5283 if (*p != 'x')
5284 goto graphic_error;
5285 p++;
5286 h = strtol(p, (char **)&p, 10);
5287 if (h <= 0)
5288 goto graphic_error;
5289 if (*p == 'x') {
5290 p++;
5291 depth = strtol(p, (char **)&p, 10);
5292 if (depth != 8 && depth != 15 && depth != 16 &&
5293 depth != 24 && depth != 32)
5294 goto graphic_error;
5295 } else if (*p == '\0') {
5296 depth = graphic_depth;
5297 } else {
5298 goto graphic_error;
5301 graphic_width = w;
5302 graphic_height = h;
5303 graphic_depth = depth;
5305 break;
5306 #endif
5307 case QEMU_OPTION_echr:
5309 char *r;
5310 term_escape_char = strtol(optarg, &r, 0);
5311 if (r == optarg)
5312 printf("Bad argument to echr\n");
5313 break;
5315 case QEMU_OPTION_monitor:
5316 if (monitor_device_index >= MAX_MONITOR_DEVICES) {
5317 fprintf(stderr, "qemu: too many monitor devices\n");
5318 exit(1);
5320 monitor_devices[monitor_device_index] = optarg;
5321 monitor_device_index++;
5322 break;
5323 case QEMU_OPTION_chardev:
5324 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5325 if (!opts) {
5326 fprintf(stderr, "parse error: %s\n", optarg);
5327 exit(1);
5329 if (qemu_chr_open_opts(opts, NULL) == NULL) {
5330 exit(1);
5332 break;
5333 case QEMU_OPTION_serial:
5334 if (serial_device_index >= MAX_SERIAL_PORTS) {
5335 fprintf(stderr, "qemu: too many serial ports\n");
5336 exit(1);
5338 serial_devices[serial_device_index] = optarg;
5339 serial_device_index++;
5340 break;
5341 case QEMU_OPTION_watchdog:
5342 if (watchdog) {
5343 fprintf(stderr,
5344 "qemu: only one watchdog option may be given\n");
5345 return 1;
5347 watchdog = optarg;
5348 break;
5349 case QEMU_OPTION_watchdog_action:
5350 if (select_watchdog_action(optarg) == -1) {
5351 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5352 exit(1);
5354 break;
5355 case QEMU_OPTION_virtiocon:
5356 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5357 fprintf(stderr, "qemu: too many virtio consoles\n");
5358 exit(1);
5360 virtio_consoles[virtio_console_index] = optarg;
5361 virtio_console_index++;
5362 break;
5363 case QEMU_OPTION_parallel:
5364 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5365 fprintf(stderr, "qemu: too many parallel ports\n");
5366 exit(1);
5368 parallel_devices[parallel_device_index] = optarg;
5369 parallel_device_index++;
5370 break;
5371 case QEMU_OPTION_loadvm:
5372 loadvm = optarg;
5373 break;
5374 case QEMU_OPTION_full_screen:
5375 full_screen = 1;
5376 break;
5377 #ifdef CONFIG_SDL
5378 case QEMU_OPTION_no_frame:
5379 no_frame = 1;
5380 break;
5381 case QEMU_OPTION_alt_grab:
5382 alt_grab = 1;
5383 break;
5384 case QEMU_OPTION_ctrl_grab:
5385 ctrl_grab = 1;
5386 break;
5387 case QEMU_OPTION_no_quit:
5388 no_quit = 1;
5389 break;
5390 case QEMU_OPTION_sdl:
5391 display_type = DT_SDL;
5392 break;
5393 #endif
5394 case QEMU_OPTION_pidfile:
5395 pid_file = optarg;
5396 break;
5397 #ifdef TARGET_I386
5398 case QEMU_OPTION_win2k_hack:
5399 win2k_install_hack = 1;
5400 break;
5401 case QEMU_OPTION_rtc_td_hack:
5402 rtc_td_hack = 1;
5403 break;
5404 case QEMU_OPTION_acpitable:
5405 if(acpi_table_add(optarg) < 0) {
5406 fprintf(stderr, "Wrong acpi table provided\n");
5407 exit(1);
5409 break;
5410 case QEMU_OPTION_smbios:
5411 if(smbios_entry_add(optarg) < 0) {
5412 fprintf(stderr, "Wrong smbios provided\n");
5413 exit(1);
5415 break;
5416 #endif
5417 #ifdef CONFIG_KVM
5418 #ifdef KVM_UPSTREAM
5419 case QEMU_OPTION_enable_kvm:
5420 kvm_allowed = 1;
5421 #endif
5422 break;
5423 case QEMU_OPTION_no_kvm:
5424 kvm_allowed = 0;
5425 break;
5426 case QEMU_OPTION_no_kvm_irqchip: {
5427 kvm_irqchip = 0;
5428 kvm_pit = 0;
5429 break;
5431 case QEMU_OPTION_no_kvm_pit: {
5432 kvm_pit = 0;
5433 break;
5435 case QEMU_OPTION_no_kvm_pit_reinjection: {
5436 kvm_pit_reinject = 0;
5437 break;
5439 case QEMU_OPTION_enable_nesting: {
5440 kvm_nested = 1;
5441 break;
5443 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5444 case QEMU_OPTION_pcidevice:
5445 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5446 fprintf(stderr, "Too many assigned devices\n");
5447 exit(1);
5449 assigned_devices[assigned_devices_index] = optarg;
5450 assigned_devices_index++;
5451 break;
5452 #endif
5453 #endif
5454 case QEMU_OPTION_usb:
5455 usb_enabled = 1;
5456 break;
5457 case QEMU_OPTION_usbdevice:
5458 usb_enabled = 1;
5459 add_device_config(DEV_USB, optarg);
5460 break;
5461 case QEMU_OPTION_device:
5462 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5463 exit(1);
5465 break;
5466 case QEMU_OPTION_smp:
5467 smp_parse(optarg);
5468 if (smp_cpus < 1) {
5469 fprintf(stderr, "Invalid number of CPUs\n");
5470 exit(1);
5472 if (max_cpus < smp_cpus) {
5473 fprintf(stderr, "maxcpus must be equal to or greater than "
5474 "smp\n");
5475 exit(1);
5477 if (max_cpus > 255) {
5478 fprintf(stderr, "Unsupported number of maxcpus\n");
5479 exit(1);
5481 break;
5482 case QEMU_OPTION_vnc:
5483 display_type = DT_VNC;
5484 vnc_display = optarg;
5485 break;
5486 #ifdef TARGET_I386
5487 case QEMU_OPTION_no_acpi:
5488 acpi_enabled = 0;
5489 break;
5490 case QEMU_OPTION_no_hpet:
5491 no_hpet = 1;
5492 break;
5493 case QEMU_OPTION_balloon:
5494 if (balloon_parse(optarg) < 0) {
5495 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5496 exit(1);
5498 break;
5499 #endif
5500 case QEMU_OPTION_no_reboot:
5501 no_reboot = 1;
5502 break;
5503 case QEMU_OPTION_no_shutdown:
5504 no_shutdown = 1;
5505 break;
5506 case QEMU_OPTION_show_cursor:
5507 cursor_hide = 0;
5508 break;
5509 case QEMU_OPTION_uuid:
5510 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5511 fprintf(stderr, "Fail to parse UUID string."
5512 " Wrong format.\n");
5513 exit(1);
5515 break;
5516 #ifndef _WIN32
5517 case QEMU_OPTION_daemonize:
5518 daemonize = 1;
5519 break;
5520 #endif
5521 case QEMU_OPTION_option_rom:
5522 if (nb_option_roms >= MAX_OPTION_ROMS) {
5523 fprintf(stderr, "Too many option ROMs\n");
5524 exit(1);
5526 option_rom[nb_option_roms] = optarg;
5527 nb_option_roms++;
5528 break;
5529 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5530 case QEMU_OPTION_semihosting:
5531 semihosting_enabled = 1;
5532 break;
5533 #endif
5534 case QEMU_OPTION_tdf:
5535 time_drift_fix = 1;
5536 break;
5537 case QEMU_OPTION_kvm_shadow_memory:
5538 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5539 break;
5540 case QEMU_OPTION_mempath:
5541 mem_path = optarg;
5542 break;
5543 #ifdef MAP_POPULATE
5544 case QEMU_OPTION_mem_prealloc:
5545 mem_prealloc = !mem_prealloc;
5546 break;
5547 #endif
5548 case QEMU_OPTION_name:
5549 qemu_name = qemu_strdup(optarg);
5551 char *p = strchr(qemu_name, ',');
5552 if (p != NULL) {
5553 *p++ = 0;
5554 if (strncmp(p, "process=", 8)) {
5555 fprintf(stderr, "Unknown subargument %s to -name", p);
5556 exit(1);
5558 p += 8;
5559 set_proc_name(p);
5562 break;
5563 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5564 case QEMU_OPTION_prom_env:
5565 if (nb_prom_envs >= MAX_PROM_ENVS) {
5566 fprintf(stderr, "Too many prom variables\n");
5567 exit(1);
5569 prom_envs[nb_prom_envs] = optarg;
5570 nb_prom_envs++;
5571 break;
5572 #endif
5573 #ifdef TARGET_ARM
5574 case QEMU_OPTION_old_param:
5575 old_param = 1;
5576 break;
5577 #endif
5578 case QEMU_OPTION_clock:
5579 configure_alarms(optarg);
5580 break;
5581 case QEMU_OPTION_startdate:
5582 configure_rtc_date_offset(optarg, 1);
5583 break;
5584 case QEMU_OPTION_rtc:
5585 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5586 if (!opts) {
5587 fprintf(stderr, "parse error: %s\n", optarg);
5588 exit(1);
5590 configure_rtc(opts);
5591 break;
5592 case QEMU_OPTION_tb_size:
5593 tb_size = strtol(optarg, NULL, 0);
5594 if (tb_size < 0)
5595 tb_size = 0;
5596 break;
5597 case QEMU_OPTION_icount:
5598 use_icount = 1;
5599 if (strcmp(optarg, "auto") == 0) {
5600 icount_time_shift = -1;
5601 } else {
5602 icount_time_shift = strtol(optarg, NULL, 0);
5604 break;
5605 case QEMU_OPTION_incoming:
5606 incoming = optarg;
5607 break;
5608 #ifndef _WIN32
5609 case QEMU_OPTION_chroot:
5610 chroot_dir = optarg;
5611 break;
5612 case QEMU_OPTION_runas:
5613 run_as = optarg;
5614 break;
5615 case QEMU_OPTION_nvram:
5616 nvram = optarg;
5617 break;
5618 #endif
5619 #ifdef CONFIG_XEN
5620 case QEMU_OPTION_xen_domid:
5621 xen_domid = atoi(optarg);
5622 break;
5623 case QEMU_OPTION_xen_create:
5624 xen_mode = XEN_CREATE;
5625 break;
5626 case QEMU_OPTION_xen_attach:
5627 xen_mode = XEN_ATTACH;
5628 break;
5629 #endif
5634 /* If no data_dir is specified then try to find it relative to the
5635 executable path. */
5636 if (!data_dir) {
5637 data_dir = find_datadir(argv[0]);
5639 /* If all else fails use the install patch specified when building. */
5640 if (!data_dir) {
5641 data_dir = CONFIG_QEMU_SHAREDIR;
5645 * Default to max_cpus = smp_cpus, in case the user doesn't
5646 * specify a max_cpus value.
5648 if (!max_cpus)
5649 max_cpus = smp_cpus;
5651 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5652 if (smp_cpus > machine->max_cpus) {
5653 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5654 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5655 machine->max_cpus);
5656 exit(1);
5659 if (display_type == DT_NOGRAPHIC) {
5660 if (serial_device_index == 0)
5661 serial_devices[0] = "stdio";
5662 if (parallel_device_index == 0)
5663 parallel_devices[0] = "null";
5664 if (strncmp(monitor_devices[0], "vc", 2) == 0) {
5665 monitor_devices[0] = "stdio";
5669 #ifndef _WIN32
5670 if (daemonize) {
5671 pid_t pid;
5673 if (pipe(fds) == -1)
5674 exit(1);
5676 pid = fork();
5677 if (pid > 0) {
5678 uint8_t status;
5679 ssize_t len;
5681 close(fds[1]);
5683 again:
5684 len = read(fds[0], &status, 1);
5685 if (len == -1 && (errno == EINTR))
5686 goto again;
5688 if (len != 1)
5689 exit(1);
5690 else if (status == 1) {
5691 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5692 exit(1);
5693 } else
5694 exit(0);
5695 } else if (pid < 0)
5696 exit(1);
5698 setsid();
5700 pid = fork();
5701 if (pid > 0)
5702 exit(0);
5703 else if (pid < 0)
5704 exit(1);
5706 umask(027);
5708 signal(SIGTSTP, SIG_IGN);
5709 signal(SIGTTOU, SIG_IGN);
5710 signal(SIGTTIN, SIG_IGN);
5713 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5714 if (daemonize) {
5715 uint8_t status = 1;
5716 write(fds[1], &status, 1);
5717 } else
5718 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5719 exit(1);
5721 #endif
5723 if (kvm_enabled()) {
5724 int ret;
5726 ret = kvm_init(smp_cpus);
5727 if (ret < 0) {
5728 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5729 fprintf(stderr, "failed to initialize KVM\n");
5730 exit(1);
5731 #endif
5732 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5733 kvm_allowed = 0;
5737 if (qemu_init_main_loop()) {
5738 fprintf(stderr, "qemu_init_main_loop failed\n");
5739 exit(1);
5741 linux_boot = (kernel_filename != NULL);
5743 if (!linux_boot && *kernel_cmdline != '\0') {
5744 fprintf(stderr, "-append only allowed with -kernel option\n");
5745 exit(1);
5748 if (!linux_boot && initrd_filename != NULL) {
5749 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5750 exit(1);
5753 #ifndef _WIN32
5754 /* Win32 doesn't support line-buffering and requires size >= 2 */
5755 setvbuf(stdout, NULL, _IOLBF, 0);
5756 #endif
5758 if (init_timer_alarm() < 0) {
5759 fprintf(stderr, "could not initialize alarm timer\n");
5760 exit(1);
5762 if (use_icount && icount_time_shift < 0) {
5763 use_icount = 2;
5764 /* 125MIPS seems a reasonable initial guess at the guest speed.
5765 It will be corrected fairly quickly anyway. */
5766 icount_time_shift = 3;
5767 init_icount_adjust();
5770 #ifdef _WIN32
5771 socket_init();
5772 #endif
5774 if (net_init_clients() < 0) {
5775 exit(1);
5778 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5779 net_set_boot_mask(net_boot);
5781 /* init the bluetooth world */
5782 if (foreach_device_config(DEV_BT, bt_parse))
5783 exit(1);
5785 /* init the memory */
5786 if (ram_size == 0)
5787 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5789 /* init the dynamic translator */
5790 cpu_exec_init_all(tb_size * 1024 * 1024);
5792 bdrv_init();
5794 /* we always create the cdrom drive, even if no disk is there */
5795 drive_add(NULL, CDROM_ALIAS);
5797 /* we always create at least one floppy */
5798 drive_add(NULL, FD_ALIAS, 0);
5800 /* we always create one sd slot, even if no card is in it */
5801 drive_add(NULL, SD_ALIAS);
5803 /* open the virtual block devices */
5804 if (snapshot)
5805 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5806 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5807 exit(1);
5809 vmstate_register(0, &vmstate_timers ,&timers_state);
5810 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5812 /* Maintain compatibility with multiple stdio monitors */
5813 if (!strcmp(monitor_devices[0],"stdio")) {
5814 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5815 const char *devname = serial_devices[i];
5816 if (devname && !strcmp(devname,"mon:stdio")) {
5817 monitor_devices[0] = NULL;
5818 break;
5819 } else if (devname && !strcmp(devname,"stdio")) {
5820 monitor_devices[0] = NULL;
5821 serial_devices[i] = "mon:stdio";
5822 break;
5827 if (nb_numa_nodes > 0) {
5828 int i;
5830 if (nb_numa_nodes > smp_cpus) {
5831 nb_numa_nodes = smp_cpus;
5834 /* If no memory size if given for any node, assume the default case
5835 * and distribute the available memory equally across all nodes
5837 for (i = 0; i < nb_numa_nodes; i++) {
5838 if (node_mem[i] != 0)
5839 break;
5841 if (i == nb_numa_nodes) {
5842 uint64_t usedmem = 0;
5844 /* On Linux, the each node's border has to be 8MB aligned,
5845 * the final node gets the rest.
5847 for (i = 0; i < nb_numa_nodes - 1; i++) {
5848 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5849 usedmem += node_mem[i];
5851 node_mem[i] = ram_size - usedmem;
5854 for (i = 0; i < nb_numa_nodes; i++) {
5855 if (node_cpumask[i] != 0)
5856 break;
5858 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5859 * must cope with this anyway, because there are BIOSes out there in
5860 * real machines which also use this scheme.
5862 if (i == nb_numa_nodes) {
5863 for (i = 0; i < smp_cpus; i++) {
5864 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5869 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5870 const char *devname = monitor_devices[i];
5871 if (devname && strcmp(devname, "none")) {
5872 char label[32];
5873 if (i == 0) {
5874 snprintf(label, sizeof(label), "monitor");
5875 } else {
5876 snprintf(label, sizeof(label), "monitor%d", i);
5878 monitor_hds[i] = qemu_chr_open(label, devname, NULL);
5879 if (!monitor_hds[i]) {
5880 fprintf(stderr, "qemu: could not open monitor device '%s'\n",
5881 devname);
5882 exit(1);
5887 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5888 const char *devname = serial_devices[i];
5889 if (devname && strcmp(devname, "none")) {
5890 char label[32];
5891 snprintf(label, sizeof(label), "serial%d", i);
5892 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5893 if (!serial_hds[i]) {
5894 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
5895 devname, strerror(errno));
5896 exit(1);
5901 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5902 const char *devname = parallel_devices[i];
5903 if (devname && strcmp(devname, "none")) {
5904 char label[32];
5905 snprintf(label, sizeof(label), "parallel%d", i);
5906 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5907 if (!parallel_hds[i]) {
5908 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
5909 devname, strerror(errno));
5910 exit(1);
5915 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5916 const char *devname = virtio_consoles[i];
5917 if (devname && strcmp(devname, "none")) {
5918 char label[32];
5919 snprintf(label, sizeof(label), "virtcon%d", i);
5920 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5921 if (!virtcon_hds[i]) {
5922 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
5923 devname, strerror(errno));
5924 exit(1);
5929 module_call_init(MODULE_INIT_DEVICE);
5931 if (watchdog) {
5932 i = select_watchdog(watchdog);
5933 if (i > 0)
5934 exit (i == 1 ? 1 : 0);
5937 if (machine->compat_props) {
5938 qdev_prop_register_compat(machine->compat_props);
5940 machine->init(ram_size, boot_devices,
5941 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5944 #ifndef _WIN32
5945 /* must be after terminal init, SDL library changes signal handlers */
5946 sighandler_setup();
5947 #endif
5949 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5950 for (i = 0; i < nb_numa_nodes; i++) {
5951 if (node_cpumask[i] & (1 << env->cpu_index)) {
5952 env->numa_node = i;
5957 current_machine = machine;
5959 /* init USB devices */
5960 if (usb_enabled) {
5961 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5962 exit(1);
5965 /* init generic devices */
5966 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5967 exit(1);
5969 if (!display_state)
5970 dumb_display_init();
5971 /* just use the first displaystate for the moment */
5972 ds = display_state;
5974 if (display_type == DT_DEFAULT) {
5975 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5976 display_type = DT_SDL;
5977 #else
5978 display_type = DT_VNC;
5979 vnc_display = "localhost:0,to=99";
5980 show_vnc_port = 1;
5981 #endif
5985 switch (display_type) {
5986 case DT_NOGRAPHIC:
5987 break;
5988 #if defined(CONFIG_CURSES)
5989 case DT_CURSES:
5990 curses_display_init(ds, full_screen);
5991 break;
5992 #endif
5993 #if defined(CONFIG_SDL)
5994 case DT_SDL:
5995 sdl_display_init(ds, full_screen, no_frame);
5996 break;
5997 #elif defined(CONFIG_COCOA)
5998 case DT_SDL:
5999 cocoa_display_init(ds, full_screen);
6000 break;
6001 #endif
6002 case DT_VNC:
6003 vnc_display_init(ds);
6004 if (vnc_display_open(ds, vnc_display) < 0)
6005 exit(1);
6007 if (show_vnc_port) {
6008 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6010 break;
6011 default:
6012 break;
6014 dpy_resize(ds);
6016 dcl = ds->listeners;
6017 while (dcl != NULL) {
6018 if (dcl->dpy_refresh != NULL) {
6019 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6020 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6022 dcl = dcl->next;
6025 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6026 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6027 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6030 text_consoles_set_display(display_state);
6031 qemu_chr_initial_reset();
6033 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
6034 if (monitor_devices[i] && monitor_hds[i]) {
6035 monitor_init(monitor_hds[i],
6036 MONITOR_USE_READLINE |
6037 ((i == 0) ? MONITOR_IS_DEFAULT : 0));
6041 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6042 const char *devname = serial_devices[i];
6043 if (devname && strcmp(devname, "none")) {
6044 if (strstart(devname, "vc", 0))
6045 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6049 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6050 const char *devname = parallel_devices[i];
6051 if (devname && strcmp(devname, "none")) {
6052 if (strstart(devname, "vc", 0))
6053 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6057 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6058 const char *devname = virtio_consoles[i];
6059 if (virtcon_hds[i] && devname) {
6060 if (strstart(devname, "vc", 0))
6061 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6065 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6066 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6067 gdbstub_dev);
6068 exit(1);
6071 qdev_machine_creation_done();
6073 rom_load_all();
6075 if (loadvm) {
6076 if (load_vmstate(cur_mon, loadvm) < 0) {
6077 autostart = 0;
6081 if (incoming) {
6082 qemu_start_incoming_migration(incoming);
6083 } else if (autostart) {
6084 vm_start();
6087 #ifndef _WIN32
6088 if (daemonize) {
6089 uint8_t status = 0;
6090 ssize_t len;
6092 again1:
6093 len = write(fds[1], &status, 1);
6094 if (len == -1 && (errno == EINTR))
6095 goto again1;
6097 if (len != 1)
6098 exit(1);
6100 chdir("/");
6101 TFR(fd = open("/dev/null", O_RDWR));
6102 if (fd == -1)
6103 exit(1);
6106 if (run_as) {
6107 pwd = getpwnam(run_as);
6108 if (!pwd) {
6109 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6110 exit(1);
6114 if (chroot_dir) {
6115 if (chroot(chroot_dir) < 0) {
6116 fprintf(stderr, "chroot failed\n");
6117 exit(1);
6119 chdir("/");
6122 if (run_as) {
6123 if (setgid(pwd->pw_gid) < 0) {
6124 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6125 exit(1);
6127 if (setuid(pwd->pw_uid) < 0) {
6128 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6129 exit(1);
6131 if (setuid(0) != -1) {
6132 fprintf(stderr, "Dropping privileges failed\n");
6133 exit(1);
6137 if (daemonize) {
6138 dup2(fd, 0);
6139 dup2(fd, 1);
6140 dup2(fd, 2);
6142 close(fd);
6144 #endif
6146 main_loop();
6147 quit_timers();
6148 net_cleanup();
6150 return 0;