New API for asynchronous monitor commands
[qemu.git] / vl.c
blob5e8c775089675fab7ff8a889d811d8e81d793191
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <libgen.h>
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #include <arpa/inet.h>
48 #include <dirent.h>
49 #include <netdb.h>
50 #include <sys/select.h>
51 #ifdef CONFIG_BSD
52 #include <sys/stat.h>
53 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
54 #include <libutil.h>
55 #else
56 #include <util.h>
57 #endif
58 #else
59 #ifdef __linux__
60 #include <pty.h>
61 #include <malloc.h>
62 #include <linux/rtc.h>
63 #include <sys/prctl.h>
65 /* For the benefit of older linux systems which don't supply it,
66 we use a local copy of hpet.h. */
67 /* #include <linux/hpet.h> */
68 #include "hpet.h"
70 #include <linux/ppdev.h>
71 #include <linux/parport.h>
72 #endif
73 #ifdef __sun__
74 #include <sys/stat.h>
75 #include <sys/ethernet.h>
76 #include <sys/sockio.h>
77 #include <netinet/arp.h>
78 #include <netinet/in.h>
79 #include <netinet/in_systm.h>
80 #include <netinet/ip.h>
81 #include <netinet/ip_icmp.h> // must come after ip.h
82 #include <netinet/udp.h>
83 #include <netinet/tcp.h>
84 #include <net/if.h>
85 #include <syslog.h>
86 #include <stropts.h>
87 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
88 discussion about Solaris header problems */
89 extern int madvise(caddr_t, size_t, int);
90 #endif
91 #endif
92 #endif
94 #if defined(__OpenBSD__)
95 #include <util.h>
96 #endif
98 #if defined(CONFIG_VDE)
99 #include <libvdeplug.h>
100 #endif
102 #ifdef _WIN32
103 #include <windows.h>
104 #include <mmsystem.h>
105 #endif
107 #ifdef CONFIG_SDL
108 #if defined(__APPLE__) || defined(main)
109 #include <SDL.h>
110 int qemu_main(int argc, char **argv, char **envp);
111 int main(int argc, char **argv)
113 return qemu_main(argc, argv, NULL);
115 #undef main
116 #define main qemu_main
117 #endif
118 #endif /* CONFIG_SDL */
120 #ifdef CONFIG_COCOA
121 #undef main
122 #define main qemu_main
123 #endif /* CONFIG_COCOA */
125 #include "hw/hw.h"
126 #include "hw/boards.h"
127 #include "hw/usb.h"
128 #include "hw/pcmcia.h"
129 #include "hw/pc.h"
130 #include "hw/audiodev.h"
131 #include "hw/isa.h"
132 #include "hw/baum.h"
133 #include "hw/bt.h"
134 #include "hw/watchdog.h"
135 #include "hw/smbios.h"
136 #include "hw/xen.h"
137 #include "hw/qdev.h"
138 #include "hw/loader.h"
139 #include "bt-host.h"
140 #include "net.h"
141 #include "net/slirp.h"
142 #include "monitor.h"
143 #include "console.h"
144 #include "sysemu.h"
145 #include "gdbstub.h"
146 #include "qemu-timer.h"
147 #include "qemu-char.h"
148 #include "cache-utils.h"
149 #include "block.h"
150 #include "block_int.h"
151 #include "block-migration.h"
152 #include "dma.h"
153 #include "audio/audio.h"
154 #include "migration.h"
155 #include "kvm.h"
156 #include "balloon.h"
157 #include "qemu-option.h"
158 #include "qemu-config.h"
159 #include "qemu-objects.h"
161 #include "disas.h"
163 #include "exec-all.h"
165 #include "qemu_socket.h"
167 #include "slirp/libslirp.h"
169 #include "qemu-queue.h"
171 //#define DEBUG_NET
172 //#define DEBUG_SLIRP
174 #define DEFAULT_RAM_SIZE 128
176 #define MAX_VIRTIO_CONSOLES 1
178 static const char *data_dir;
179 const char *bios_name = NULL;
180 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181 to store the VM snapshots */
182 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
183 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
184 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
185 static DisplayState *display_state;
186 DisplayType display_type = DT_DEFAULT;
187 const char* keyboard_layout = NULL;
188 ram_addr_t ram_size;
189 int nb_nics;
190 NICInfo nd_table[MAX_NICS];
191 int vm_running;
192 int autostart;
193 static int rtc_utc = 1;
194 static int rtc_date_offset = -1; /* -1 means no change */
195 QEMUClock *rtc_clock;
196 int vga_interface_type = VGA_NONE;
197 #ifdef TARGET_SPARC
198 int graphic_width = 1024;
199 int graphic_height = 768;
200 int graphic_depth = 8;
201 #else
202 int graphic_width = 800;
203 int graphic_height = 600;
204 int graphic_depth = 15;
205 #endif
206 static int full_screen = 0;
207 #ifdef CONFIG_SDL
208 static int no_frame = 0;
209 #endif
210 int no_quit = 0;
211 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
212 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
213 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
214 #ifdef TARGET_I386
215 int win2k_install_hack = 0;
216 int rtc_td_hack = 0;
217 #endif
218 int usb_enabled = 0;
219 int singlestep = 0;
220 int smp_cpus = 1;
221 int max_cpus = 0;
222 int smp_cores = 1;
223 int smp_threads = 1;
224 const char *vnc_display;
225 int acpi_enabled = 1;
226 int no_hpet = 0;
227 int fd_bootchk = 1;
228 int no_reboot = 0;
229 int no_shutdown = 0;
230 int cursor_hide = 1;
231 int graphic_rotate = 0;
232 uint8_t irq0override = 1;
233 #ifndef _WIN32
234 int daemonize = 0;
235 #endif
236 const char *watchdog;
237 const char *option_rom[MAX_OPTION_ROMS];
238 int nb_option_roms;
239 int semihosting_enabled = 0;
240 #ifdef TARGET_ARM
241 int old_param = 0;
242 #endif
243 const char *qemu_name;
244 int alt_grab = 0;
245 int ctrl_grab = 0;
246 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
247 unsigned int nb_prom_envs = 0;
248 const char *prom_envs[MAX_PROM_ENVS];
249 #endif
250 int boot_menu;
252 int nb_numa_nodes;
253 uint64_t node_mem[MAX_NODES];
254 uint64_t node_cpumask[MAX_NODES];
256 static CPUState *cur_cpu;
257 static CPUState *next_cpu;
258 static int timer_alarm_pending = 1;
259 /* Conversion factor from emulated instructions to virtual clock ticks. */
260 static int icount_time_shift;
261 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
262 #define MAX_ICOUNT_SHIFT 10
263 /* Compensate for varying guest execution speed. */
264 static int64_t qemu_icount_bias;
265 static QEMUTimer *icount_rt_timer;
266 static QEMUTimer *icount_vm_timer;
267 static QEMUTimer *nographic_timer;
269 uint8_t qemu_uuid[16];
271 static QEMUBootSetHandler *boot_set_handler;
272 static void *boot_set_opaque;
274 static int default_serial = 1;
275 static int default_parallel = 1;
276 static int default_virtcon = 1;
277 static int default_monitor = 1;
278 static int default_vga = 1;
279 static int default_floppy = 1;
280 static int default_cdrom = 1;
281 static int default_sdcard = 1;
283 static struct {
284 const char *driver;
285 int *flag;
286 } default_list[] = {
287 { .driver = "isa-serial", .flag = &default_serial },
288 { .driver = "isa-parallel", .flag = &default_parallel },
289 { .driver = "isa-fdc", .flag = &default_floppy },
290 { .driver = "ide-drive", .flag = &default_cdrom },
291 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
292 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
293 { .driver = "virtio-serial", .flag = &default_virtcon },
294 { .driver = "VGA", .flag = &default_vga },
295 { .driver = "cirrus-vga", .flag = &default_vga },
296 { .driver = "vmware-svga", .flag = &default_vga },
299 static int default_driver_check(QemuOpts *opts, void *opaque)
301 const char *driver = qemu_opt_get(opts, "driver");
302 int i;
304 if (!driver)
305 return 0;
306 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
307 if (strcmp(default_list[i].driver, driver) != 0)
308 continue;
309 *(default_list[i].flag) = 0;
311 return 0;
314 /***********************************************************/
315 /* x86 ISA bus support */
317 target_phys_addr_t isa_mem_base = 0;
318 PicState2 *isa_pic;
320 /***********************************************************/
321 void hw_error(const char *fmt, ...)
323 va_list ap;
324 CPUState *env;
326 va_start(ap, fmt);
327 fprintf(stderr, "qemu: hardware error: ");
328 vfprintf(stderr, fmt, ap);
329 fprintf(stderr, "\n");
330 for(env = first_cpu; env != NULL; env = env->next_cpu) {
331 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
332 #ifdef TARGET_I386
333 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
334 #else
335 cpu_dump_state(env, stderr, fprintf, 0);
336 #endif
338 va_end(ap);
339 abort();
342 static void set_proc_name(const char *s)
344 #if defined(__linux__) && defined(PR_SET_NAME)
345 char name[16];
346 if (!s)
347 return;
348 name[sizeof(name) - 1] = 0;
349 strncpy(name, s, sizeof(name));
350 /* Could rewrite argv[0] too, but that's a bit more complicated.
351 This simple way is enough for `top'. */
352 prctl(PR_SET_NAME, name);
353 #endif
356 /***************/
357 /* ballooning */
359 static QEMUBalloonEvent *qemu_balloon_event;
360 void *qemu_balloon_event_opaque;
362 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
364 qemu_balloon_event = func;
365 qemu_balloon_event_opaque = opaque;
368 void qemu_balloon(ram_addr_t target)
370 if (qemu_balloon_event)
371 qemu_balloon_event(qemu_balloon_event_opaque, target);
374 ram_addr_t qemu_balloon_status(void)
376 if (qemu_balloon_event)
377 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
378 return 0;
382 /***********************************************************/
383 /* real time host monotonic timer */
385 /* compute with 96 bit intermediate result: (a*b)/c */
386 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
388 union {
389 uint64_t ll;
390 struct {
391 #ifdef HOST_WORDS_BIGENDIAN
392 uint32_t high, low;
393 #else
394 uint32_t low, high;
395 #endif
396 } l;
397 } u, res;
398 uint64_t rl, rh;
400 u.ll = a;
401 rl = (uint64_t)u.l.low * (uint64_t)b;
402 rh = (uint64_t)u.l.high * (uint64_t)b;
403 rh += (rl >> 32);
404 res.l.high = rh / c;
405 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
406 return res.ll;
409 static int64_t get_clock_realtime(void)
411 struct timeval tv;
413 gettimeofday(&tv, NULL);
414 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
417 #ifdef WIN32
419 static int64_t clock_freq;
421 static void init_get_clock(void)
423 LARGE_INTEGER freq;
424 int ret;
425 ret = QueryPerformanceFrequency(&freq);
426 if (ret == 0) {
427 fprintf(stderr, "Could not calibrate ticks\n");
428 exit(1);
430 clock_freq = freq.QuadPart;
433 static int64_t get_clock(void)
435 LARGE_INTEGER ti;
436 QueryPerformanceCounter(&ti);
437 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
440 #else
442 static int use_rt_clock;
444 static void init_get_clock(void)
446 use_rt_clock = 0;
447 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
448 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
450 struct timespec ts;
451 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
452 use_rt_clock = 1;
455 #endif
458 static int64_t get_clock(void)
460 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
461 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
462 if (use_rt_clock) {
463 struct timespec ts;
464 clock_gettime(CLOCK_MONOTONIC, &ts);
465 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
466 } else
467 #endif
469 /* XXX: using gettimeofday leads to problems if the date
470 changes, so it should be avoided. */
471 return get_clock_realtime();
474 #endif
476 /* Return the virtual CPU time, based on the instruction counter. */
477 static int64_t cpu_get_icount(void)
479 int64_t icount;
480 CPUState *env = cpu_single_env;;
481 icount = qemu_icount;
482 if (env) {
483 if (!can_do_io(env))
484 fprintf(stderr, "Bad clock read\n");
485 icount -= (env->icount_decr.u16.low + env->icount_extra);
487 return qemu_icount_bias + (icount << icount_time_shift);
490 /***********************************************************/
491 /* guest cycle counter */
493 typedef struct TimersState {
494 int64_t cpu_ticks_prev;
495 int64_t cpu_ticks_offset;
496 int64_t cpu_clock_offset;
497 int32_t cpu_ticks_enabled;
498 int64_t dummy;
499 } TimersState;
501 TimersState timers_state;
503 /* return the host CPU cycle counter and handle stop/restart */
504 int64_t cpu_get_ticks(void)
506 if (use_icount) {
507 return cpu_get_icount();
509 if (!timers_state.cpu_ticks_enabled) {
510 return timers_state.cpu_ticks_offset;
511 } else {
512 int64_t ticks;
513 ticks = cpu_get_real_ticks();
514 if (timers_state.cpu_ticks_prev > ticks) {
515 /* Note: non increasing ticks may happen if the host uses
516 software suspend */
517 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
519 timers_state.cpu_ticks_prev = ticks;
520 return ticks + timers_state.cpu_ticks_offset;
524 /* return the host CPU monotonic timer and handle stop/restart */
525 static int64_t cpu_get_clock(void)
527 int64_t ti;
528 if (!timers_state.cpu_ticks_enabled) {
529 return timers_state.cpu_clock_offset;
530 } else {
531 ti = get_clock();
532 return ti + timers_state.cpu_clock_offset;
536 /* enable cpu_get_ticks() */
537 void cpu_enable_ticks(void)
539 if (!timers_state.cpu_ticks_enabled) {
540 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
541 timers_state.cpu_clock_offset -= get_clock();
542 timers_state.cpu_ticks_enabled = 1;
546 /* disable cpu_get_ticks() : the clock is stopped. You must not call
547 cpu_get_ticks() after that. */
548 void cpu_disable_ticks(void)
550 if (timers_state.cpu_ticks_enabled) {
551 timers_state.cpu_ticks_offset = cpu_get_ticks();
552 timers_state.cpu_clock_offset = cpu_get_clock();
553 timers_state.cpu_ticks_enabled = 0;
557 /***********************************************************/
558 /* timers */
560 #define QEMU_CLOCK_REALTIME 0
561 #define QEMU_CLOCK_VIRTUAL 1
562 #define QEMU_CLOCK_HOST 2
564 struct QEMUClock {
565 int type;
566 /* XXX: add frequency */
569 struct QEMUTimer {
570 QEMUClock *clock;
571 int64_t expire_time;
572 QEMUTimerCB *cb;
573 void *opaque;
574 struct QEMUTimer *next;
577 struct qemu_alarm_timer {
578 char const *name;
579 unsigned int flags;
581 int (*start)(struct qemu_alarm_timer *t);
582 void (*stop)(struct qemu_alarm_timer *t);
583 void (*rearm)(struct qemu_alarm_timer *t);
584 void *priv;
587 #define ALARM_FLAG_DYNTICKS 0x1
588 #define ALARM_FLAG_EXPIRED 0x2
590 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
592 return t && (t->flags & ALARM_FLAG_DYNTICKS);
595 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
597 if (!alarm_has_dynticks(t))
598 return;
600 t->rearm(t);
603 /* TODO: MIN_TIMER_REARM_US should be optimized */
604 #define MIN_TIMER_REARM_US 250
606 static struct qemu_alarm_timer *alarm_timer;
608 #ifdef _WIN32
610 struct qemu_alarm_win32 {
611 MMRESULT timerId;
612 unsigned int period;
613 } alarm_win32_data = {0, -1};
615 static int win32_start_timer(struct qemu_alarm_timer *t);
616 static void win32_stop_timer(struct qemu_alarm_timer *t);
617 static void win32_rearm_timer(struct qemu_alarm_timer *t);
619 #else
621 static int unix_start_timer(struct qemu_alarm_timer *t);
622 static void unix_stop_timer(struct qemu_alarm_timer *t);
624 #ifdef __linux__
626 static int dynticks_start_timer(struct qemu_alarm_timer *t);
627 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
628 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
630 static int hpet_start_timer(struct qemu_alarm_timer *t);
631 static void hpet_stop_timer(struct qemu_alarm_timer *t);
633 static int rtc_start_timer(struct qemu_alarm_timer *t);
634 static void rtc_stop_timer(struct qemu_alarm_timer *t);
636 #endif /* __linux__ */
638 #endif /* _WIN32 */
640 /* Correlation between real and virtual time is always going to be
641 fairly approximate, so ignore small variation.
642 When the guest is idle real and virtual time will be aligned in
643 the IO wait loop. */
644 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
646 static void icount_adjust(void)
648 int64_t cur_time;
649 int64_t cur_icount;
650 int64_t delta;
651 static int64_t last_delta;
652 /* If the VM is not running, then do nothing. */
653 if (!vm_running)
654 return;
656 cur_time = cpu_get_clock();
657 cur_icount = qemu_get_clock(vm_clock);
658 delta = cur_icount - cur_time;
659 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
660 if (delta > 0
661 && last_delta + ICOUNT_WOBBLE < delta * 2
662 && icount_time_shift > 0) {
663 /* The guest is getting too far ahead. Slow time down. */
664 icount_time_shift--;
666 if (delta < 0
667 && last_delta - ICOUNT_WOBBLE > delta * 2
668 && icount_time_shift < MAX_ICOUNT_SHIFT) {
669 /* The guest is getting too far behind. Speed time up. */
670 icount_time_shift++;
672 last_delta = delta;
673 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
676 static void icount_adjust_rt(void * opaque)
678 qemu_mod_timer(icount_rt_timer,
679 qemu_get_clock(rt_clock) + 1000);
680 icount_adjust();
683 static void icount_adjust_vm(void * opaque)
685 qemu_mod_timer(icount_vm_timer,
686 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
687 icount_adjust();
690 static void init_icount_adjust(void)
692 /* Have both realtime and virtual time triggers for speed adjustment.
693 The realtime trigger catches emulated time passing too slowly,
694 the virtual time trigger catches emulated time passing too fast.
695 Realtime triggers occur even when idle, so use them less frequently
696 than VM triggers. */
697 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
698 qemu_mod_timer(icount_rt_timer,
699 qemu_get_clock(rt_clock) + 1000);
700 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
701 qemu_mod_timer(icount_vm_timer,
702 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
705 static struct qemu_alarm_timer alarm_timers[] = {
706 #ifndef _WIN32
707 #ifdef __linux__
708 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
709 dynticks_stop_timer, dynticks_rearm_timer, NULL},
710 /* HPET - if available - is preferred */
711 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
712 /* ...otherwise try RTC */
713 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
714 #endif
715 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
716 #else
717 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
718 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
719 {"win32", 0, win32_start_timer,
720 win32_stop_timer, NULL, &alarm_win32_data},
721 #endif
722 {NULL, }
725 static void show_available_alarms(void)
727 int i;
729 printf("Available alarm timers, in order of precedence:\n");
730 for (i = 0; alarm_timers[i].name; i++)
731 printf("%s\n", alarm_timers[i].name);
734 static void configure_alarms(char const *opt)
736 int i;
737 int cur = 0;
738 int count = ARRAY_SIZE(alarm_timers) - 1;
739 char *arg;
740 char *name;
741 struct qemu_alarm_timer tmp;
743 if (!strcmp(opt, "?")) {
744 show_available_alarms();
745 exit(0);
748 arg = qemu_strdup(opt);
750 /* Reorder the array */
751 name = strtok(arg, ",");
752 while (name) {
753 for (i = 0; i < count && alarm_timers[i].name; i++) {
754 if (!strcmp(alarm_timers[i].name, name))
755 break;
758 if (i == count) {
759 fprintf(stderr, "Unknown clock %s\n", name);
760 goto next;
763 if (i < cur)
764 /* Ignore */
765 goto next;
767 /* Swap */
768 tmp = alarm_timers[i];
769 alarm_timers[i] = alarm_timers[cur];
770 alarm_timers[cur] = tmp;
772 cur++;
773 next:
774 name = strtok(NULL, ",");
777 qemu_free(arg);
779 if (cur) {
780 /* Disable remaining timers */
781 for (i = cur; i < count; i++)
782 alarm_timers[i].name = NULL;
783 } else {
784 show_available_alarms();
785 exit(1);
789 #define QEMU_NUM_CLOCKS 3
791 QEMUClock *rt_clock;
792 QEMUClock *vm_clock;
793 QEMUClock *host_clock;
795 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
797 static QEMUClock *qemu_new_clock(int type)
799 QEMUClock *clock;
800 clock = qemu_mallocz(sizeof(QEMUClock));
801 clock->type = type;
802 return clock;
805 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
807 QEMUTimer *ts;
809 ts = qemu_mallocz(sizeof(QEMUTimer));
810 ts->clock = clock;
811 ts->cb = cb;
812 ts->opaque = opaque;
813 return ts;
816 void qemu_free_timer(QEMUTimer *ts)
818 qemu_free(ts);
821 /* stop a timer, but do not dealloc it */
822 void qemu_del_timer(QEMUTimer *ts)
824 QEMUTimer **pt, *t;
826 /* NOTE: this code must be signal safe because
827 qemu_timer_expired() can be called from a signal. */
828 pt = &active_timers[ts->clock->type];
829 for(;;) {
830 t = *pt;
831 if (!t)
832 break;
833 if (t == ts) {
834 *pt = t->next;
835 break;
837 pt = &t->next;
841 /* modify the current timer so that it will be fired when current_time
842 >= expire_time. The corresponding callback will be called. */
843 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
845 QEMUTimer **pt, *t;
847 qemu_del_timer(ts);
849 /* add the timer in the sorted list */
850 /* NOTE: this code must be signal safe because
851 qemu_timer_expired() can be called from a signal. */
852 pt = &active_timers[ts->clock->type];
853 for(;;) {
854 t = *pt;
855 if (!t)
856 break;
857 if (t->expire_time > expire_time)
858 break;
859 pt = &t->next;
861 ts->expire_time = expire_time;
862 ts->next = *pt;
863 *pt = ts;
865 /* Rearm if necessary */
866 if (pt == &active_timers[ts->clock->type]) {
867 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
868 qemu_rearm_alarm_timer(alarm_timer);
870 /* Interrupt execution to force deadline recalculation. */
871 if (use_icount)
872 qemu_notify_event();
876 int qemu_timer_pending(QEMUTimer *ts)
878 QEMUTimer *t;
879 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
880 if (t == ts)
881 return 1;
883 return 0;
886 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
888 if (!timer_head)
889 return 0;
890 return (timer_head->expire_time <= current_time);
893 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
895 QEMUTimer *ts;
897 for(;;) {
898 ts = *ptimer_head;
899 if (!ts || ts->expire_time > current_time)
900 break;
901 /* remove timer from the list before calling the callback */
902 *ptimer_head = ts->next;
903 ts->next = NULL;
905 /* run the callback (the timer list can be modified) */
906 ts->cb(ts->opaque);
910 int64_t qemu_get_clock(QEMUClock *clock)
912 switch(clock->type) {
913 case QEMU_CLOCK_REALTIME:
914 return get_clock() / 1000000;
915 default:
916 case QEMU_CLOCK_VIRTUAL:
917 if (use_icount) {
918 return cpu_get_icount();
919 } else {
920 return cpu_get_clock();
922 case QEMU_CLOCK_HOST:
923 return get_clock_realtime();
927 static void init_clocks(void)
929 init_get_clock();
930 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
931 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
932 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
934 rtc_clock = host_clock;
937 /* save a timer */
938 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
940 uint64_t expire_time;
942 if (qemu_timer_pending(ts)) {
943 expire_time = ts->expire_time;
944 } else {
945 expire_time = -1;
947 qemu_put_be64(f, expire_time);
950 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
952 uint64_t expire_time;
954 expire_time = qemu_get_be64(f);
955 if (expire_time != -1) {
956 qemu_mod_timer(ts, expire_time);
957 } else {
958 qemu_del_timer(ts);
962 static const VMStateDescription vmstate_timers = {
963 .name = "timer",
964 .version_id = 2,
965 .minimum_version_id = 1,
966 .minimum_version_id_old = 1,
967 .fields = (VMStateField []) {
968 VMSTATE_INT64(cpu_ticks_offset, TimersState),
969 VMSTATE_INT64(dummy, TimersState),
970 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
971 VMSTATE_END_OF_LIST()
975 static void qemu_event_increment(void);
977 #ifdef _WIN32
978 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
979 DWORD_PTR dwUser, DWORD_PTR dw1,
980 DWORD_PTR dw2)
981 #else
982 static void host_alarm_handler(int host_signum)
983 #endif
985 #if 0
986 #define DISP_FREQ 1000
988 static int64_t delta_min = INT64_MAX;
989 static int64_t delta_max, delta_cum, last_clock, delta, ti;
990 static int count;
991 ti = qemu_get_clock(vm_clock);
992 if (last_clock != 0) {
993 delta = ti - last_clock;
994 if (delta < delta_min)
995 delta_min = delta;
996 if (delta > delta_max)
997 delta_max = delta;
998 delta_cum += delta;
999 if (++count == DISP_FREQ) {
1000 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1001 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1002 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1003 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1004 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1005 count = 0;
1006 delta_min = INT64_MAX;
1007 delta_max = 0;
1008 delta_cum = 0;
1011 last_clock = ti;
1013 #endif
1014 if (alarm_has_dynticks(alarm_timer) ||
1015 (!use_icount &&
1016 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1017 qemu_get_clock(vm_clock))) ||
1018 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1019 qemu_get_clock(rt_clock)) ||
1020 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1021 qemu_get_clock(host_clock))) {
1022 qemu_event_increment();
1023 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1025 #ifndef CONFIG_IOTHREAD
1026 if (next_cpu) {
1027 /* stop the currently executing cpu because a timer occured */
1028 cpu_exit(next_cpu);
1030 #endif
1031 timer_alarm_pending = 1;
1032 qemu_notify_event();
1036 static int64_t qemu_next_deadline(void)
1038 /* To avoid problems with overflow limit this to 2^32. */
1039 int64_t delta = INT32_MAX;
1041 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1042 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1043 qemu_get_clock(vm_clock);
1045 if (active_timers[QEMU_CLOCK_HOST]) {
1046 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1047 qemu_get_clock(host_clock);
1048 if (hdelta < delta)
1049 delta = hdelta;
1052 if (delta < 0)
1053 delta = 0;
1055 return delta;
1058 #if defined(__linux__)
1059 static uint64_t qemu_next_deadline_dyntick(void)
1061 int64_t delta;
1062 int64_t rtdelta;
1064 if (use_icount)
1065 delta = INT32_MAX;
1066 else
1067 delta = (qemu_next_deadline() + 999) / 1000;
1069 if (active_timers[QEMU_CLOCK_REALTIME]) {
1070 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1071 qemu_get_clock(rt_clock))*1000;
1072 if (rtdelta < delta)
1073 delta = rtdelta;
1076 if (delta < MIN_TIMER_REARM_US)
1077 delta = MIN_TIMER_REARM_US;
1079 return delta;
1081 #endif
1083 #ifndef _WIN32
1085 /* Sets a specific flag */
1086 static int fcntl_setfl(int fd, int flag)
1088 int flags;
1090 flags = fcntl(fd, F_GETFL);
1091 if (flags == -1)
1092 return -errno;
1094 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1095 return -errno;
1097 return 0;
1100 #if defined(__linux__)
1102 #define RTC_FREQ 1024
1104 static void enable_sigio_timer(int fd)
1106 struct sigaction act;
1108 /* timer signal */
1109 sigfillset(&act.sa_mask);
1110 act.sa_flags = 0;
1111 act.sa_handler = host_alarm_handler;
1113 sigaction(SIGIO, &act, NULL);
1114 fcntl_setfl(fd, O_ASYNC);
1115 fcntl(fd, F_SETOWN, getpid());
1118 static int hpet_start_timer(struct qemu_alarm_timer *t)
1120 struct hpet_info info;
1121 int r, fd;
1123 fd = qemu_open("/dev/hpet", O_RDONLY);
1124 if (fd < 0)
1125 return -1;
1127 /* Set frequency */
1128 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1129 if (r < 0) {
1130 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1131 "error, but for better emulation accuracy type:\n"
1132 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1133 goto fail;
1136 /* Check capabilities */
1137 r = ioctl(fd, HPET_INFO, &info);
1138 if (r < 0)
1139 goto fail;
1141 /* Enable periodic mode */
1142 r = ioctl(fd, HPET_EPI, 0);
1143 if (info.hi_flags && (r < 0))
1144 goto fail;
1146 /* Enable interrupt */
1147 r = ioctl(fd, HPET_IE_ON, 0);
1148 if (r < 0)
1149 goto fail;
1151 enable_sigio_timer(fd);
1152 t->priv = (void *)(long)fd;
1154 return 0;
1155 fail:
1156 close(fd);
1157 return -1;
1160 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1162 int fd = (long)t->priv;
1164 close(fd);
1167 static int rtc_start_timer(struct qemu_alarm_timer *t)
1169 int rtc_fd;
1170 unsigned long current_rtc_freq = 0;
1172 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1173 if (rtc_fd < 0)
1174 return -1;
1175 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1176 if (current_rtc_freq != RTC_FREQ &&
1177 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1178 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1179 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1180 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1181 goto fail;
1183 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1184 fail:
1185 close(rtc_fd);
1186 return -1;
1189 enable_sigio_timer(rtc_fd);
1191 t->priv = (void *)(long)rtc_fd;
1193 return 0;
1196 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1198 int rtc_fd = (long)t->priv;
1200 close(rtc_fd);
1203 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1205 struct sigevent ev;
1206 timer_t host_timer;
1207 struct sigaction act;
1209 sigfillset(&act.sa_mask);
1210 act.sa_flags = 0;
1211 act.sa_handler = host_alarm_handler;
1213 sigaction(SIGALRM, &act, NULL);
1216 * Initialize ev struct to 0 to avoid valgrind complaining
1217 * about uninitialized data in timer_create call
1219 memset(&ev, 0, sizeof(ev));
1220 ev.sigev_value.sival_int = 0;
1221 ev.sigev_notify = SIGEV_SIGNAL;
1222 ev.sigev_signo = SIGALRM;
1224 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1225 perror("timer_create");
1227 /* disable dynticks */
1228 fprintf(stderr, "Dynamic Ticks disabled\n");
1230 return -1;
1233 t->priv = (void *)(long)host_timer;
1235 return 0;
1238 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1240 timer_t host_timer = (timer_t)(long)t->priv;
1242 timer_delete(host_timer);
1245 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1247 timer_t host_timer = (timer_t)(long)t->priv;
1248 struct itimerspec timeout;
1249 int64_t nearest_delta_us = INT64_MAX;
1250 int64_t current_us;
1252 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1253 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1254 !active_timers[QEMU_CLOCK_HOST])
1255 return;
1257 nearest_delta_us = qemu_next_deadline_dyntick();
1259 /* check whether a timer is already running */
1260 if (timer_gettime(host_timer, &timeout)) {
1261 perror("gettime");
1262 fprintf(stderr, "Internal timer error: aborting\n");
1263 exit(1);
1265 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1266 if (current_us && current_us <= nearest_delta_us)
1267 return;
1269 timeout.it_interval.tv_sec = 0;
1270 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1271 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1272 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1273 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1274 perror("settime");
1275 fprintf(stderr, "Internal timer error: aborting\n");
1276 exit(1);
1280 #endif /* defined(__linux__) */
1282 static int unix_start_timer(struct qemu_alarm_timer *t)
1284 struct sigaction act;
1285 struct itimerval itv;
1286 int err;
1288 /* timer signal */
1289 sigfillset(&act.sa_mask);
1290 act.sa_flags = 0;
1291 act.sa_handler = host_alarm_handler;
1293 sigaction(SIGALRM, &act, NULL);
1295 itv.it_interval.tv_sec = 0;
1296 /* for i386 kernel 2.6 to get 1 ms */
1297 itv.it_interval.tv_usec = 999;
1298 itv.it_value.tv_sec = 0;
1299 itv.it_value.tv_usec = 10 * 1000;
1301 err = setitimer(ITIMER_REAL, &itv, NULL);
1302 if (err)
1303 return -1;
1305 return 0;
1308 static void unix_stop_timer(struct qemu_alarm_timer *t)
1310 struct itimerval itv;
1312 memset(&itv, 0, sizeof(itv));
1313 setitimer(ITIMER_REAL, &itv, NULL);
1316 #endif /* !defined(_WIN32) */
1319 #ifdef _WIN32
1321 static int win32_start_timer(struct qemu_alarm_timer *t)
1323 TIMECAPS tc;
1324 struct qemu_alarm_win32 *data = t->priv;
1325 UINT flags;
1327 memset(&tc, 0, sizeof(tc));
1328 timeGetDevCaps(&tc, sizeof(tc));
1330 if (data->period < tc.wPeriodMin)
1331 data->period = tc.wPeriodMin;
1333 timeBeginPeriod(data->period);
1335 flags = TIME_CALLBACK_FUNCTION;
1336 if (alarm_has_dynticks(t))
1337 flags |= TIME_ONESHOT;
1338 else
1339 flags |= TIME_PERIODIC;
1341 data->timerId = timeSetEvent(1, // interval (ms)
1342 data->period, // resolution
1343 host_alarm_handler, // function
1344 (DWORD)t, // parameter
1345 flags);
1347 if (!data->timerId) {
1348 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1349 GetLastError());
1350 timeEndPeriod(data->period);
1351 return -1;
1354 return 0;
1357 static void win32_stop_timer(struct qemu_alarm_timer *t)
1359 struct qemu_alarm_win32 *data = t->priv;
1361 timeKillEvent(data->timerId);
1362 timeEndPeriod(data->period);
1365 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1367 struct qemu_alarm_win32 *data = t->priv;
1369 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1370 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1371 !active_timers[QEMU_CLOCK_HOST])
1372 return;
1374 timeKillEvent(data->timerId);
1376 data->timerId = timeSetEvent(1,
1377 data->period,
1378 host_alarm_handler,
1379 (DWORD)t,
1380 TIME_ONESHOT | TIME_PERIODIC);
1382 if (!data->timerId) {
1383 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1384 GetLastError());
1386 timeEndPeriod(data->period);
1387 exit(1);
1391 #endif /* _WIN32 */
1393 static int init_timer_alarm(void)
1395 struct qemu_alarm_timer *t = NULL;
1396 int i, err = -1;
1398 for (i = 0; alarm_timers[i].name; i++) {
1399 t = &alarm_timers[i];
1401 err = t->start(t);
1402 if (!err)
1403 break;
1406 if (err) {
1407 err = -ENOENT;
1408 goto fail;
1411 alarm_timer = t;
1413 return 0;
1415 fail:
1416 return err;
1419 static void quit_timers(void)
1421 alarm_timer->stop(alarm_timer);
1422 alarm_timer = NULL;
1425 /***********************************************************/
1426 /* host time/date access */
1427 void qemu_get_timedate(struct tm *tm, int offset)
1429 time_t ti;
1430 struct tm *ret;
1432 time(&ti);
1433 ti += offset;
1434 if (rtc_date_offset == -1) {
1435 if (rtc_utc)
1436 ret = gmtime(&ti);
1437 else
1438 ret = localtime(&ti);
1439 } else {
1440 ti -= rtc_date_offset;
1441 ret = gmtime(&ti);
1444 memcpy(tm, ret, sizeof(struct tm));
1447 int qemu_timedate_diff(struct tm *tm)
1449 time_t seconds;
1451 if (rtc_date_offset == -1)
1452 if (rtc_utc)
1453 seconds = mktimegm(tm);
1454 else
1455 seconds = mktime(tm);
1456 else
1457 seconds = mktimegm(tm) + rtc_date_offset;
1459 return seconds - time(NULL);
1462 static void configure_rtc_date_offset(const char *startdate, int legacy)
1464 time_t rtc_start_date;
1465 struct tm tm;
1467 if (!strcmp(startdate, "now") && legacy) {
1468 rtc_date_offset = -1;
1469 } else {
1470 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1471 &tm.tm_year,
1472 &tm.tm_mon,
1473 &tm.tm_mday,
1474 &tm.tm_hour,
1475 &tm.tm_min,
1476 &tm.tm_sec) == 6) {
1477 /* OK */
1478 } else if (sscanf(startdate, "%d-%d-%d",
1479 &tm.tm_year,
1480 &tm.tm_mon,
1481 &tm.tm_mday) == 3) {
1482 tm.tm_hour = 0;
1483 tm.tm_min = 0;
1484 tm.tm_sec = 0;
1485 } else {
1486 goto date_fail;
1488 tm.tm_year -= 1900;
1489 tm.tm_mon--;
1490 rtc_start_date = mktimegm(&tm);
1491 if (rtc_start_date == -1) {
1492 date_fail:
1493 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1494 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1495 exit(1);
1497 rtc_date_offset = time(NULL) - rtc_start_date;
1501 static void configure_rtc(QemuOpts *opts)
1503 const char *value;
1505 value = qemu_opt_get(opts, "base");
1506 if (value) {
1507 if (!strcmp(value, "utc")) {
1508 rtc_utc = 1;
1509 } else if (!strcmp(value, "localtime")) {
1510 rtc_utc = 0;
1511 } else {
1512 configure_rtc_date_offset(value, 0);
1515 value = qemu_opt_get(opts, "clock");
1516 if (value) {
1517 if (!strcmp(value, "host")) {
1518 rtc_clock = host_clock;
1519 } else if (!strcmp(value, "vm")) {
1520 rtc_clock = vm_clock;
1521 } else {
1522 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1523 exit(1);
1526 #ifdef CONFIG_TARGET_I386
1527 value = qemu_opt_get(opts, "driftfix");
1528 if (value) {
1529 if (!strcmp(buf, "slew")) {
1530 rtc_td_hack = 1;
1531 } else if (!strcmp(buf, "none")) {
1532 rtc_td_hack = 0;
1533 } else {
1534 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1535 exit(1);
1538 #endif
1541 #ifdef _WIN32
1542 static void socket_cleanup(void)
1544 WSACleanup();
1547 static int socket_init(void)
1549 WSADATA Data;
1550 int ret, err;
1552 ret = WSAStartup(MAKEWORD(2,2), &Data);
1553 if (ret != 0) {
1554 err = WSAGetLastError();
1555 fprintf(stderr, "WSAStartup: %d\n", err);
1556 return -1;
1558 atexit(socket_cleanup);
1559 return 0;
1561 #endif
1563 /***********************************************************/
1564 /* Bluetooth support */
1565 static int nb_hcis;
1566 static int cur_hci;
1567 static struct HCIInfo *hci_table[MAX_NICS];
1569 static struct bt_vlan_s {
1570 struct bt_scatternet_s net;
1571 int id;
1572 struct bt_vlan_s *next;
1573 } *first_bt_vlan;
1575 /* find or alloc a new bluetooth "VLAN" */
1576 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1578 struct bt_vlan_s **pvlan, *vlan;
1579 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1580 if (vlan->id == id)
1581 return &vlan->net;
1583 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1584 vlan->id = id;
1585 pvlan = &first_bt_vlan;
1586 while (*pvlan != NULL)
1587 pvlan = &(*pvlan)->next;
1588 *pvlan = vlan;
1589 return &vlan->net;
1592 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1596 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1598 return -ENOTSUP;
1601 static struct HCIInfo null_hci = {
1602 .cmd_send = null_hci_send,
1603 .sco_send = null_hci_send,
1604 .acl_send = null_hci_send,
1605 .bdaddr_set = null_hci_addr_set,
1608 struct HCIInfo *qemu_next_hci(void)
1610 if (cur_hci == nb_hcis)
1611 return &null_hci;
1613 return hci_table[cur_hci++];
1616 static struct HCIInfo *hci_init(const char *str)
1618 char *endp;
1619 struct bt_scatternet_s *vlan = 0;
1621 if (!strcmp(str, "null"))
1622 /* null */
1623 return &null_hci;
1624 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1625 /* host[:hciN] */
1626 return bt_host_hci(str[4] ? str + 5 : "hci0");
1627 else if (!strncmp(str, "hci", 3)) {
1628 /* hci[,vlan=n] */
1629 if (str[3]) {
1630 if (!strncmp(str + 3, ",vlan=", 6)) {
1631 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1632 if (*endp)
1633 vlan = 0;
1635 } else
1636 vlan = qemu_find_bt_vlan(0);
1637 if (vlan)
1638 return bt_new_hci(vlan);
1641 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1643 return 0;
1646 static int bt_hci_parse(const char *str)
1648 struct HCIInfo *hci;
1649 bdaddr_t bdaddr;
1651 if (nb_hcis >= MAX_NICS) {
1652 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1653 return -1;
1656 hci = hci_init(str);
1657 if (!hci)
1658 return -1;
1660 bdaddr.b[0] = 0x52;
1661 bdaddr.b[1] = 0x54;
1662 bdaddr.b[2] = 0x00;
1663 bdaddr.b[3] = 0x12;
1664 bdaddr.b[4] = 0x34;
1665 bdaddr.b[5] = 0x56 + nb_hcis;
1666 hci->bdaddr_set(hci, bdaddr.b);
1668 hci_table[nb_hcis++] = hci;
1670 return 0;
1673 static void bt_vhci_add(int vlan_id)
1675 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1677 if (!vlan->slave)
1678 fprintf(stderr, "qemu: warning: adding a VHCI to "
1679 "an empty scatternet %i\n", vlan_id);
1681 bt_vhci_init(bt_new_hci(vlan));
1684 static struct bt_device_s *bt_device_add(const char *opt)
1686 struct bt_scatternet_s *vlan;
1687 int vlan_id = 0;
1688 char *endp = strstr(opt, ",vlan=");
1689 int len = (endp ? endp - opt : strlen(opt)) + 1;
1690 char devname[10];
1692 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1694 if (endp) {
1695 vlan_id = strtol(endp + 6, &endp, 0);
1696 if (*endp) {
1697 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1698 return 0;
1702 vlan = qemu_find_bt_vlan(vlan_id);
1704 if (!vlan->slave)
1705 fprintf(stderr, "qemu: warning: adding a slave device to "
1706 "an empty scatternet %i\n", vlan_id);
1708 if (!strcmp(devname, "keyboard"))
1709 return bt_keyboard_init(vlan);
1711 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1712 return 0;
1715 static int bt_parse(const char *opt)
1717 const char *endp, *p;
1718 int vlan;
1720 if (strstart(opt, "hci", &endp)) {
1721 if (!*endp || *endp == ',') {
1722 if (*endp)
1723 if (!strstart(endp, ",vlan=", 0))
1724 opt = endp + 1;
1726 return bt_hci_parse(opt);
1728 } else if (strstart(opt, "vhci", &endp)) {
1729 if (!*endp || *endp == ',') {
1730 if (*endp) {
1731 if (strstart(endp, ",vlan=", &p)) {
1732 vlan = strtol(p, (char **) &endp, 0);
1733 if (*endp) {
1734 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1735 return 1;
1737 } else {
1738 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1739 return 1;
1741 } else
1742 vlan = 0;
1744 bt_vhci_add(vlan);
1745 return 0;
1747 } else if (strstart(opt, "device:", &endp))
1748 return !bt_device_add(endp);
1750 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1751 return 1;
1754 /***********************************************************/
1755 /* QEMU Block devices */
1757 #define HD_ALIAS "index=%d,media=disk"
1758 #define CDROM_ALIAS "index=2,media=cdrom"
1759 #define FD_ALIAS "index=%d,if=floppy"
1760 #define PFLASH_ALIAS "if=pflash"
1761 #define MTD_ALIAS "if=mtd"
1762 #define SD_ALIAS "index=0,if=sd"
1764 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1766 va_list ap;
1767 char optstr[1024];
1768 QemuOpts *opts;
1770 va_start(ap, fmt);
1771 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1772 va_end(ap);
1774 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1775 if (!opts) {
1776 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1777 __FUNCTION__, optstr);
1778 return NULL;
1780 if (file)
1781 qemu_opt_set(opts, "file", file);
1782 return opts;
1785 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1787 DriveInfo *dinfo;
1789 /* seek interface, bus and unit */
1791 QTAILQ_FOREACH(dinfo, &drives, next) {
1792 if (dinfo->type == type &&
1793 dinfo->bus == bus &&
1794 dinfo->unit == unit)
1795 return dinfo;
1798 return NULL;
1801 DriveInfo *drive_get_by_id(const char *id)
1803 DriveInfo *dinfo;
1805 QTAILQ_FOREACH(dinfo, &drives, next) {
1806 if (strcmp(id, dinfo->id))
1807 continue;
1808 return dinfo;
1810 return NULL;
1813 int drive_get_max_bus(BlockInterfaceType type)
1815 int max_bus;
1816 DriveInfo *dinfo;
1818 max_bus = -1;
1819 QTAILQ_FOREACH(dinfo, &drives, next) {
1820 if(dinfo->type == type &&
1821 dinfo->bus > max_bus)
1822 max_bus = dinfo->bus;
1824 return max_bus;
1827 const char *drive_get_serial(BlockDriverState *bdrv)
1829 DriveInfo *dinfo;
1831 QTAILQ_FOREACH(dinfo, &drives, next) {
1832 if (dinfo->bdrv == bdrv)
1833 return dinfo->serial;
1836 return "\0";
1839 BlockInterfaceErrorAction drive_get_on_error(
1840 BlockDriverState *bdrv, int is_read)
1842 DriveInfo *dinfo;
1844 QTAILQ_FOREACH(dinfo, &drives, next) {
1845 if (dinfo->bdrv == bdrv)
1846 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1849 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1852 static void bdrv_format_print(void *opaque, const char *name)
1854 fprintf(stderr, " %s", name);
1857 void drive_uninit(DriveInfo *dinfo)
1859 qemu_opts_del(dinfo->opts);
1860 bdrv_delete(dinfo->bdrv);
1861 QTAILQ_REMOVE(&drives, dinfo, next);
1862 qemu_free(dinfo);
1865 static int parse_block_error_action(const char *buf, int is_read)
1867 if (!strcmp(buf, "ignore")) {
1868 return BLOCK_ERR_IGNORE;
1869 } else if (!is_read && !strcmp(buf, "enospc")) {
1870 return BLOCK_ERR_STOP_ENOSPC;
1871 } else if (!strcmp(buf, "stop")) {
1872 return BLOCK_ERR_STOP_ANY;
1873 } else if (!strcmp(buf, "report")) {
1874 return BLOCK_ERR_REPORT;
1875 } else {
1876 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1877 buf, is_read ? "read" : "write");
1878 return -1;
1882 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1883 int *fatal_error)
1885 const char *buf;
1886 const char *file = NULL;
1887 char devname[128];
1888 const char *serial;
1889 const char *mediastr = "";
1890 BlockInterfaceType type;
1891 enum { MEDIA_DISK, MEDIA_CDROM } media;
1892 int bus_id, unit_id;
1893 int cyls, heads, secs, translation;
1894 BlockDriver *drv = NULL;
1895 QEMUMachine *machine = opaque;
1896 int max_devs;
1897 int index;
1898 int cache;
1899 int aio = 0;
1900 int ro = 0;
1901 int bdrv_flags;
1902 int on_read_error, on_write_error;
1903 const char *devaddr;
1904 DriveInfo *dinfo;
1905 int snapshot = 0;
1907 *fatal_error = 1;
1909 translation = BIOS_ATA_TRANSLATION_AUTO;
1910 cache = 1;
1912 if (machine && machine->use_scsi) {
1913 type = IF_SCSI;
1914 max_devs = MAX_SCSI_DEVS;
1915 pstrcpy(devname, sizeof(devname), "scsi");
1916 } else {
1917 type = IF_IDE;
1918 max_devs = MAX_IDE_DEVS;
1919 pstrcpy(devname, sizeof(devname), "ide");
1921 media = MEDIA_DISK;
1923 /* extract parameters */
1924 bus_id = qemu_opt_get_number(opts, "bus", 0);
1925 unit_id = qemu_opt_get_number(opts, "unit", -1);
1926 index = qemu_opt_get_number(opts, "index", -1);
1928 cyls = qemu_opt_get_number(opts, "cyls", 0);
1929 heads = qemu_opt_get_number(opts, "heads", 0);
1930 secs = qemu_opt_get_number(opts, "secs", 0);
1932 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1933 ro = qemu_opt_get_bool(opts, "readonly", 0);
1935 file = qemu_opt_get(opts, "file");
1936 serial = qemu_opt_get(opts, "serial");
1938 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1939 pstrcpy(devname, sizeof(devname), buf);
1940 if (!strcmp(buf, "ide")) {
1941 type = IF_IDE;
1942 max_devs = MAX_IDE_DEVS;
1943 } else if (!strcmp(buf, "scsi")) {
1944 type = IF_SCSI;
1945 max_devs = MAX_SCSI_DEVS;
1946 } else if (!strcmp(buf, "floppy")) {
1947 type = IF_FLOPPY;
1948 max_devs = 0;
1949 } else if (!strcmp(buf, "pflash")) {
1950 type = IF_PFLASH;
1951 max_devs = 0;
1952 } else if (!strcmp(buf, "mtd")) {
1953 type = IF_MTD;
1954 max_devs = 0;
1955 } else if (!strcmp(buf, "sd")) {
1956 type = IF_SD;
1957 max_devs = 0;
1958 } else if (!strcmp(buf, "virtio")) {
1959 type = IF_VIRTIO;
1960 max_devs = 0;
1961 } else if (!strcmp(buf, "xen")) {
1962 type = IF_XEN;
1963 max_devs = 0;
1964 } else if (!strcmp(buf, "none")) {
1965 type = IF_NONE;
1966 max_devs = 0;
1967 } else {
1968 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1969 return NULL;
1973 if (cyls || heads || secs) {
1974 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
1975 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1976 return NULL;
1978 if (heads < 1 || (type == IF_IDE && heads > 16)) {
1979 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1980 return NULL;
1982 if (secs < 1 || (type == IF_IDE && secs > 63)) {
1983 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
1984 return NULL;
1988 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
1989 if (!cyls) {
1990 fprintf(stderr,
1991 "qemu: '%s' trans must be used with cyls,heads and secs\n",
1992 buf);
1993 return NULL;
1995 if (!strcmp(buf, "none"))
1996 translation = BIOS_ATA_TRANSLATION_NONE;
1997 else if (!strcmp(buf, "lba"))
1998 translation = BIOS_ATA_TRANSLATION_LBA;
1999 else if (!strcmp(buf, "auto"))
2000 translation = BIOS_ATA_TRANSLATION_AUTO;
2001 else {
2002 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2003 return NULL;
2007 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2008 if (!strcmp(buf, "disk")) {
2009 media = MEDIA_DISK;
2010 } else if (!strcmp(buf, "cdrom")) {
2011 if (cyls || secs || heads) {
2012 fprintf(stderr,
2013 "qemu: '%s' invalid physical CHS format\n", buf);
2014 return NULL;
2016 media = MEDIA_CDROM;
2017 } else {
2018 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2019 return NULL;
2023 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2024 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2025 cache = 0;
2026 else if (!strcmp(buf, "writethrough"))
2027 cache = 1;
2028 else if (!strcmp(buf, "writeback"))
2029 cache = 2;
2030 else {
2031 fprintf(stderr, "qemu: invalid cache option\n");
2032 return NULL;
2036 #ifdef CONFIG_LINUX_AIO
2037 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2038 if (!strcmp(buf, "threads"))
2039 aio = 0;
2040 else if (!strcmp(buf, "native"))
2041 aio = 1;
2042 else {
2043 fprintf(stderr, "qemu: invalid aio option\n");
2044 return NULL;
2047 #endif
2049 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2050 if (strcmp(buf, "?") == 0) {
2051 fprintf(stderr, "qemu: Supported formats:");
2052 bdrv_iterate_format(bdrv_format_print, NULL);
2053 fprintf(stderr, "\n");
2054 return NULL;
2056 drv = bdrv_find_whitelisted_format(buf);
2057 if (!drv) {
2058 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2059 return NULL;
2063 on_write_error = BLOCK_ERR_STOP_ENOSPC;
2064 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2065 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2066 fprintf(stderr, "werror is no supported by this format\n");
2067 return NULL;
2070 on_write_error = parse_block_error_action(buf, 0);
2071 if (on_write_error < 0) {
2072 return NULL;
2076 on_read_error = BLOCK_ERR_REPORT;
2077 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2078 if (type != IF_IDE && type != IF_VIRTIO) {
2079 fprintf(stderr, "rerror is no supported by this format\n");
2080 return NULL;
2083 on_read_error = parse_block_error_action(buf, 1);
2084 if (on_read_error < 0) {
2085 return NULL;
2089 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2090 if (type != IF_VIRTIO) {
2091 fprintf(stderr, "addr is not supported\n");
2092 return NULL;
2096 /* compute bus and unit according index */
2098 if (index != -1) {
2099 if (bus_id != 0 || unit_id != -1) {
2100 fprintf(stderr,
2101 "qemu: index cannot be used with bus and unit\n");
2102 return NULL;
2104 if (max_devs == 0)
2106 unit_id = index;
2107 bus_id = 0;
2108 } else {
2109 unit_id = index % max_devs;
2110 bus_id = index / max_devs;
2114 /* if user doesn't specify a unit_id,
2115 * try to find the first free
2118 if (unit_id == -1) {
2119 unit_id = 0;
2120 while (drive_get(type, bus_id, unit_id) != NULL) {
2121 unit_id++;
2122 if (max_devs && unit_id >= max_devs) {
2123 unit_id -= max_devs;
2124 bus_id++;
2129 /* check unit id */
2131 if (max_devs && unit_id >= max_devs) {
2132 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2133 unit_id, max_devs - 1);
2134 return NULL;
2138 * ignore multiple definitions
2141 if (drive_get(type, bus_id, unit_id) != NULL) {
2142 *fatal_error = 0;
2143 return NULL;
2146 /* init */
2148 dinfo = qemu_mallocz(sizeof(*dinfo));
2149 if ((buf = qemu_opts_id(opts)) != NULL) {
2150 dinfo->id = qemu_strdup(buf);
2151 } else {
2152 /* no id supplied -> create one */
2153 dinfo->id = qemu_mallocz(32);
2154 if (type == IF_IDE || type == IF_SCSI)
2155 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2156 if (max_devs)
2157 snprintf(dinfo->id, 32, "%s%i%s%i",
2158 devname, bus_id, mediastr, unit_id);
2159 else
2160 snprintf(dinfo->id, 32, "%s%s%i",
2161 devname, mediastr, unit_id);
2163 dinfo->bdrv = bdrv_new(dinfo->id);
2164 dinfo->devaddr = devaddr;
2165 dinfo->type = type;
2166 dinfo->bus = bus_id;
2167 dinfo->unit = unit_id;
2168 dinfo->on_read_error = on_read_error;
2169 dinfo->on_write_error = on_write_error;
2170 dinfo->opts = opts;
2171 if (serial)
2172 strncpy(dinfo->serial, serial, sizeof(serial));
2173 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2175 switch(type) {
2176 case IF_IDE:
2177 case IF_SCSI:
2178 case IF_XEN:
2179 case IF_NONE:
2180 switch(media) {
2181 case MEDIA_DISK:
2182 if (cyls != 0) {
2183 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2184 bdrv_set_translation_hint(dinfo->bdrv, translation);
2186 break;
2187 case MEDIA_CDROM:
2188 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2189 break;
2191 break;
2192 case IF_SD:
2193 /* FIXME: This isn't really a floppy, but it's a reasonable
2194 approximation. */
2195 case IF_FLOPPY:
2196 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2197 break;
2198 case IF_PFLASH:
2199 case IF_MTD:
2200 break;
2201 case IF_VIRTIO:
2202 /* add virtio block device */
2203 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2204 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2205 qemu_opt_set(opts, "drive", dinfo->id);
2206 if (devaddr)
2207 qemu_opt_set(opts, "addr", devaddr);
2208 break;
2209 case IF_COUNT:
2210 abort();
2212 if (!file) {
2213 *fatal_error = 0;
2214 return NULL;
2216 bdrv_flags = 0;
2217 if (snapshot) {
2218 bdrv_flags |= BDRV_O_SNAPSHOT;
2219 cache = 2; /* always use write-back with snapshot */
2221 if (cache == 0) /* no caching */
2222 bdrv_flags |= BDRV_O_NOCACHE;
2223 else if (cache == 2) /* write-back */
2224 bdrv_flags |= BDRV_O_CACHE_WB;
2226 if (aio == 1) {
2227 bdrv_flags |= BDRV_O_NATIVE_AIO;
2228 } else {
2229 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2232 if (ro == 1) {
2233 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2234 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2235 return NULL;
2239 * cdrom is read-only. Set it now, after above interface checking
2240 * since readonly attribute not explicitly required, so no error.
2242 if (media == MEDIA_CDROM) {
2243 ro = 1;
2245 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2247 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2248 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2249 file, strerror(errno));
2250 return NULL;
2253 if (bdrv_key_required(dinfo->bdrv))
2254 autostart = 0;
2255 *fatal_error = 0;
2256 return dinfo;
2259 static int drive_init_func(QemuOpts *opts, void *opaque)
2261 QEMUMachine *machine = opaque;
2262 int fatal_error = 0;
2264 if (drive_init(opts, machine, &fatal_error) == NULL) {
2265 if (fatal_error)
2266 return 1;
2268 return 0;
2271 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2273 if (NULL == qemu_opt_get(opts, "snapshot")) {
2274 qemu_opt_set(opts, "snapshot", "on");
2276 return 0;
2279 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2281 boot_set_handler = func;
2282 boot_set_opaque = opaque;
2285 int qemu_boot_set(const char *boot_devices)
2287 if (!boot_set_handler) {
2288 return -EINVAL;
2290 return boot_set_handler(boot_set_opaque, boot_devices);
2293 static int parse_bootdevices(char *devices)
2295 /* We just do some generic consistency checks */
2296 const char *p;
2297 int bitmap = 0;
2299 for (p = devices; *p != '\0'; p++) {
2300 /* Allowed boot devices are:
2301 * a-b: floppy disk drives
2302 * c-f: IDE disk drives
2303 * g-m: machine implementation dependant drives
2304 * n-p: network devices
2305 * It's up to each machine implementation to check if the given boot
2306 * devices match the actual hardware implementation and firmware
2307 * features.
2309 if (*p < 'a' || *p > 'p') {
2310 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2311 exit(1);
2313 if (bitmap & (1 << (*p - 'a'))) {
2314 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2315 exit(1);
2317 bitmap |= 1 << (*p - 'a');
2319 return bitmap;
2322 static void restore_boot_devices(void *opaque)
2324 char *standard_boot_devices = opaque;
2326 qemu_boot_set(standard_boot_devices);
2328 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2329 qemu_free(standard_boot_devices);
2332 static void numa_add(const char *optarg)
2334 char option[128];
2335 char *endptr;
2336 unsigned long long value, endvalue;
2337 int nodenr;
2339 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2340 if (!strcmp(option, "node")) {
2341 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2342 nodenr = nb_numa_nodes;
2343 } else {
2344 nodenr = strtoull(option, NULL, 10);
2347 if (get_param_value(option, 128, "mem", optarg) == 0) {
2348 node_mem[nodenr] = 0;
2349 } else {
2350 value = strtoull(option, &endptr, 0);
2351 switch (*endptr) {
2352 case 0: case 'M': case 'm':
2353 value <<= 20;
2354 break;
2355 case 'G': case 'g':
2356 value <<= 30;
2357 break;
2359 node_mem[nodenr] = value;
2361 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2362 node_cpumask[nodenr] = 0;
2363 } else {
2364 value = strtoull(option, &endptr, 10);
2365 if (value >= 64) {
2366 value = 63;
2367 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2368 } else {
2369 if (*endptr == '-') {
2370 endvalue = strtoull(endptr+1, &endptr, 10);
2371 if (endvalue >= 63) {
2372 endvalue = 62;
2373 fprintf(stderr,
2374 "only 63 CPUs in NUMA mode supported.\n");
2376 value = (1 << (endvalue + 1)) - (1 << value);
2377 } else {
2378 value = 1 << value;
2381 node_cpumask[nodenr] = value;
2383 nb_numa_nodes++;
2385 return;
2388 static void smp_parse(const char *optarg)
2390 int smp, sockets = 0, threads = 0, cores = 0;
2391 char *endptr;
2392 char option[128];
2394 smp = strtoul(optarg, &endptr, 10);
2395 if (endptr != optarg) {
2396 if (*endptr == ',') {
2397 endptr++;
2400 if (get_param_value(option, 128, "sockets", endptr) != 0)
2401 sockets = strtoull(option, NULL, 10);
2402 if (get_param_value(option, 128, "cores", endptr) != 0)
2403 cores = strtoull(option, NULL, 10);
2404 if (get_param_value(option, 128, "threads", endptr) != 0)
2405 threads = strtoull(option, NULL, 10);
2406 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2407 max_cpus = strtoull(option, NULL, 10);
2409 /* compute missing values, prefer sockets over cores over threads */
2410 if (smp == 0 || sockets == 0) {
2411 sockets = sockets > 0 ? sockets : 1;
2412 cores = cores > 0 ? cores : 1;
2413 threads = threads > 0 ? threads : 1;
2414 if (smp == 0) {
2415 smp = cores * threads * sockets;
2417 } else {
2418 if (cores == 0) {
2419 threads = threads > 0 ? threads : 1;
2420 cores = smp / (sockets * threads);
2421 } else {
2422 if (sockets) {
2423 threads = smp / (cores * sockets);
2427 smp_cpus = smp;
2428 smp_cores = cores > 0 ? cores : 1;
2429 smp_threads = threads > 0 ? threads : 1;
2430 if (max_cpus == 0)
2431 max_cpus = smp_cpus;
2434 /***********************************************************/
2435 /* USB devices */
2437 static int usb_device_add(const char *devname, int is_hotplug)
2439 const char *p;
2440 USBDevice *dev = NULL;
2442 if (!usb_enabled)
2443 return -1;
2445 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2446 dev = usbdevice_create(devname);
2447 if (dev)
2448 goto done;
2450 /* the other ones */
2451 if (strstart(devname, "host:", &p)) {
2452 dev = usb_host_device_open(p);
2453 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2454 dev = usb_bt_init(devname[2] ? hci_init(p) :
2455 bt_new_hci(qemu_find_bt_vlan(0)));
2456 } else {
2457 return -1;
2459 if (!dev)
2460 return -1;
2462 done:
2463 return 0;
2466 static int usb_device_del(const char *devname)
2468 int bus_num, addr;
2469 const char *p;
2471 if (strstart(devname, "host:", &p))
2472 return usb_host_device_close(p);
2474 if (!usb_enabled)
2475 return -1;
2477 p = strchr(devname, '.');
2478 if (!p)
2479 return -1;
2480 bus_num = strtoul(devname, NULL, 0);
2481 addr = strtoul(p + 1, NULL, 0);
2483 return usb_device_delete_addr(bus_num, addr);
2486 static int usb_parse(const char *cmdline)
2488 int r;
2489 r = usb_device_add(cmdline, 0);
2490 if (r < 0) {
2491 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2493 return r;
2496 void do_usb_add(Monitor *mon, const QDict *qdict)
2498 const char *devname = qdict_get_str(qdict, "devname");
2499 if (usb_device_add(devname, 1) < 0) {
2500 qemu_error("could not add USB device '%s'\n", devname);
2504 void do_usb_del(Monitor *mon, const QDict *qdict)
2506 const char *devname = qdict_get_str(qdict, "devname");
2507 if (usb_device_del(devname) < 0) {
2508 qemu_error("could not delete USB device '%s'\n", devname);
2512 /***********************************************************/
2513 /* PCMCIA/Cardbus */
2515 static struct pcmcia_socket_entry_s {
2516 PCMCIASocket *socket;
2517 struct pcmcia_socket_entry_s *next;
2518 } *pcmcia_sockets = 0;
2520 void pcmcia_socket_register(PCMCIASocket *socket)
2522 struct pcmcia_socket_entry_s *entry;
2524 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2525 entry->socket = socket;
2526 entry->next = pcmcia_sockets;
2527 pcmcia_sockets = entry;
2530 void pcmcia_socket_unregister(PCMCIASocket *socket)
2532 struct pcmcia_socket_entry_s *entry, **ptr;
2534 ptr = &pcmcia_sockets;
2535 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2536 if (entry->socket == socket) {
2537 *ptr = entry->next;
2538 qemu_free(entry);
2542 void pcmcia_info(Monitor *mon)
2544 struct pcmcia_socket_entry_s *iter;
2546 if (!pcmcia_sockets)
2547 monitor_printf(mon, "No PCMCIA sockets\n");
2549 for (iter = pcmcia_sockets; iter; iter = iter->next)
2550 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2551 iter->socket->attached ? iter->socket->card_string :
2552 "Empty");
2555 /***********************************************************/
2556 /* register display */
2558 struct DisplayAllocator default_allocator = {
2559 defaultallocator_create_displaysurface,
2560 defaultallocator_resize_displaysurface,
2561 defaultallocator_free_displaysurface
2564 void register_displaystate(DisplayState *ds)
2566 DisplayState **s;
2567 s = &display_state;
2568 while (*s != NULL)
2569 s = &(*s)->next;
2570 ds->next = NULL;
2571 *s = ds;
2574 DisplayState *get_displaystate(void)
2576 return display_state;
2579 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2581 if(ds->allocator == &default_allocator) ds->allocator = da;
2582 return ds->allocator;
2585 /* dumb display */
2587 static void dumb_display_init(void)
2589 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2590 ds->allocator = &default_allocator;
2591 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2592 register_displaystate(ds);
2595 /***********************************************************/
2596 /* I/O handling */
2598 typedef struct IOHandlerRecord {
2599 int fd;
2600 IOCanRWHandler *fd_read_poll;
2601 IOHandler *fd_read;
2602 IOHandler *fd_write;
2603 int deleted;
2604 void *opaque;
2605 /* temporary data */
2606 struct pollfd *ufd;
2607 struct IOHandlerRecord *next;
2608 } IOHandlerRecord;
2610 static IOHandlerRecord *first_io_handler;
2612 /* XXX: fd_read_poll should be suppressed, but an API change is
2613 necessary in the character devices to suppress fd_can_read(). */
2614 int qemu_set_fd_handler2(int fd,
2615 IOCanRWHandler *fd_read_poll,
2616 IOHandler *fd_read,
2617 IOHandler *fd_write,
2618 void *opaque)
2620 IOHandlerRecord **pioh, *ioh;
2622 if (!fd_read && !fd_write) {
2623 pioh = &first_io_handler;
2624 for(;;) {
2625 ioh = *pioh;
2626 if (ioh == NULL)
2627 break;
2628 if (ioh->fd == fd) {
2629 ioh->deleted = 1;
2630 break;
2632 pioh = &ioh->next;
2634 } else {
2635 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2636 if (ioh->fd == fd)
2637 goto found;
2639 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2640 ioh->next = first_io_handler;
2641 first_io_handler = ioh;
2642 found:
2643 ioh->fd = fd;
2644 ioh->fd_read_poll = fd_read_poll;
2645 ioh->fd_read = fd_read;
2646 ioh->fd_write = fd_write;
2647 ioh->opaque = opaque;
2648 ioh->deleted = 0;
2650 return 0;
2653 int qemu_set_fd_handler(int fd,
2654 IOHandler *fd_read,
2655 IOHandler *fd_write,
2656 void *opaque)
2658 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2661 #ifdef _WIN32
2662 /***********************************************************/
2663 /* Polling handling */
2665 typedef struct PollingEntry {
2666 PollingFunc *func;
2667 void *opaque;
2668 struct PollingEntry *next;
2669 } PollingEntry;
2671 static PollingEntry *first_polling_entry;
2673 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2675 PollingEntry **ppe, *pe;
2676 pe = qemu_mallocz(sizeof(PollingEntry));
2677 pe->func = func;
2678 pe->opaque = opaque;
2679 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2680 *ppe = pe;
2681 return 0;
2684 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2686 PollingEntry **ppe, *pe;
2687 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2688 pe = *ppe;
2689 if (pe->func == func && pe->opaque == opaque) {
2690 *ppe = pe->next;
2691 qemu_free(pe);
2692 break;
2697 /***********************************************************/
2698 /* Wait objects support */
2699 typedef struct WaitObjects {
2700 int num;
2701 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2702 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2703 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2704 } WaitObjects;
2706 static WaitObjects wait_objects = {0};
2708 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2710 WaitObjects *w = &wait_objects;
2712 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2713 return -1;
2714 w->events[w->num] = handle;
2715 w->func[w->num] = func;
2716 w->opaque[w->num] = opaque;
2717 w->num++;
2718 return 0;
2721 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2723 int i, found;
2724 WaitObjects *w = &wait_objects;
2726 found = 0;
2727 for (i = 0; i < w->num; i++) {
2728 if (w->events[i] == handle)
2729 found = 1;
2730 if (found) {
2731 w->events[i] = w->events[i + 1];
2732 w->func[i] = w->func[i + 1];
2733 w->opaque[i] = w->opaque[i + 1];
2736 if (found)
2737 w->num--;
2739 #endif
2741 /***********************************************************/
2742 /* ram save/restore */
2744 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2745 #define RAM_SAVE_FLAG_COMPRESS 0x02
2746 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2747 #define RAM_SAVE_FLAG_PAGE 0x08
2748 #define RAM_SAVE_FLAG_EOS 0x10
2750 static int is_dup_page(uint8_t *page, uint8_t ch)
2752 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2753 uint32_t *array = (uint32_t *)page;
2754 int i;
2756 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2757 if (array[i] != val)
2758 return 0;
2761 return 1;
2764 static int ram_save_block(QEMUFile *f)
2766 static ram_addr_t current_addr = 0;
2767 ram_addr_t saved_addr = current_addr;
2768 ram_addr_t addr = 0;
2769 int found = 0;
2771 while (addr < last_ram_offset) {
2772 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2773 uint8_t *p;
2775 cpu_physical_memory_reset_dirty(current_addr,
2776 current_addr + TARGET_PAGE_SIZE,
2777 MIGRATION_DIRTY_FLAG);
2779 p = qemu_get_ram_ptr(current_addr);
2781 if (is_dup_page(p, *p)) {
2782 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2783 qemu_put_byte(f, *p);
2784 } else {
2785 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2786 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2789 found = 1;
2790 break;
2792 addr += TARGET_PAGE_SIZE;
2793 current_addr = (saved_addr + addr) % last_ram_offset;
2796 return found;
2799 static uint64_t bytes_transferred;
2801 static ram_addr_t ram_save_remaining(void)
2803 ram_addr_t addr;
2804 ram_addr_t count = 0;
2806 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2807 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2808 count++;
2811 return count;
2814 uint64_t ram_bytes_remaining(void)
2816 return ram_save_remaining() * TARGET_PAGE_SIZE;
2819 uint64_t ram_bytes_transferred(void)
2821 return bytes_transferred;
2824 uint64_t ram_bytes_total(void)
2826 return last_ram_offset;
2829 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2831 ram_addr_t addr;
2832 uint64_t bytes_transferred_last;
2833 double bwidth = 0;
2834 uint64_t expected_time = 0;
2836 if (stage < 0) {
2837 cpu_physical_memory_set_dirty_tracking(0);
2838 return 0;
2841 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2842 qemu_file_set_error(f);
2843 return 0;
2846 if (stage == 1) {
2847 bytes_transferred = 0;
2849 /* Make sure all dirty bits are set */
2850 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2851 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2852 cpu_physical_memory_set_dirty(addr);
2855 /* Enable dirty memory tracking */
2856 cpu_physical_memory_set_dirty_tracking(1);
2858 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2861 bytes_transferred_last = bytes_transferred;
2862 bwidth = get_clock();
2864 while (!qemu_file_rate_limit(f)) {
2865 int ret;
2867 ret = ram_save_block(f);
2868 bytes_transferred += ret * TARGET_PAGE_SIZE;
2869 if (ret == 0) /* no more blocks */
2870 break;
2873 bwidth = get_clock() - bwidth;
2874 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2876 /* if we haven't transferred anything this round, force expected_time to a
2877 * a very high value, but without crashing */
2878 if (bwidth == 0)
2879 bwidth = 0.000001;
2881 /* try transferring iterative blocks of memory */
2882 if (stage == 3) {
2883 /* flush all remaining blocks regardless of rate limiting */
2884 while (ram_save_block(f) != 0) {
2885 bytes_transferred += TARGET_PAGE_SIZE;
2887 cpu_physical_memory_set_dirty_tracking(0);
2890 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2892 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2894 return (stage == 2) && (expected_time <= migrate_max_downtime());
2897 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2899 ram_addr_t addr;
2900 int flags;
2902 if (version_id != 3)
2903 return -EINVAL;
2905 do {
2906 addr = qemu_get_be64(f);
2908 flags = addr & ~TARGET_PAGE_MASK;
2909 addr &= TARGET_PAGE_MASK;
2911 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2912 if (addr != last_ram_offset)
2913 return -EINVAL;
2916 if (flags & RAM_SAVE_FLAG_COMPRESS) {
2917 uint8_t ch = qemu_get_byte(f);
2918 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2919 #ifndef _WIN32
2920 if (ch == 0 &&
2921 (!kvm_enabled() || kvm_has_sync_mmu())) {
2922 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2924 #endif
2925 } else if (flags & RAM_SAVE_FLAG_PAGE) {
2926 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2928 if (qemu_file_has_error(f)) {
2929 return -EIO;
2931 } while (!(flags & RAM_SAVE_FLAG_EOS));
2933 return 0;
2936 void qemu_service_io(void)
2938 qemu_notify_event();
2941 /***********************************************************/
2942 /* machine registration */
2944 static QEMUMachine *first_machine = NULL;
2945 QEMUMachine *current_machine = NULL;
2947 int qemu_register_machine(QEMUMachine *m)
2949 QEMUMachine **pm;
2950 pm = &first_machine;
2951 while (*pm != NULL)
2952 pm = &(*pm)->next;
2953 m->next = NULL;
2954 *pm = m;
2955 return 0;
2958 static QEMUMachine *find_machine(const char *name)
2960 QEMUMachine *m;
2962 for(m = first_machine; m != NULL; m = m->next) {
2963 if (!strcmp(m->name, name))
2964 return m;
2965 if (m->alias && !strcmp(m->alias, name))
2966 return m;
2968 return NULL;
2971 static QEMUMachine *find_default_machine(void)
2973 QEMUMachine *m;
2975 for(m = first_machine; m != NULL; m = m->next) {
2976 if (m->is_default) {
2977 return m;
2980 return NULL;
2983 /***********************************************************/
2984 /* main execution loop */
2986 static void gui_update(void *opaque)
2988 uint64_t interval = GUI_REFRESH_INTERVAL;
2989 DisplayState *ds = opaque;
2990 DisplayChangeListener *dcl = ds->listeners;
2992 dpy_refresh(ds);
2994 while (dcl != NULL) {
2995 if (dcl->gui_timer_interval &&
2996 dcl->gui_timer_interval < interval)
2997 interval = dcl->gui_timer_interval;
2998 dcl = dcl->next;
3000 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3003 static void nographic_update(void *opaque)
3005 uint64_t interval = GUI_REFRESH_INTERVAL;
3007 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3010 struct vm_change_state_entry {
3011 VMChangeStateHandler *cb;
3012 void *opaque;
3013 QLIST_ENTRY (vm_change_state_entry) entries;
3016 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3018 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3019 void *opaque)
3021 VMChangeStateEntry *e;
3023 e = qemu_mallocz(sizeof (*e));
3025 e->cb = cb;
3026 e->opaque = opaque;
3027 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3028 return e;
3031 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3033 QLIST_REMOVE (e, entries);
3034 qemu_free (e);
3037 static void vm_state_notify(int running, int reason)
3039 VMChangeStateEntry *e;
3041 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3042 e->cb(e->opaque, running, reason);
3046 static void resume_all_vcpus(void);
3047 static void pause_all_vcpus(void);
3049 void vm_start(void)
3051 if (!vm_running) {
3052 cpu_enable_ticks();
3053 vm_running = 1;
3054 vm_state_notify(1, 0);
3055 qemu_rearm_alarm_timer(alarm_timer);
3056 resume_all_vcpus();
3060 /* reset/shutdown handler */
3062 typedef struct QEMUResetEntry {
3063 QTAILQ_ENTRY(QEMUResetEntry) entry;
3064 QEMUResetHandler *func;
3065 void *opaque;
3066 } QEMUResetEntry;
3068 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3069 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3070 static int reset_requested;
3071 static int shutdown_requested;
3072 static int powerdown_requested;
3073 static int debug_requested;
3074 static int vmstop_requested;
3076 int qemu_shutdown_requested(void)
3078 int r = shutdown_requested;
3079 shutdown_requested = 0;
3080 return r;
3083 int qemu_reset_requested(void)
3085 int r = reset_requested;
3086 reset_requested = 0;
3087 return r;
3090 int qemu_powerdown_requested(void)
3092 int r = powerdown_requested;
3093 powerdown_requested = 0;
3094 return r;
3097 static int qemu_debug_requested(void)
3099 int r = debug_requested;
3100 debug_requested = 0;
3101 return r;
3104 static int qemu_vmstop_requested(void)
3106 int r = vmstop_requested;
3107 vmstop_requested = 0;
3108 return r;
3111 static void do_vm_stop(int reason)
3113 if (vm_running) {
3114 cpu_disable_ticks();
3115 vm_running = 0;
3116 pause_all_vcpus();
3117 vm_state_notify(0, reason);
3121 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3123 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3125 re->func = func;
3126 re->opaque = opaque;
3127 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3130 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3132 QEMUResetEntry *re;
3134 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3135 if (re->func == func && re->opaque == opaque) {
3136 QTAILQ_REMOVE(&reset_handlers, re, entry);
3137 qemu_free(re);
3138 return;
3143 void qemu_system_reset(void)
3145 QEMUResetEntry *re, *nre;
3147 /* reset all devices */
3148 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3149 re->func(re->opaque);
3153 void qemu_system_reset_request(void)
3155 if (no_reboot) {
3156 shutdown_requested = 1;
3157 } else {
3158 reset_requested = 1;
3160 qemu_notify_event();
3163 void qemu_system_shutdown_request(void)
3165 shutdown_requested = 1;
3166 qemu_notify_event();
3169 void qemu_system_powerdown_request(void)
3171 powerdown_requested = 1;
3172 qemu_notify_event();
3175 #ifdef CONFIG_IOTHREAD
3176 static void qemu_system_vmstop_request(int reason)
3178 vmstop_requested = reason;
3179 qemu_notify_event();
3181 #endif
3183 #ifndef _WIN32
3184 static int io_thread_fd = -1;
3186 static void qemu_event_increment(void)
3188 static const char byte = 0;
3189 ssize_t ret;
3191 if (io_thread_fd == -1)
3192 return;
3194 ret = write(io_thread_fd, &byte, sizeof(byte));
3195 if (ret < 0 && (errno != EINTR && errno != EAGAIN)) {
3196 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
3197 strerror(errno));
3198 exit (1);
3202 static void qemu_event_read(void *opaque)
3204 int fd = (unsigned long)opaque;
3205 ssize_t len;
3207 /* Drain the notify pipe */
3208 do {
3209 char buffer[512];
3210 len = read(fd, buffer, sizeof(buffer));
3211 } while ((len == -1 && errno == EINTR) || len > 0);
3214 static int qemu_event_init(void)
3216 int err;
3217 int fds[2];
3219 err = qemu_pipe(fds);
3220 if (err == -1)
3221 return -errno;
3223 err = fcntl_setfl(fds[0], O_NONBLOCK);
3224 if (err < 0)
3225 goto fail;
3227 err = fcntl_setfl(fds[1], O_NONBLOCK);
3228 if (err < 0)
3229 goto fail;
3231 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3232 (void *)(unsigned long)fds[0]);
3234 io_thread_fd = fds[1];
3235 return 0;
3237 fail:
3238 close(fds[0]);
3239 close(fds[1]);
3240 return err;
3242 #else
3243 HANDLE qemu_event_handle;
3245 static void dummy_event_handler(void *opaque)
3249 static int qemu_event_init(void)
3251 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3252 if (!qemu_event_handle) {
3253 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3254 return -1;
3256 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3257 return 0;
3260 static void qemu_event_increment(void)
3262 if (!SetEvent(qemu_event_handle)) {
3263 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3264 GetLastError());
3265 exit (1);
3268 #endif
3270 static int cpu_can_run(CPUState *env)
3272 if (env->stop)
3273 return 0;
3274 if (env->stopped)
3275 return 0;
3276 return 1;
3279 #ifndef CONFIG_IOTHREAD
3280 static int qemu_init_main_loop(void)
3282 return qemu_event_init();
3285 void qemu_init_vcpu(void *_env)
3287 CPUState *env = _env;
3289 env->nr_cores = smp_cores;
3290 env->nr_threads = smp_threads;
3291 if (kvm_enabled())
3292 kvm_init_vcpu(env);
3293 return;
3296 int qemu_cpu_self(void *env)
3298 return 1;
3301 static void resume_all_vcpus(void)
3305 static void pause_all_vcpus(void)
3309 void qemu_cpu_kick(void *env)
3311 return;
3314 void qemu_notify_event(void)
3316 CPUState *env = cpu_single_env;
3318 if (env) {
3319 cpu_exit(env);
3323 void qemu_mutex_lock_iothread(void) {}
3324 void qemu_mutex_unlock_iothread(void) {}
3326 void vm_stop(int reason)
3328 do_vm_stop(reason);
3331 #else /* CONFIG_IOTHREAD */
3333 #include "qemu-thread.h"
3335 QemuMutex qemu_global_mutex;
3336 static QemuMutex qemu_fair_mutex;
3338 static QemuThread io_thread;
3340 static QemuThread *tcg_cpu_thread;
3341 static QemuCond *tcg_halt_cond;
3343 static int qemu_system_ready;
3344 /* cpu creation */
3345 static QemuCond qemu_cpu_cond;
3346 /* system init */
3347 static QemuCond qemu_system_cond;
3348 static QemuCond qemu_pause_cond;
3350 static void block_io_signals(void);
3351 static void unblock_io_signals(void);
3352 static int tcg_has_work(void);
3354 static int qemu_init_main_loop(void)
3356 int ret;
3358 ret = qemu_event_init();
3359 if (ret)
3360 return ret;
3362 qemu_cond_init(&qemu_pause_cond);
3363 qemu_mutex_init(&qemu_fair_mutex);
3364 qemu_mutex_init(&qemu_global_mutex);
3365 qemu_mutex_lock(&qemu_global_mutex);
3367 unblock_io_signals();
3368 qemu_thread_self(&io_thread);
3370 return 0;
3373 static void qemu_wait_io_event(CPUState *env)
3375 while (!tcg_has_work())
3376 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3378 qemu_mutex_unlock(&qemu_global_mutex);
3381 * Users of qemu_global_mutex can be starved, having no chance
3382 * to acquire it since this path will get to it first.
3383 * So use another lock to provide fairness.
3385 qemu_mutex_lock(&qemu_fair_mutex);
3386 qemu_mutex_unlock(&qemu_fair_mutex);
3388 qemu_mutex_lock(&qemu_global_mutex);
3389 if (env->stop) {
3390 env->stop = 0;
3391 env->stopped = 1;
3392 qemu_cond_signal(&qemu_pause_cond);
3396 static int qemu_cpu_exec(CPUState *env);
3398 static void *kvm_cpu_thread_fn(void *arg)
3400 CPUState *env = arg;
3402 block_io_signals();
3403 qemu_thread_self(env->thread);
3404 if (kvm_enabled())
3405 kvm_init_vcpu(env);
3407 /* signal CPU creation */
3408 qemu_mutex_lock(&qemu_global_mutex);
3409 env->created = 1;
3410 qemu_cond_signal(&qemu_cpu_cond);
3412 /* and wait for machine initialization */
3413 while (!qemu_system_ready)
3414 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3416 while (1) {
3417 if (cpu_can_run(env))
3418 qemu_cpu_exec(env);
3419 qemu_wait_io_event(env);
3422 return NULL;
3425 static void tcg_cpu_exec(void);
3427 static void *tcg_cpu_thread_fn(void *arg)
3429 CPUState *env = arg;
3431 block_io_signals();
3432 qemu_thread_self(env->thread);
3434 /* signal CPU creation */
3435 qemu_mutex_lock(&qemu_global_mutex);
3436 for (env = first_cpu; env != NULL; env = env->next_cpu)
3437 env->created = 1;
3438 qemu_cond_signal(&qemu_cpu_cond);
3440 /* and wait for machine initialization */
3441 while (!qemu_system_ready)
3442 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3444 while (1) {
3445 tcg_cpu_exec();
3446 qemu_wait_io_event(cur_cpu);
3449 return NULL;
3452 void qemu_cpu_kick(void *_env)
3454 CPUState *env = _env;
3455 qemu_cond_broadcast(env->halt_cond);
3456 if (kvm_enabled())
3457 qemu_thread_signal(env->thread, SIGUSR1);
3460 int qemu_cpu_self(void *_env)
3462 CPUState *env = _env;
3463 QemuThread this;
3465 qemu_thread_self(&this);
3467 return qemu_thread_equal(&this, env->thread);
3470 static void cpu_signal(int sig)
3472 if (cpu_single_env)
3473 cpu_exit(cpu_single_env);
3476 static void block_io_signals(void)
3478 sigset_t set;
3479 struct sigaction sigact;
3481 sigemptyset(&set);
3482 sigaddset(&set, SIGUSR2);
3483 sigaddset(&set, SIGIO);
3484 sigaddset(&set, SIGALRM);
3485 pthread_sigmask(SIG_BLOCK, &set, NULL);
3487 sigemptyset(&set);
3488 sigaddset(&set, SIGUSR1);
3489 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3491 memset(&sigact, 0, sizeof(sigact));
3492 sigact.sa_handler = cpu_signal;
3493 sigaction(SIGUSR1, &sigact, NULL);
3496 static void unblock_io_signals(void)
3498 sigset_t set;
3500 sigemptyset(&set);
3501 sigaddset(&set, SIGUSR2);
3502 sigaddset(&set, SIGIO);
3503 sigaddset(&set, SIGALRM);
3504 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3506 sigemptyset(&set);
3507 sigaddset(&set, SIGUSR1);
3508 pthread_sigmask(SIG_BLOCK, &set, NULL);
3511 static void qemu_signal_lock(unsigned int msecs)
3513 qemu_mutex_lock(&qemu_fair_mutex);
3515 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3516 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3517 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3518 break;
3520 qemu_mutex_unlock(&qemu_fair_mutex);
3523 void qemu_mutex_lock_iothread(void)
3525 if (kvm_enabled()) {
3526 qemu_mutex_lock(&qemu_fair_mutex);
3527 qemu_mutex_lock(&qemu_global_mutex);
3528 qemu_mutex_unlock(&qemu_fair_mutex);
3529 } else
3530 qemu_signal_lock(100);
3533 void qemu_mutex_unlock_iothread(void)
3535 qemu_mutex_unlock(&qemu_global_mutex);
3538 static int all_vcpus_paused(void)
3540 CPUState *penv = first_cpu;
3542 while (penv) {
3543 if (!penv->stopped)
3544 return 0;
3545 penv = (CPUState *)penv->next_cpu;
3548 return 1;
3551 static void pause_all_vcpus(void)
3553 CPUState *penv = first_cpu;
3555 while (penv) {
3556 penv->stop = 1;
3557 qemu_thread_signal(penv->thread, SIGUSR1);
3558 qemu_cpu_kick(penv);
3559 penv = (CPUState *)penv->next_cpu;
3562 while (!all_vcpus_paused()) {
3563 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3564 penv = first_cpu;
3565 while (penv) {
3566 qemu_thread_signal(penv->thread, SIGUSR1);
3567 penv = (CPUState *)penv->next_cpu;
3572 static void resume_all_vcpus(void)
3574 CPUState *penv = first_cpu;
3576 while (penv) {
3577 penv->stop = 0;
3578 penv->stopped = 0;
3579 qemu_thread_signal(penv->thread, SIGUSR1);
3580 qemu_cpu_kick(penv);
3581 penv = (CPUState *)penv->next_cpu;
3585 static void tcg_init_vcpu(void *_env)
3587 CPUState *env = _env;
3588 /* share a single thread for all cpus with TCG */
3589 if (!tcg_cpu_thread) {
3590 env->thread = qemu_mallocz(sizeof(QemuThread));
3591 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3592 qemu_cond_init(env->halt_cond);
3593 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3594 while (env->created == 0)
3595 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3596 tcg_cpu_thread = env->thread;
3597 tcg_halt_cond = env->halt_cond;
3598 } else {
3599 env->thread = tcg_cpu_thread;
3600 env->halt_cond = tcg_halt_cond;
3604 static void kvm_start_vcpu(CPUState *env)
3606 env->thread = qemu_mallocz(sizeof(QemuThread));
3607 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3608 qemu_cond_init(env->halt_cond);
3609 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3610 while (env->created == 0)
3611 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3614 void qemu_init_vcpu(void *_env)
3616 CPUState *env = _env;
3618 env->nr_cores = smp_cores;
3619 env->nr_threads = smp_threads;
3620 if (kvm_enabled())
3621 kvm_start_vcpu(env);
3622 else
3623 tcg_init_vcpu(env);
3626 void qemu_notify_event(void)
3628 qemu_event_increment();
3631 void vm_stop(int reason)
3633 QemuThread me;
3634 qemu_thread_self(&me);
3636 if (!qemu_thread_equal(&me, &io_thread)) {
3637 qemu_system_vmstop_request(reason);
3639 * FIXME: should not return to device code in case
3640 * vm_stop() has been requested.
3642 if (cpu_single_env) {
3643 cpu_exit(cpu_single_env);
3644 cpu_single_env->stop = 1;
3646 return;
3648 do_vm_stop(reason);
3651 #endif
3654 #ifdef _WIN32
3655 static void host_main_loop_wait(int *timeout)
3657 int ret, ret2, i;
3658 PollingEntry *pe;
3661 /* XXX: need to suppress polling by better using win32 events */
3662 ret = 0;
3663 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3664 ret |= pe->func(pe->opaque);
3666 if (ret == 0) {
3667 int err;
3668 WaitObjects *w = &wait_objects;
3670 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3671 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3672 if (w->func[ret - WAIT_OBJECT_0])
3673 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3675 /* Check for additional signaled events */
3676 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3678 /* Check if event is signaled */
3679 ret2 = WaitForSingleObject(w->events[i], 0);
3680 if(ret2 == WAIT_OBJECT_0) {
3681 if (w->func[i])
3682 w->func[i](w->opaque[i]);
3683 } else if (ret2 == WAIT_TIMEOUT) {
3684 } else {
3685 err = GetLastError();
3686 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3689 } else if (ret == WAIT_TIMEOUT) {
3690 } else {
3691 err = GetLastError();
3692 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3696 *timeout = 0;
3698 #else
3699 static void host_main_loop_wait(int *timeout)
3702 #endif
3704 void main_loop_wait(int timeout)
3706 IOHandlerRecord *ioh;
3707 fd_set rfds, wfds, xfds;
3708 int ret, nfds;
3709 struct timeval tv;
3711 qemu_bh_update_timeout(&timeout);
3713 host_main_loop_wait(&timeout);
3715 /* poll any events */
3716 /* XXX: separate device handlers from system ones */
3717 nfds = -1;
3718 FD_ZERO(&rfds);
3719 FD_ZERO(&wfds);
3720 FD_ZERO(&xfds);
3721 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3722 if (ioh->deleted)
3723 continue;
3724 if (ioh->fd_read &&
3725 (!ioh->fd_read_poll ||
3726 ioh->fd_read_poll(ioh->opaque) != 0)) {
3727 FD_SET(ioh->fd, &rfds);
3728 if (ioh->fd > nfds)
3729 nfds = ioh->fd;
3731 if (ioh->fd_write) {
3732 FD_SET(ioh->fd, &wfds);
3733 if (ioh->fd > nfds)
3734 nfds = ioh->fd;
3738 tv.tv_sec = timeout / 1000;
3739 tv.tv_usec = (timeout % 1000) * 1000;
3741 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3743 qemu_mutex_unlock_iothread();
3744 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3745 qemu_mutex_lock_iothread();
3746 if (ret > 0) {
3747 IOHandlerRecord **pioh;
3749 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3750 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3751 ioh->fd_read(ioh->opaque);
3753 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3754 ioh->fd_write(ioh->opaque);
3758 /* remove deleted IO handlers */
3759 pioh = &first_io_handler;
3760 while (*pioh) {
3761 ioh = *pioh;
3762 if (ioh->deleted) {
3763 *pioh = ioh->next;
3764 qemu_free(ioh);
3765 } else
3766 pioh = &ioh->next;
3770 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3772 /* rearm timer, if not periodic */
3773 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3774 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3775 qemu_rearm_alarm_timer(alarm_timer);
3778 /* vm time timers */
3779 if (vm_running) {
3780 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3781 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3782 qemu_get_clock(vm_clock));
3785 /* real time timers */
3786 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3787 qemu_get_clock(rt_clock));
3789 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3790 qemu_get_clock(host_clock));
3792 /* Check bottom-halves last in case any of the earlier events triggered
3793 them. */
3794 qemu_bh_poll();
3798 static int qemu_cpu_exec(CPUState *env)
3800 int ret;
3801 #ifdef CONFIG_PROFILER
3802 int64_t ti;
3803 #endif
3805 #ifdef CONFIG_PROFILER
3806 ti = profile_getclock();
3807 #endif
3808 if (use_icount) {
3809 int64_t count;
3810 int decr;
3811 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3812 env->icount_decr.u16.low = 0;
3813 env->icount_extra = 0;
3814 count = qemu_next_deadline();
3815 count = (count + (1 << icount_time_shift) - 1)
3816 >> icount_time_shift;
3817 qemu_icount += count;
3818 decr = (count > 0xffff) ? 0xffff : count;
3819 count -= decr;
3820 env->icount_decr.u16.low = decr;
3821 env->icount_extra = count;
3823 ret = cpu_exec(env);
3824 #ifdef CONFIG_PROFILER
3825 qemu_time += profile_getclock() - ti;
3826 #endif
3827 if (use_icount) {
3828 /* Fold pending instructions back into the
3829 instruction counter, and clear the interrupt flag. */
3830 qemu_icount -= (env->icount_decr.u16.low
3831 + env->icount_extra);
3832 env->icount_decr.u32 = 0;
3833 env->icount_extra = 0;
3835 return ret;
3838 static void tcg_cpu_exec(void)
3840 int ret = 0;
3842 if (next_cpu == NULL)
3843 next_cpu = first_cpu;
3844 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3845 CPUState *env = cur_cpu = next_cpu;
3847 if (!vm_running)
3848 break;
3849 if (timer_alarm_pending) {
3850 timer_alarm_pending = 0;
3851 break;
3853 if (cpu_can_run(env))
3854 ret = qemu_cpu_exec(env);
3855 if (ret == EXCP_DEBUG) {
3856 gdb_set_stop_cpu(env);
3857 debug_requested = 1;
3858 break;
3863 static int cpu_has_work(CPUState *env)
3865 if (env->stop)
3866 return 1;
3867 if (env->stopped)
3868 return 0;
3869 if (!env->halted)
3870 return 1;
3871 if (qemu_cpu_has_work(env))
3872 return 1;
3873 return 0;
3876 static int tcg_has_work(void)
3878 CPUState *env;
3880 for (env = first_cpu; env != NULL; env = env->next_cpu)
3881 if (cpu_has_work(env))
3882 return 1;
3883 return 0;
3886 static int qemu_calculate_timeout(void)
3888 #ifndef CONFIG_IOTHREAD
3889 int timeout;
3891 if (!vm_running)
3892 timeout = 5000;
3893 else if (tcg_has_work())
3894 timeout = 0;
3895 else if (!use_icount)
3896 timeout = 5000;
3897 else {
3898 /* XXX: use timeout computed from timers */
3899 int64_t add;
3900 int64_t delta;
3901 /* Advance virtual time to the next event. */
3902 if (use_icount == 1) {
3903 /* When not using an adaptive execution frequency
3904 we tend to get badly out of sync with real time,
3905 so just delay for a reasonable amount of time. */
3906 delta = 0;
3907 } else {
3908 delta = cpu_get_icount() - cpu_get_clock();
3910 if (delta > 0) {
3911 /* If virtual time is ahead of real time then just
3912 wait for IO. */
3913 timeout = (delta / 1000000) + 1;
3914 } else {
3915 /* Wait for either IO to occur or the next
3916 timer event. */
3917 add = qemu_next_deadline();
3918 /* We advance the timer before checking for IO.
3919 Limit the amount we advance so that early IO
3920 activity won't get the guest too far ahead. */
3921 if (add > 10000000)
3922 add = 10000000;
3923 delta += add;
3924 add = (add + (1 << icount_time_shift) - 1)
3925 >> icount_time_shift;
3926 qemu_icount += add;
3927 timeout = delta / 1000000;
3928 if (timeout < 0)
3929 timeout = 0;
3933 return timeout;
3934 #else /* CONFIG_IOTHREAD */
3935 return 1000;
3936 #endif
3939 static int vm_can_run(void)
3941 if (powerdown_requested)
3942 return 0;
3943 if (reset_requested)
3944 return 0;
3945 if (shutdown_requested)
3946 return 0;
3947 if (debug_requested)
3948 return 0;
3949 return 1;
3952 qemu_irq qemu_system_powerdown;
3954 static void main_loop(void)
3956 int r;
3958 #ifdef CONFIG_IOTHREAD
3959 qemu_system_ready = 1;
3960 qemu_cond_broadcast(&qemu_system_cond);
3961 #endif
3963 for (;;) {
3964 do {
3965 #ifdef CONFIG_PROFILER
3966 int64_t ti;
3967 #endif
3968 #ifndef CONFIG_IOTHREAD
3969 tcg_cpu_exec();
3970 #endif
3971 #ifdef CONFIG_PROFILER
3972 ti = profile_getclock();
3973 #endif
3974 main_loop_wait(qemu_calculate_timeout());
3975 #ifdef CONFIG_PROFILER
3976 dev_time += profile_getclock() - ti;
3977 #endif
3978 } while (vm_can_run());
3980 if (qemu_debug_requested()) {
3981 monitor_protocol_event(QEVENT_DEBUG, NULL);
3982 vm_stop(EXCP_DEBUG);
3984 if (qemu_shutdown_requested()) {
3985 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
3986 if (no_shutdown) {
3987 vm_stop(0);
3988 no_shutdown = 0;
3989 } else
3990 break;
3992 if (qemu_reset_requested()) {
3993 monitor_protocol_event(QEVENT_RESET, NULL);
3994 pause_all_vcpus();
3995 qemu_system_reset();
3996 resume_all_vcpus();
3998 if (qemu_powerdown_requested()) {
3999 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4000 qemu_irq_raise(qemu_system_powerdown);
4002 if ((r = qemu_vmstop_requested())) {
4003 monitor_protocol_event(QEVENT_STOP, NULL);
4004 vm_stop(r);
4007 pause_all_vcpus();
4010 static void version(void)
4012 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4015 static void help(int exitcode)
4017 version();
4018 printf("usage: %s [options] [disk_image]\n"
4019 "\n"
4020 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4021 "\n"
4022 #define DEF(option, opt_arg, opt_enum, opt_help) \
4023 opt_help
4024 #define DEFHEADING(text) stringify(text) "\n"
4025 #include "qemu-options.h"
4026 #undef DEF
4027 #undef DEFHEADING
4028 #undef GEN_DOCS
4029 "\n"
4030 "During emulation, the following keys are useful:\n"
4031 "ctrl-alt-f toggle full screen\n"
4032 "ctrl-alt-n switch to virtual console 'n'\n"
4033 "ctrl-alt toggle mouse and keyboard grab\n"
4034 "\n"
4035 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4037 "qemu",
4038 DEFAULT_RAM_SIZE,
4039 #ifndef _WIN32
4040 DEFAULT_NETWORK_SCRIPT,
4041 DEFAULT_NETWORK_DOWN_SCRIPT,
4042 #endif
4043 DEFAULT_GDBSTUB_PORT,
4044 "/tmp/qemu.log");
4045 exit(exitcode);
4048 #define HAS_ARG 0x0001
4050 enum {
4051 #define DEF(option, opt_arg, opt_enum, opt_help) \
4052 opt_enum,
4053 #define DEFHEADING(text)
4054 #include "qemu-options.h"
4055 #undef DEF
4056 #undef DEFHEADING
4057 #undef GEN_DOCS
4060 typedef struct QEMUOption {
4061 const char *name;
4062 int flags;
4063 int index;
4064 } QEMUOption;
4066 static const QEMUOption qemu_options[] = {
4067 { "h", 0, QEMU_OPTION_h },
4068 #define DEF(option, opt_arg, opt_enum, opt_help) \
4069 { option, opt_arg, opt_enum },
4070 #define DEFHEADING(text)
4071 #include "qemu-options.h"
4072 #undef DEF
4073 #undef DEFHEADING
4074 #undef GEN_DOCS
4075 { NULL },
4078 #ifdef HAS_AUDIO
4079 struct soundhw soundhw[] = {
4080 #ifdef HAS_AUDIO_CHOICE
4081 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4083 "pcspk",
4084 "PC speaker",
4087 { .init_isa = pcspk_audio_init }
4089 #endif
4091 #ifdef CONFIG_SB16
4093 "sb16",
4094 "Creative Sound Blaster 16",
4097 { .init_isa = SB16_init }
4099 #endif
4101 #ifdef CONFIG_CS4231A
4103 "cs4231a",
4104 "CS4231A",
4107 { .init_isa = cs4231a_init }
4109 #endif
4111 #ifdef CONFIG_ADLIB
4113 "adlib",
4114 #ifdef HAS_YMF262
4115 "Yamaha YMF262 (OPL3)",
4116 #else
4117 "Yamaha YM3812 (OPL2)",
4118 #endif
4121 { .init_isa = Adlib_init }
4123 #endif
4125 #ifdef CONFIG_GUS
4127 "gus",
4128 "Gravis Ultrasound GF1",
4131 { .init_isa = GUS_init }
4133 #endif
4135 #ifdef CONFIG_AC97
4137 "ac97",
4138 "Intel 82801AA AC97 Audio",
4141 { .init_pci = ac97_init }
4143 #endif
4145 #ifdef CONFIG_ES1370
4147 "es1370",
4148 "ENSONIQ AudioPCI ES1370",
4151 { .init_pci = es1370_init }
4153 #endif
4155 #endif /* HAS_AUDIO_CHOICE */
4157 { NULL, NULL, 0, 0, { NULL } }
4160 static void select_soundhw (const char *optarg)
4162 struct soundhw *c;
4164 if (*optarg == '?') {
4165 show_valid_cards:
4167 printf ("Valid sound card names (comma separated):\n");
4168 for (c = soundhw; c->name; ++c) {
4169 printf ("%-11s %s\n", c->name, c->descr);
4171 printf ("\n-soundhw all will enable all of the above\n");
4172 exit (*optarg != '?');
4174 else {
4175 size_t l;
4176 const char *p;
4177 char *e;
4178 int bad_card = 0;
4180 if (!strcmp (optarg, "all")) {
4181 for (c = soundhw; c->name; ++c) {
4182 c->enabled = 1;
4184 return;
4187 p = optarg;
4188 while (*p) {
4189 e = strchr (p, ',');
4190 l = !e ? strlen (p) : (size_t) (e - p);
4192 for (c = soundhw; c->name; ++c) {
4193 if (!strncmp (c->name, p, l) && !c->name[l]) {
4194 c->enabled = 1;
4195 break;
4199 if (!c->name) {
4200 if (l > 80) {
4201 fprintf (stderr,
4202 "Unknown sound card name (too big to show)\n");
4204 else {
4205 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4206 (int) l, p);
4208 bad_card = 1;
4210 p += l + (e != NULL);
4213 if (bad_card)
4214 goto show_valid_cards;
4217 #endif
4219 static void select_vgahw (const char *p)
4221 const char *opts;
4223 default_vga = 0;
4224 vga_interface_type = VGA_NONE;
4225 if (strstart(p, "std", &opts)) {
4226 vga_interface_type = VGA_STD;
4227 } else if (strstart(p, "cirrus", &opts)) {
4228 vga_interface_type = VGA_CIRRUS;
4229 } else if (strstart(p, "vmware", &opts)) {
4230 vga_interface_type = VGA_VMWARE;
4231 } else if (strstart(p, "xenfb", &opts)) {
4232 vga_interface_type = VGA_XENFB;
4233 } else if (!strstart(p, "none", &opts)) {
4234 invalid_vga:
4235 fprintf(stderr, "Unknown vga type: %s\n", p);
4236 exit(1);
4238 while (*opts) {
4239 const char *nextopt;
4241 if (strstart(opts, ",retrace=", &nextopt)) {
4242 opts = nextopt;
4243 if (strstart(opts, "dumb", &nextopt))
4244 vga_retrace_method = VGA_RETRACE_DUMB;
4245 else if (strstart(opts, "precise", &nextopt))
4246 vga_retrace_method = VGA_RETRACE_PRECISE;
4247 else goto invalid_vga;
4248 } else goto invalid_vga;
4249 opts = nextopt;
4253 #ifdef TARGET_I386
4254 static int balloon_parse(const char *arg)
4256 QemuOpts *opts;
4258 if (strcmp(arg, "none") == 0) {
4259 return 0;
4262 if (!strncmp(arg, "virtio", 6)) {
4263 if (arg[6] == ',') {
4264 /* have params -> parse them */
4265 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4266 if (!opts)
4267 return -1;
4268 } else {
4269 /* create empty opts */
4270 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4272 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4273 return 0;
4276 return -1;
4278 #endif
4280 #ifdef _WIN32
4281 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4283 exit(STATUS_CONTROL_C_EXIT);
4284 return TRUE;
4286 #endif
4288 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4290 int ret;
4292 if(strlen(str) != 36)
4293 return -1;
4295 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4296 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4297 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4299 if(ret != 16)
4300 return -1;
4302 #ifdef TARGET_I386
4303 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4304 #endif
4306 return 0;
4309 #ifndef _WIN32
4311 static void termsig_handler(int signal)
4313 qemu_system_shutdown_request();
4316 static void sigchld_handler(int signal)
4318 waitpid(-1, NULL, WNOHANG);
4321 static void sighandler_setup(void)
4323 struct sigaction act;
4325 memset(&act, 0, sizeof(act));
4326 act.sa_handler = termsig_handler;
4327 sigaction(SIGINT, &act, NULL);
4328 sigaction(SIGHUP, &act, NULL);
4329 sigaction(SIGTERM, &act, NULL);
4331 act.sa_handler = sigchld_handler;
4332 act.sa_flags = SA_NOCLDSTOP;
4333 sigaction(SIGCHLD, &act, NULL);
4336 #endif
4338 #ifdef _WIN32
4339 /* Look for support files in the same directory as the executable. */
4340 static char *find_datadir(const char *argv0)
4342 char *p;
4343 char buf[MAX_PATH];
4344 DWORD len;
4346 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4347 if (len == 0) {
4348 return NULL;
4351 buf[len] = 0;
4352 p = buf + len - 1;
4353 while (p != buf && *p != '\\')
4354 p--;
4355 *p = 0;
4356 if (access(buf, R_OK) == 0) {
4357 return qemu_strdup(buf);
4359 return NULL;
4361 #else /* !_WIN32 */
4363 /* Find a likely location for support files using the location of the binary.
4364 For installed binaries this will be "$bindir/../share/qemu". When
4365 running from the build tree this will be "$bindir/../pc-bios". */
4366 #define SHARE_SUFFIX "/share/qemu"
4367 #define BUILD_SUFFIX "/pc-bios"
4368 static char *find_datadir(const char *argv0)
4370 char *dir;
4371 char *p = NULL;
4372 char *res;
4373 char buf[PATH_MAX];
4374 size_t max_len;
4376 #if defined(__linux__)
4378 int len;
4379 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4380 if (len > 0) {
4381 buf[len] = 0;
4382 p = buf;
4385 #elif defined(__FreeBSD__)
4387 int len;
4388 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4389 if (len > 0) {
4390 buf[len] = 0;
4391 p = buf;
4394 #endif
4395 /* If we don't have any way of figuring out the actual executable
4396 location then try argv[0]. */
4397 if (!p) {
4398 p = realpath(argv0, buf);
4399 if (!p) {
4400 return NULL;
4403 dir = dirname(p);
4404 dir = dirname(dir);
4406 max_len = strlen(dir) +
4407 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4408 res = qemu_mallocz(max_len);
4409 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4410 if (access(res, R_OK)) {
4411 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4412 if (access(res, R_OK)) {
4413 qemu_free(res);
4414 res = NULL;
4418 return res;
4420 #undef SHARE_SUFFIX
4421 #undef BUILD_SUFFIX
4422 #endif
4424 char *qemu_find_file(int type, const char *name)
4426 int len;
4427 const char *subdir;
4428 char *buf;
4430 /* If name contains path separators then try it as a straight path. */
4431 if ((strchr(name, '/') || strchr(name, '\\'))
4432 && access(name, R_OK) == 0) {
4433 return qemu_strdup(name);
4435 switch (type) {
4436 case QEMU_FILE_TYPE_BIOS:
4437 subdir = "";
4438 break;
4439 case QEMU_FILE_TYPE_KEYMAP:
4440 subdir = "keymaps/";
4441 break;
4442 default:
4443 abort();
4445 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4446 buf = qemu_mallocz(len);
4447 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4448 if (access(buf, R_OK)) {
4449 qemu_free(buf);
4450 return NULL;
4452 return buf;
4455 static int device_init_func(QemuOpts *opts, void *opaque)
4457 DeviceState *dev;
4459 dev = qdev_device_add(opts);
4460 if (!dev)
4461 return -1;
4462 return 0;
4465 static int chardev_init_func(QemuOpts *opts, void *opaque)
4467 CharDriverState *chr;
4469 chr = qemu_chr_open_opts(opts, NULL);
4470 if (!chr)
4471 return -1;
4472 return 0;
4475 static int mon_init_func(QemuOpts *opts, void *opaque)
4477 CharDriverState *chr;
4478 const char *chardev;
4479 const char *mode;
4480 int flags;
4482 mode = qemu_opt_get(opts, "mode");
4483 if (mode == NULL) {
4484 mode = "readline";
4486 if (strcmp(mode, "readline") == 0) {
4487 flags = MONITOR_USE_READLINE;
4488 } else if (strcmp(mode, "control") == 0) {
4489 flags = MONITOR_USE_CONTROL;
4490 } else {
4491 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4492 exit(1);
4495 if (qemu_opt_get_bool(opts, "default", 0))
4496 flags |= MONITOR_IS_DEFAULT;
4498 chardev = qemu_opt_get(opts, "chardev");
4499 chr = qemu_chr_find(chardev);
4500 if (chr == NULL) {
4501 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4502 exit(1);
4505 monitor_init(chr, flags);
4506 return 0;
4509 static void monitor_parse(const char *optarg, const char *mode)
4511 static int monitor_device_index = 0;
4512 QemuOpts *opts;
4513 const char *p;
4514 char label[32];
4515 int def = 0;
4517 if (strstart(optarg, "chardev:", &p)) {
4518 snprintf(label, sizeof(label), "%s", p);
4519 } else {
4520 if (monitor_device_index) {
4521 snprintf(label, sizeof(label), "monitor%d",
4522 monitor_device_index);
4523 } else {
4524 snprintf(label, sizeof(label), "monitor");
4525 def = 1;
4527 opts = qemu_chr_parse_compat(label, optarg);
4528 if (!opts) {
4529 fprintf(stderr, "parse error: %s\n", optarg);
4530 exit(1);
4534 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4535 if (!opts) {
4536 fprintf(stderr, "duplicate chardev: %s\n", label);
4537 exit(1);
4539 qemu_opt_set(opts, "mode", mode);
4540 qemu_opt_set(opts, "chardev", label);
4541 if (def)
4542 qemu_opt_set(opts, "default", "on");
4543 monitor_device_index++;
4546 struct device_config {
4547 enum {
4548 DEV_USB, /* -usbdevice */
4549 DEV_BT, /* -bt */
4550 DEV_SERIAL, /* -serial */
4551 DEV_PARALLEL, /* -parallel */
4552 DEV_VIRTCON, /* -virtioconsole */
4553 DEV_DEBUGCON, /* -debugcon */
4554 } type;
4555 const char *cmdline;
4556 QTAILQ_ENTRY(device_config) next;
4558 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4560 static void add_device_config(int type, const char *cmdline)
4562 struct device_config *conf;
4564 conf = qemu_mallocz(sizeof(*conf));
4565 conf->type = type;
4566 conf->cmdline = cmdline;
4567 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4570 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4572 struct device_config *conf;
4573 int rc;
4575 QTAILQ_FOREACH(conf, &device_configs, next) {
4576 if (conf->type != type)
4577 continue;
4578 rc = func(conf->cmdline);
4579 if (0 != rc)
4580 return rc;
4582 return 0;
4585 static int serial_parse(const char *devname)
4587 static int index = 0;
4588 char label[32];
4590 if (strcmp(devname, "none") == 0)
4591 return 0;
4592 if (index == MAX_SERIAL_PORTS) {
4593 fprintf(stderr, "qemu: too many serial ports\n");
4594 exit(1);
4596 snprintf(label, sizeof(label), "serial%d", index);
4597 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4598 if (!serial_hds[index]) {
4599 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4600 devname, strerror(errno));
4601 return -1;
4603 index++;
4604 return 0;
4607 static int parallel_parse(const char *devname)
4609 static int index = 0;
4610 char label[32];
4612 if (strcmp(devname, "none") == 0)
4613 return 0;
4614 if (index == MAX_PARALLEL_PORTS) {
4615 fprintf(stderr, "qemu: too many parallel ports\n");
4616 exit(1);
4618 snprintf(label, sizeof(label), "parallel%d", index);
4619 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4620 if (!parallel_hds[index]) {
4621 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4622 devname, strerror(errno));
4623 return -1;
4625 index++;
4626 return 0;
4629 static int virtcon_parse(const char *devname)
4631 static int index = 0;
4632 char label[32];
4633 QemuOpts *bus_opts, *dev_opts;
4635 if (strcmp(devname, "none") == 0)
4636 return 0;
4637 if (index == MAX_VIRTIO_CONSOLES) {
4638 fprintf(stderr, "qemu: too many virtio consoles\n");
4639 exit(1);
4642 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4643 qemu_opt_set(bus_opts, "driver", "virtio-serial");
4645 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4646 qemu_opt_set(dev_opts, "driver", "virtconsole");
4648 snprintf(label, sizeof(label), "virtcon%d", index);
4649 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4650 if (!virtcon_hds[index]) {
4651 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4652 devname, strerror(errno));
4653 return -1;
4655 qemu_opt_set(dev_opts, "chardev", label);
4657 index++;
4658 return 0;
4661 static int debugcon_parse(const char *devname)
4663 QemuOpts *opts;
4665 if (!qemu_chr_open("debugcon", devname, NULL)) {
4666 exit(1);
4668 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4669 if (!opts) {
4670 fprintf(stderr, "qemu: already have a debugcon device\n");
4671 exit(1);
4673 qemu_opt_set(opts, "driver", "isa-debugcon");
4674 qemu_opt_set(opts, "chardev", "debugcon");
4675 return 0;
4678 static const QEMUOption *lookup_opt(int argc, char **argv,
4679 const char **poptarg, int *poptind)
4681 const QEMUOption *popt;
4682 int optind = *poptind;
4683 char *r = argv[optind];
4684 const char *optarg;
4686 optind++;
4687 /* Treat --foo the same as -foo. */
4688 if (r[1] == '-')
4689 r++;
4690 popt = qemu_options;
4691 for(;;) {
4692 if (!popt->name) {
4693 fprintf(stderr, "%s: invalid option -- '%s'\n",
4694 argv[0], r);
4695 exit(1);
4697 if (!strcmp(popt->name, r + 1))
4698 break;
4699 popt++;
4701 if (popt->flags & HAS_ARG) {
4702 if (optind >= argc) {
4703 fprintf(stderr, "%s: option '%s' requires an argument\n",
4704 argv[0], r);
4705 exit(1);
4707 optarg = argv[optind++];
4708 } else {
4709 optarg = NULL;
4712 *poptarg = optarg;
4713 *poptind = optind;
4715 return popt;
4718 int main(int argc, char **argv, char **envp)
4720 const char *gdbstub_dev = NULL;
4721 uint32_t boot_devices_bitmap = 0;
4722 int i;
4723 int snapshot, linux_boot, net_boot;
4724 const char *initrd_filename;
4725 const char *kernel_filename, *kernel_cmdline;
4726 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4727 DisplayState *ds;
4728 DisplayChangeListener *dcl;
4729 int cyls, heads, secs, translation;
4730 QemuOpts *hda_opts = NULL, *opts;
4731 int optind;
4732 const char *optarg;
4733 const char *loadvm = NULL;
4734 QEMUMachine *machine;
4735 const char *cpu_model;
4736 #ifndef _WIN32
4737 int fds[2];
4738 #endif
4739 int tb_size;
4740 const char *pid_file = NULL;
4741 const char *incoming = NULL;
4742 #ifndef _WIN32
4743 int fd = 0;
4744 struct passwd *pwd = NULL;
4745 const char *chroot_dir = NULL;
4746 const char *run_as = NULL;
4747 #endif
4748 CPUState *env;
4749 int show_vnc_port = 0;
4750 int defconfig = 1;
4752 init_clocks();
4754 qemu_errors_to_file(stderr);
4755 qemu_cache_utils_init(envp);
4757 QLIST_INIT (&vm_change_state_head);
4758 #ifndef _WIN32
4760 struct sigaction act;
4761 sigfillset(&act.sa_mask);
4762 act.sa_flags = 0;
4763 act.sa_handler = SIG_IGN;
4764 sigaction(SIGPIPE, &act, NULL);
4766 #else
4767 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4768 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4769 QEMU to run on a single CPU */
4771 HANDLE h;
4772 DWORD mask, smask;
4773 int i;
4774 h = GetCurrentProcess();
4775 if (GetProcessAffinityMask(h, &mask, &smask)) {
4776 for(i = 0; i < 32; i++) {
4777 if (mask & (1 << i))
4778 break;
4780 if (i != 32) {
4781 mask = 1 << i;
4782 SetProcessAffinityMask(h, mask);
4786 #endif
4788 module_call_init(MODULE_INIT_MACHINE);
4789 machine = find_default_machine();
4790 cpu_model = NULL;
4791 initrd_filename = NULL;
4792 ram_size = 0;
4793 snapshot = 0;
4794 kernel_filename = NULL;
4795 kernel_cmdline = "";
4796 cyls = heads = secs = 0;
4797 translation = BIOS_ATA_TRANSLATION_AUTO;
4799 for (i = 0; i < MAX_NODES; i++) {
4800 node_mem[i] = 0;
4801 node_cpumask[i] = 0;
4804 nb_numa_nodes = 0;
4805 nb_nics = 0;
4807 tb_size = 0;
4808 autostart= 1;
4810 /* first pass of option parsing */
4811 optind = 1;
4812 while (optind < argc) {
4813 if (argv[optind][0] != '-') {
4814 /* disk image */
4815 continue;
4816 } else {
4817 const QEMUOption *popt;
4819 popt = lookup_opt(argc, argv, &optarg, &optind);
4820 switch (popt->index) {
4821 case QEMU_OPTION_nodefconfig:
4822 defconfig=0;
4823 break;
4828 if (defconfig) {
4829 FILE *fp;
4830 fp = fopen(CONFIG_QEMU_CONFDIR "/qemu.conf", "r");
4831 if (fp) {
4832 if (qemu_config_parse(fp) != 0) {
4833 exit(1);
4835 fclose(fp);
4838 fp = fopen(CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf", "r");
4839 if (fp) {
4840 if (qemu_config_parse(fp) != 0) {
4841 exit(1);
4843 fclose(fp);
4847 /* second pass of option parsing */
4848 optind = 1;
4849 for(;;) {
4850 if (optind >= argc)
4851 break;
4852 if (argv[optind][0] != '-') {
4853 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4854 } else {
4855 const QEMUOption *popt;
4857 popt = lookup_opt(argc, argv, &optarg, &optind);
4858 switch(popt->index) {
4859 case QEMU_OPTION_M:
4860 machine = find_machine(optarg);
4861 if (!machine) {
4862 QEMUMachine *m;
4863 printf("Supported machines are:\n");
4864 for(m = first_machine; m != NULL; m = m->next) {
4865 if (m->alias)
4866 printf("%-10s %s (alias of %s)\n",
4867 m->alias, m->desc, m->name);
4868 printf("%-10s %s%s\n",
4869 m->name, m->desc,
4870 m->is_default ? " (default)" : "");
4872 exit(*optarg != '?');
4874 break;
4875 case QEMU_OPTION_cpu:
4876 /* hw initialization will check this */
4877 if (*optarg == '?') {
4878 /* XXX: implement xxx_cpu_list for targets that still miss it */
4879 #if defined(cpu_list)
4880 cpu_list(stdout, &fprintf);
4881 #endif
4882 exit(0);
4883 } else {
4884 cpu_model = optarg;
4886 break;
4887 case QEMU_OPTION_initrd:
4888 initrd_filename = optarg;
4889 break;
4890 case QEMU_OPTION_hda:
4891 if (cyls == 0)
4892 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4893 else
4894 hda_opts = drive_add(optarg, HD_ALIAS
4895 ",cyls=%d,heads=%d,secs=%d%s",
4896 0, cyls, heads, secs,
4897 translation == BIOS_ATA_TRANSLATION_LBA ?
4898 ",trans=lba" :
4899 translation == BIOS_ATA_TRANSLATION_NONE ?
4900 ",trans=none" : "");
4901 break;
4902 case QEMU_OPTION_hdb:
4903 case QEMU_OPTION_hdc:
4904 case QEMU_OPTION_hdd:
4905 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4906 break;
4907 case QEMU_OPTION_drive:
4908 drive_add(NULL, "%s", optarg);
4909 break;
4910 case QEMU_OPTION_set:
4911 if (qemu_set_option(optarg) != 0)
4912 exit(1);
4913 break;
4914 case QEMU_OPTION_global:
4915 if (qemu_global_option(optarg) != 0)
4916 exit(1);
4917 break;
4918 case QEMU_OPTION_mtdblock:
4919 drive_add(optarg, MTD_ALIAS);
4920 break;
4921 case QEMU_OPTION_sd:
4922 drive_add(optarg, SD_ALIAS);
4923 break;
4924 case QEMU_OPTION_pflash:
4925 drive_add(optarg, PFLASH_ALIAS);
4926 break;
4927 case QEMU_OPTION_snapshot:
4928 snapshot = 1;
4929 break;
4930 case QEMU_OPTION_hdachs:
4932 const char *p;
4933 p = optarg;
4934 cyls = strtol(p, (char **)&p, 0);
4935 if (cyls < 1 || cyls > 16383)
4936 goto chs_fail;
4937 if (*p != ',')
4938 goto chs_fail;
4939 p++;
4940 heads = strtol(p, (char **)&p, 0);
4941 if (heads < 1 || heads > 16)
4942 goto chs_fail;
4943 if (*p != ',')
4944 goto chs_fail;
4945 p++;
4946 secs = strtol(p, (char **)&p, 0);
4947 if (secs < 1 || secs > 63)
4948 goto chs_fail;
4949 if (*p == ',') {
4950 p++;
4951 if (!strcmp(p, "none"))
4952 translation = BIOS_ATA_TRANSLATION_NONE;
4953 else if (!strcmp(p, "lba"))
4954 translation = BIOS_ATA_TRANSLATION_LBA;
4955 else if (!strcmp(p, "auto"))
4956 translation = BIOS_ATA_TRANSLATION_AUTO;
4957 else
4958 goto chs_fail;
4959 } else if (*p != '\0') {
4960 chs_fail:
4961 fprintf(stderr, "qemu: invalid physical CHS format\n");
4962 exit(1);
4964 if (hda_opts != NULL) {
4965 char num[16];
4966 snprintf(num, sizeof(num), "%d", cyls);
4967 qemu_opt_set(hda_opts, "cyls", num);
4968 snprintf(num, sizeof(num), "%d", heads);
4969 qemu_opt_set(hda_opts, "heads", num);
4970 snprintf(num, sizeof(num), "%d", secs);
4971 qemu_opt_set(hda_opts, "secs", num);
4972 if (translation == BIOS_ATA_TRANSLATION_LBA)
4973 qemu_opt_set(hda_opts, "trans", "lba");
4974 if (translation == BIOS_ATA_TRANSLATION_NONE)
4975 qemu_opt_set(hda_opts, "trans", "none");
4978 break;
4979 case QEMU_OPTION_numa:
4980 if (nb_numa_nodes >= MAX_NODES) {
4981 fprintf(stderr, "qemu: too many NUMA nodes\n");
4982 exit(1);
4984 numa_add(optarg);
4985 break;
4986 case QEMU_OPTION_nographic:
4987 display_type = DT_NOGRAPHIC;
4988 break;
4989 #ifdef CONFIG_CURSES
4990 case QEMU_OPTION_curses:
4991 display_type = DT_CURSES;
4992 break;
4993 #endif
4994 case QEMU_OPTION_portrait:
4995 graphic_rotate = 1;
4996 break;
4997 case QEMU_OPTION_kernel:
4998 kernel_filename = optarg;
4999 break;
5000 case QEMU_OPTION_append:
5001 kernel_cmdline = optarg;
5002 break;
5003 case QEMU_OPTION_cdrom:
5004 drive_add(optarg, CDROM_ALIAS);
5005 break;
5006 case QEMU_OPTION_boot:
5008 static const char * const params[] = {
5009 "order", "once", "menu", NULL
5011 char buf[sizeof(boot_devices)];
5012 char *standard_boot_devices;
5013 int legacy = 0;
5015 if (!strchr(optarg, '=')) {
5016 legacy = 1;
5017 pstrcpy(buf, sizeof(buf), optarg);
5018 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5019 fprintf(stderr,
5020 "qemu: unknown boot parameter '%s' in '%s'\n",
5021 buf, optarg);
5022 exit(1);
5025 if (legacy ||
5026 get_param_value(buf, sizeof(buf), "order", optarg)) {
5027 boot_devices_bitmap = parse_bootdevices(buf);
5028 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5030 if (!legacy) {
5031 if (get_param_value(buf, sizeof(buf),
5032 "once", optarg)) {
5033 boot_devices_bitmap |= parse_bootdevices(buf);
5034 standard_boot_devices = qemu_strdup(boot_devices);
5035 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5036 qemu_register_reset(restore_boot_devices,
5037 standard_boot_devices);
5039 if (get_param_value(buf, sizeof(buf),
5040 "menu", optarg)) {
5041 if (!strcmp(buf, "on")) {
5042 boot_menu = 1;
5043 } else if (!strcmp(buf, "off")) {
5044 boot_menu = 0;
5045 } else {
5046 fprintf(stderr,
5047 "qemu: invalid option value '%s'\n",
5048 buf);
5049 exit(1);
5054 break;
5055 case QEMU_OPTION_fda:
5056 case QEMU_OPTION_fdb:
5057 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5058 break;
5059 #ifdef TARGET_I386
5060 case QEMU_OPTION_no_fd_bootchk:
5061 fd_bootchk = 0;
5062 break;
5063 #endif
5064 case QEMU_OPTION_netdev:
5065 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5066 exit(1);
5068 break;
5069 case QEMU_OPTION_net:
5070 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5071 exit(1);
5073 break;
5074 #ifdef CONFIG_SLIRP
5075 case QEMU_OPTION_tftp:
5076 legacy_tftp_prefix = optarg;
5077 break;
5078 case QEMU_OPTION_bootp:
5079 legacy_bootp_filename = optarg;
5080 break;
5081 #ifndef _WIN32
5082 case QEMU_OPTION_smb:
5083 if (net_slirp_smb(optarg) < 0)
5084 exit(1);
5085 break;
5086 #endif
5087 case QEMU_OPTION_redir:
5088 if (net_slirp_redir(optarg) < 0)
5089 exit(1);
5090 break;
5091 #endif
5092 case QEMU_OPTION_bt:
5093 add_device_config(DEV_BT, optarg);
5094 break;
5095 #ifdef HAS_AUDIO
5096 case QEMU_OPTION_audio_help:
5097 AUD_help ();
5098 exit (0);
5099 break;
5100 case QEMU_OPTION_soundhw:
5101 select_soundhw (optarg);
5102 break;
5103 #endif
5104 case QEMU_OPTION_h:
5105 help(0);
5106 break;
5107 case QEMU_OPTION_version:
5108 version();
5109 exit(0);
5110 break;
5111 case QEMU_OPTION_m: {
5112 uint64_t value;
5113 char *ptr;
5115 value = strtoul(optarg, &ptr, 10);
5116 switch (*ptr) {
5117 case 0: case 'M': case 'm':
5118 value <<= 20;
5119 break;
5120 case 'G': case 'g':
5121 value <<= 30;
5122 break;
5123 default:
5124 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5125 exit(1);
5128 /* On 32-bit hosts, QEMU is limited by virtual address space */
5129 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5130 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5131 exit(1);
5133 if (value != (uint64_t)(ram_addr_t)value) {
5134 fprintf(stderr, "qemu: ram size too large\n");
5135 exit(1);
5137 ram_size = value;
5138 break;
5140 case QEMU_OPTION_d:
5142 int mask;
5143 const CPULogItem *item;
5145 mask = cpu_str_to_log_mask(optarg);
5146 if (!mask) {
5147 printf("Log items (comma separated):\n");
5148 for(item = cpu_log_items; item->mask != 0; item++) {
5149 printf("%-10s %s\n", item->name, item->help);
5151 exit(1);
5153 cpu_set_log(mask);
5155 break;
5156 case QEMU_OPTION_s:
5157 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5158 break;
5159 case QEMU_OPTION_gdb:
5160 gdbstub_dev = optarg;
5161 break;
5162 case QEMU_OPTION_L:
5163 data_dir = optarg;
5164 break;
5165 case QEMU_OPTION_bios:
5166 bios_name = optarg;
5167 break;
5168 case QEMU_OPTION_singlestep:
5169 singlestep = 1;
5170 break;
5171 case QEMU_OPTION_S:
5172 autostart = 0;
5173 break;
5174 case QEMU_OPTION_k:
5175 keyboard_layout = optarg;
5176 break;
5177 case QEMU_OPTION_localtime:
5178 rtc_utc = 0;
5179 break;
5180 case QEMU_OPTION_vga:
5181 select_vgahw (optarg);
5182 break;
5183 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5184 case QEMU_OPTION_g:
5186 const char *p;
5187 int w, h, depth;
5188 p = optarg;
5189 w = strtol(p, (char **)&p, 10);
5190 if (w <= 0) {
5191 graphic_error:
5192 fprintf(stderr, "qemu: invalid resolution or depth\n");
5193 exit(1);
5195 if (*p != 'x')
5196 goto graphic_error;
5197 p++;
5198 h = strtol(p, (char **)&p, 10);
5199 if (h <= 0)
5200 goto graphic_error;
5201 if (*p == 'x') {
5202 p++;
5203 depth = strtol(p, (char **)&p, 10);
5204 if (depth != 8 && depth != 15 && depth != 16 &&
5205 depth != 24 && depth != 32)
5206 goto graphic_error;
5207 } else if (*p == '\0') {
5208 depth = graphic_depth;
5209 } else {
5210 goto graphic_error;
5213 graphic_width = w;
5214 graphic_height = h;
5215 graphic_depth = depth;
5217 break;
5218 #endif
5219 case QEMU_OPTION_echr:
5221 char *r;
5222 term_escape_char = strtol(optarg, &r, 0);
5223 if (r == optarg)
5224 printf("Bad argument to echr\n");
5225 break;
5227 case QEMU_OPTION_monitor:
5228 monitor_parse(optarg, "readline");
5229 default_monitor = 0;
5230 break;
5231 case QEMU_OPTION_qmp:
5232 monitor_parse(optarg, "control");
5233 default_monitor = 0;
5234 break;
5235 case QEMU_OPTION_mon:
5236 opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5237 if (!opts) {
5238 fprintf(stderr, "parse error: %s\n", optarg);
5239 exit(1);
5241 default_monitor = 0;
5242 break;
5243 case QEMU_OPTION_chardev:
5244 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5245 if (!opts) {
5246 fprintf(stderr, "parse error: %s\n", optarg);
5247 exit(1);
5249 break;
5250 case QEMU_OPTION_serial:
5251 add_device_config(DEV_SERIAL, optarg);
5252 default_serial = 0;
5253 break;
5254 case QEMU_OPTION_watchdog:
5255 if (watchdog) {
5256 fprintf(stderr,
5257 "qemu: only one watchdog option may be given\n");
5258 return 1;
5260 watchdog = optarg;
5261 break;
5262 case QEMU_OPTION_watchdog_action:
5263 if (select_watchdog_action(optarg) == -1) {
5264 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5265 exit(1);
5267 break;
5268 case QEMU_OPTION_virtiocon:
5269 add_device_config(DEV_VIRTCON, optarg);
5270 default_virtcon = 0;
5271 break;
5272 case QEMU_OPTION_parallel:
5273 add_device_config(DEV_PARALLEL, optarg);
5274 default_parallel = 0;
5275 break;
5276 case QEMU_OPTION_debugcon:
5277 add_device_config(DEV_DEBUGCON, optarg);
5278 break;
5279 case QEMU_OPTION_loadvm:
5280 loadvm = optarg;
5281 break;
5282 case QEMU_OPTION_full_screen:
5283 full_screen = 1;
5284 break;
5285 #ifdef CONFIG_SDL
5286 case QEMU_OPTION_no_frame:
5287 no_frame = 1;
5288 break;
5289 case QEMU_OPTION_alt_grab:
5290 alt_grab = 1;
5291 break;
5292 case QEMU_OPTION_ctrl_grab:
5293 ctrl_grab = 1;
5294 break;
5295 case QEMU_OPTION_no_quit:
5296 no_quit = 1;
5297 break;
5298 case QEMU_OPTION_sdl:
5299 display_type = DT_SDL;
5300 break;
5301 #endif
5302 case QEMU_OPTION_pidfile:
5303 pid_file = optarg;
5304 break;
5305 #ifdef TARGET_I386
5306 case QEMU_OPTION_win2k_hack:
5307 win2k_install_hack = 1;
5308 break;
5309 case QEMU_OPTION_rtc_td_hack:
5310 rtc_td_hack = 1;
5311 break;
5312 case QEMU_OPTION_acpitable:
5313 if(acpi_table_add(optarg) < 0) {
5314 fprintf(stderr, "Wrong acpi table provided\n");
5315 exit(1);
5317 break;
5318 case QEMU_OPTION_smbios:
5319 if(smbios_entry_add(optarg) < 0) {
5320 fprintf(stderr, "Wrong smbios provided\n");
5321 exit(1);
5323 break;
5324 #endif
5325 #ifdef CONFIG_KVM
5326 case QEMU_OPTION_enable_kvm:
5327 kvm_allowed = 1;
5328 break;
5329 #endif
5330 case QEMU_OPTION_usb:
5331 usb_enabled = 1;
5332 break;
5333 case QEMU_OPTION_usbdevice:
5334 usb_enabled = 1;
5335 add_device_config(DEV_USB, optarg);
5336 break;
5337 case QEMU_OPTION_device:
5338 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5339 exit(1);
5341 break;
5342 case QEMU_OPTION_smp:
5343 smp_parse(optarg);
5344 if (smp_cpus < 1) {
5345 fprintf(stderr, "Invalid number of CPUs\n");
5346 exit(1);
5348 if (max_cpus < smp_cpus) {
5349 fprintf(stderr, "maxcpus must be equal to or greater than "
5350 "smp\n");
5351 exit(1);
5353 if (max_cpus > 255) {
5354 fprintf(stderr, "Unsupported number of maxcpus\n");
5355 exit(1);
5357 break;
5358 case QEMU_OPTION_vnc:
5359 display_type = DT_VNC;
5360 vnc_display = optarg;
5361 break;
5362 #ifdef TARGET_I386
5363 case QEMU_OPTION_no_acpi:
5364 acpi_enabled = 0;
5365 break;
5366 case QEMU_OPTION_no_hpet:
5367 no_hpet = 1;
5368 break;
5369 case QEMU_OPTION_balloon:
5370 if (balloon_parse(optarg) < 0) {
5371 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5372 exit(1);
5374 break;
5375 #endif
5376 case QEMU_OPTION_no_reboot:
5377 no_reboot = 1;
5378 break;
5379 case QEMU_OPTION_no_shutdown:
5380 no_shutdown = 1;
5381 break;
5382 case QEMU_OPTION_show_cursor:
5383 cursor_hide = 0;
5384 break;
5385 case QEMU_OPTION_uuid:
5386 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5387 fprintf(stderr, "Fail to parse UUID string."
5388 " Wrong format.\n");
5389 exit(1);
5391 break;
5392 #ifndef _WIN32
5393 case QEMU_OPTION_daemonize:
5394 daemonize = 1;
5395 break;
5396 #endif
5397 case QEMU_OPTION_option_rom:
5398 if (nb_option_roms >= MAX_OPTION_ROMS) {
5399 fprintf(stderr, "Too many option ROMs\n");
5400 exit(1);
5402 option_rom[nb_option_roms] = optarg;
5403 nb_option_roms++;
5404 break;
5405 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5406 case QEMU_OPTION_semihosting:
5407 semihosting_enabled = 1;
5408 break;
5409 #endif
5410 case QEMU_OPTION_name:
5411 qemu_name = qemu_strdup(optarg);
5413 char *p = strchr(qemu_name, ',');
5414 if (p != NULL) {
5415 *p++ = 0;
5416 if (strncmp(p, "process=", 8)) {
5417 fprintf(stderr, "Unknown subargument %s to -name", p);
5418 exit(1);
5420 p += 8;
5421 set_proc_name(p);
5424 break;
5425 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5426 case QEMU_OPTION_prom_env:
5427 if (nb_prom_envs >= MAX_PROM_ENVS) {
5428 fprintf(stderr, "Too many prom variables\n");
5429 exit(1);
5431 prom_envs[nb_prom_envs] = optarg;
5432 nb_prom_envs++;
5433 break;
5434 #endif
5435 #ifdef TARGET_ARM
5436 case QEMU_OPTION_old_param:
5437 old_param = 1;
5438 break;
5439 #endif
5440 case QEMU_OPTION_clock:
5441 configure_alarms(optarg);
5442 break;
5443 case QEMU_OPTION_startdate:
5444 configure_rtc_date_offset(optarg, 1);
5445 break;
5446 case QEMU_OPTION_rtc:
5447 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5448 if (!opts) {
5449 fprintf(stderr, "parse error: %s\n", optarg);
5450 exit(1);
5452 configure_rtc(opts);
5453 break;
5454 case QEMU_OPTION_tb_size:
5455 tb_size = strtol(optarg, NULL, 0);
5456 if (tb_size < 0)
5457 tb_size = 0;
5458 break;
5459 case QEMU_OPTION_icount:
5460 use_icount = 1;
5461 if (strcmp(optarg, "auto") == 0) {
5462 icount_time_shift = -1;
5463 } else {
5464 icount_time_shift = strtol(optarg, NULL, 0);
5466 break;
5467 case QEMU_OPTION_incoming:
5468 incoming = optarg;
5469 break;
5470 case QEMU_OPTION_nodefaults:
5471 default_serial = 0;
5472 default_parallel = 0;
5473 default_virtcon = 0;
5474 default_monitor = 0;
5475 default_vga = 0;
5476 default_net = 0;
5477 default_floppy = 0;
5478 default_cdrom = 0;
5479 default_sdcard = 0;
5480 break;
5481 #ifndef _WIN32
5482 case QEMU_OPTION_chroot:
5483 chroot_dir = optarg;
5484 break;
5485 case QEMU_OPTION_runas:
5486 run_as = optarg;
5487 break;
5488 #endif
5489 #ifdef CONFIG_XEN
5490 case QEMU_OPTION_xen_domid:
5491 xen_domid = atoi(optarg);
5492 break;
5493 case QEMU_OPTION_xen_create:
5494 xen_mode = XEN_CREATE;
5495 break;
5496 case QEMU_OPTION_xen_attach:
5497 xen_mode = XEN_ATTACH;
5498 break;
5499 #endif
5500 case QEMU_OPTION_readconfig:
5502 FILE *fp;
5503 fp = fopen(optarg, "r");
5504 if (fp == NULL) {
5505 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5506 exit(1);
5508 if (qemu_config_parse(fp) != 0) {
5509 exit(1);
5511 fclose(fp);
5512 break;
5514 case QEMU_OPTION_writeconfig:
5516 FILE *fp;
5517 if (strcmp(optarg, "-") == 0) {
5518 fp = stdout;
5519 } else {
5520 fp = fopen(optarg, "w");
5521 if (fp == NULL) {
5522 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5523 exit(1);
5526 qemu_config_write(fp);
5527 fclose(fp);
5528 break;
5534 /* If no data_dir is specified then try to find it relative to the
5535 executable path. */
5536 if (!data_dir) {
5537 data_dir = find_datadir(argv[0]);
5539 /* If all else fails use the install patch specified when building. */
5540 if (!data_dir) {
5541 data_dir = CONFIG_QEMU_SHAREDIR;
5545 * Default to max_cpus = smp_cpus, in case the user doesn't
5546 * specify a max_cpus value.
5548 if (!max_cpus)
5549 max_cpus = smp_cpus;
5551 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5552 if (smp_cpus > machine->max_cpus) {
5553 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5554 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5555 machine->max_cpus);
5556 exit(1);
5559 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5560 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5562 if (machine->no_serial) {
5563 default_serial = 0;
5565 if (machine->no_parallel) {
5566 default_parallel = 0;
5568 if (!machine->use_virtcon) {
5569 default_virtcon = 0;
5571 if (machine->no_vga) {
5572 default_vga = 0;
5574 if (machine->no_floppy) {
5575 default_floppy = 0;
5577 if (machine->no_cdrom) {
5578 default_cdrom = 0;
5580 if (machine->no_sdcard) {
5581 default_sdcard = 0;
5584 if (display_type == DT_NOGRAPHIC) {
5585 if (default_parallel)
5586 add_device_config(DEV_PARALLEL, "null");
5587 if (default_serial && default_monitor) {
5588 add_device_config(DEV_SERIAL, "mon:stdio");
5589 } else if (default_virtcon && default_monitor) {
5590 add_device_config(DEV_VIRTCON, "mon:stdio");
5591 } else {
5592 if (default_serial)
5593 add_device_config(DEV_SERIAL, "stdio");
5594 if (default_virtcon)
5595 add_device_config(DEV_VIRTCON, "stdio");
5596 if (default_monitor)
5597 monitor_parse("stdio", "readline");
5599 } else {
5600 if (default_serial)
5601 add_device_config(DEV_SERIAL, "vc:80Cx24C");
5602 if (default_parallel)
5603 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5604 if (default_monitor)
5605 monitor_parse("vc:80Cx24C", "readline");
5606 if (default_virtcon)
5607 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5609 if (default_vga)
5610 vga_interface_type = VGA_CIRRUS;
5612 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5613 exit(1);
5615 #ifndef _WIN32
5616 if (daemonize) {
5617 pid_t pid;
5619 if (pipe(fds) == -1)
5620 exit(1);
5622 pid = fork();
5623 if (pid > 0) {
5624 uint8_t status;
5625 ssize_t len;
5627 close(fds[1]);
5629 again:
5630 len = read(fds[0], &status, 1);
5631 if (len == -1 && (errno == EINTR))
5632 goto again;
5634 if (len != 1)
5635 exit(1);
5636 else if (status == 1) {
5637 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5638 exit(1);
5639 } else
5640 exit(0);
5641 } else if (pid < 0)
5642 exit(1);
5644 close(fds[0]);
5645 qemu_set_cloexec(fds[1]);
5647 setsid();
5649 pid = fork();
5650 if (pid > 0)
5651 exit(0);
5652 else if (pid < 0)
5653 exit(1);
5655 umask(027);
5657 signal(SIGTSTP, SIG_IGN);
5658 signal(SIGTTOU, SIG_IGN);
5659 signal(SIGTTIN, SIG_IGN);
5661 #endif
5663 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5664 #ifndef _WIN32
5665 if (daemonize) {
5666 uint8_t status = 1;
5667 if (write(fds[1], &status, 1) != 1) {
5668 perror("daemonize. Writing to pipe\n");
5670 } else
5671 #endif
5672 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5673 exit(1);
5676 if (kvm_enabled()) {
5677 int ret;
5679 ret = kvm_init(smp_cpus);
5680 if (ret < 0) {
5681 fprintf(stderr, "failed to initialize KVM\n");
5682 exit(1);
5686 if (qemu_init_main_loop()) {
5687 fprintf(stderr, "qemu_init_main_loop failed\n");
5688 exit(1);
5690 linux_boot = (kernel_filename != NULL);
5692 if (!linux_boot && *kernel_cmdline != '\0') {
5693 fprintf(stderr, "-append only allowed with -kernel option\n");
5694 exit(1);
5697 if (!linux_boot && initrd_filename != NULL) {
5698 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5699 exit(1);
5702 #ifndef _WIN32
5703 /* Win32 doesn't support line-buffering and requires size >= 2 */
5704 setvbuf(stdout, NULL, _IOLBF, 0);
5705 #endif
5707 if (init_timer_alarm() < 0) {
5708 fprintf(stderr, "could not initialize alarm timer\n");
5709 exit(1);
5711 if (use_icount && icount_time_shift < 0) {
5712 use_icount = 2;
5713 /* 125MIPS seems a reasonable initial guess at the guest speed.
5714 It will be corrected fairly quickly anyway. */
5715 icount_time_shift = 3;
5716 init_icount_adjust();
5719 #ifdef _WIN32
5720 socket_init();
5721 #endif
5723 if (net_init_clients() < 0) {
5724 exit(1);
5727 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5728 net_set_boot_mask(net_boot);
5730 /* init the bluetooth world */
5731 if (foreach_device_config(DEV_BT, bt_parse))
5732 exit(1);
5734 /* init the memory */
5735 if (ram_size == 0)
5736 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5738 /* init the dynamic translator */
5739 cpu_exec_init_all(tb_size * 1024 * 1024);
5741 bdrv_init_with_whitelist();
5743 blk_mig_init();
5745 if (default_cdrom) {
5746 /* we always create the cdrom drive, even if no disk is there */
5747 drive_add(NULL, CDROM_ALIAS);
5750 if (default_floppy) {
5751 /* we always create at least one floppy */
5752 drive_add(NULL, FD_ALIAS, 0);
5755 if (default_sdcard) {
5756 /* we always create one sd slot, even if no card is in it */
5757 drive_add(NULL, SD_ALIAS);
5760 /* open the virtual block devices */
5761 if (snapshot)
5762 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5763 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5764 exit(1);
5766 vmstate_register(0, &vmstate_timers ,&timers_state);
5767 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5768 ram_load, NULL);
5770 if (nb_numa_nodes > 0) {
5771 int i;
5773 if (nb_numa_nodes > smp_cpus) {
5774 nb_numa_nodes = smp_cpus;
5777 /* If no memory size if given for any node, assume the default case
5778 * and distribute the available memory equally across all nodes
5780 for (i = 0; i < nb_numa_nodes; i++) {
5781 if (node_mem[i] != 0)
5782 break;
5784 if (i == nb_numa_nodes) {
5785 uint64_t usedmem = 0;
5787 /* On Linux, the each node's border has to be 8MB aligned,
5788 * the final node gets the rest.
5790 for (i = 0; i < nb_numa_nodes - 1; i++) {
5791 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5792 usedmem += node_mem[i];
5794 node_mem[i] = ram_size - usedmem;
5797 for (i = 0; i < nb_numa_nodes; i++) {
5798 if (node_cpumask[i] != 0)
5799 break;
5801 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5802 * must cope with this anyway, because there are BIOSes out there in
5803 * real machines which also use this scheme.
5805 if (i == nb_numa_nodes) {
5806 for (i = 0; i < smp_cpus; i++) {
5807 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5812 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5813 exit(1);
5814 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5815 exit(1);
5816 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5817 exit(1);
5818 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5819 exit(1);
5821 module_call_init(MODULE_INIT_DEVICE);
5823 if (watchdog) {
5824 i = select_watchdog(watchdog);
5825 if (i > 0)
5826 exit (i == 1 ? 1 : 0);
5829 if (machine->compat_props) {
5830 qdev_prop_register_global_list(machine->compat_props);
5832 qemu_add_globals();
5834 machine->init(ram_size, boot_devices,
5835 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5838 #ifndef _WIN32
5839 /* must be after terminal init, SDL library changes signal handlers */
5840 sighandler_setup();
5841 #endif
5843 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5844 for (i = 0; i < nb_numa_nodes; i++) {
5845 if (node_cpumask[i] & (1 << env->cpu_index)) {
5846 env->numa_node = i;
5851 current_machine = machine;
5853 /* init USB devices */
5854 if (usb_enabled) {
5855 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5856 exit(1);
5859 /* init generic devices */
5860 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5861 exit(1);
5863 if (!display_state)
5864 dumb_display_init();
5865 /* just use the first displaystate for the moment */
5866 ds = display_state;
5868 if (display_type == DT_DEFAULT) {
5869 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5870 display_type = DT_SDL;
5871 #else
5872 display_type = DT_VNC;
5873 vnc_display = "localhost:0,to=99";
5874 show_vnc_port = 1;
5875 #endif
5879 switch (display_type) {
5880 case DT_NOGRAPHIC:
5881 break;
5882 #if defined(CONFIG_CURSES)
5883 case DT_CURSES:
5884 curses_display_init(ds, full_screen);
5885 break;
5886 #endif
5887 #if defined(CONFIG_SDL)
5888 case DT_SDL:
5889 sdl_display_init(ds, full_screen, no_frame);
5890 break;
5891 #elif defined(CONFIG_COCOA)
5892 case DT_SDL:
5893 cocoa_display_init(ds, full_screen);
5894 break;
5895 #endif
5896 case DT_VNC:
5897 vnc_display_init(ds);
5898 if (vnc_display_open(ds, vnc_display) < 0)
5899 exit(1);
5901 if (show_vnc_port) {
5902 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5904 break;
5905 default:
5906 break;
5908 dpy_resize(ds);
5910 dcl = ds->listeners;
5911 while (dcl != NULL) {
5912 if (dcl->dpy_refresh != NULL) {
5913 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5914 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5916 dcl = dcl->next;
5919 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5920 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5921 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5924 text_consoles_set_display(display_state);
5926 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
5927 exit(1);
5929 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5930 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5931 gdbstub_dev);
5932 exit(1);
5935 qdev_machine_creation_done();
5937 if (rom_load_all() != 0) {
5938 fprintf(stderr, "rom loading failed\n");
5939 exit(1);
5942 qemu_system_reset();
5943 if (loadvm) {
5944 if (load_vmstate(cur_mon, loadvm) < 0) {
5945 autostart = 0;
5949 if (incoming) {
5950 qemu_start_incoming_migration(incoming);
5951 } else if (autostart) {
5952 vm_start();
5955 #ifndef _WIN32
5956 if (daemonize) {
5957 uint8_t status = 0;
5958 ssize_t len;
5960 again1:
5961 len = write(fds[1], &status, 1);
5962 if (len == -1 && (errno == EINTR))
5963 goto again1;
5965 if (len != 1)
5966 exit(1);
5968 if (chdir("/")) {
5969 perror("not able to chdir to /");
5970 exit(1);
5972 TFR(fd = qemu_open("/dev/null", O_RDWR));
5973 if (fd == -1)
5974 exit(1);
5977 if (run_as) {
5978 pwd = getpwnam(run_as);
5979 if (!pwd) {
5980 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5981 exit(1);
5985 if (chroot_dir) {
5986 if (chroot(chroot_dir) < 0) {
5987 fprintf(stderr, "chroot failed\n");
5988 exit(1);
5990 if (chdir("/")) {
5991 perror("not able to chdir to /");
5992 exit(1);
5996 if (run_as) {
5997 if (setgid(pwd->pw_gid) < 0) {
5998 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5999 exit(1);
6001 if (setuid(pwd->pw_uid) < 0) {
6002 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6003 exit(1);
6005 if (setuid(0) != -1) {
6006 fprintf(stderr, "Dropping privileges failed\n");
6007 exit(1);
6011 if (daemonize) {
6012 dup2(fd, 0);
6013 dup2(fd, 1);
6014 dup2(fd, 2);
6016 close(fd);
6018 #endif
6020 main_loop();
6021 quit_timers();
6022 net_cleanup();
6024 return 0;