kill regs_to_env and env_to_regs
[qemu.git] / vl.c
blob06cb40df5cbdf7072c7622652a04f4cb5c6ef48c
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 static const char *data_dir;
177 const char *bios_name = NULL;
178 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
179 to store the VM snapshots */
180 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
181 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
182 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
183 static DisplayState *display_state;
184 DisplayType display_type = DT_DEFAULT;
185 const char* keyboard_layout = NULL;
186 ram_addr_t ram_size;
187 int nb_nics;
188 NICInfo nd_table[MAX_NICS];
189 int vm_running;
190 int autostart;
191 static int rtc_utc = 1;
192 static int rtc_date_offset = -1; /* -1 means no change */
193 QEMUClock *rtc_clock;
194 int vga_interface_type = VGA_NONE;
195 #ifdef TARGET_SPARC
196 int graphic_width = 1024;
197 int graphic_height = 768;
198 int graphic_depth = 8;
199 #else
200 int graphic_width = 800;
201 int graphic_height = 600;
202 int graphic_depth = 15;
203 #endif
204 static int full_screen = 0;
205 #ifdef CONFIG_SDL
206 static int no_frame = 0;
207 #endif
208 int no_quit = 0;
209 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
210 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
211 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
212 #ifdef TARGET_I386
213 int win2k_install_hack = 0;
214 int rtc_td_hack = 0;
215 #endif
216 int usb_enabled = 0;
217 int singlestep = 0;
218 int smp_cpus = 1;
219 int max_cpus = 0;
220 int smp_cores = 1;
221 int smp_threads = 1;
222 const char *vnc_display;
223 int acpi_enabled = 1;
224 int no_hpet = 0;
225 int fd_bootchk = 1;
226 int no_reboot = 0;
227 int no_shutdown = 0;
228 int cursor_hide = 1;
229 int graphic_rotate = 0;
230 uint8_t irq0override = 1;
231 #ifndef _WIN32
232 int daemonize = 0;
233 #endif
234 const char *watchdog;
235 const char *option_rom[MAX_OPTION_ROMS];
236 int nb_option_roms;
237 int semihosting_enabled = 0;
238 #ifdef TARGET_ARM
239 int old_param = 0;
240 #endif
241 const char *qemu_name;
242 int alt_grab = 0;
243 int ctrl_grab = 0;
244 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
245 unsigned int nb_prom_envs = 0;
246 const char *prom_envs[MAX_PROM_ENVS];
247 #endif
248 int boot_menu;
250 int nb_numa_nodes;
251 uint64_t node_mem[MAX_NODES];
252 uint64_t node_cpumask[MAX_NODES];
254 static CPUState *cur_cpu;
255 static CPUState *next_cpu;
256 static int timer_alarm_pending = 1;
257 /* Conversion factor from emulated instructions to virtual clock ticks. */
258 static int icount_time_shift;
259 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
260 #define MAX_ICOUNT_SHIFT 10
261 /* Compensate for varying guest execution speed. */
262 static int64_t qemu_icount_bias;
263 static QEMUTimer *icount_rt_timer;
264 static QEMUTimer *icount_vm_timer;
265 static QEMUTimer *nographic_timer;
267 uint8_t qemu_uuid[16];
269 static QEMUBootSetHandler *boot_set_handler;
270 static void *boot_set_opaque;
272 static int default_serial = 1;
273 static int default_parallel = 1;
274 static int default_virtcon = 1;
275 static int default_monitor = 1;
276 static int default_vga = 1;
277 static int default_floppy = 1;
278 static int default_cdrom = 1;
279 static int default_sdcard = 1;
281 static struct {
282 const char *driver;
283 int *flag;
284 } default_list[] = {
285 { .driver = "isa-serial", .flag = &default_serial },
286 { .driver = "isa-parallel", .flag = &default_parallel },
287 { .driver = "isa-fdc", .flag = &default_floppy },
288 { .driver = "ide-drive", .flag = &default_cdrom },
289 { .driver = "virtio-console-pci", .flag = &default_virtcon },
290 { .driver = "virtio-console-s390", .flag = &default_virtcon },
291 { .driver = "VGA", .flag = &default_vga },
292 { .driver = "cirrus-vga", .flag = &default_vga },
293 { .driver = "vmware-svga", .flag = &default_vga },
296 static int default_driver_check(QemuOpts *opts, void *opaque)
298 const char *driver = qemu_opt_get(opts, "driver");
299 int i;
301 if (!driver)
302 return 0;
303 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
304 if (strcmp(default_list[i].driver, driver) != 0)
305 continue;
306 *(default_list[i].flag) = 0;
308 return 0;
311 /***********************************************************/
312 /* x86 ISA bus support */
314 target_phys_addr_t isa_mem_base = 0;
315 PicState2 *isa_pic;
317 /***********************************************************/
318 void hw_error(const char *fmt, ...)
320 va_list ap;
321 CPUState *env;
323 va_start(ap, fmt);
324 fprintf(stderr, "qemu: hardware error: ");
325 vfprintf(stderr, fmt, ap);
326 fprintf(stderr, "\n");
327 for(env = first_cpu; env != NULL; env = env->next_cpu) {
328 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
329 #ifdef TARGET_I386
330 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
331 #else
332 cpu_dump_state(env, stderr, fprintf, 0);
333 #endif
335 va_end(ap);
336 abort();
339 static void set_proc_name(const char *s)
341 #if defined(__linux__) && defined(PR_SET_NAME)
342 char name[16];
343 if (!s)
344 return;
345 name[sizeof(name) - 1] = 0;
346 strncpy(name, s, sizeof(name));
347 /* Could rewrite argv[0] too, but that's a bit more complicated.
348 This simple way is enough for `top'. */
349 prctl(PR_SET_NAME, name);
350 #endif
353 /***************/
354 /* ballooning */
356 static QEMUBalloonEvent *qemu_balloon_event;
357 void *qemu_balloon_event_opaque;
359 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
361 qemu_balloon_event = func;
362 qemu_balloon_event_opaque = opaque;
365 void qemu_balloon(ram_addr_t target)
367 if (qemu_balloon_event)
368 qemu_balloon_event(qemu_balloon_event_opaque, target);
371 ram_addr_t qemu_balloon_status(void)
373 if (qemu_balloon_event)
374 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
375 return 0;
379 /***********************************************************/
380 /* real time host monotonic timer */
382 /* compute with 96 bit intermediate result: (a*b)/c */
383 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
385 union {
386 uint64_t ll;
387 struct {
388 #ifdef HOST_WORDS_BIGENDIAN
389 uint32_t high, low;
390 #else
391 uint32_t low, high;
392 #endif
393 } l;
394 } u, res;
395 uint64_t rl, rh;
397 u.ll = a;
398 rl = (uint64_t)u.l.low * (uint64_t)b;
399 rh = (uint64_t)u.l.high * (uint64_t)b;
400 rh += (rl >> 32);
401 res.l.high = rh / c;
402 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
403 return res.ll;
406 static int64_t get_clock_realtime(void)
408 struct timeval tv;
410 gettimeofday(&tv, NULL);
411 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
414 #ifdef WIN32
416 static int64_t clock_freq;
418 static void init_get_clock(void)
420 LARGE_INTEGER freq;
421 int ret;
422 ret = QueryPerformanceFrequency(&freq);
423 if (ret == 0) {
424 fprintf(stderr, "Could not calibrate ticks\n");
425 exit(1);
427 clock_freq = freq.QuadPart;
430 static int64_t get_clock(void)
432 LARGE_INTEGER ti;
433 QueryPerformanceCounter(&ti);
434 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
437 #else
439 static int use_rt_clock;
441 static void init_get_clock(void)
443 use_rt_clock = 0;
444 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
445 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
447 struct timespec ts;
448 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
449 use_rt_clock = 1;
452 #endif
455 static int64_t get_clock(void)
457 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
458 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
459 if (use_rt_clock) {
460 struct timespec ts;
461 clock_gettime(CLOCK_MONOTONIC, &ts);
462 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
463 } else
464 #endif
466 /* XXX: using gettimeofday leads to problems if the date
467 changes, so it should be avoided. */
468 return get_clock_realtime();
471 #endif
473 /* Return the virtual CPU time, based on the instruction counter. */
474 static int64_t cpu_get_icount(void)
476 int64_t icount;
477 CPUState *env = cpu_single_env;;
478 icount = qemu_icount;
479 if (env) {
480 if (!can_do_io(env))
481 fprintf(stderr, "Bad clock read\n");
482 icount -= (env->icount_decr.u16.low + env->icount_extra);
484 return qemu_icount_bias + (icount << icount_time_shift);
487 /***********************************************************/
488 /* guest cycle counter */
490 typedef struct TimersState {
491 int64_t cpu_ticks_prev;
492 int64_t cpu_ticks_offset;
493 int64_t cpu_clock_offset;
494 int32_t cpu_ticks_enabled;
495 int64_t dummy;
496 } TimersState;
498 TimersState timers_state;
500 /* return the host CPU cycle counter and handle stop/restart */
501 int64_t cpu_get_ticks(void)
503 if (use_icount) {
504 return cpu_get_icount();
506 if (!timers_state.cpu_ticks_enabled) {
507 return timers_state.cpu_ticks_offset;
508 } else {
509 int64_t ticks;
510 ticks = cpu_get_real_ticks();
511 if (timers_state.cpu_ticks_prev > ticks) {
512 /* Note: non increasing ticks may happen if the host uses
513 software suspend */
514 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
516 timers_state.cpu_ticks_prev = ticks;
517 return ticks + timers_state.cpu_ticks_offset;
521 /* return the host CPU monotonic timer and handle stop/restart */
522 static int64_t cpu_get_clock(void)
524 int64_t ti;
525 if (!timers_state.cpu_ticks_enabled) {
526 return timers_state.cpu_clock_offset;
527 } else {
528 ti = get_clock();
529 return ti + timers_state.cpu_clock_offset;
533 /* enable cpu_get_ticks() */
534 void cpu_enable_ticks(void)
536 if (!timers_state.cpu_ticks_enabled) {
537 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
538 timers_state.cpu_clock_offset -= get_clock();
539 timers_state.cpu_ticks_enabled = 1;
543 /* disable cpu_get_ticks() : the clock is stopped. You must not call
544 cpu_get_ticks() after that. */
545 void cpu_disable_ticks(void)
547 if (timers_state.cpu_ticks_enabled) {
548 timers_state.cpu_ticks_offset = cpu_get_ticks();
549 timers_state.cpu_clock_offset = cpu_get_clock();
550 timers_state.cpu_ticks_enabled = 0;
554 /***********************************************************/
555 /* timers */
557 #define QEMU_CLOCK_REALTIME 0
558 #define QEMU_CLOCK_VIRTUAL 1
559 #define QEMU_CLOCK_HOST 2
561 struct QEMUClock {
562 int type;
563 /* XXX: add frequency */
566 struct QEMUTimer {
567 QEMUClock *clock;
568 int64_t expire_time;
569 QEMUTimerCB *cb;
570 void *opaque;
571 struct QEMUTimer *next;
574 struct qemu_alarm_timer {
575 char const *name;
576 unsigned int flags;
578 int (*start)(struct qemu_alarm_timer *t);
579 void (*stop)(struct qemu_alarm_timer *t);
580 void (*rearm)(struct qemu_alarm_timer *t);
581 void *priv;
584 #define ALARM_FLAG_DYNTICKS 0x1
585 #define ALARM_FLAG_EXPIRED 0x2
587 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
589 return t && (t->flags & ALARM_FLAG_DYNTICKS);
592 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
594 if (!alarm_has_dynticks(t))
595 return;
597 t->rearm(t);
600 /* TODO: MIN_TIMER_REARM_US should be optimized */
601 #define MIN_TIMER_REARM_US 250
603 static struct qemu_alarm_timer *alarm_timer;
605 #ifdef _WIN32
607 struct qemu_alarm_win32 {
608 MMRESULT timerId;
609 unsigned int period;
610 } alarm_win32_data = {0, -1};
612 static int win32_start_timer(struct qemu_alarm_timer *t);
613 static void win32_stop_timer(struct qemu_alarm_timer *t);
614 static void win32_rearm_timer(struct qemu_alarm_timer *t);
616 #else
618 static int unix_start_timer(struct qemu_alarm_timer *t);
619 static void unix_stop_timer(struct qemu_alarm_timer *t);
621 #ifdef __linux__
623 static int dynticks_start_timer(struct qemu_alarm_timer *t);
624 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
625 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
627 static int hpet_start_timer(struct qemu_alarm_timer *t);
628 static void hpet_stop_timer(struct qemu_alarm_timer *t);
630 static int rtc_start_timer(struct qemu_alarm_timer *t);
631 static void rtc_stop_timer(struct qemu_alarm_timer *t);
633 #endif /* __linux__ */
635 #endif /* _WIN32 */
637 /* Correlation between real and virtual time is always going to be
638 fairly approximate, so ignore small variation.
639 When the guest is idle real and virtual time will be aligned in
640 the IO wait loop. */
641 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
643 static void icount_adjust(void)
645 int64_t cur_time;
646 int64_t cur_icount;
647 int64_t delta;
648 static int64_t last_delta;
649 /* If the VM is not running, then do nothing. */
650 if (!vm_running)
651 return;
653 cur_time = cpu_get_clock();
654 cur_icount = qemu_get_clock(vm_clock);
655 delta = cur_icount - cur_time;
656 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
657 if (delta > 0
658 && last_delta + ICOUNT_WOBBLE < delta * 2
659 && icount_time_shift > 0) {
660 /* The guest is getting too far ahead. Slow time down. */
661 icount_time_shift--;
663 if (delta < 0
664 && last_delta - ICOUNT_WOBBLE > delta * 2
665 && icount_time_shift < MAX_ICOUNT_SHIFT) {
666 /* The guest is getting too far behind. Speed time up. */
667 icount_time_shift++;
669 last_delta = delta;
670 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
673 static void icount_adjust_rt(void * opaque)
675 qemu_mod_timer(icount_rt_timer,
676 qemu_get_clock(rt_clock) + 1000);
677 icount_adjust();
680 static void icount_adjust_vm(void * opaque)
682 qemu_mod_timer(icount_vm_timer,
683 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
684 icount_adjust();
687 static void init_icount_adjust(void)
689 /* Have both realtime and virtual time triggers for speed adjustment.
690 The realtime trigger catches emulated time passing too slowly,
691 the virtual time trigger catches emulated time passing too fast.
692 Realtime triggers occur even when idle, so use them less frequently
693 than VM triggers. */
694 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
695 qemu_mod_timer(icount_rt_timer,
696 qemu_get_clock(rt_clock) + 1000);
697 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
698 qemu_mod_timer(icount_vm_timer,
699 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
702 static struct qemu_alarm_timer alarm_timers[] = {
703 #ifndef _WIN32
704 #ifdef __linux__
705 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
706 dynticks_stop_timer, dynticks_rearm_timer, NULL},
707 /* HPET - if available - is preferred */
708 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
709 /* ...otherwise try RTC */
710 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
711 #endif
712 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
713 #else
714 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
715 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
716 {"win32", 0, win32_start_timer,
717 win32_stop_timer, NULL, &alarm_win32_data},
718 #endif
719 {NULL, }
722 static void show_available_alarms(void)
724 int i;
726 printf("Available alarm timers, in order of precedence:\n");
727 for (i = 0; alarm_timers[i].name; i++)
728 printf("%s\n", alarm_timers[i].name);
731 static void configure_alarms(char const *opt)
733 int i;
734 int cur = 0;
735 int count = ARRAY_SIZE(alarm_timers) - 1;
736 char *arg;
737 char *name;
738 struct qemu_alarm_timer tmp;
740 if (!strcmp(opt, "?")) {
741 show_available_alarms();
742 exit(0);
745 arg = qemu_strdup(opt);
747 /* Reorder the array */
748 name = strtok(arg, ",");
749 while (name) {
750 for (i = 0; i < count && alarm_timers[i].name; i++) {
751 if (!strcmp(alarm_timers[i].name, name))
752 break;
755 if (i == count) {
756 fprintf(stderr, "Unknown clock %s\n", name);
757 goto next;
760 if (i < cur)
761 /* Ignore */
762 goto next;
764 /* Swap */
765 tmp = alarm_timers[i];
766 alarm_timers[i] = alarm_timers[cur];
767 alarm_timers[cur] = tmp;
769 cur++;
770 next:
771 name = strtok(NULL, ",");
774 qemu_free(arg);
776 if (cur) {
777 /* Disable remaining timers */
778 for (i = cur; i < count; i++)
779 alarm_timers[i].name = NULL;
780 } else {
781 show_available_alarms();
782 exit(1);
786 #define QEMU_NUM_CLOCKS 3
788 QEMUClock *rt_clock;
789 QEMUClock *vm_clock;
790 QEMUClock *host_clock;
792 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
794 static QEMUClock *qemu_new_clock(int type)
796 QEMUClock *clock;
797 clock = qemu_mallocz(sizeof(QEMUClock));
798 clock->type = type;
799 return clock;
802 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
804 QEMUTimer *ts;
806 ts = qemu_mallocz(sizeof(QEMUTimer));
807 ts->clock = clock;
808 ts->cb = cb;
809 ts->opaque = opaque;
810 return ts;
813 void qemu_free_timer(QEMUTimer *ts)
815 qemu_free(ts);
818 /* stop a timer, but do not dealloc it */
819 void qemu_del_timer(QEMUTimer *ts)
821 QEMUTimer **pt, *t;
823 /* NOTE: this code must be signal safe because
824 qemu_timer_expired() can be called from a signal. */
825 pt = &active_timers[ts->clock->type];
826 for(;;) {
827 t = *pt;
828 if (!t)
829 break;
830 if (t == ts) {
831 *pt = t->next;
832 break;
834 pt = &t->next;
838 /* modify the current timer so that it will be fired when current_time
839 >= expire_time. The corresponding callback will be called. */
840 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
842 QEMUTimer **pt, *t;
844 qemu_del_timer(ts);
846 /* add the timer in the sorted list */
847 /* NOTE: this code must be signal safe because
848 qemu_timer_expired() can be called from a signal. */
849 pt = &active_timers[ts->clock->type];
850 for(;;) {
851 t = *pt;
852 if (!t)
853 break;
854 if (t->expire_time > expire_time)
855 break;
856 pt = &t->next;
858 ts->expire_time = expire_time;
859 ts->next = *pt;
860 *pt = ts;
862 /* Rearm if necessary */
863 if (pt == &active_timers[ts->clock->type]) {
864 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
865 qemu_rearm_alarm_timer(alarm_timer);
867 /* Interrupt execution to force deadline recalculation. */
868 if (use_icount)
869 qemu_notify_event();
873 int qemu_timer_pending(QEMUTimer *ts)
875 QEMUTimer *t;
876 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
877 if (t == ts)
878 return 1;
880 return 0;
883 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
885 if (!timer_head)
886 return 0;
887 return (timer_head->expire_time <= current_time);
890 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
892 QEMUTimer *ts;
894 for(;;) {
895 ts = *ptimer_head;
896 if (!ts || ts->expire_time > current_time)
897 break;
898 /* remove timer from the list before calling the callback */
899 *ptimer_head = ts->next;
900 ts->next = NULL;
902 /* run the callback (the timer list can be modified) */
903 ts->cb(ts->opaque);
907 int64_t qemu_get_clock(QEMUClock *clock)
909 switch(clock->type) {
910 case QEMU_CLOCK_REALTIME:
911 return get_clock() / 1000000;
912 default:
913 case QEMU_CLOCK_VIRTUAL:
914 if (use_icount) {
915 return cpu_get_icount();
916 } else {
917 return cpu_get_clock();
919 case QEMU_CLOCK_HOST:
920 return get_clock_realtime();
924 static void init_clocks(void)
926 init_get_clock();
927 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
928 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
929 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
931 rtc_clock = host_clock;
934 /* save a timer */
935 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
937 uint64_t expire_time;
939 if (qemu_timer_pending(ts)) {
940 expire_time = ts->expire_time;
941 } else {
942 expire_time = -1;
944 qemu_put_be64(f, expire_time);
947 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
949 uint64_t expire_time;
951 expire_time = qemu_get_be64(f);
952 if (expire_time != -1) {
953 qemu_mod_timer(ts, expire_time);
954 } else {
955 qemu_del_timer(ts);
959 static const VMStateDescription vmstate_timers = {
960 .name = "timer",
961 .version_id = 2,
962 .minimum_version_id = 1,
963 .minimum_version_id_old = 1,
964 .fields = (VMStateField []) {
965 VMSTATE_INT64(cpu_ticks_offset, TimersState),
966 VMSTATE_INT64(dummy, TimersState),
967 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
968 VMSTATE_END_OF_LIST()
972 static void qemu_event_increment(void);
974 #ifdef _WIN32
975 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
976 DWORD_PTR dwUser, DWORD_PTR dw1,
977 DWORD_PTR dw2)
978 #else
979 static void host_alarm_handler(int host_signum)
980 #endif
982 #if 0
983 #define DISP_FREQ 1000
985 static int64_t delta_min = INT64_MAX;
986 static int64_t delta_max, delta_cum, last_clock, delta, ti;
987 static int count;
988 ti = qemu_get_clock(vm_clock);
989 if (last_clock != 0) {
990 delta = ti - last_clock;
991 if (delta < delta_min)
992 delta_min = delta;
993 if (delta > delta_max)
994 delta_max = delta;
995 delta_cum += delta;
996 if (++count == DISP_FREQ) {
997 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
998 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
999 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1000 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1001 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1002 count = 0;
1003 delta_min = INT64_MAX;
1004 delta_max = 0;
1005 delta_cum = 0;
1008 last_clock = ti;
1010 #endif
1011 if (alarm_has_dynticks(alarm_timer) ||
1012 (!use_icount &&
1013 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1014 qemu_get_clock(vm_clock))) ||
1015 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1016 qemu_get_clock(rt_clock)) ||
1017 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1018 qemu_get_clock(host_clock))) {
1019 qemu_event_increment();
1020 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1022 #ifndef CONFIG_IOTHREAD
1023 if (next_cpu) {
1024 /* stop the currently executing cpu because a timer occured */
1025 cpu_exit(next_cpu);
1027 #endif
1028 timer_alarm_pending = 1;
1029 qemu_notify_event();
1033 static int64_t qemu_next_deadline(void)
1035 /* To avoid problems with overflow limit this to 2^32. */
1036 int64_t delta = INT32_MAX;
1038 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1039 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1040 qemu_get_clock(vm_clock);
1042 if (active_timers[QEMU_CLOCK_HOST]) {
1043 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1044 qemu_get_clock(host_clock);
1045 if (hdelta < delta)
1046 delta = hdelta;
1049 if (delta < 0)
1050 delta = 0;
1052 return delta;
1055 #if defined(__linux__)
1056 static uint64_t qemu_next_deadline_dyntick(void)
1058 int64_t delta;
1059 int64_t rtdelta;
1061 if (use_icount)
1062 delta = INT32_MAX;
1063 else
1064 delta = (qemu_next_deadline() + 999) / 1000;
1066 if (active_timers[QEMU_CLOCK_REALTIME]) {
1067 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1068 qemu_get_clock(rt_clock))*1000;
1069 if (rtdelta < delta)
1070 delta = rtdelta;
1073 if (delta < MIN_TIMER_REARM_US)
1074 delta = MIN_TIMER_REARM_US;
1076 return delta;
1078 #endif
1080 #ifndef _WIN32
1082 /* Sets a specific flag */
1083 static int fcntl_setfl(int fd, int flag)
1085 int flags;
1087 flags = fcntl(fd, F_GETFL);
1088 if (flags == -1)
1089 return -errno;
1091 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1092 return -errno;
1094 return 0;
1097 #if defined(__linux__)
1099 #define RTC_FREQ 1024
1101 static void enable_sigio_timer(int fd)
1103 struct sigaction act;
1105 /* timer signal */
1106 sigfillset(&act.sa_mask);
1107 act.sa_flags = 0;
1108 act.sa_handler = host_alarm_handler;
1110 sigaction(SIGIO, &act, NULL);
1111 fcntl_setfl(fd, O_ASYNC);
1112 fcntl(fd, F_SETOWN, getpid());
1115 static int hpet_start_timer(struct qemu_alarm_timer *t)
1117 struct hpet_info info;
1118 int r, fd;
1120 fd = qemu_open("/dev/hpet", O_RDONLY);
1121 if (fd < 0)
1122 return -1;
1124 /* Set frequency */
1125 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1126 if (r < 0) {
1127 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1128 "error, but for better emulation accuracy type:\n"
1129 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1130 goto fail;
1133 /* Check capabilities */
1134 r = ioctl(fd, HPET_INFO, &info);
1135 if (r < 0)
1136 goto fail;
1138 /* Enable periodic mode */
1139 r = ioctl(fd, HPET_EPI, 0);
1140 if (info.hi_flags && (r < 0))
1141 goto fail;
1143 /* Enable interrupt */
1144 r = ioctl(fd, HPET_IE_ON, 0);
1145 if (r < 0)
1146 goto fail;
1148 enable_sigio_timer(fd);
1149 t->priv = (void *)(long)fd;
1151 return 0;
1152 fail:
1153 close(fd);
1154 return -1;
1157 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1159 int fd = (long)t->priv;
1161 close(fd);
1164 static int rtc_start_timer(struct qemu_alarm_timer *t)
1166 int rtc_fd;
1167 unsigned long current_rtc_freq = 0;
1169 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1170 if (rtc_fd < 0)
1171 return -1;
1172 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1173 if (current_rtc_freq != RTC_FREQ &&
1174 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1175 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1176 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1177 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1178 goto fail;
1180 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1181 fail:
1182 close(rtc_fd);
1183 return -1;
1186 enable_sigio_timer(rtc_fd);
1188 t->priv = (void *)(long)rtc_fd;
1190 return 0;
1193 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1195 int rtc_fd = (long)t->priv;
1197 close(rtc_fd);
1200 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1202 struct sigevent ev;
1203 timer_t host_timer;
1204 struct sigaction act;
1206 sigfillset(&act.sa_mask);
1207 act.sa_flags = 0;
1208 act.sa_handler = host_alarm_handler;
1210 sigaction(SIGALRM, &act, NULL);
1213 * Initialize ev struct to 0 to avoid valgrind complaining
1214 * about uninitialized data in timer_create call
1216 memset(&ev, 0, sizeof(ev));
1217 ev.sigev_value.sival_int = 0;
1218 ev.sigev_notify = SIGEV_SIGNAL;
1219 ev.sigev_signo = SIGALRM;
1221 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1222 perror("timer_create");
1224 /* disable dynticks */
1225 fprintf(stderr, "Dynamic Ticks disabled\n");
1227 return -1;
1230 t->priv = (void *)(long)host_timer;
1232 return 0;
1235 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1237 timer_t host_timer = (timer_t)(long)t->priv;
1239 timer_delete(host_timer);
1242 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1244 timer_t host_timer = (timer_t)(long)t->priv;
1245 struct itimerspec timeout;
1246 int64_t nearest_delta_us = INT64_MAX;
1247 int64_t current_us;
1249 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1250 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1251 !active_timers[QEMU_CLOCK_HOST])
1252 return;
1254 nearest_delta_us = qemu_next_deadline_dyntick();
1256 /* check whether a timer is already running */
1257 if (timer_gettime(host_timer, &timeout)) {
1258 perror("gettime");
1259 fprintf(stderr, "Internal timer error: aborting\n");
1260 exit(1);
1262 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1263 if (current_us && current_us <= nearest_delta_us)
1264 return;
1266 timeout.it_interval.tv_sec = 0;
1267 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1268 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1269 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1270 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1271 perror("settime");
1272 fprintf(stderr, "Internal timer error: aborting\n");
1273 exit(1);
1277 #endif /* defined(__linux__) */
1279 static int unix_start_timer(struct qemu_alarm_timer *t)
1281 struct sigaction act;
1282 struct itimerval itv;
1283 int err;
1285 /* timer signal */
1286 sigfillset(&act.sa_mask);
1287 act.sa_flags = 0;
1288 act.sa_handler = host_alarm_handler;
1290 sigaction(SIGALRM, &act, NULL);
1292 itv.it_interval.tv_sec = 0;
1293 /* for i386 kernel 2.6 to get 1 ms */
1294 itv.it_interval.tv_usec = 999;
1295 itv.it_value.tv_sec = 0;
1296 itv.it_value.tv_usec = 10 * 1000;
1298 err = setitimer(ITIMER_REAL, &itv, NULL);
1299 if (err)
1300 return -1;
1302 return 0;
1305 static void unix_stop_timer(struct qemu_alarm_timer *t)
1307 struct itimerval itv;
1309 memset(&itv, 0, sizeof(itv));
1310 setitimer(ITIMER_REAL, &itv, NULL);
1313 #endif /* !defined(_WIN32) */
1316 #ifdef _WIN32
1318 static int win32_start_timer(struct qemu_alarm_timer *t)
1320 TIMECAPS tc;
1321 struct qemu_alarm_win32 *data = t->priv;
1322 UINT flags;
1324 memset(&tc, 0, sizeof(tc));
1325 timeGetDevCaps(&tc, sizeof(tc));
1327 if (data->period < tc.wPeriodMin)
1328 data->period = tc.wPeriodMin;
1330 timeBeginPeriod(data->period);
1332 flags = TIME_CALLBACK_FUNCTION;
1333 if (alarm_has_dynticks(t))
1334 flags |= TIME_ONESHOT;
1335 else
1336 flags |= TIME_PERIODIC;
1338 data->timerId = timeSetEvent(1, // interval (ms)
1339 data->period, // resolution
1340 host_alarm_handler, // function
1341 (DWORD)t, // parameter
1342 flags);
1344 if (!data->timerId) {
1345 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1346 GetLastError());
1347 timeEndPeriod(data->period);
1348 return -1;
1351 return 0;
1354 static void win32_stop_timer(struct qemu_alarm_timer *t)
1356 struct qemu_alarm_win32 *data = t->priv;
1358 timeKillEvent(data->timerId);
1359 timeEndPeriod(data->period);
1362 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1364 struct qemu_alarm_win32 *data = t->priv;
1366 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1367 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1368 !active_timers[QEMU_CLOCK_HOST])
1369 return;
1371 timeKillEvent(data->timerId);
1373 data->timerId = timeSetEvent(1,
1374 data->period,
1375 host_alarm_handler,
1376 (DWORD)t,
1377 TIME_ONESHOT | TIME_PERIODIC);
1379 if (!data->timerId) {
1380 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1381 GetLastError());
1383 timeEndPeriod(data->period);
1384 exit(1);
1388 #endif /* _WIN32 */
1390 static int init_timer_alarm(void)
1392 struct qemu_alarm_timer *t = NULL;
1393 int i, err = -1;
1395 for (i = 0; alarm_timers[i].name; i++) {
1396 t = &alarm_timers[i];
1398 err = t->start(t);
1399 if (!err)
1400 break;
1403 if (err) {
1404 err = -ENOENT;
1405 goto fail;
1408 alarm_timer = t;
1410 return 0;
1412 fail:
1413 return err;
1416 static void quit_timers(void)
1418 alarm_timer->stop(alarm_timer);
1419 alarm_timer = NULL;
1422 /***********************************************************/
1423 /* host time/date access */
1424 void qemu_get_timedate(struct tm *tm, int offset)
1426 time_t ti;
1427 struct tm *ret;
1429 time(&ti);
1430 ti += offset;
1431 if (rtc_date_offset == -1) {
1432 if (rtc_utc)
1433 ret = gmtime(&ti);
1434 else
1435 ret = localtime(&ti);
1436 } else {
1437 ti -= rtc_date_offset;
1438 ret = gmtime(&ti);
1441 memcpy(tm, ret, sizeof(struct tm));
1444 int qemu_timedate_diff(struct tm *tm)
1446 time_t seconds;
1448 if (rtc_date_offset == -1)
1449 if (rtc_utc)
1450 seconds = mktimegm(tm);
1451 else
1452 seconds = mktime(tm);
1453 else
1454 seconds = mktimegm(tm) + rtc_date_offset;
1456 return seconds - time(NULL);
1459 static void configure_rtc_date_offset(const char *startdate, int legacy)
1461 time_t rtc_start_date;
1462 struct tm tm;
1464 if (!strcmp(startdate, "now") && legacy) {
1465 rtc_date_offset = -1;
1466 } else {
1467 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1468 &tm.tm_year,
1469 &tm.tm_mon,
1470 &tm.tm_mday,
1471 &tm.tm_hour,
1472 &tm.tm_min,
1473 &tm.tm_sec) == 6) {
1474 /* OK */
1475 } else if (sscanf(startdate, "%d-%d-%d",
1476 &tm.tm_year,
1477 &tm.tm_mon,
1478 &tm.tm_mday) == 3) {
1479 tm.tm_hour = 0;
1480 tm.tm_min = 0;
1481 tm.tm_sec = 0;
1482 } else {
1483 goto date_fail;
1485 tm.tm_year -= 1900;
1486 tm.tm_mon--;
1487 rtc_start_date = mktimegm(&tm);
1488 if (rtc_start_date == -1) {
1489 date_fail:
1490 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1491 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1492 exit(1);
1494 rtc_date_offset = time(NULL) - rtc_start_date;
1498 static void configure_rtc(QemuOpts *opts)
1500 const char *value;
1502 value = qemu_opt_get(opts, "base");
1503 if (value) {
1504 if (!strcmp(value, "utc")) {
1505 rtc_utc = 1;
1506 } else if (!strcmp(value, "localtime")) {
1507 rtc_utc = 0;
1508 } else {
1509 configure_rtc_date_offset(value, 0);
1512 value = qemu_opt_get(opts, "clock");
1513 if (value) {
1514 if (!strcmp(value, "host")) {
1515 rtc_clock = host_clock;
1516 } else if (!strcmp(value, "vm")) {
1517 rtc_clock = vm_clock;
1518 } else {
1519 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1520 exit(1);
1523 #ifdef CONFIG_TARGET_I386
1524 value = qemu_opt_get(opts, "driftfix");
1525 if (value) {
1526 if (!strcmp(buf, "slew")) {
1527 rtc_td_hack = 1;
1528 } else if (!strcmp(buf, "none")) {
1529 rtc_td_hack = 0;
1530 } else {
1531 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1532 exit(1);
1535 #endif
1538 #ifdef _WIN32
1539 static void socket_cleanup(void)
1541 WSACleanup();
1544 static int socket_init(void)
1546 WSADATA Data;
1547 int ret, err;
1549 ret = WSAStartup(MAKEWORD(2,2), &Data);
1550 if (ret != 0) {
1551 err = WSAGetLastError();
1552 fprintf(stderr, "WSAStartup: %d\n", err);
1553 return -1;
1555 atexit(socket_cleanup);
1556 return 0;
1558 #endif
1560 /***********************************************************/
1561 /* Bluetooth support */
1562 static int nb_hcis;
1563 static int cur_hci;
1564 static struct HCIInfo *hci_table[MAX_NICS];
1566 static struct bt_vlan_s {
1567 struct bt_scatternet_s net;
1568 int id;
1569 struct bt_vlan_s *next;
1570 } *first_bt_vlan;
1572 /* find or alloc a new bluetooth "VLAN" */
1573 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1575 struct bt_vlan_s **pvlan, *vlan;
1576 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1577 if (vlan->id == id)
1578 return &vlan->net;
1580 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1581 vlan->id = id;
1582 pvlan = &first_bt_vlan;
1583 while (*pvlan != NULL)
1584 pvlan = &(*pvlan)->next;
1585 *pvlan = vlan;
1586 return &vlan->net;
1589 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1593 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1595 return -ENOTSUP;
1598 static struct HCIInfo null_hci = {
1599 .cmd_send = null_hci_send,
1600 .sco_send = null_hci_send,
1601 .acl_send = null_hci_send,
1602 .bdaddr_set = null_hci_addr_set,
1605 struct HCIInfo *qemu_next_hci(void)
1607 if (cur_hci == nb_hcis)
1608 return &null_hci;
1610 return hci_table[cur_hci++];
1613 static struct HCIInfo *hci_init(const char *str)
1615 char *endp;
1616 struct bt_scatternet_s *vlan = 0;
1618 if (!strcmp(str, "null"))
1619 /* null */
1620 return &null_hci;
1621 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1622 /* host[:hciN] */
1623 return bt_host_hci(str[4] ? str + 5 : "hci0");
1624 else if (!strncmp(str, "hci", 3)) {
1625 /* hci[,vlan=n] */
1626 if (str[3]) {
1627 if (!strncmp(str + 3, ",vlan=", 6)) {
1628 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1629 if (*endp)
1630 vlan = 0;
1632 } else
1633 vlan = qemu_find_bt_vlan(0);
1634 if (vlan)
1635 return bt_new_hci(vlan);
1638 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1640 return 0;
1643 static int bt_hci_parse(const char *str)
1645 struct HCIInfo *hci;
1646 bdaddr_t bdaddr;
1648 if (nb_hcis >= MAX_NICS) {
1649 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1650 return -1;
1653 hci = hci_init(str);
1654 if (!hci)
1655 return -1;
1657 bdaddr.b[0] = 0x52;
1658 bdaddr.b[1] = 0x54;
1659 bdaddr.b[2] = 0x00;
1660 bdaddr.b[3] = 0x12;
1661 bdaddr.b[4] = 0x34;
1662 bdaddr.b[5] = 0x56 + nb_hcis;
1663 hci->bdaddr_set(hci, bdaddr.b);
1665 hci_table[nb_hcis++] = hci;
1667 return 0;
1670 static void bt_vhci_add(int vlan_id)
1672 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1674 if (!vlan->slave)
1675 fprintf(stderr, "qemu: warning: adding a VHCI to "
1676 "an empty scatternet %i\n", vlan_id);
1678 bt_vhci_init(bt_new_hci(vlan));
1681 static struct bt_device_s *bt_device_add(const char *opt)
1683 struct bt_scatternet_s *vlan;
1684 int vlan_id = 0;
1685 char *endp = strstr(opt, ",vlan=");
1686 int len = (endp ? endp - opt : strlen(opt)) + 1;
1687 char devname[10];
1689 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1691 if (endp) {
1692 vlan_id = strtol(endp + 6, &endp, 0);
1693 if (*endp) {
1694 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1695 return 0;
1699 vlan = qemu_find_bt_vlan(vlan_id);
1701 if (!vlan->slave)
1702 fprintf(stderr, "qemu: warning: adding a slave device to "
1703 "an empty scatternet %i\n", vlan_id);
1705 if (!strcmp(devname, "keyboard"))
1706 return bt_keyboard_init(vlan);
1708 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1709 return 0;
1712 static int bt_parse(const char *opt)
1714 const char *endp, *p;
1715 int vlan;
1717 if (strstart(opt, "hci", &endp)) {
1718 if (!*endp || *endp == ',') {
1719 if (*endp)
1720 if (!strstart(endp, ",vlan=", 0))
1721 opt = endp + 1;
1723 return bt_hci_parse(opt);
1725 } else if (strstart(opt, "vhci", &endp)) {
1726 if (!*endp || *endp == ',') {
1727 if (*endp) {
1728 if (strstart(endp, ",vlan=", &p)) {
1729 vlan = strtol(p, (char **) &endp, 0);
1730 if (*endp) {
1731 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1732 return 1;
1734 } else {
1735 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1736 return 1;
1738 } else
1739 vlan = 0;
1741 bt_vhci_add(vlan);
1742 return 0;
1744 } else if (strstart(opt, "device:", &endp))
1745 return !bt_device_add(endp);
1747 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1748 return 1;
1751 /***********************************************************/
1752 /* QEMU Block devices */
1754 #define HD_ALIAS "index=%d,media=disk"
1755 #define CDROM_ALIAS "index=2,media=cdrom"
1756 #define FD_ALIAS "index=%d,if=floppy"
1757 #define PFLASH_ALIAS "if=pflash"
1758 #define MTD_ALIAS "if=mtd"
1759 #define SD_ALIAS "index=0,if=sd"
1761 QemuOpts *drive_add(const char *file, const char *fmt, ...)
1763 va_list ap;
1764 char optstr[1024];
1765 QemuOpts *opts;
1767 va_start(ap, fmt);
1768 vsnprintf(optstr, sizeof(optstr), fmt, ap);
1769 va_end(ap);
1771 opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1772 if (!opts) {
1773 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1774 __FUNCTION__, optstr);
1775 return NULL;
1777 if (file)
1778 qemu_opt_set(opts, "file", file);
1779 return opts;
1782 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1784 DriveInfo *dinfo;
1786 /* seek interface, bus and unit */
1788 QTAILQ_FOREACH(dinfo, &drives, next) {
1789 if (dinfo->type == type &&
1790 dinfo->bus == bus &&
1791 dinfo->unit == unit)
1792 return dinfo;
1795 return NULL;
1798 DriveInfo *drive_get_by_id(const char *id)
1800 DriveInfo *dinfo;
1802 QTAILQ_FOREACH(dinfo, &drives, next) {
1803 if (strcmp(id, dinfo->id))
1804 continue;
1805 return dinfo;
1807 return NULL;
1810 int drive_get_max_bus(BlockInterfaceType type)
1812 int max_bus;
1813 DriveInfo *dinfo;
1815 max_bus = -1;
1816 QTAILQ_FOREACH(dinfo, &drives, next) {
1817 if(dinfo->type == type &&
1818 dinfo->bus > max_bus)
1819 max_bus = dinfo->bus;
1821 return max_bus;
1824 const char *drive_get_serial(BlockDriverState *bdrv)
1826 DriveInfo *dinfo;
1828 QTAILQ_FOREACH(dinfo, &drives, next) {
1829 if (dinfo->bdrv == bdrv)
1830 return dinfo->serial;
1833 return "\0";
1836 BlockInterfaceErrorAction drive_get_on_error(
1837 BlockDriverState *bdrv, int is_read)
1839 DriveInfo *dinfo;
1841 QTAILQ_FOREACH(dinfo, &drives, next) {
1842 if (dinfo->bdrv == bdrv)
1843 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1846 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1849 static void bdrv_format_print(void *opaque, const char *name)
1851 fprintf(stderr, " %s", name);
1854 void drive_uninit(DriveInfo *dinfo)
1856 qemu_opts_del(dinfo->opts);
1857 bdrv_delete(dinfo->bdrv);
1858 QTAILQ_REMOVE(&drives, dinfo, next);
1859 qemu_free(dinfo);
1862 static int parse_block_error_action(const char *buf, int is_read)
1864 if (!strcmp(buf, "ignore")) {
1865 return BLOCK_ERR_IGNORE;
1866 } else if (!is_read && !strcmp(buf, "enospc")) {
1867 return BLOCK_ERR_STOP_ENOSPC;
1868 } else if (!strcmp(buf, "stop")) {
1869 return BLOCK_ERR_STOP_ANY;
1870 } else if (!strcmp(buf, "report")) {
1871 return BLOCK_ERR_REPORT;
1872 } else {
1873 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1874 buf, is_read ? "read" : "write");
1875 return -1;
1879 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1880 int *fatal_error)
1882 const char *buf;
1883 const char *file = NULL;
1884 char devname[128];
1885 const char *serial;
1886 const char *mediastr = "";
1887 BlockInterfaceType type;
1888 enum { MEDIA_DISK, MEDIA_CDROM } media;
1889 int bus_id, unit_id;
1890 int cyls, heads, secs, translation;
1891 BlockDriver *drv = NULL;
1892 QEMUMachine *machine = opaque;
1893 int max_devs;
1894 int index;
1895 int cache;
1896 int aio = 0;
1897 int ro = 0;
1898 int bdrv_flags;
1899 int on_read_error, on_write_error;
1900 const char *devaddr;
1901 DriveInfo *dinfo;
1902 int snapshot = 0;
1904 *fatal_error = 1;
1906 translation = BIOS_ATA_TRANSLATION_AUTO;
1907 cache = 1;
1909 if (machine && machine->use_scsi) {
1910 type = IF_SCSI;
1911 max_devs = MAX_SCSI_DEVS;
1912 pstrcpy(devname, sizeof(devname), "scsi");
1913 } else {
1914 type = IF_IDE;
1915 max_devs = MAX_IDE_DEVS;
1916 pstrcpy(devname, sizeof(devname), "ide");
1918 media = MEDIA_DISK;
1920 /* extract parameters */
1921 bus_id = qemu_opt_get_number(opts, "bus", 0);
1922 unit_id = qemu_opt_get_number(opts, "unit", -1);
1923 index = qemu_opt_get_number(opts, "index", -1);
1925 cyls = qemu_opt_get_number(opts, "cyls", 0);
1926 heads = qemu_opt_get_number(opts, "heads", 0);
1927 secs = qemu_opt_get_number(opts, "secs", 0);
1929 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1930 ro = qemu_opt_get_bool(opts, "readonly", 0);
1932 file = qemu_opt_get(opts, "file");
1933 serial = qemu_opt_get(opts, "serial");
1935 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1936 pstrcpy(devname, sizeof(devname), buf);
1937 if (!strcmp(buf, "ide")) {
1938 type = IF_IDE;
1939 max_devs = MAX_IDE_DEVS;
1940 } else if (!strcmp(buf, "scsi")) {
1941 type = IF_SCSI;
1942 max_devs = MAX_SCSI_DEVS;
1943 } else if (!strcmp(buf, "floppy")) {
1944 type = IF_FLOPPY;
1945 max_devs = 0;
1946 } else if (!strcmp(buf, "pflash")) {
1947 type = IF_PFLASH;
1948 max_devs = 0;
1949 } else if (!strcmp(buf, "mtd")) {
1950 type = IF_MTD;
1951 max_devs = 0;
1952 } else if (!strcmp(buf, "sd")) {
1953 type = IF_SD;
1954 max_devs = 0;
1955 } else if (!strcmp(buf, "virtio")) {
1956 type = IF_VIRTIO;
1957 max_devs = 0;
1958 } else if (!strcmp(buf, "xen")) {
1959 type = IF_XEN;
1960 max_devs = 0;
1961 } else if (!strcmp(buf, "none")) {
1962 type = IF_NONE;
1963 max_devs = 0;
1964 } else {
1965 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1966 return NULL;
1970 if (cyls || heads || secs) {
1971 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
1972 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1973 return NULL;
1975 if (heads < 1 || (type == IF_IDE && heads > 16)) {
1976 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1977 return NULL;
1979 if (secs < 1 || (type == IF_IDE && secs > 63)) {
1980 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
1981 return NULL;
1985 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
1986 if (!cyls) {
1987 fprintf(stderr,
1988 "qemu: '%s' trans must be used with cyls,heads and secs\n",
1989 buf);
1990 return NULL;
1992 if (!strcmp(buf, "none"))
1993 translation = BIOS_ATA_TRANSLATION_NONE;
1994 else if (!strcmp(buf, "lba"))
1995 translation = BIOS_ATA_TRANSLATION_LBA;
1996 else if (!strcmp(buf, "auto"))
1997 translation = BIOS_ATA_TRANSLATION_AUTO;
1998 else {
1999 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2000 return NULL;
2004 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2005 if (!strcmp(buf, "disk")) {
2006 media = MEDIA_DISK;
2007 } else if (!strcmp(buf, "cdrom")) {
2008 if (cyls || secs || heads) {
2009 fprintf(stderr,
2010 "qemu: '%s' invalid physical CHS format\n", buf);
2011 return NULL;
2013 media = MEDIA_CDROM;
2014 } else {
2015 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2016 return NULL;
2020 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2021 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2022 cache = 0;
2023 else if (!strcmp(buf, "writethrough"))
2024 cache = 1;
2025 else if (!strcmp(buf, "writeback"))
2026 cache = 2;
2027 else {
2028 fprintf(stderr, "qemu: invalid cache option\n");
2029 return NULL;
2033 #ifdef CONFIG_LINUX_AIO
2034 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2035 if (!strcmp(buf, "threads"))
2036 aio = 0;
2037 else if (!strcmp(buf, "native"))
2038 aio = 1;
2039 else {
2040 fprintf(stderr, "qemu: invalid aio option\n");
2041 return NULL;
2044 #endif
2046 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2047 if (strcmp(buf, "?") == 0) {
2048 fprintf(stderr, "qemu: Supported formats:");
2049 bdrv_iterate_format(bdrv_format_print, NULL);
2050 fprintf(stderr, "\n");
2051 return NULL;
2053 drv = bdrv_find_whitelisted_format(buf);
2054 if (!drv) {
2055 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2056 return NULL;
2060 on_write_error = BLOCK_ERR_STOP_ENOSPC;
2061 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2062 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2063 fprintf(stderr, "werror is no supported by this format\n");
2064 return NULL;
2067 on_write_error = parse_block_error_action(buf, 0);
2068 if (on_write_error < 0) {
2069 return NULL;
2073 on_read_error = BLOCK_ERR_REPORT;
2074 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2075 if (type != IF_IDE && type != IF_VIRTIO) {
2076 fprintf(stderr, "rerror is no supported by this format\n");
2077 return NULL;
2080 on_read_error = parse_block_error_action(buf, 1);
2081 if (on_read_error < 0) {
2082 return NULL;
2086 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2087 if (type != IF_VIRTIO) {
2088 fprintf(stderr, "addr is not supported\n");
2089 return NULL;
2093 /* compute bus and unit according index */
2095 if (index != -1) {
2096 if (bus_id != 0 || unit_id != -1) {
2097 fprintf(stderr,
2098 "qemu: index cannot be used with bus and unit\n");
2099 return NULL;
2101 if (max_devs == 0)
2103 unit_id = index;
2104 bus_id = 0;
2105 } else {
2106 unit_id = index % max_devs;
2107 bus_id = index / max_devs;
2111 /* if user doesn't specify a unit_id,
2112 * try to find the first free
2115 if (unit_id == -1) {
2116 unit_id = 0;
2117 while (drive_get(type, bus_id, unit_id) != NULL) {
2118 unit_id++;
2119 if (max_devs && unit_id >= max_devs) {
2120 unit_id -= max_devs;
2121 bus_id++;
2126 /* check unit id */
2128 if (max_devs && unit_id >= max_devs) {
2129 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2130 unit_id, max_devs - 1);
2131 return NULL;
2135 * ignore multiple definitions
2138 if (drive_get(type, bus_id, unit_id) != NULL) {
2139 *fatal_error = 0;
2140 return NULL;
2143 /* init */
2145 dinfo = qemu_mallocz(sizeof(*dinfo));
2146 if ((buf = qemu_opts_id(opts)) != NULL) {
2147 dinfo->id = qemu_strdup(buf);
2148 } else {
2149 /* no id supplied -> create one */
2150 dinfo->id = qemu_mallocz(32);
2151 if (type == IF_IDE || type == IF_SCSI)
2152 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2153 if (max_devs)
2154 snprintf(dinfo->id, 32, "%s%i%s%i",
2155 devname, bus_id, mediastr, unit_id);
2156 else
2157 snprintf(dinfo->id, 32, "%s%s%i",
2158 devname, mediastr, unit_id);
2160 dinfo->bdrv = bdrv_new(dinfo->id);
2161 dinfo->devaddr = devaddr;
2162 dinfo->type = type;
2163 dinfo->bus = bus_id;
2164 dinfo->unit = unit_id;
2165 dinfo->on_read_error = on_read_error;
2166 dinfo->on_write_error = on_write_error;
2167 dinfo->opts = opts;
2168 if (serial)
2169 strncpy(dinfo->serial, serial, sizeof(serial));
2170 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2172 switch(type) {
2173 case IF_IDE:
2174 case IF_SCSI:
2175 case IF_XEN:
2176 case IF_NONE:
2177 switch(media) {
2178 case MEDIA_DISK:
2179 if (cyls != 0) {
2180 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2181 bdrv_set_translation_hint(dinfo->bdrv, translation);
2183 break;
2184 case MEDIA_CDROM:
2185 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2186 break;
2188 break;
2189 case IF_SD:
2190 /* FIXME: This isn't really a floppy, but it's a reasonable
2191 approximation. */
2192 case IF_FLOPPY:
2193 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2194 break;
2195 case IF_PFLASH:
2196 case IF_MTD:
2197 break;
2198 case IF_VIRTIO:
2199 /* add virtio block device */
2200 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2201 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2202 qemu_opt_set(opts, "drive", dinfo->id);
2203 if (devaddr)
2204 qemu_opt_set(opts, "addr", devaddr);
2205 break;
2206 case IF_COUNT:
2207 abort();
2209 if (!file) {
2210 *fatal_error = 0;
2211 return NULL;
2213 bdrv_flags = 0;
2214 if (snapshot) {
2215 bdrv_flags |= BDRV_O_SNAPSHOT;
2216 cache = 2; /* always use write-back with snapshot */
2218 if (cache == 0) /* no caching */
2219 bdrv_flags |= BDRV_O_NOCACHE;
2220 else if (cache == 2) /* write-back */
2221 bdrv_flags |= BDRV_O_CACHE_WB;
2223 if (aio == 1) {
2224 bdrv_flags |= BDRV_O_NATIVE_AIO;
2225 } else {
2226 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2229 if (ro == 1) {
2230 if (type == IF_IDE) {
2231 fprintf(stderr, "qemu: readonly flag not supported for drive with ide interface\n");
2232 return NULL;
2234 (void)bdrv_set_read_only(dinfo->bdrv, 1);
2237 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2238 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2239 file, strerror(errno));
2240 return NULL;
2243 if (bdrv_key_required(dinfo->bdrv))
2244 autostart = 0;
2245 *fatal_error = 0;
2246 return dinfo;
2249 static int drive_init_func(QemuOpts *opts, void *opaque)
2251 QEMUMachine *machine = opaque;
2252 int fatal_error = 0;
2254 if (drive_init(opts, machine, &fatal_error) == NULL) {
2255 if (fatal_error)
2256 return 1;
2258 return 0;
2261 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2263 if (NULL == qemu_opt_get(opts, "snapshot")) {
2264 qemu_opt_set(opts, "snapshot", "on");
2266 return 0;
2269 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2271 boot_set_handler = func;
2272 boot_set_opaque = opaque;
2275 int qemu_boot_set(const char *boot_devices)
2277 if (!boot_set_handler) {
2278 return -EINVAL;
2280 return boot_set_handler(boot_set_opaque, boot_devices);
2283 static int parse_bootdevices(char *devices)
2285 /* We just do some generic consistency checks */
2286 const char *p;
2287 int bitmap = 0;
2289 for (p = devices; *p != '\0'; p++) {
2290 /* Allowed boot devices are:
2291 * a-b: floppy disk drives
2292 * c-f: IDE disk drives
2293 * g-m: machine implementation dependant drives
2294 * n-p: network devices
2295 * It's up to each machine implementation to check if the given boot
2296 * devices match the actual hardware implementation and firmware
2297 * features.
2299 if (*p < 'a' || *p > 'p') {
2300 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2301 exit(1);
2303 if (bitmap & (1 << (*p - 'a'))) {
2304 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2305 exit(1);
2307 bitmap |= 1 << (*p - 'a');
2309 return bitmap;
2312 static void restore_boot_devices(void *opaque)
2314 char *standard_boot_devices = opaque;
2316 qemu_boot_set(standard_boot_devices);
2318 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2319 qemu_free(standard_boot_devices);
2322 static void numa_add(const char *optarg)
2324 char option[128];
2325 char *endptr;
2326 unsigned long long value, endvalue;
2327 int nodenr;
2329 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2330 if (!strcmp(option, "node")) {
2331 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2332 nodenr = nb_numa_nodes;
2333 } else {
2334 nodenr = strtoull(option, NULL, 10);
2337 if (get_param_value(option, 128, "mem", optarg) == 0) {
2338 node_mem[nodenr] = 0;
2339 } else {
2340 value = strtoull(option, &endptr, 0);
2341 switch (*endptr) {
2342 case 0: case 'M': case 'm':
2343 value <<= 20;
2344 break;
2345 case 'G': case 'g':
2346 value <<= 30;
2347 break;
2349 node_mem[nodenr] = value;
2351 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2352 node_cpumask[nodenr] = 0;
2353 } else {
2354 value = strtoull(option, &endptr, 10);
2355 if (value >= 64) {
2356 value = 63;
2357 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2358 } else {
2359 if (*endptr == '-') {
2360 endvalue = strtoull(endptr+1, &endptr, 10);
2361 if (endvalue >= 63) {
2362 endvalue = 62;
2363 fprintf(stderr,
2364 "only 63 CPUs in NUMA mode supported.\n");
2366 value = (1 << (endvalue + 1)) - (1 << value);
2367 } else {
2368 value = 1 << value;
2371 node_cpumask[nodenr] = value;
2373 nb_numa_nodes++;
2375 return;
2378 static void smp_parse(const char *optarg)
2380 int smp, sockets = 0, threads = 0, cores = 0;
2381 char *endptr;
2382 char option[128];
2384 smp = strtoul(optarg, &endptr, 10);
2385 if (endptr != optarg) {
2386 if (*endptr == ',') {
2387 endptr++;
2390 if (get_param_value(option, 128, "sockets", endptr) != 0)
2391 sockets = strtoull(option, NULL, 10);
2392 if (get_param_value(option, 128, "cores", endptr) != 0)
2393 cores = strtoull(option, NULL, 10);
2394 if (get_param_value(option, 128, "threads", endptr) != 0)
2395 threads = strtoull(option, NULL, 10);
2396 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2397 max_cpus = strtoull(option, NULL, 10);
2399 /* compute missing values, prefer sockets over cores over threads */
2400 if (smp == 0 || sockets == 0) {
2401 sockets = sockets > 0 ? sockets : 1;
2402 cores = cores > 0 ? cores : 1;
2403 threads = threads > 0 ? threads : 1;
2404 if (smp == 0) {
2405 smp = cores * threads * sockets;
2407 } else {
2408 if (cores == 0) {
2409 threads = threads > 0 ? threads : 1;
2410 cores = smp / (sockets * threads);
2411 } else {
2412 if (sockets) {
2413 threads = smp / (cores * sockets);
2417 smp_cpus = smp;
2418 smp_cores = cores > 0 ? cores : 1;
2419 smp_threads = threads > 0 ? threads : 1;
2420 if (max_cpus == 0)
2421 max_cpus = smp_cpus;
2424 /***********************************************************/
2425 /* USB devices */
2427 static int usb_device_add(const char *devname, int is_hotplug)
2429 const char *p;
2430 USBDevice *dev = NULL;
2432 if (!usb_enabled)
2433 return -1;
2435 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2436 dev = usbdevice_create(devname);
2437 if (dev)
2438 goto done;
2440 /* the other ones */
2441 if (strstart(devname, "host:", &p)) {
2442 dev = usb_host_device_open(p);
2443 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2444 dev = usb_bt_init(devname[2] ? hci_init(p) :
2445 bt_new_hci(qemu_find_bt_vlan(0)));
2446 } else {
2447 return -1;
2449 if (!dev)
2450 return -1;
2452 done:
2453 return 0;
2456 static int usb_device_del(const char *devname)
2458 int bus_num, addr;
2459 const char *p;
2461 if (strstart(devname, "host:", &p))
2462 return usb_host_device_close(p);
2464 if (!usb_enabled)
2465 return -1;
2467 p = strchr(devname, '.');
2468 if (!p)
2469 return -1;
2470 bus_num = strtoul(devname, NULL, 0);
2471 addr = strtoul(p + 1, NULL, 0);
2473 return usb_device_delete_addr(bus_num, addr);
2476 static int usb_parse(const char *cmdline)
2478 int r;
2479 r = usb_device_add(cmdline, 0);
2480 if (r < 0) {
2481 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2483 return r;
2486 void do_usb_add(Monitor *mon, const QDict *qdict)
2488 const char *devname = qdict_get_str(qdict, "devname");
2489 if (usb_device_add(devname, 1) < 0) {
2490 qemu_error("could not add USB device '%s'\n", devname);
2494 void do_usb_del(Monitor *mon, const QDict *qdict)
2496 const char *devname = qdict_get_str(qdict, "devname");
2497 if (usb_device_del(devname) < 0) {
2498 qemu_error("could not delete USB device '%s'\n", devname);
2502 /***********************************************************/
2503 /* PCMCIA/Cardbus */
2505 static struct pcmcia_socket_entry_s {
2506 PCMCIASocket *socket;
2507 struct pcmcia_socket_entry_s *next;
2508 } *pcmcia_sockets = 0;
2510 void pcmcia_socket_register(PCMCIASocket *socket)
2512 struct pcmcia_socket_entry_s *entry;
2514 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2515 entry->socket = socket;
2516 entry->next = pcmcia_sockets;
2517 pcmcia_sockets = entry;
2520 void pcmcia_socket_unregister(PCMCIASocket *socket)
2522 struct pcmcia_socket_entry_s *entry, **ptr;
2524 ptr = &pcmcia_sockets;
2525 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2526 if (entry->socket == socket) {
2527 *ptr = entry->next;
2528 qemu_free(entry);
2532 void pcmcia_info(Monitor *mon)
2534 struct pcmcia_socket_entry_s *iter;
2536 if (!pcmcia_sockets)
2537 monitor_printf(mon, "No PCMCIA sockets\n");
2539 for (iter = pcmcia_sockets; iter; iter = iter->next)
2540 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2541 iter->socket->attached ? iter->socket->card_string :
2542 "Empty");
2545 /***********************************************************/
2546 /* register display */
2548 struct DisplayAllocator default_allocator = {
2549 defaultallocator_create_displaysurface,
2550 defaultallocator_resize_displaysurface,
2551 defaultallocator_free_displaysurface
2554 void register_displaystate(DisplayState *ds)
2556 DisplayState **s;
2557 s = &display_state;
2558 while (*s != NULL)
2559 s = &(*s)->next;
2560 ds->next = NULL;
2561 *s = ds;
2564 DisplayState *get_displaystate(void)
2566 return display_state;
2569 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2571 if(ds->allocator == &default_allocator) ds->allocator = da;
2572 return ds->allocator;
2575 /* dumb display */
2577 static void dumb_display_init(void)
2579 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2580 ds->allocator = &default_allocator;
2581 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2582 register_displaystate(ds);
2585 /***********************************************************/
2586 /* I/O handling */
2588 typedef struct IOHandlerRecord {
2589 int fd;
2590 IOCanRWHandler *fd_read_poll;
2591 IOHandler *fd_read;
2592 IOHandler *fd_write;
2593 int deleted;
2594 void *opaque;
2595 /* temporary data */
2596 struct pollfd *ufd;
2597 struct IOHandlerRecord *next;
2598 } IOHandlerRecord;
2600 static IOHandlerRecord *first_io_handler;
2602 /* XXX: fd_read_poll should be suppressed, but an API change is
2603 necessary in the character devices to suppress fd_can_read(). */
2604 int qemu_set_fd_handler2(int fd,
2605 IOCanRWHandler *fd_read_poll,
2606 IOHandler *fd_read,
2607 IOHandler *fd_write,
2608 void *opaque)
2610 IOHandlerRecord **pioh, *ioh;
2612 if (!fd_read && !fd_write) {
2613 pioh = &first_io_handler;
2614 for(;;) {
2615 ioh = *pioh;
2616 if (ioh == NULL)
2617 break;
2618 if (ioh->fd == fd) {
2619 ioh->deleted = 1;
2620 break;
2622 pioh = &ioh->next;
2624 } else {
2625 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2626 if (ioh->fd == fd)
2627 goto found;
2629 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2630 ioh->next = first_io_handler;
2631 first_io_handler = ioh;
2632 found:
2633 ioh->fd = fd;
2634 ioh->fd_read_poll = fd_read_poll;
2635 ioh->fd_read = fd_read;
2636 ioh->fd_write = fd_write;
2637 ioh->opaque = opaque;
2638 ioh->deleted = 0;
2640 return 0;
2643 int qemu_set_fd_handler(int fd,
2644 IOHandler *fd_read,
2645 IOHandler *fd_write,
2646 void *opaque)
2648 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2651 #ifdef _WIN32
2652 /***********************************************************/
2653 /* Polling handling */
2655 typedef struct PollingEntry {
2656 PollingFunc *func;
2657 void *opaque;
2658 struct PollingEntry *next;
2659 } PollingEntry;
2661 static PollingEntry *first_polling_entry;
2663 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2665 PollingEntry **ppe, *pe;
2666 pe = qemu_mallocz(sizeof(PollingEntry));
2667 pe->func = func;
2668 pe->opaque = opaque;
2669 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2670 *ppe = pe;
2671 return 0;
2674 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2676 PollingEntry **ppe, *pe;
2677 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2678 pe = *ppe;
2679 if (pe->func == func && pe->opaque == opaque) {
2680 *ppe = pe->next;
2681 qemu_free(pe);
2682 break;
2687 /***********************************************************/
2688 /* Wait objects support */
2689 typedef struct WaitObjects {
2690 int num;
2691 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2692 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2693 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2694 } WaitObjects;
2696 static WaitObjects wait_objects = {0};
2698 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2700 WaitObjects *w = &wait_objects;
2702 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2703 return -1;
2704 w->events[w->num] = handle;
2705 w->func[w->num] = func;
2706 w->opaque[w->num] = opaque;
2707 w->num++;
2708 return 0;
2711 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2713 int i, found;
2714 WaitObjects *w = &wait_objects;
2716 found = 0;
2717 for (i = 0; i < w->num; i++) {
2718 if (w->events[i] == handle)
2719 found = 1;
2720 if (found) {
2721 w->events[i] = w->events[i + 1];
2722 w->func[i] = w->func[i + 1];
2723 w->opaque[i] = w->opaque[i + 1];
2726 if (found)
2727 w->num--;
2729 #endif
2731 /***********************************************************/
2732 /* ram save/restore */
2734 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2735 #define RAM_SAVE_FLAG_COMPRESS 0x02
2736 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2737 #define RAM_SAVE_FLAG_PAGE 0x08
2738 #define RAM_SAVE_FLAG_EOS 0x10
2740 static int is_dup_page(uint8_t *page, uint8_t ch)
2742 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2743 uint32_t *array = (uint32_t *)page;
2744 int i;
2746 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2747 if (array[i] != val)
2748 return 0;
2751 return 1;
2754 static int ram_save_block(QEMUFile *f)
2756 static ram_addr_t current_addr = 0;
2757 ram_addr_t saved_addr = current_addr;
2758 ram_addr_t addr = 0;
2759 int found = 0;
2761 while (addr < last_ram_offset) {
2762 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2763 uint8_t *p;
2765 cpu_physical_memory_reset_dirty(current_addr,
2766 current_addr + TARGET_PAGE_SIZE,
2767 MIGRATION_DIRTY_FLAG);
2769 p = qemu_get_ram_ptr(current_addr);
2771 if (is_dup_page(p, *p)) {
2772 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2773 qemu_put_byte(f, *p);
2774 } else {
2775 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2776 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2779 found = 1;
2780 break;
2782 addr += TARGET_PAGE_SIZE;
2783 current_addr = (saved_addr + addr) % last_ram_offset;
2786 return found;
2789 static uint64_t bytes_transferred;
2791 static ram_addr_t ram_save_remaining(void)
2793 ram_addr_t addr;
2794 ram_addr_t count = 0;
2796 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2797 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2798 count++;
2801 return count;
2804 uint64_t ram_bytes_remaining(void)
2806 return ram_save_remaining() * TARGET_PAGE_SIZE;
2809 uint64_t ram_bytes_transferred(void)
2811 return bytes_transferred;
2814 uint64_t ram_bytes_total(void)
2816 return last_ram_offset;
2819 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2821 ram_addr_t addr;
2822 uint64_t bytes_transferred_last;
2823 double bwidth = 0;
2824 uint64_t expected_time = 0;
2826 if (stage < 0) {
2827 cpu_physical_memory_set_dirty_tracking(0);
2828 return 0;
2831 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2832 qemu_file_set_error(f);
2833 return 0;
2836 if (stage == 1) {
2837 bytes_transferred = 0;
2839 /* Make sure all dirty bits are set */
2840 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2841 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2842 cpu_physical_memory_set_dirty(addr);
2845 /* Enable dirty memory tracking */
2846 cpu_physical_memory_set_dirty_tracking(1);
2848 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2851 bytes_transferred_last = bytes_transferred;
2852 bwidth = get_clock();
2854 while (!qemu_file_rate_limit(f)) {
2855 int ret;
2857 ret = ram_save_block(f);
2858 bytes_transferred += ret * TARGET_PAGE_SIZE;
2859 if (ret == 0) /* no more blocks */
2860 break;
2863 bwidth = get_clock() - bwidth;
2864 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2866 /* if we haven't transferred anything this round, force expected_time to a
2867 * a very high value, but without crashing */
2868 if (bwidth == 0)
2869 bwidth = 0.000001;
2871 /* try transferring iterative blocks of memory */
2872 if (stage == 3) {
2873 /* flush all remaining blocks regardless of rate limiting */
2874 while (ram_save_block(f) != 0) {
2875 bytes_transferred += TARGET_PAGE_SIZE;
2877 cpu_physical_memory_set_dirty_tracking(0);
2880 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2882 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2884 return (stage == 2) && (expected_time <= migrate_max_downtime());
2887 static int ram_load(QEMUFile *f, void *opaque, int version_id)
2889 ram_addr_t addr;
2890 int flags;
2892 if (version_id != 3)
2893 return -EINVAL;
2895 do {
2896 addr = qemu_get_be64(f);
2898 flags = addr & ~TARGET_PAGE_MASK;
2899 addr &= TARGET_PAGE_MASK;
2901 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2902 if (addr != last_ram_offset)
2903 return -EINVAL;
2906 if (flags & RAM_SAVE_FLAG_COMPRESS) {
2907 uint8_t ch = qemu_get_byte(f);
2908 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2909 #ifndef _WIN32
2910 if (ch == 0 &&
2911 (!kvm_enabled() || kvm_has_sync_mmu())) {
2912 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2914 #endif
2915 } else if (flags & RAM_SAVE_FLAG_PAGE) {
2916 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2918 if (qemu_file_has_error(f)) {
2919 return -EIO;
2921 } while (!(flags & RAM_SAVE_FLAG_EOS));
2923 return 0;
2926 void qemu_service_io(void)
2928 qemu_notify_event();
2931 /***********************************************************/
2932 /* machine registration */
2934 static QEMUMachine *first_machine = NULL;
2935 QEMUMachine *current_machine = NULL;
2937 int qemu_register_machine(QEMUMachine *m)
2939 QEMUMachine **pm;
2940 pm = &first_machine;
2941 while (*pm != NULL)
2942 pm = &(*pm)->next;
2943 m->next = NULL;
2944 *pm = m;
2945 return 0;
2948 static QEMUMachine *find_machine(const char *name)
2950 QEMUMachine *m;
2952 for(m = first_machine; m != NULL; m = m->next) {
2953 if (!strcmp(m->name, name))
2954 return m;
2955 if (m->alias && !strcmp(m->alias, name))
2956 return m;
2958 return NULL;
2961 static QEMUMachine *find_default_machine(void)
2963 QEMUMachine *m;
2965 for(m = first_machine; m != NULL; m = m->next) {
2966 if (m->is_default) {
2967 return m;
2970 return NULL;
2973 /***********************************************************/
2974 /* main execution loop */
2976 static void gui_update(void *opaque)
2978 uint64_t interval = GUI_REFRESH_INTERVAL;
2979 DisplayState *ds = opaque;
2980 DisplayChangeListener *dcl = ds->listeners;
2982 dpy_refresh(ds);
2984 while (dcl != NULL) {
2985 if (dcl->gui_timer_interval &&
2986 dcl->gui_timer_interval < interval)
2987 interval = dcl->gui_timer_interval;
2988 dcl = dcl->next;
2990 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
2993 static void nographic_update(void *opaque)
2995 uint64_t interval = GUI_REFRESH_INTERVAL;
2997 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3000 struct vm_change_state_entry {
3001 VMChangeStateHandler *cb;
3002 void *opaque;
3003 QLIST_ENTRY (vm_change_state_entry) entries;
3006 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3008 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3009 void *opaque)
3011 VMChangeStateEntry *e;
3013 e = qemu_mallocz(sizeof (*e));
3015 e->cb = cb;
3016 e->opaque = opaque;
3017 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3018 return e;
3021 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3023 QLIST_REMOVE (e, entries);
3024 qemu_free (e);
3027 static void vm_state_notify(int running, int reason)
3029 VMChangeStateEntry *e;
3031 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3032 e->cb(e->opaque, running, reason);
3036 static void resume_all_vcpus(void);
3037 static void pause_all_vcpus(void);
3039 void vm_start(void)
3041 if (!vm_running) {
3042 cpu_enable_ticks();
3043 vm_running = 1;
3044 vm_state_notify(1, 0);
3045 qemu_rearm_alarm_timer(alarm_timer);
3046 resume_all_vcpus();
3050 /* reset/shutdown handler */
3052 typedef struct QEMUResetEntry {
3053 QTAILQ_ENTRY(QEMUResetEntry) entry;
3054 QEMUResetHandler *func;
3055 void *opaque;
3056 } QEMUResetEntry;
3058 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3059 QTAILQ_HEAD_INITIALIZER(reset_handlers);
3060 static int reset_requested;
3061 static int shutdown_requested;
3062 static int powerdown_requested;
3063 static int debug_requested;
3064 static int vmstop_requested;
3066 int qemu_shutdown_requested(void)
3068 int r = shutdown_requested;
3069 shutdown_requested = 0;
3070 return r;
3073 int qemu_reset_requested(void)
3075 int r = reset_requested;
3076 reset_requested = 0;
3077 return r;
3080 int qemu_powerdown_requested(void)
3082 int r = powerdown_requested;
3083 powerdown_requested = 0;
3084 return r;
3087 static int qemu_debug_requested(void)
3089 int r = debug_requested;
3090 debug_requested = 0;
3091 return r;
3094 static int qemu_vmstop_requested(void)
3096 int r = vmstop_requested;
3097 vmstop_requested = 0;
3098 return r;
3101 static void do_vm_stop(int reason)
3103 if (vm_running) {
3104 cpu_disable_ticks();
3105 vm_running = 0;
3106 pause_all_vcpus();
3107 vm_state_notify(0, reason);
3111 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3113 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3115 re->func = func;
3116 re->opaque = opaque;
3117 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3120 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3122 QEMUResetEntry *re;
3124 QTAILQ_FOREACH(re, &reset_handlers, entry) {
3125 if (re->func == func && re->opaque == opaque) {
3126 QTAILQ_REMOVE(&reset_handlers, re, entry);
3127 qemu_free(re);
3128 return;
3133 void qemu_system_reset(void)
3135 QEMUResetEntry *re, *nre;
3137 /* reset all devices */
3138 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3139 re->func(re->opaque);
3143 void qemu_system_reset_request(void)
3145 if (no_reboot) {
3146 shutdown_requested = 1;
3147 } else {
3148 reset_requested = 1;
3150 qemu_notify_event();
3153 void qemu_system_shutdown_request(void)
3155 shutdown_requested = 1;
3156 qemu_notify_event();
3159 void qemu_system_powerdown_request(void)
3161 powerdown_requested = 1;
3162 qemu_notify_event();
3165 #ifdef CONFIG_IOTHREAD
3166 static void qemu_system_vmstop_request(int reason)
3168 vmstop_requested = reason;
3169 qemu_notify_event();
3171 #endif
3173 #ifndef _WIN32
3174 static int io_thread_fd = -1;
3176 static void qemu_event_increment(void)
3178 static const char byte = 0;
3180 if (io_thread_fd == -1)
3181 return;
3183 write(io_thread_fd, &byte, sizeof(byte));
3186 static void qemu_event_read(void *opaque)
3188 int fd = (unsigned long)opaque;
3189 ssize_t len;
3191 /* Drain the notify pipe */
3192 do {
3193 char buffer[512];
3194 len = read(fd, buffer, sizeof(buffer));
3195 } while ((len == -1 && errno == EINTR) || len > 0);
3198 static int qemu_event_init(void)
3200 int err;
3201 int fds[2];
3203 err = qemu_pipe(fds);
3204 if (err == -1)
3205 return -errno;
3207 err = fcntl_setfl(fds[0], O_NONBLOCK);
3208 if (err < 0)
3209 goto fail;
3211 err = fcntl_setfl(fds[1], O_NONBLOCK);
3212 if (err < 0)
3213 goto fail;
3215 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3216 (void *)(unsigned long)fds[0]);
3218 io_thread_fd = fds[1];
3219 return 0;
3221 fail:
3222 close(fds[0]);
3223 close(fds[1]);
3224 return err;
3226 #else
3227 HANDLE qemu_event_handle;
3229 static void dummy_event_handler(void *opaque)
3233 static int qemu_event_init(void)
3235 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3236 if (!qemu_event_handle) {
3237 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3238 return -1;
3240 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3241 return 0;
3244 static void qemu_event_increment(void)
3246 if (!SetEvent(qemu_event_handle)) {
3247 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3248 GetLastError());
3249 exit (1);
3252 #endif
3254 static int cpu_can_run(CPUState *env)
3256 if (env->stop)
3257 return 0;
3258 if (env->stopped)
3259 return 0;
3260 return 1;
3263 #ifndef CONFIG_IOTHREAD
3264 static int qemu_init_main_loop(void)
3266 return qemu_event_init();
3269 void qemu_init_vcpu(void *_env)
3271 CPUState *env = _env;
3273 env->nr_cores = smp_cores;
3274 env->nr_threads = smp_threads;
3275 if (kvm_enabled())
3276 kvm_init_vcpu(env);
3277 return;
3280 int qemu_cpu_self(void *env)
3282 return 1;
3285 static void resume_all_vcpus(void)
3289 static void pause_all_vcpus(void)
3293 void qemu_cpu_kick(void *env)
3295 return;
3298 void qemu_notify_event(void)
3300 CPUState *env = cpu_single_env;
3302 if (env) {
3303 cpu_exit(env);
3307 void qemu_mutex_lock_iothread(void) {}
3308 void qemu_mutex_unlock_iothread(void) {}
3310 void vm_stop(int reason)
3312 do_vm_stop(reason);
3315 #else /* CONFIG_IOTHREAD */
3317 #include "qemu-thread.h"
3319 QemuMutex qemu_global_mutex;
3320 static QemuMutex qemu_fair_mutex;
3322 static QemuThread io_thread;
3324 static QemuThread *tcg_cpu_thread;
3325 static QemuCond *tcg_halt_cond;
3327 static int qemu_system_ready;
3328 /* cpu creation */
3329 static QemuCond qemu_cpu_cond;
3330 /* system init */
3331 static QemuCond qemu_system_cond;
3332 static QemuCond qemu_pause_cond;
3334 static void block_io_signals(void);
3335 static void unblock_io_signals(void);
3336 static int tcg_has_work(void);
3338 static int qemu_init_main_loop(void)
3340 int ret;
3342 ret = qemu_event_init();
3343 if (ret)
3344 return ret;
3346 qemu_cond_init(&qemu_pause_cond);
3347 qemu_mutex_init(&qemu_fair_mutex);
3348 qemu_mutex_init(&qemu_global_mutex);
3349 qemu_mutex_lock(&qemu_global_mutex);
3351 unblock_io_signals();
3352 qemu_thread_self(&io_thread);
3354 return 0;
3357 static void qemu_wait_io_event(CPUState *env)
3359 while (!tcg_has_work())
3360 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3362 qemu_mutex_unlock(&qemu_global_mutex);
3365 * Users of qemu_global_mutex can be starved, having no chance
3366 * to acquire it since this path will get to it first.
3367 * So use another lock to provide fairness.
3369 qemu_mutex_lock(&qemu_fair_mutex);
3370 qemu_mutex_unlock(&qemu_fair_mutex);
3372 qemu_mutex_lock(&qemu_global_mutex);
3373 if (env->stop) {
3374 env->stop = 0;
3375 env->stopped = 1;
3376 qemu_cond_signal(&qemu_pause_cond);
3380 static int qemu_cpu_exec(CPUState *env);
3382 static void *kvm_cpu_thread_fn(void *arg)
3384 CPUState *env = arg;
3386 block_io_signals();
3387 qemu_thread_self(env->thread);
3388 if (kvm_enabled())
3389 kvm_init_vcpu(env);
3391 /* signal CPU creation */
3392 qemu_mutex_lock(&qemu_global_mutex);
3393 env->created = 1;
3394 qemu_cond_signal(&qemu_cpu_cond);
3396 /* and wait for machine initialization */
3397 while (!qemu_system_ready)
3398 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3400 while (1) {
3401 if (cpu_can_run(env))
3402 qemu_cpu_exec(env);
3403 qemu_wait_io_event(env);
3406 return NULL;
3409 static void tcg_cpu_exec(void);
3411 static void *tcg_cpu_thread_fn(void *arg)
3413 CPUState *env = arg;
3415 block_io_signals();
3416 qemu_thread_self(env->thread);
3418 /* signal CPU creation */
3419 qemu_mutex_lock(&qemu_global_mutex);
3420 for (env = first_cpu; env != NULL; env = env->next_cpu)
3421 env->created = 1;
3422 qemu_cond_signal(&qemu_cpu_cond);
3424 /* and wait for machine initialization */
3425 while (!qemu_system_ready)
3426 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3428 while (1) {
3429 tcg_cpu_exec();
3430 qemu_wait_io_event(cur_cpu);
3433 return NULL;
3436 void qemu_cpu_kick(void *_env)
3438 CPUState *env = _env;
3439 qemu_cond_broadcast(env->halt_cond);
3440 if (kvm_enabled())
3441 qemu_thread_signal(env->thread, SIGUSR1);
3444 int qemu_cpu_self(void *_env)
3446 CPUState *env = _env;
3447 QemuThread this;
3449 qemu_thread_self(&this);
3451 return qemu_thread_equal(&this, env->thread);
3454 static void cpu_signal(int sig)
3456 if (cpu_single_env)
3457 cpu_exit(cpu_single_env);
3460 static void block_io_signals(void)
3462 sigset_t set;
3463 struct sigaction sigact;
3465 sigemptyset(&set);
3466 sigaddset(&set, SIGUSR2);
3467 sigaddset(&set, SIGIO);
3468 sigaddset(&set, SIGALRM);
3469 pthread_sigmask(SIG_BLOCK, &set, NULL);
3471 sigemptyset(&set);
3472 sigaddset(&set, SIGUSR1);
3473 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3475 memset(&sigact, 0, sizeof(sigact));
3476 sigact.sa_handler = cpu_signal;
3477 sigaction(SIGUSR1, &sigact, NULL);
3480 static void unblock_io_signals(void)
3482 sigset_t set;
3484 sigemptyset(&set);
3485 sigaddset(&set, SIGUSR2);
3486 sigaddset(&set, SIGIO);
3487 sigaddset(&set, SIGALRM);
3488 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3490 sigemptyset(&set);
3491 sigaddset(&set, SIGUSR1);
3492 pthread_sigmask(SIG_BLOCK, &set, NULL);
3495 static void qemu_signal_lock(unsigned int msecs)
3497 qemu_mutex_lock(&qemu_fair_mutex);
3499 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3500 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3501 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3502 break;
3504 qemu_mutex_unlock(&qemu_fair_mutex);
3507 void qemu_mutex_lock_iothread(void)
3509 if (kvm_enabled()) {
3510 qemu_mutex_lock(&qemu_fair_mutex);
3511 qemu_mutex_lock(&qemu_global_mutex);
3512 qemu_mutex_unlock(&qemu_fair_mutex);
3513 } else
3514 qemu_signal_lock(100);
3517 void qemu_mutex_unlock_iothread(void)
3519 qemu_mutex_unlock(&qemu_global_mutex);
3522 static int all_vcpus_paused(void)
3524 CPUState *penv = first_cpu;
3526 while (penv) {
3527 if (!penv->stopped)
3528 return 0;
3529 penv = (CPUState *)penv->next_cpu;
3532 return 1;
3535 static void pause_all_vcpus(void)
3537 CPUState *penv = first_cpu;
3539 while (penv) {
3540 penv->stop = 1;
3541 qemu_thread_signal(penv->thread, SIGUSR1);
3542 qemu_cpu_kick(penv);
3543 penv = (CPUState *)penv->next_cpu;
3546 while (!all_vcpus_paused()) {
3547 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3548 penv = first_cpu;
3549 while (penv) {
3550 qemu_thread_signal(penv->thread, SIGUSR1);
3551 penv = (CPUState *)penv->next_cpu;
3556 static void resume_all_vcpus(void)
3558 CPUState *penv = first_cpu;
3560 while (penv) {
3561 penv->stop = 0;
3562 penv->stopped = 0;
3563 qemu_thread_signal(penv->thread, SIGUSR1);
3564 qemu_cpu_kick(penv);
3565 penv = (CPUState *)penv->next_cpu;
3569 static void tcg_init_vcpu(void *_env)
3571 CPUState *env = _env;
3572 /* share a single thread for all cpus with TCG */
3573 if (!tcg_cpu_thread) {
3574 env->thread = qemu_mallocz(sizeof(QemuThread));
3575 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3576 qemu_cond_init(env->halt_cond);
3577 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3578 while (env->created == 0)
3579 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3580 tcg_cpu_thread = env->thread;
3581 tcg_halt_cond = env->halt_cond;
3582 } else {
3583 env->thread = tcg_cpu_thread;
3584 env->halt_cond = tcg_halt_cond;
3588 static void kvm_start_vcpu(CPUState *env)
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, kvm_cpu_thread_fn, env);
3594 while (env->created == 0)
3595 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3598 void qemu_init_vcpu(void *_env)
3600 CPUState *env = _env;
3602 env->nr_cores = smp_cores;
3603 env->nr_threads = smp_threads;
3604 if (kvm_enabled())
3605 kvm_start_vcpu(env);
3606 else
3607 tcg_init_vcpu(env);
3610 void qemu_notify_event(void)
3612 qemu_event_increment();
3615 void vm_stop(int reason)
3617 QemuThread me;
3618 qemu_thread_self(&me);
3620 if (!qemu_thread_equal(&me, &io_thread)) {
3621 qemu_system_vmstop_request(reason);
3623 * FIXME: should not return to device code in case
3624 * vm_stop() has been requested.
3626 if (cpu_single_env) {
3627 cpu_exit(cpu_single_env);
3628 cpu_single_env->stop = 1;
3630 return;
3632 do_vm_stop(reason);
3635 #endif
3638 #ifdef _WIN32
3639 static void host_main_loop_wait(int *timeout)
3641 int ret, ret2, i;
3642 PollingEntry *pe;
3645 /* XXX: need to suppress polling by better using win32 events */
3646 ret = 0;
3647 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3648 ret |= pe->func(pe->opaque);
3650 if (ret == 0) {
3651 int err;
3652 WaitObjects *w = &wait_objects;
3654 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3655 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3656 if (w->func[ret - WAIT_OBJECT_0])
3657 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3659 /* Check for additional signaled events */
3660 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3662 /* Check if event is signaled */
3663 ret2 = WaitForSingleObject(w->events[i], 0);
3664 if(ret2 == WAIT_OBJECT_0) {
3665 if (w->func[i])
3666 w->func[i](w->opaque[i]);
3667 } else if (ret2 == WAIT_TIMEOUT) {
3668 } else {
3669 err = GetLastError();
3670 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3673 } else if (ret == WAIT_TIMEOUT) {
3674 } else {
3675 err = GetLastError();
3676 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3680 *timeout = 0;
3682 #else
3683 static void host_main_loop_wait(int *timeout)
3686 #endif
3688 void main_loop_wait(int timeout)
3690 IOHandlerRecord *ioh;
3691 fd_set rfds, wfds, xfds;
3692 int ret, nfds;
3693 struct timeval tv;
3695 qemu_bh_update_timeout(&timeout);
3697 host_main_loop_wait(&timeout);
3699 /* poll any events */
3700 /* XXX: separate device handlers from system ones */
3701 nfds = -1;
3702 FD_ZERO(&rfds);
3703 FD_ZERO(&wfds);
3704 FD_ZERO(&xfds);
3705 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3706 if (ioh->deleted)
3707 continue;
3708 if (ioh->fd_read &&
3709 (!ioh->fd_read_poll ||
3710 ioh->fd_read_poll(ioh->opaque) != 0)) {
3711 FD_SET(ioh->fd, &rfds);
3712 if (ioh->fd > nfds)
3713 nfds = ioh->fd;
3715 if (ioh->fd_write) {
3716 FD_SET(ioh->fd, &wfds);
3717 if (ioh->fd > nfds)
3718 nfds = ioh->fd;
3722 tv.tv_sec = timeout / 1000;
3723 tv.tv_usec = (timeout % 1000) * 1000;
3725 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3727 qemu_mutex_unlock_iothread();
3728 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3729 qemu_mutex_lock_iothread();
3730 if (ret > 0) {
3731 IOHandlerRecord **pioh;
3733 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3734 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3735 ioh->fd_read(ioh->opaque);
3737 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3738 ioh->fd_write(ioh->opaque);
3742 /* remove deleted IO handlers */
3743 pioh = &first_io_handler;
3744 while (*pioh) {
3745 ioh = *pioh;
3746 if (ioh->deleted) {
3747 *pioh = ioh->next;
3748 qemu_free(ioh);
3749 } else
3750 pioh = &ioh->next;
3754 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3756 /* rearm timer, if not periodic */
3757 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3758 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3759 qemu_rearm_alarm_timer(alarm_timer);
3762 /* vm time timers */
3763 if (vm_running) {
3764 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3765 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3766 qemu_get_clock(vm_clock));
3769 /* real time timers */
3770 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3771 qemu_get_clock(rt_clock));
3773 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3774 qemu_get_clock(host_clock));
3776 /* Check bottom-halves last in case any of the earlier events triggered
3777 them. */
3778 qemu_bh_poll();
3782 static int qemu_cpu_exec(CPUState *env)
3784 int ret;
3785 #ifdef CONFIG_PROFILER
3786 int64_t ti;
3787 #endif
3789 #ifdef CONFIG_PROFILER
3790 ti = profile_getclock();
3791 #endif
3792 if (use_icount) {
3793 int64_t count;
3794 int decr;
3795 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3796 env->icount_decr.u16.low = 0;
3797 env->icount_extra = 0;
3798 count = qemu_next_deadline();
3799 count = (count + (1 << icount_time_shift) - 1)
3800 >> icount_time_shift;
3801 qemu_icount += count;
3802 decr = (count > 0xffff) ? 0xffff : count;
3803 count -= decr;
3804 env->icount_decr.u16.low = decr;
3805 env->icount_extra = count;
3807 ret = cpu_exec(env);
3808 #ifdef CONFIG_PROFILER
3809 qemu_time += profile_getclock() - ti;
3810 #endif
3811 if (use_icount) {
3812 /* Fold pending instructions back into the
3813 instruction counter, and clear the interrupt flag. */
3814 qemu_icount -= (env->icount_decr.u16.low
3815 + env->icount_extra);
3816 env->icount_decr.u32 = 0;
3817 env->icount_extra = 0;
3819 return ret;
3822 static void tcg_cpu_exec(void)
3824 int ret = 0;
3826 if (next_cpu == NULL)
3827 next_cpu = first_cpu;
3828 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3829 CPUState *env = cur_cpu = next_cpu;
3831 if (!vm_running)
3832 break;
3833 if (timer_alarm_pending) {
3834 timer_alarm_pending = 0;
3835 break;
3837 if (cpu_can_run(env))
3838 ret = qemu_cpu_exec(env);
3839 if (ret == EXCP_DEBUG) {
3840 gdb_set_stop_cpu(env);
3841 debug_requested = 1;
3842 break;
3847 static int cpu_has_work(CPUState *env)
3849 if (env->stop)
3850 return 1;
3851 if (env->stopped)
3852 return 0;
3853 if (!env->halted)
3854 return 1;
3855 if (qemu_cpu_has_work(env))
3856 return 1;
3857 return 0;
3860 static int tcg_has_work(void)
3862 CPUState *env;
3864 for (env = first_cpu; env != NULL; env = env->next_cpu)
3865 if (cpu_has_work(env))
3866 return 1;
3867 return 0;
3870 static int qemu_calculate_timeout(void)
3872 #ifndef CONFIG_IOTHREAD
3873 int timeout;
3875 if (!vm_running)
3876 timeout = 5000;
3877 else if (tcg_has_work())
3878 timeout = 0;
3879 else if (!use_icount)
3880 timeout = 5000;
3881 else {
3882 /* XXX: use timeout computed from timers */
3883 int64_t add;
3884 int64_t delta;
3885 /* Advance virtual time to the next event. */
3886 if (use_icount == 1) {
3887 /* When not using an adaptive execution frequency
3888 we tend to get badly out of sync with real time,
3889 so just delay for a reasonable amount of time. */
3890 delta = 0;
3891 } else {
3892 delta = cpu_get_icount() - cpu_get_clock();
3894 if (delta > 0) {
3895 /* If virtual time is ahead of real time then just
3896 wait for IO. */
3897 timeout = (delta / 1000000) + 1;
3898 } else {
3899 /* Wait for either IO to occur or the next
3900 timer event. */
3901 add = qemu_next_deadline();
3902 /* We advance the timer before checking for IO.
3903 Limit the amount we advance so that early IO
3904 activity won't get the guest too far ahead. */
3905 if (add > 10000000)
3906 add = 10000000;
3907 delta += add;
3908 add = (add + (1 << icount_time_shift) - 1)
3909 >> icount_time_shift;
3910 qemu_icount += add;
3911 timeout = delta / 1000000;
3912 if (timeout < 0)
3913 timeout = 0;
3917 return timeout;
3918 #else /* CONFIG_IOTHREAD */
3919 return 1000;
3920 #endif
3923 static int vm_can_run(void)
3925 if (powerdown_requested)
3926 return 0;
3927 if (reset_requested)
3928 return 0;
3929 if (shutdown_requested)
3930 return 0;
3931 if (debug_requested)
3932 return 0;
3933 return 1;
3936 qemu_irq qemu_system_powerdown;
3938 static void main_loop(void)
3940 int r;
3942 #ifdef CONFIG_IOTHREAD
3943 qemu_system_ready = 1;
3944 qemu_cond_broadcast(&qemu_system_cond);
3945 #endif
3947 for (;;) {
3948 do {
3949 #ifdef CONFIG_PROFILER
3950 int64_t ti;
3951 #endif
3952 #ifndef CONFIG_IOTHREAD
3953 tcg_cpu_exec();
3954 #endif
3955 #ifdef CONFIG_PROFILER
3956 ti = profile_getclock();
3957 #endif
3958 main_loop_wait(qemu_calculate_timeout());
3959 #ifdef CONFIG_PROFILER
3960 dev_time += profile_getclock() - ti;
3961 #endif
3962 } while (vm_can_run());
3964 if (qemu_debug_requested()) {
3965 monitor_protocol_event(QEVENT_DEBUG, NULL);
3966 vm_stop(EXCP_DEBUG);
3968 if (qemu_shutdown_requested()) {
3969 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
3970 if (no_shutdown) {
3971 vm_stop(0);
3972 no_shutdown = 0;
3973 } else
3974 break;
3976 if (qemu_reset_requested()) {
3977 monitor_protocol_event(QEVENT_RESET, NULL);
3978 pause_all_vcpus();
3979 qemu_system_reset();
3980 resume_all_vcpus();
3982 if (qemu_powerdown_requested()) {
3983 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
3984 qemu_irq_raise(qemu_system_powerdown);
3986 if ((r = qemu_vmstop_requested())) {
3987 monitor_protocol_event(QEVENT_STOP, NULL);
3988 vm_stop(r);
3991 pause_all_vcpus();
3994 static void version(void)
3996 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
3999 static void help(int exitcode)
4001 version();
4002 printf("usage: %s [options] [disk_image]\n"
4003 "\n"
4004 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4005 "\n"
4006 #define DEF(option, opt_arg, opt_enum, opt_help) \
4007 opt_help
4008 #define DEFHEADING(text) stringify(text) "\n"
4009 #include "qemu-options.h"
4010 #undef DEF
4011 #undef DEFHEADING
4012 #undef GEN_DOCS
4013 "\n"
4014 "During emulation, the following keys are useful:\n"
4015 "ctrl-alt-f toggle full screen\n"
4016 "ctrl-alt-n switch to virtual console 'n'\n"
4017 "ctrl-alt toggle mouse and keyboard grab\n"
4018 "\n"
4019 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4021 "qemu",
4022 DEFAULT_RAM_SIZE,
4023 #ifndef _WIN32
4024 DEFAULT_NETWORK_SCRIPT,
4025 DEFAULT_NETWORK_DOWN_SCRIPT,
4026 #endif
4027 DEFAULT_GDBSTUB_PORT,
4028 "/tmp/qemu.log");
4029 exit(exitcode);
4032 #define HAS_ARG 0x0001
4034 enum {
4035 #define DEF(option, opt_arg, opt_enum, opt_help) \
4036 opt_enum,
4037 #define DEFHEADING(text)
4038 #include "qemu-options.h"
4039 #undef DEF
4040 #undef DEFHEADING
4041 #undef GEN_DOCS
4044 typedef struct QEMUOption {
4045 const char *name;
4046 int flags;
4047 int index;
4048 } QEMUOption;
4050 static const QEMUOption qemu_options[] = {
4051 { "h", 0, QEMU_OPTION_h },
4052 #define DEF(option, opt_arg, opt_enum, opt_help) \
4053 { option, opt_arg, opt_enum },
4054 #define DEFHEADING(text)
4055 #include "qemu-options.h"
4056 #undef DEF
4057 #undef DEFHEADING
4058 #undef GEN_DOCS
4059 { NULL },
4062 #ifdef HAS_AUDIO
4063 struct soundhw soundhw[] = {
4064 #ifdef HAS_AUDIO_CHOICE
4065 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4067 "pcspk",
4068 "PC speaker",
4071 { .init_isa = pcspk_audio_init }
4073 #endif
4075 #ifdef CONFIG_SB16
4077 "sb16",
4078 "Creative Sound Blaster 16",
4081 { .init_isa = SB16_init }
4083 #endif
4085 #ifdef CONFIG_CS4231A
4087 "cs4231a",
4088 "CS4231A",
4091 { .init_isa = cs4231a_init }
4093 #endif
4095 #ifdef CONFIG_ADLIB
4097 "adlib",
4098 #ifdef HAS_YMF262
4099 "Yamaha YMF262 (OPL3)",
4100 #else
4101 "Yamaha YM3812 (OPL2)",
4102 #endif
4105 { .init_isa = Adlib_init }
4107 #endif
4109 #ifdef CONFIG_GUS
4111 "gus",
4112 "Gravis Ultrasound GF1",
4115 { .init_isa = GUS_init }
4117 #endif
4119 #ifdef CONFIG_AC97
4121 "ac97",
4122 "Intel 82801AA AC97 Audio",
4125 { .init_pci = ac97_init }
4127 #endif
4129 #ifdef CONFIG_ES1370
4131 "es1370",
4132 "ENSONIQ AudioPCI ES1370",
4135 { .init_pci = es1370_init }
4137 #endif
4139 #endif /* HAS_AUDIO_CHOICE */
4141 { NULL, NULL, 0, 0, { NULL } }
4144 static void select_soundhw (const char *optarg)
4146 struct soundhw *c;
4148 if (*optarg == '?') {
4149 show_valid_cards:
4151 printf ("Valid sound card names (comma separated):\n");
4152 for (c = soundhw; c->name; ++c) {
4153 printf ("%-11s %s\n", c->name, c->descr);
4155 printf ("\n-soundhw all will enable all of the above\n");
4156 exit (*optarg != '?');
4158 else {
4159 size_t l;
4160 const char *p;
4161 char *e;
4162 int bad_card = 0;
4164 if (!strcmp (optarg, "all")) {
4165 for (c = soundhw; c->name; ++c) {
4166 c->enabled = 1;
4168 return;
4171 p = optarg;
4172 while (*p) {
4173 e = strchr (p, ',');
4174 l = !e ? strlen (p) : (size_t) (e - p);
4176 for (c = soundhw; c->name; ++c) {
4177 if (!strncmp (c->name, p, l) && !c->name[l]) {
4178 c->enabled = 1;
4179 break;
4183 if (!c->name) {
4184 if (l > 80) {
4185 fprintf (stderr,
4186 "Unknown sound card name (too big to show)\n");
4188 else {
4189 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4190 (int) l, p);
4192 bad_card = 1;
4194 p += l + (e != NULL);
4197 if (bad_card)
4198 goto show_valid_cards;
4201 #endif
4203 static void select_vgahw (const char *p)
4205 const char *opts;
4207 default_vga = 0;
4208 vga_interface_type = VGA_NONE;
4209 if (strstart(p, "std", &opts)) {
4210 vga_interface_type = VGA_STD;
4211 } else if (strstart(p, "cirrus", &opts)) {
4212 vga_interface_type = VGA_CIRRUS;
4213 } else if (strstart(p, "vmware", &opts)) {
4214 vga_interface_type = VGA_VMWARE;
4215 } else if (strstart(p, "xenfb", &opts)) {
4216 vga_interface_type = VGA_XENFB;
4217 } else if (!strstart(p, "none", &opts)) {
4218 invalid_vga:
4219 fprintf(stderr, "Unknown vga type: %s\n", p);
4220 exit(1);
4222 while (*opts) {
4223 const char *nextopt;
4225 if (strstart(opts, ",retrace=", &nextopt)) {
4226 opts = nextopt;
4227 if (strstart(opts, "dumb", &nextopt))
4228 vga_retrace_method = VGA_RETRACE_DUMB;
4229 else if (strstart(opts, "precise", &nextopt))
4230 vga_retrace_method = VGA_RETRACE_PRECISE;
4231 else goto invalid_vga;
4232 } else goto invalid_vga;
4233 opts = nextopt;
4237 #ifdef TARGET_I386
4238 static int balloon_parse(const char *arg)
4240 QemuOpts *opts;
4242 if (strcmp(arg, "none") == 0) {
4243 return 0;
4246 if (!strncmp(arg, "virtio", 6)) {
4247 if (arg[6] == ',') {
4248 /* have params -> parse them */
4249 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4250 if (!opts)
4251 return -1;
4252 } else {
4253 /* create empty opts */
4254 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4256 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4257 return 0;
4260 return -1;
4262 #endif
4264 #ifdef _WIN32
4265 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4267 exit(STATUS_CONTROL_C_EXIT);
4268 return TRUE;
4270 #endif
4272 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4274 int ret;
4276 if(strlen(str) != 36)
4277 return -1;
4279 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4280 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4281 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4283 if(ret != 16)
4284 return -1;
4286 #ifdef TARGET_I386
4287 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4288 #endif
4290 return 0;
4293 #ifndef _WIN32
4295 static void termsig_handler(int signal)
4297 qemu_system_shutdown_request();
4300 static void sigchld_handler(int signal)
4302 waitpid(-1, NULL, WNOHANG);
4305 static void sighandler_setup(void)
4307 struct sigaction act;
4309 memset(&act, 0, sizeof(act));
4310 act.sa_handler = termsig_handler;
4311 sigaction(SIGINT, &act, NULL);
4312 sigaction(SIGHUP, &act, NULL);
4313 sigaction(SIGTERM, &act, NULL);
4315 act.sa_handler = sigchld_handler;
4316 act.sa_flags = SA_NOCLDSTOP;
4317 sigaction(SIGCHLD, &act, NULL);
4320 #endif
4322 #ifdef _WIN32
4323 /* Look for support files in the same directory as the executable. */
4324 static char *find_datadir(const char *argv0)
4326 char *p;
4327 char buf[MAX_PATH];
4328 DWORD len;
4330 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4331 if (len == 0) {
4332 return NULL;
4335 buf[len] = 0;
4336 p = buf + len - 1;
4337 while (p != buf && *p != '\\')
4338 p--;
4339 *p = 0;
4340 if (access(buf, R_OK) == 0) {
4341 return qemu_strdup(buf);
4343 return NULL;
4345 #else /* !_WIN32 */
4347 /* Find a likely location for support files using the location of the binary.
4348 For installed binaries this will be "$bindir/../share/qemu". When
4349 running from the build tree this will be "$bindir/../pc-bios". */
4350 #define SHARE_SUFFIX "/share/qemu"
4351 #define BUILD_SUFFIX "/pc-bios"
4352 static char *find_datadir(const char *argv0)
4354 char *dir;
4355 char *p = NULL;
4356 char *res;
4357 char buf[PATH_MAX];
4358 size_t max_len;
4360 #if defined(__linux__)
4362 int len;
4363 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4364 if (len > 0) {
4365 buf[len] = 0;
4366 p = buf;
4369 #elif defined(__FreeBSD__)
4371 int len;
4372 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4373 if (len > 0) {
4374 buf[len] = 0;
4375 p = buf;
4378 #endif
4379 /* If we don't have any way of figuring out the actual executable
4380 location then try argv[0]. */
4381 if (!p) {
4382 p = realpath(argv0, buf);
4383 if (!p) {
4384 return NULL;
4387 dir = dirname(p);
4388 dir = dirname(dir);
4390 max_len = strlen(dir) +
4391 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4392 res = qemu_mallocz(max_len);
4393 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4394 if (access(res, R_OK)) {
4395 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4396 if (access(res, R_OK)) {
4397 qemu_free(res);
4398 res = NULL;
4402 return res;
4404 #undef SHARE_SUFFIX
4405 #undef BUILD_SUFFIX
4406 #endif
4408 char *qemu_find_file(int type, const char *name)
4410 int len;
4411 const char *subdir;
4412 char *buf;
4414 /* If name contains path separators then try it as a straight path. */
4415 if ((strchr(name, '/') || strchr(name, '\\'))
4416 && access(name, R_OK) == 0) {
4417 return qemu_strdup(name);
4419 switch (type) {
4420 case QEMU_FILE_TYPE_BIOS:
4421 subdir = "";
4422 break;
4423 case QEMU_FILE_TYPE_KEYMAP:
4424 subdir = "keymaps/";
4425 break;
4426 default:
4427 abort();
4429 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4430 buf = qemu_mallocz(len);
4431 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4432 if (access(buf, R_OK)) {
4433 qemu_free(buf);
4434 return NULL;
4436 return buf;
4439 static int device_init_func(QemuOpts *opts, void *opaque)
4441 DeviceState *dev;
4443 dev = qdev_device_add(opts);
4444 if (!dev)
4445 return -1;
4446 return 0;
4449 static int chardev_init_func(QemuOpts *opts, void *opaque)
4451 CharDriverState *chr;
4453 chr = qemu_chr_open_opts(opts, NULL);
4454 if (!chr)
4455 return -1;
4456 return 0;
4459 static int mon_init_func(QemuOpts *opts, void *opaque)
4461 CharDriverState *chr;
4462 const char *chardev;
4463 const char *mode;
4464 int flags;
4466 mode = qemu_opt_get(opts, "mode");
4467 if (mode == NULL) {
4468 mode = "readline";
4470 if (strcmp(mode, "readline") == 0) {
4471 flags = MONITOR_USE_READLINE;
4472 } else if (strcmp(mode, "control") == 0) {
4473 flags = MONITOR_USE_CONTROL;
4474 } else {
4475 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4476 exit(1);
4479 if (qemu_opt_get_bool(opts, "default", 0))
4480 flags |= MONITOR_IS_DEFAULT;
4482 chardev = qemu_opt_get(opts, "chardev");
4483 chr = qemu_chr_find(chardev);
4484 if (chr == NULL) {
4485 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4486 exit(1);
4489 monitor_init(chr, flags);
4490 return 0;
4493 static void monitor_parse(const char *optarg, const char *mode)
4495 static int monitor_device_index = 0;
4496 QemuOpts *opts;
4497 const char *p;
4498 char label[32];
4499 int def = 0;
4501 if (strstart(optarg, "chardev:", &p)) {
4502 snprintf(label, sizeof(label), "%s", p);
4503 } else {
4504 if (monitor_device_index) {
4505 snprintf(label, sizeof(label), "monitor%d",
4506 monitor_device_index);
4507 } else {
4508 snprintf(label, sizeof(label), "monitor");
4509 def = 1;
4511 opts = qemu_chr_parse_compat(label, optarg);
4512 if (!opts) {
4513 fprintf(stderr, "parse error: %s\n", optarg);
4514 exit(1);
4518 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4519 if (!opts) {
4520 fprintf(stderr, "duplicate chardev: %s\n", label);
4521 exit(1);
4523 qemu_opt_set(opts, "mode", mode);
4524 qemu_opt_set(opts, "chardev", label);
4525 if (def)
4526 qemu_opt_set(opts, "default", "on");
4527 monitor_device_index++;
4530 struct device_config {
4531 enum {
4532 DEV_USB, /* -usbdevice */
4533 DEV_BT, /* -bt */
4534 DEV_SERIAL, /* -serial */
4535 DEV_PARALLEL, /* -parallel */
4536 DEV_VIRTCON, /* -virtioconsole */
4537 DEV_DEBUGCON, /* -debugcon */
4538 } type;
4539 const char *cmdline;
4540 QTAILQ_ENTRY(device_config) next;
4542 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4544 static void add_device_config(int type, const char *cmdline)
4546 struct device_config *conf;
4548 conf = qemu_mallocz(sizeof(*conf));
4549 conf->type = type;
4550 conf->cmdline = cmdline;
4551 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4554 static int foreach_device_config(int type, int (*func)(const char *cmdline))
4556 struct device_config *conf;
4557 int rc;
4559 QTAILQ_FOREACH(conf, &device_configs, next) {
4560 if (conf->type != type)
4561 continue;
4562 rc = func(conf->cmdline);
4563 if (0 != rc)
4564 return rc;
4566 return 0;
4569 static int serial_parse(const char *devname)
4571 static int index = 0;
4572 char label[32];
4574 if (strcmp(devname, "none") == 0)
4575 return 0;
4576 if (index == MAX_SERIAL_PORTS) {
4577 fprintf(stderr, "qemu: too many serial ports\n");
4578 exit(1);
4580 snprintf(label, sizeof(label), "serial%d", index);
4581 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4582 if (!serial_hds[index]) {
4583 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4584 devname, strerror(errno));
4585 return -1;
4587 index++;
4588 return 0;
4591 static int parallel_parse(const char *devname)
4593 static int index = 0;
4594 char label[32];
4596 if (strcmp(devname, "none") == 0)
4597 return 0;
4598 if (index == MAX_PARALLEL_PORTS) {
4599 fprintf(stderr, "qemu: too many parallel ports\n");
4600 exit(1);
4602 snprintf(label, sizeof(label), "parallel%d", index);
4603 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4604 if (!parallel_hds[index]) {
4605 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4606 devname, strerror(errno));
4607 return -1;
4609 index++;
4610 return 0;
4613 static int virtcon_parse(const char *devname)
4615 static int index = 0;
4616 char label[32];
4618 if (strcmp(devname, "none") == 0)
4619 return 0;
4620 if (index == MAX_VIRTIO_CONSOLES) {
4621 fprintf(stderr, "qemu: too many virtio consoles\n");
4622 exit(1);
4624 snprintf(label, sizeof(label), "virtcon%d", index);
4625 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4626 if (!virtcon_hds[index]) {
4627 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4628 devname, strerror(errno));
4629 return -1;
4631 index++;
4632 return 0;
4635 static int debugcon_parse(const char *devname)
4637 QemuOpts *opts;
4639 if (!qemu_chr_open("debugcon", devname, NULL)) {
4640 exit(1);
4642 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4643 if (!opts) {
4644 fprintf(stderr, "qemu: already have a debugcon device\n");
4645 exit(1);
4647 qemu_opt_set(opts, "driver", "isa-debugcon");
4648 qemu_opt_set(opts, "chardev", "debugcon");
4649 return 0;
4652 int main(int argc, char **argv, char **envp)
4654 const char *gdbstub_dev = NULL;
4655 uint32_t boot_devices_bitmap = 0;
4656 int i;
4657 int snapshot, linux_boot, net_boot;
4658 const char *initrd_filename;
4659 const char *kernel_filename, *kernel_cmdline;
4660 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4661 DisplayState *ds;
4662 DisplayChangeListener *dcl;
4663 int cyls, heads, secs, translation;
4664 QemuOpts *hda_opts = NULL, *opts;
4665 int optind;
4666 const char *r, *optarg;
4667 const char *loadvm = NULL;
4668 QEMUMachine *machine;
4669 const char *cpu_model;
4670 #ifndef _WIN32
4671 int fds[2];
4672 #endif
4673 int tb_size;
4674 const char *pid_file = NULL;
4675 const char *incoming = NULL;
4676 #ifndef _WIN32
4677 int fd = 0;
4678 struct passwd *pwd = NULL;
4679 const char *chroot_dir = NULL;
4680 const char *run_as = NULL;
4681 #endif
4682 CPUState *env;
4683 int show_vnc_port = 0;
4685 init_clocks();
4687 qemu_errors_to_file(stderr);
4688 qemu_cache_utils_init(envp);
4690 QLIST_INIT (&vm_change_state_head);
4691 #ifndef _WIN32
4693 struct sigaction act;
4694 sigfillset(&act.sa_mask);
4695 act.sa_flags = 0;
4696 act.sa_handler = SIG_IGN;
4697 sigaction(SIGPIPE, &act, NULL);
4699 #else
4700 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4701 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4702 QEMU to run on a single CPU */
4704 HANDLE h;
4705 DWORD mask, smask;
4706 int i;
4707 h = GetCurrentProcess();
4708 if (GetProcessAffinityMask(h, &mask, &smask)) {
4709 for(i = 0; i < 32; i++) {
4710 if (mask & (1 << i))
4711 break;
4713 if (i != 32) {
4714 mask = 1 << i;
4715 SetProcessAffinityMask(h, mask);
4719 #endif
4721 module_call_init(MODULE_INIT_MACHINE);
4722 machine = find_default_machine();
4723 cpu_model = NULL;
4724 initrd_filename = NULL;
4725 ram_size = 0;
4726 snapshot = 0;
4727 kernel_filename = NULL;
4728 kernel_cmdline = "";
4729 cyls = heads = secs = 0;
4730 translation = BIOS_ATA_TRANSLATION_AUTO;
4732 for (i = 0; i < MAX_NODES; i++) {
4733 node_mem[i] = 0;
4734 node_cpumask[i] = 0;
4737 nb_numa_nodes = 0;
4738 nb_nics = 0;
4740 tb_size = 0;
4741 autostart= 1;
4743 optind = 1;
4744 for(;;) {
4745 if (optind >= argc)
4746 break;
4747 r = argv[optind];
4748 if (r[0] != '-') {
4749 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4750 } else {
4751 const QEMUOption *popt;
4753 optind++;
4754 /* Treat --foo the same as -foo. */
4755 if (r[1] == '-')
4756 r++;
4757 popt = qemu_options;
4758 for(;;) {
4759 if (!popt->name) {
4760 fprintf(stderr, "%s: invalid option -- '%s'\n",
4761 argv[0], r);
4762 exit(1);
4764 if (!strcmp(popt->name, r + 1))
4765 break;
4766 popt++;
4768 if (popt->flags & HAS_ARG) {
4769 if (optind >= argc) {
4770 fprintf(stderr, "%s: option '%s' requires an argument\n",
4771 argv[0], r);
4772 exit(1);
4774 optarg = argv[optind++];
4775 } else {
4776 optarg = NULL;
4779 switch(popt->index) {
4780 case QEMU_OPTION_M:
4781 machine = find_machine(optarg);
4782 if (!machine) {
4783 QEMUMachine *m;
4784 printf("Supported machines are:\n");
4785 for(m = first_machine; m != NULL; m = m->next) {
4786 if (m->alias)
4787 printf("%-10s %s (alias of %s)\n",
4788 m->alias, m->desc, m->name);
4789 printf("%-10s %s%s\n",
4790 m->name, m->desc,
4791 m->is_default ? " (default)" : "");
4793 exit(*optarg != '?');
4795 break;
4796 case QEMU_OPTION_cpu:
4797 /* hw initialization will check this */
4798 if (*optarg == '?') {
4799 /* XXX: implement xxx_cpu_list for targets that still miss it */
4800 #if defined(cpu_list)
4801 cpu_list(stdout, &fprintf);
4802 #endif
4803 exit(0);
4804 } else {
4805 cpu_model = optarg;
4807 break;
4808 case QEMU_OPTION_initrd:
4809 initrd_filename = optarg;
4810 break;
4811 case QEMU_OPTION_hda:
4812 if (cyls == 0)
4813 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4814 else
4815 hda_opts = drive_add(optarg, HD_ALIAS
4816 ",cyls=%d,heads=%d,secs=%d%s",
4817 0, cyls, heads, secs,
4818 translation == BIOS_ATA_TRANSLATION_LBA ?
4819 ",trans=lba" :
4820 translation == BIOS_ATA_TRANSLATION_NONE ?
4821 ",trans=none" : "");
4822 break;
4823 case QEMU_OPTION_hdb:
4824 case QEMU_OPTION_hdc:
4825 case QEMU_OPTION_hdd:
4826 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4827 break;
4828 case QEMU_OPTION_drive:
4829 drive_add(NULL, "%s", optarg);
4830 break;
4831 case QEMU_OPTION_set:
4832 if (qemu_set_option(optarg) != 0)
4833 exit(1);
4834 break;
4835 case QEMU_OPTION_global:
4836 if (qemu_global_option(optarg) != 0)
4837 exit(1);
4838 break;
4839 case QEMU_OPTION_mtdblock:
4840 drive_add(optarg, MTD_ALIAS);
4841 break;
4842 case QEMU_OPTION_sd:
4843 drive_add(optarg, SD_ALIAS);
4844 break;
4845 case QEMU_OPTION_pflash:
4846 drive_add(optarg, PFLASH_ALIAS);
4847 break;
4848 case QEMU_OPTION_snapshot:
4849 snapshot = 1;
4850 break;
4851 case QEMU_OPTION_hdachs:
4853 const char *p;
4854 p = optarg;
4855 cyls = strtol(p, (char **)&p, 0);
4856 if (cyls < 1 || cyls > 16383)
4857 goto chs_fail;
4858 if (*p != ',')
4859 goto chs_fail;
4860 p++;
4861 heads = strtol(p, (char **)&p, 0);
4862 if (heads < 1 || heads > 16)
4863 goto chs_fail;
4864 if (*p != ',')
4865 goto chs_fail;
4866 p++;
4867 secs = strtol(p, (char **)&p, 0);
4868 if (secs < 1 || secs > 63)
4869 goto chs_fail;
4870 if (*p == ',') {
4871 p++;
4872 if (!strcmp(p, "none"))
4873 translation = BIOS_ATA_TRANSLATION_NONE;
4874 else if (!strcmp(p, "lba"))
4875 translation = BIOS_ATA_TRANSLATION_LBA;
4876 else if (!strcmp(p, "auto"))
4877 translation = BIOS_ATA_TRANSLATION_AUTO;
4878 else
4879 goto chs_fail;
4880 } else if (*p != '\0') {
4881 chs_fail:
4882 fprintf(stderr, "qemu: invalid physical CHS format\n");
4883 exit(1);
4885 if (hda_opts != NULL) {
4886 char num[16];
4887 snprintf(num, sizeof(num), "%d", cyls);
4888 qemu_opt_set(hda_opts, "cyls", num);
4889 snprintf(num, sizeof(num), "%d", heads);
4890 qemu_opt_set(hda_opts, "heads", num);
4891 snprintf(num, sizeof(num), "%d", secs);
4892 qemu_opt_set(hda_opts, "secs", num);
4893 if (translation == BIOS_ATA_TRANSLATION_LBA)
4894 qemu_opt_set(hda_opts, "trans", "lba");
4895 if (translation == BIOS_ATA_TRANSLATION_NONE)
4896 qemu_opt_set(hda_opts, "trans", "none");
4899 break;
4900 case QEMU_OPTION_numa:
4901 if (nb_numa_nodes >= MAX_NODES) {
4902 fprintf(stderr, "qemu: too many NUMA nodes\n");
4903 exit(1);
4905 numa_add(optarg);
4906 break;
4907 case QEMU_OPTION_nographic:
4908 display_type = DT_NOGRAPHIC;
4909 break;
4910 #ifdef CONFIG_CURSES
4911 case QEMU_OPTION_curses:
4912 display_type = DT_CURSES;
4913 break;
4914 #endif
4915 case QEMU_OPTION_portrait:
4916 graphic_rotate = 1;
4917 break;
4918 case QEMU_OPTION_kernel:
4919 kernel_filename = optarg;
4920 break;
4921 case QEMU_OPTION_append:
4922 kernel_cmdline = optarg;
4923 break;
4924 case QEMU_OPTION_cdrom:
4925 drive_add(optarg, CDROM_ALIAS);
4926 break;
4927 case QEMU_OPTION_boot:
4929 static const char * const params[] = {
4930 "order", "once", "menu", NULL
4932 char buf[sizeof(boot_devices)];
4933 char *standard_boot_devices;
4934 int legacy = 0;
4936 if (!strchr(optarg, '=')) {
4937 legacy = 1;
4938 pstrcpy(buf, sizeof(buf), optarg);
4939 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4940 fprintf(stderr,
4941 "qemu: unknown boot parameter '%s' in '%s'\n",
4942 buf, optarg);
4943 exit(1);
4946 if (legacy ||
4947 get_param_value(buf, sizeof(buf), "order", optarg)) {
4948 boot_devices_bitmap = parse_bootdevices(buf);
4949 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4951 if (!legacy) {
4952 if (get_param_value(buf, sizeof(buf),
4953 "once", optarg)) {
4954 boot_devices_bitmap |= parse_bootdevices(buf);
4955 standard_boot_devices = qemu_strdup(boot_devices);
4956 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4957 qemu_register_reset(restore_boot_devices,
4958 standard_boot_devices);
4960 if (get_param_value(buf, sizeof(buf),
4961 "menu", optarg)) {
4962 if (!strcmp(buf, "on")) {
4963 boot_menu = 1;
4964 } else if (!strcmp(buf, "off")) {
4965 boot_menu = 0;
4966 } else {
4967 fprintf(stderr,
4968 "qemu: invalid option value '%s'\n",
4969 buf);
4970 exit(1);
4975 break;
4976 case QEMU_OPTION_fda:
4977 case QEMU_OPTION_fdb:
4978 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4979 break;
4980 #ifdef TARGET_I386
4981 case QEMU_OPTION_no_fd_bootchk:
4982 fd_bootchk = 0;
4983 break;
4984 #endif
4985 case QEMU_OPTION_netdev:
4986 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4987 exit(1);
4989 break;
4990 case QEMU_OPTION_net:
4991 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
4992 exit(1);
4994 break;
4995 #ifdef CONFIG_SLIRP
4996 case QEMU_OPTION_tftp:
4997 legacy_tftp_prefix = optarg;
4998 break;
4999 case QEMU_OPTION_bootp:
5000 legacy_bootp_filename = optarg;
5001 break;
5002 #ifndef _WIN32
5003 case QEMU_OPTION_smb:
5004 if (net_slirp_smb(optarg) < 0)
5005 exit(1);
5006 break;
5007 #endif
5008 case QEMU_OPTION_redir:
5009 if (net_slirp_redir(optarg) < 0)
5010 exit(1);
5011 break;
5012 #endif
5013 case QEMU_OPTION_bt:
5014 add_device_config(DEV_BT, optarg);
5015 break;
5016 #ifdef HAS_AUDIO
5017 case QEMU_OPTION_audio_help:
5018 AUD_help ();
5019 exit (0);
5020 break;
5021 case QEMU_OPTION_soundhw:
5022 select_soundhw (optarg);
5023 break;
5024 #endif
5025 case QEMU_OPTION_h:
5026 help(0);
5027 break;
5028 case QEMU_OPTION_version:
5029 version();
5030 exit(0);
5031 break;
5032 case QEMU_OPTION_m: {
5033 uint64_t value;
5034 char *ptr;
5036 value = strtoul(optarg, &ptr, 10);
5037 switch (*ptr) {
5038 case 0: case 'M': case 'm':
5039 value <<= 20;
5040 break;
5041 case 'G': case 'g':
5042 value <<= 30;
5043 break;
5044 default:
5045 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5046 exit(1);
5049 /* On 32-bit hosts, QEMU is limited by virtual address space */
5050 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5051 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5052 exit(1);
5054 if (value != (uint64_t)(ram_addr_t)value) {
5055 fprintf(stderr, "qemu: ram size too large\n");
5056 exit(1);
5058 ram_size = value;
5059 break;
5061 case QEMU_OPTION_d:
5063 int mask;
5064 const CPULogItem *item;
5066 mask = cpu_str_to_log_mask(optarg);
5067 if (!mask) {
5068 printf("Log items (comma separated):\n");
5069 for(item = cpu_log_items; item->mask != 0; item++) {
5070 printf("%-10s %s\n", item->name, item->help);
5072 exit(1);
5074 cpu_set_log(mask);
5076 break;
5077 case QEMU_OPTION_s:
5078 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5079 break;
5080 case QEMU_OPTION_gdb:
5081 gdbstub_dev = optarg;
5082 break;
5083 case QEMU_OPTION_L:
5084 data_dir = optarg;
5085 break;
5086 case QEMU_OPTION_bios:
5087 bios_name = optarg;
5088 break;
5089 case QEMU_OPTION_singlestep:
5090 singlestep = 1;
5091 break;
5092 case QEMU_OPTION_S:
5093 autostart = 0;
5094 break;
5095 case QEMU_OPTION_k:
5096 keyboard_layout = optarg;
5097 break;
5098 case QEMU_OPTION_localtime:
5099 rtc_utc = 0;
5100 break;
5101 case QEMU_OPTION_vga:
5102 select_vgahw (optarg);
5103 break;
5104 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5105 case QEMU_OPTION_g:
5107 const char *p;
5108 int w, h, depth;
5109 p = optarg;
5110 w = strtol(p, (char **)&p, 10);
5111 if (w <= 0) {
5112 graphic_error:
5113 fprintf(stderr, "qemu: invalid resolution or depth\n");
5114 exit(1);
5116 if (*p != 'x')
5117 goto graphic_error;
5118 p++;
5119 h = strtol(p, (char **)&p, 10);
5120 if (h <= 0)
5121 goto graphic_error;
5122 if (*p == 'x') {
5123 p++;
5124 depth = strtol(p, (char **)&p, 10);
5125 if (depth != 8 && depth != 15 && depth != 16 &&
5126 depth != 24 && depth != 32)
5127 goto graphic_error;
5128 } else if (*p == '\0') {
5129 depth = graphic_depth;
5130 } else {
5131 goto graphic_error;
5134 graphic_width = w;
5135 graphic_height = h;
5136 graphic_depth = depth;
5138 break;
5139 #endif
5140 case QEMU_OPTION_echr:
5142 char *r;
5143 term_escape_char = strtol(optarg, &r, 0);
5144 if (r == optarg)
5145 printf("Bad argument to echr\n");
5146 break;
5148 case QEMU_OPTION_monitor:
5149 monitor_parse(optarg, "readline");
5150 default_monitor = 0;
5151 break;
5152 case QEMU_OPTION_qmp:
5153 monitor_parse(optarg, "control");
5154 default_monitor = 0;
5155 break;
5156 case QEMU_OPTION_mon:
5157 opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5158 if (!opts) {
5159 fprintf(stderr, "parse error: %s\n", optarg);
5160 exit(1);
5162 default_monitor = 0;
5163 break;
5164 case QEMU_OPTION_chardev:
5165 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5166 if (!opts) {
5167 fprintf(stderr, "parse error: %s\n", optarg);
5168 exit(1);
5170 break;
5171 case QEMU_OPTION_serial:
5172 add_device_config(DEV_SERIAL, optarg);
5173 default_serial = 0;
5174 break;
5175 case QEMU_OPTION_watchdog:
5176 if (watchdog) {
5177 fprintf(stderr,
5178 "qemu: only one watchdog option may be given\n");
5179 return 1;
5181 watchdog = optarg;
5182 break;
5183 case QEMU_OPTION_watchdog_action:
5184 if (select_watchdog_action(optarg) == -1) {
5185 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5186 exit(1);
5188 break;
5189 case QEMU_OPTION_virtiocon:
5190 add_device_config(DEV_VIRTCON, optarg);
5191 default_virtcon = 0;
5192 break;
5193 case QEMU_OPTION_parallel:
5194 add_device_config(DEV_PARALLEL, optarg);
5195 default_parallel = 0;
5196 break;
5197 case QEMU_OPTION_debugcon:
5198 add_device_config(DEV_DEBUGCON, optarg);
5199 break;
5200 case QEMU_OPTION_loadvm:
5201 loadvm = optarg;
5202 break;
5203 case QEMU_OPTION_full_screen:
5204 full_screen = 1;
5205 break;
5206 #ifdef CONFIG_SDL
5207 case QEMU_OPTION_no_frame:
5208 no_frame = 1;
5209 break;
5210 case QEMU_OPTION_alt_grab:
5211 alt_grab = 1;
5212 break;
5213 case QEMU_OPTION_ctrl_grab:
5214 ctrl_grab = 1;
5215 break;
5216 case QEMU_OPTION_no_quit:
5217 no_quit = 1;
5218 break;
5219 case QEMU_OPTION_sdl:
5220 display_type = DT_SDL;
5221 break;
5222 #endif
5223 case QEMU_OPTION_pidfile:
5224 pid_file = optarg;
5225 break;
5226 #ifdef TARGET_I386
5227 case QEMU_OPTION_win2k_hack:
5228 win2k_install_hack = 1;
5229 break;
5230 case QEMU_OPTION_rtc_td_hack:
5231 rtc_td_hack = 1;
5232 break;
5233 case QEMU_OPTION_acpitable:
5234 if(acpi_table_add(optarg) < 0) {
5235 fprintf(stderr, "Wrong acpi table provided\n");
5236 exit(1);
5238 break;
5239 case QEMU_OPTION_smbios:
5240 if(smbios_entry_add(optarg) < 0) {
5241 fprintf(stderr, "Wrong smbios provided\n");
5242 exit(1);
5244 break;
5245 #endif
5246 #ifdef CONFIG_KVM
5247 case QEMU_OPTION_enable_kvm:
5248 kvm_allowed = 1;
5249 break;
5250 #endif
5251 case QEMU_OPTION_usb:
5252 usb_enabled = 1;
5253 break;
5254 case QEMU_OPTION_usbdevice:
5255 usb_enabled = 1;
5256 add_device_config(DEV_USB, optarg);
5257 break;
5258 case QEMU_OPTION_device:
5259 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5260 exit(1);
5262 break;
5263 case QEMU_OPTION_smp:
5264 smp_parse(optarg);
5265 if (smp_cpus < 1) {
5266 fprintf(stderr, "Invalid number of CPUs\n");
5267 exit(1);
5269 if (max_cpus < smp_cpus) {
5270 fprintf(stderr, "maxcpus must be equal to or greater than "
5271 "smp\n");
5272 exit(1);
5274 if (max_cpus > 255) {
5275 fprintf(stderr, "Unsupported number of maxcpus\n");
5276 exit(1);
5278 break;
5279 case QEMU_OPTION_vnc:
5280 display_type = DT_VNC;
5281 vnc_display = optarg;
5282 break;
5283 #ifdef TARGET_I386
5284 case QEMU_OPTION_no_acpi:
5285 acpi_enabled = 0;
5286 break;
5287 case QEMU_OPTION_no_hpet:
5288 no_hpet = 1;
5289 break;
5290 case QEMU_OPTION_balloon:
5291 if (balloon_parse(optarg) < 0) {
5292 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5293 exit(1);
5295 break;
5296 #endif
5297 case QEMU_OPTION_no_reboot:
5298 no_reboot = 1;
5299 break;
5300 case QEMU_OPTION_no_shutdown:
5301 no_shutdown = 1;
5302 break;
5303 case QEMU_OPTION_show_cursor:
5304 cursor_hide = 0;
5305 break;
5306 case QEMU_OPTION_uuid:
5307 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5308 fprintf(stderr, "Fail to parse UUID string."
5309 " Wrong format.\n");
5310 exit(1);
5312 break;
5313 #ifndef _WIN32
5314 case QEMU_OPTION_daemonize:
5315 daemonize = 1;
5316 break;
5317 #endif
5318 case QEMU_OPTION_option_rom:
5319 if (nb_option_roms >= MAX_OPTION_ROMS) {
5320 fprintf(stderr, "Too many option ROMs\n");
5321 exit(1);
5323 option_rom[nb_option_roms] = optarg;
5324 nb_option_roms++;
5325 break;
5326 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5327 case QEMU_OPTION_semihosting:
5328 semihosting_enabled = 1;
5329 break;
5330 #endif
5331 case QEMU_OPTION_name:
5332 qemu_name = qemu_strdup(optarg);
5334 char *p = strchr(qemu_name, ',');
5335 if (p != NULL) {
5336 *p++ = 0;
5337 if (strncmp(p, "process=", 8)) {
5338 fprintf(stderr, "Unknown subargument %s to -name", p);
5339 exit(1);
5341 p += 8;
5342 set_proc_name(p);
5345 break;
5346 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5347 case QEMU_OPTION_prom_env:
5348 if (nb_prom_envs >= MAX_PROM_ENVS) {
5349 fprintf(stderr, "Too many prom variables\n");
5350 exit(1);
5352 prom_envs[nb_prom_envs] = optarg;
5353 nb_prom_envs++;
5354 break;
5355 #endif
5356 #ifdef TARGET_ARM
5357 case QEMU_OPTION_old_param:
5358 old_param = 1;
5359 break;
5360 #endif
5361 case QEMU_OPTION_clock:
5362 configure_alarms(optarg);
5363 break;
5364 case QEMU_OPTION_startdate:
5365 configure_rtc_date_offset(optarg, 1);
5366 break;
5367 case QEMU_OPTION_rtc:
5368 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5369 if (!opts) {
5370 fprintf(stderr, "parse error: %s\n", optarg);
5371 exit(1);
5373 configure_rtc(opts);
5374 break;
5375 case QEMU_OPTION_tb_size:
5376 tb_size = strtol(optarg, NULL, 0);
5377 if (tb_size < 0)
5378 tb_size = 0;
5379 break;
5380 case QEMU_OPTION_icount:
5381 use_icount = 1;
5382 if (strcmp(optarg, "auto") == 0) {
5383 icount_time_shift = -1;
5384 } else {
5385 icount_time_shift = strtol(optarg, NULL, 0);
5387 break;
5388 case QEMU_OPTION_incoming:
5389 incoming = optarg;
5390 break;
5391 case QEMU_OPTION_nodefaults:
5392 default_serial = 0;
5393 default_parallel = 0;
5394 default_virtcon = 0;
5395 default_monitor = 0;
5396 default_vga = 0;
5397 default_net = 0;
5398 default_floppy = 0;
5399 default_cdrom = 0;
5400 default_sdcard = 0;
5401 break;
5402 #ifndef _WIN32
5403 case QEMU_OPTION_chroot:
5404 chroot_dir = optarg;
5405 break;
5406 case QEMU_OPTION_runas:
5407 run_as = optarg;
5408 break;
5409 #endif
5410 #ifdef CONFIG_XEN
5411 case QEMU_OPTION_xen_domid:
5412 xen_domid = atoi(optarg);
5413 break;
5414 case QEMU_OPTION_xen_create:
5415 xen_mode = XEN_CREATE;
5416 break;
5417 case QEMU_OPTION_xen_attach:
5418 xen_mode = XEN_ATTACH;
5419 break;
5420 #endif
5421 case QEMU_OPTION_readconfig:
5423 FILE *fp;
5424 fp = fopen(optarg, "r");
5425 if (fp == NULL) {
5426 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5427 exit(1);
5429 if (qemu_config_parse(fp) != 0) {
5430 exit(1);
5432 fclose(fp);
5433 break;
5435 case QEMU_OPTION_writeconfig:
5437 FILE *fp;
5438 if (strcmp(optarg, "-") == 0) {
5439 fp = stdout;
5440 } else {
5441 fp = fopen(optarg, "w");
5442 if (fp == NULL) {
5443 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5444 exit(1);
5447 qemu_config_write(fp);
5448 fclose(fp);
5449 break;
5455 /* If no data_dir is specified then try to find it relative to the
5456 executable path. */
5457 if (!data_dir) {
5458 data_dir = find_datadir(argv[0]);
5460 /* If all else fails use the install patch specified when building. */
5461 if (!data_dir) {
5462 data_dir = CONFIG_QEMU_SHAREDIR;
5466 * Default to max_cpus = smp_cpus, in case the user doesn't
5467 * specify a max_cpus value.
5469 if (!max_cpus)
5470 max_cpus = smp_cpus;
5472 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5473 if (smp_cpus > machine->max_cpus) {
5474 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5475 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5476 machine->max_cpus);
5477 exit(1);
5480 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5481 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5483 if (machine->no_serial) {
5484 default_serial = 0;
5486 if (machine->no_parallel) {
5487 default_parallel = 0;
5489 if (!machine->use_virtcon) {
5490 default_virtcon = 0;
5492 if (machine->no_vga) {
5493 default_vga = 0;
5495 if (machine->no_floppy) {
5496 default_floppy = 0;
5498 if (machine->no_cdrom) {
5499 default_cdrom = 0;
5501 if (machine->no_sdcard) {
5502 default_sdcard = 0;
5505 if (display_type == DT_NOGRAPHIC) {
5506 if (default_parallel)
5507 add_device_config(DEV_PARALLEL, "null");
5508 if (default_serial && default_monitor) {
5509 add_device_config(DEV_SERIAL, "mon:stdio");
5510 } else if (default_virtcon && default_monitor) {
5511 add_device_config(DEV_VIRTCON, "mon:stdio");
5512 } else {
5513 if (default_serial)
5514 add_device_config(DEV_SERIAL, "stdio");
5515 if (default_virtcon)
5516 add_device_config(DEV_VIRTCON, "stdio");
5517 if (default_monitor)
5518 monitor_parse("stdio", "readline");
5520 } else {
5521 if (default_serial)
5522 add_device_config(DEV_SERIAL, "vc:80Cx24C");
5523 if (default_parallel)
5524 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5525 if (default_monitor)
5526 monitor_parse("vc:80Cx24C", "readline");
5527 if (default_virtcon)
5528 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5530 if (default_vga)
5531 vga_interface_type = VGA_CIRRUS;
5533 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5534 exit(1);
5536 #ifndef _WIN32
5537 if (daemonize) {
5538 pid_t pid;
5540 if (pipe(fds) == -1)
5541 exit(1);
5543 pid = fork();
5544 if (pid > 0) {
5545 uint8_t status;
5546 ssize_t len;
5548 close(fds[1]);
5550 again:
5551 len = read(fds[0], &status, 1);
5552 if (len == -1 && (errno == EINTR))
5553 goto again;
5555 if (len != 1)
5556 exit(1);
5557 else if (status == 1) {
5558 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5559 exit(1);
5560 } else
5561 exit(0);
5562 } else if (pid < 0)
5563 exit(1);
5565 close(fds[0]);
5566 qemu_set_cloexec(fds[1]);
5568 setsid();
5570 pid = fork();
5571 if (pid > 0)
5572 exit(0);
5573 else if (pid < 0)
5574 exit(1);
5576 umask(027);
5578 signal(SIGTSTP, SIG_IGN);
5579 signal(SIGTTOU, SIG_IGN);
5580 signal(SIGTTIN, SIG_IGN);
5582 #endif
5584 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5585 #ifndef _WIN32
5586 if (daemonize) {
5587 uint8_t status = 1;
5588 write(fds[1], &status, 1);
5589 } else
5590 #endif
5591 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5592 exit(1);
5595 if (kvm_enabled()) {
5596 int ret;
5598 ret = kvm_init(smp_cpus);
5599 if (ret < 0) {
5600 fprintf(stderr, "failed to initialize KVM\n");
5601 exit(1);
5605 if (qemu_init_main_loop()) {
5606 fprintf(stderr, "qemu_init_main_loop failed\n");
5607 exit(1);
5609 linux_boot = (kernel_filename != NULL);
5611 if (!linux_boot && *kernel_cmdline != '\0') {
5612 fprintf(stderr, "-append only allowed with -kernel option\n");
5613 exit(1);
5616 if (!linux_boot && initrd_filename != NULL) {
5617 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5618 exit(1);
5621 #ifndef _WIN32
5622 /* Win32 doesn't support line-buffering and requires size >= 2 */
5623 setvbuf(stdout, NULL, _IOLBF, 0);
5624 #endif
5626 if (init_timer_alarm() < 0) {
5627 fprintf(stderr, "could not initialize alarm timer\n");
5628 exit(1);
5630 if (use_icount && icount_time_shift < 0) {
5631 use_icount = 2;
5632 /* 125MIPS seems a reasonable initial guess at the guest speed.
5633 It will be corrected fairly quickly anyway. */
5634 icount_time_shift = 3;
5635 init_icount_adjust();
5638 #ifdef _WIN32
5639 socket_init();
5640 #endif
5642 if (net_init_clients() < 0) {
5643 exit(1);
5646 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5647 net_set_boot_mask(net_boot);
5649 /* init the bluetooth world */
5650 if (foreach_device_config(DEV_BT, bt_parse))
5651 exit(1);
5653 /* init the memory */
5654 if (ram_size == 0)
5655 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5657 /* init the dynamic translator */
5658 cpu_exec_init_all(tb_size * 1024 * 1024);
5660 bdrv_init_with_whitelist();
5662 blk_mig_init();
5664 if (default_cdrom) {
5665 /* we always create the cdrom drive, even if no disk is there */
5666 drive_add(NULL, CDROM_ALIAS);
5669 if (default_floppy) {
5670 /* we always create at least one floppy */
5671 drive_add(NULL, FD_ALIAS, 0);
5674 if (default_sdcard) {
5675 /* we always create one sd slot, even if no card is in it */
5676 drive_add(NULL, SD_ALIAS);
5679 /* open the virtual block devices */
5680 if (snapshot)
5681 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5682 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5683 exit(1);
5685 vmstate_register(0, &vmstate_timers ,&timers_state);
5686 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5687 ram_load, NULL);
5689 if (nb_numa_nodes > 0) {
5690 int i;
5692 if (nb_numa_nodes > smp_cpus) {
5693 nb_numa_nodes = smp_cpus;
5696 /* If no memory size if given for any node, assume the default case
5697 * and distribute the available memory equally across all nodes
5699 for (i = 0; i < nb_numa_nodes; i++) {
5700 if (node_mem[i] != 0)
5701 break;
5703 if (i == nb_numa_nodes) {
5704 uint64_t usedmem = 0;
5706 /* On Linux, the each node's border has to be 8MB aligned,
5707 * the final node gets the rest.
5709 for (i = 0; i < nb_numa_nodes - 1; i++) {
5710 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5711 usedmem += node_mem[i];
5713 node_mem[i] = ram_size - usedmem;
5716 for (i = 0; i < nb_numa_nodes; i++) {
5717 if (node_cpumask[i] != 0)
5718 break;
5720 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5721 * must cope with this anyway, because there are BIOSes out there in
5722 * real machines which also use this scheme.
5724 if (i == nb_numa_nodes) {
5725 for (i = 0; i < smp_cpus; i++) {
5726 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5731 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5732 exit(1);
5733 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5734 exit(1);
5735 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5736 exit(1);
5737 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5738 exit(1);
5740 module_call_init(MODULE_INIT_DEVICE);
5742 if (watchdog) {
5743 i = select_watchdog(watchdog);
5744 if (i > 0)
5745 exit (i == 1 ? 1 : 0);
5748 if (machine->compat_props) {
5749 qdev_prop_register_global_list(machine->compat_props);
5751 qemu_add_globals();
5753 machine->init(ram_size, boot_devices,
5754 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5757 #ifndef _WIN32
5758 /* must be after terminal init, SDL library changes signal handlers */
5759 sighandler_setup();
5760 #endif
5762 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5763 for (i = 0; i < nb_numa_nodes; i++) {
5764 if (node_cpumask[i] & (1 << env->cpu_index)) {
5765 env->numa_node = i;
5770 current_machine = machine;
5772 /* init USB devices */
5773 if (usb_enabled) {
5774 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5775 exit(1);
5778 /* init generic devices */
5779 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5780 exit(1);
5782 if (!display_state)
5783 dumb_display_init();
5784 /* just use the first displaystate for the moment */
5785 ds = display_state;
5787 if (display_type == DT_DEFAULT) {
5788 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5789 display_type = DT_SDL;
5790 #else
5791 display_type = DT_VNC;
5792 vnc_display = "localhost:0,to=99";
5793 show_vnc_port = 1;
5794 #endif
5798 switch (display_type) {
5799 case DT_NOGRAPHIC:
5800 break;
5801 #if defined(CONFIG_CURSES)
5802 case DT_CURSES:
5803 curses_display_init(ds, full_screen);
5804 break;
5805 #endif
5806 #if defined(CONFIG_SDL)
5807 case DT_SDL:
5808 sdl_display_init(ds, full_screen, no_frame);
5809 break;
5810 #elif defined(CONFIG_COCOA)
5811 case DT_SDL:
5812 cocoa_display_init(ds, full_screen);
5813 break;
5814 #endif
5815 case DT_VNC:
5816 vnc_display_init(ds);
5817 if (vnc_display_open(ds, vnc_display) < 0)
5818 exit(1);
5820 if (show_vnc_port) {
5821 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5823 break;
5824 default:
5825 break;
5827 dpy_resize(ds);
5829 dcl = ds->listeners;
5830 while (dcl != NULL) {
5831 if (dcl->dpy_refresh != NULL) {
5832 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5833 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5835 dcl = dcl->next;
5838 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5839 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5840 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5843 text_consoles_set_display(display_state);
5845 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
5846 exit(1);
5848 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5849 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5850 gdbstub_dev);
5851 exit(1);
5854 qdev_machine_creation_done();
5856 if (rom_load_all() != 0) {
5857 fprintf(stderr, "rom loading failed\n");
5858 exit(1);
5861 qemu_system_reset();
5862 if (loadvm) {
5863 if (load_vmstate(cur_mon, loadvm) < 0) {
5864 autostart = 0;
5868 if (incoming) {
5869 qemu_start_incoming_migration(incoming);
5870 } else if (autostart) {
5871 vm_start();
5874 #ifndef _WIN32
5875 if (daemonize) {
5876 uint8_t status = 0;
5877 ssize_t len;
5879 again1:
5880 len = write(fds[1], &status, 1);
5881 if (len == -1 && (errno == EINTR))
5882 goto again1;
5884 if (len != 1)
5885 exit(1);
5887 chdir("/");
5888 TFR(fd = qemu_open("/dev/null", O_RDWR));
5889 if (fd == -1)
5890 exit(1);
5893 if (run_as) {
5894 pwd = getpwnam(run_as);
5895 if (!pwd) {
5896 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5897 exit(1);
5901 if (chroot_dir) {
5902 if (chroot(chroot_dir) < 0) {
5903 fprintf(stderr, "chroot failed\n");
5904 exit(1);
5906 chdir("/");
5909 if (run_as) {
5910 if (setgid(pwd->pw_gid) < 0) {
5911 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5912 exit(1);
5914 if (setuid(pwd->pw_uid) < 0) {
5915 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5916 exit(1);
5918 if (setuid(0) != -1) {
5919 fprintf(stderr, "Dropping privileges failed\n");
5920 exit(1);
5924 if (daemonize) {
5925 dup2(fd, 0);
5926 dup2(fd, 1);
5927 dup2(fd, 2);
5929 close(fd);
5931 #endif
5933 main_loop();
5934 quit_timers();
5935 net_cleanup();
5937 return 0;