]> git.proxmox.com Git - mirror_qemu.git/blame - vl.c
do not use qemu_event_increment outside qemu_notify_event
[mirror_qemu.git] / vl.c
CommitLineData
0824d6fc 1/*
80cabfad 2 * QEMU System Emulator
5fafdf24 3 *
68d0f70e 4 * Copyright (c) 2003-2008 Fabrice Bellard
5fafdf24 5 *
1df912cf
FB
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:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
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.
0824d6fc 23 */
0824d6fc 24#include <unistd.h>
0824d6fc
FB
25#include <fcntl.h>
26#include <signal.h>
27#include <time.h>
0824d6fc 28#include <errno.h>
67b915a5 29#include <sys/time.h>
c88676f8 30#include <zlib.h>
67b915a5 31
71e72a19 32/* Needed early for CONFIG_BSD etc. */
d40cdb10
BS
33#include "config-host.h"
34
67b915a5 35#ifndef _WIN32
5cea8590 36#include <libgen.h>
0858532e 37#include <pwd.h>
67b915a5 38#include <sys/times.h>
f1510b2c 39#include <sys/wait.h>
67b915a5 40#include <termios.h>
67b915a5 41#include <sys/mman.h>
f1510b2c 42#include <sys/ioctl.h>
24646c7e 43#include <sys/resource.h>
f1510b2c 44#include <sys/socket.h>
c94c8d64 45#include <netinet/in.h>
24646c7e 46#include <net/if.h>
24646c7e 47#include <arpa/inet.h>
9d728e8c 48#include <dirent.h>
7c9d8e07 49#include <netdb.h>
cb4b976b 50#include <sys/select.h>
71e72a19 51#ifdef CONFIG_BSD
7d3505c5 52#include <sys/stat.h>
a167ba50 53#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
7d3505c5 54#include <libutil.h>
24646c7e
BS
55#else
56#include <util.h>
128ab2ff 57#endif
bbe813a2 58#else
223f0d72 59#ifdef __linux__
7d3505c5
FB
60#include <pty.h>
61#include <malloc.h>
fd872598 62#include <linux/rtc.h>
1889465a 63#include <sys/prctl.h>
bd494f4c
TS
64
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"
69
e57a8c0e 70#include <linux/ppdev.h>
5867c88a 71#include <linux/parport.h>
223f0d72
BS
72#endif
73#ifdef __sun__
d5d10bc3
TS
74#include <sys/stat.h>
75#include <sys/ethernet.h>
76#include <sys/sockio.h>
d5d10bc3
TS
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>
8d32cf0e
BS
87/* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
88 discussion about Solaris header problems */
89extern int madvise(caddr_t, size_t, int);
67b915a5 90#endif
7d3505c5 91#endif
ec530c81 92#endif
67b915a5 93
9892fbfb
BS
94#if defined(__OpenBSD__)
95#include <util.h>
96#endif
97
8a16d273
TS
98#if defined(CONFIG_VDE)
99#include <libvdeplug.h>
100#endif
101
67b915a5 102#ifdef _WIN32
49dc768d 103#include <windows.h>
4fddf62a 104#include <mmsystem.h>
67b915a5
FB
105#endif
106
73332e5c 107#ifdef CONFIG_SDL
59a36a2f 108#if defined(__APPLE__) || defined(main)
6693665a 109#include <SDL.h>
880fec5d 110int qemu_main(int argc, char **argv, char **envp);
111int main(int argc, char **argv)
112{
59a36a2f 113 return qemu_main(argc, argv, NULL);
880fec5d 114}
115#undef main
116#define main qemu_main
96bcd4f8 117#endif
73332e5c 118#endif /* CONFIG_SDL */
0824d6fc 119
5b0753e0
FB
120#ifdef CONFIG_COCOA
121#undef main
122#define main qemu_main
123#endif /* CONFIG_COCOA */
124
511d2b14
BS
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"
9dd986cc 134#include "hw/watchdog.h"
b6f6e3d3 135#include "hw/smbios.h"
e37630ca 136#include "hw/xen.h"
bd3c948d 137#include "hw/qdev.h"
45a50b16 138#include "hw/loader.h"
5ef4efa4 139#include "bt-host.h"
511d2b14 140#include "net.h"
68ac40d2 141#include "net/slirp.h"
511d2b14
BS
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"
c163b5ca
LS
150#include "block_int.h"
151#include "block-migration.h"
a718acec 152#include "dma.h"
511d2b14
BS
153#include "audio/audio.h"
154#include "migration.h"
155#include "kvm.h"
156#include "balloon.h"
d3f24367 157#include "qemu-option.h"
7282a033 158#include "qemu-config.h"
e78c48ec 159#include "qemu-objects.h"
511d2b14 160
0824d6fc 161#include "disas.h"
fc01f7e7 162
8a7ddc38 163#include "exec-all.h"
0824d6fc 164
511d2b14
BS
165#include "qemu_socket.h"
166
d918f23e 167#include "slirp/libslirp.h"
511d2b14 168
72cf2d4f
BS
169#include "qemu-queue.h"
170
9dc63a1e
BS
171//#define DEBUG_NET
172//#define DEBUG_SLIRP
330d0414 173
1bfe856e 174#define DEFAULT_RAM_SIZE 128
313aa567 175
98b19252
AS
176#define MAX_VIRTIO_CONSOLES 1
177
5cea8590 178static const char *data_dir;
1192dad8 179const char *bios_name = NULL;
e4bcb14c 180/* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
faea38e7 181 to store the VM snapshots */
72cf2d4f
BS
182struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
183struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
cb5a7aa8 184enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
993fbfdb 185DisplayType display_type = DT_DEFAULT;
3d11d0eb 186const char* keyboard_layout = NULL;
c227f099 187ram_addr_t ram_size;
c902760f
MT
188const char *mem_path = NULL;
189#ifdef MAP_POPULATE
190int mem_prealloc = 0; /* force preallocation of physical target memory */
191#endif
c4b1fcc0 192int nb_nics;
7c9d8e07 193NICInfo nd_table[MAX_NICS];
8a7ddc38 194int vm_running;
d399f677 195int autostart;
f6503059
AZ
196static int rtc_utc = 1;
197static int rtc_date_offset = -1; /* -1 means no change */
6875204c 198QEMUClock *rtc_clock;
64465297 199int vga_interface_type = VGA_NONE;
d827220b
FB
200#ifdef TARGET_SPARC
201int graphic_width = 1024;
202int graphic_height = 768;
eee0b836 203int graphic_depth = 8;
d827220b 204#else
1bfe856e
FB
205int graphic_width = 800;
206int graphic_height = 600;
e9b137c2 207int graphic_depth = 15;
eee0b836 208#endif
dbed7e40 209static int full_screen = 0;
634a21f6 210#ifdef CONFIG_SDL
dbed7e40 211static int no_frame = 0;
634a21f6 212#endif
667accab 213int no_quit = 0;
8d11df9e 214CharDriverState *serial_hds[MAX_SERIAL_PORTS];
6508fe59 215CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
9ede2fde 216CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
a09db21f
FB
217#ifdef TARGET_I386
218int win2k_install_hack = 0;
73822ec8 219int rtc_td_hack = 0;
a09db21f 220#endif
bb36d470 221int usb_enabled = 0;
1b530a6d 222int singlestep = 0;
6a00d601 223int smp_cpus = 1;
6be68d7e 224int max_cpus = 0;
dc6b1c09
AP
225int smp_cores = 1;
226int smp_threads = 1;
73fc9742 227const char *vnc_display;
6515b203 228int acpi_enabled = 1;
16b29ae1 229int no_hpet = 0;
52ca8d6a 230int fd_bootchk = 1;
d1beab82 231int no_reboot = 0;
b2f76161 232int no_shutdown = 0;
9467cd46 233int cursor_hide = 1;
a171fe39 234int graphic_rotate = 0;
6b35e7bf 235uint8_t irq0override = 1;
b9e82a59 236#ifndef _WIN32
71e3ceb8 237int daemonize = 0;
b9e82a59 238#endif
09aaa160 239const char *watchdog;
9ae02555
TS
240const char *option_rom[MAX_OPTION_ROMS];
241int nb_option_roms;
8e71621f 242int semihosting_enabled = 0;
2b8f2d41
AZ
243#ifdef TARGET_ARM
244int old_param = 0;
245#endif
c35734b2 246const char *qemu_name;
3780e197 247int alt_grab = 0;
0ca9f8a4 248int ctrl_grab = 0;
95efd11c 249#if defined(TARGET_SPARC) || defined(TARGET_PPC)
66508601
BS
250unsigned int nb_prom_envs = 0;
251const char *prom_envs[MAX_PROM_ENVS];
252#endif
95387491 253int boot_menu;
0824d6fc 254
268a362c
AL
255int nb_numa_nodes;
256uint64_t node_mem[MAX_NODES];
257uint64_t node_cpumask[MAX_NODES];
258
ee5605e5
AZ
259static CPUState *cur_cpu;
260static CPUState *next_cpu;
bf20dc07 261/* Conversion factor from emulated instructions to virtual clock ticks. */
2e70f6ef 262static int icount_time_shift;
bf20dc07 263/* Arbitrarily pick 1MIPS as the minimum allowable speed. */
2e70f6ef
PB
264#define MAX_ICOUNT_SHIFT 10
265/* Compensate for varying guest execution speed. */
266static int64_t qemu_icount_bias;
dbed7e40
BS
267static QEMUTimer *icount_rt_timer;
268static QEMUTimer *icount_vm_timer;
9043b62d 269static QEMUTimer *nographic_timer;
ee5605e5 270
8fcb1b90
BS
271uint8_t qemu_uuid[16];
272
76e30d0f
JK
273static QEMUBootSetHandler *boot_set_handler;
274static void *boot_set_opaque;
275
cc84de95
MT
276#ifdef SIGRTMIN
277#define SIG_IPI (SIGRTMIN+4)
278#else
279#define SIG_IPI SIGUSR1
280#endif
281
998bbd74 282static int default_serial = 1;
6a5e8b0e 283static int default_parallel = 1;
986c5f78 284static int default_virtcon = 1;
abdeed06 285static int default_monitor = 1;
64465297 286static int default_vga = 1;
ac33f8fa
GH
287static int default_floppy = 1;
288static int default_cdrom = 1;
289static int default_sdcard = 1;
998bbd74
GH
290
291static struct {
292 const char *driver;
293 int *flag;
294} default_list[] = {
6a5e8b0e
GH
295 { .driver = "isa-serial", .flag = &default_serial },
296 { .driver = "isa-parallel", .flag = &default_parallel },
d8bcbabf
GH
297 { .driver = "isa-fdc", .flag = &default_floppy },
298 { .driver = "ide-drive", .flag = &default_cdrom },
392ecf54
AS
299 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
300 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
301 { .driver = "virtio-serial", .flag = &default_virtcon },
64465297 302 { .driver = "VGA", .flag = &default_vga },
69fd02ee
GH
303 { .driver = "cirrus-vga", .flag = &default_vga },
304 { .driver = "vmware-svga", .flag = &default_vga },
998bbd74
GH
305};
306
307static int default_driver_check(QemuOpts *opts, void *opaque)
308{
309 const char *driver = qemu_opt_get(opts, "driver");
310 int i;
311
312 if (!driver)
313 return 0;
314 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
315 if (strcmp(default_list[i].driver, driver) != 0)
316 continue;
317 *(default_list[i].flag) = 0;
318 }
319 return 0;
320}
321
0824d6fc 322/***********************************************************/
26aa7d72
FB
323/* x86 ISA bus support */
324
c227f099 325target_phys_addr_t isa_mem_base = 0;
3de388f6 326PicState2 *isa_pic;
0824d6fc 327
0824d6fc 328/***********************************************************/
0824d6fc
FB
329void hw_error(const char *fmt, ...)
330{
331 va_list ap;
6a00d601 332 CPUState *env;
0824d6fc
FB
333
334 va_start(ap, fmt);
335 fprintf(stderr, "qemu: hardware error: ");
336 vfprintf(stderr, fmt, ap);
337 fprintf(stderr, "\n");
6a00d601
FB
338 for(env = first_cpu; env != NULL; env = env->next_cpu) {
339 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
0824d6fc 340#ifdef TARGET_I386
6a00d601 341 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
c45886db 342#else
6a00d601 343 cpu_dump_state(env, stderr, fprintf, 0);
0824d6fc 344#endif
6a00d601 345 }
0824d6fc
FB
346 va_end(ap);
347 abort();
348}
1889465a
AK
349
350static void set_proc_name(const char *s)
351{
6ca8d0fd 352#if defined(__linux__) && defined(PR_SET_NAME)
1889465a
AK
353 char name[16];
354 if (!s)
355 return;
356 name[sizeof(name) - 1] = 0;
357 strncpy(name, s, sizeof(name));
358 /* Could rewrite argv[0] too, but that's a bit more complicated.
359 This simple way is enough for `top'. */
360 prctl(PR_SET_NAME, name);
361#endif
362}
df751fa8
AL
363
364/***************/
365/* ballooning */
366
367static QEMUBalloonEvent *qemu_balloon_event;
368void *qemu_balloon_event_opaque;
369
370void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
371{
372 qemu_balloon_event = func;
373 qemu_balloon_event_opaque = opaque;
374}
375
625a5bef 376int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
df751fa8 377{
625a5bef
AL
378 if (qemu_balloon_event) {
379 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
380 return 1;
381 } else {
382 return 0;
383 }
df751fa8
AL
384}
385
625a5bef 386int qemu_balloon_status(MonitorCompletion cb, void *opaque)
df751fa8 387{
625a5bef
AL
388 if (qemu_balloon_event) {
389 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
390 return 1;
391 } else {
392 return 0;
393 }
df751fa8 394}
0824d6fc 395
455204eb 396
8f0056b7
PB
397/***********************************************************/
398/* real time host monotonic timer */
09b26c5e 399
1dce7c3c
FB
400/* compute with 96 bit intermediate result: (a*b)/c */
401uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
0824d6fc 402{
1dce7c3c
FB
403 union {
404 uint64_t ll;
405 struct {
e2542fe2 406#ifdef HOST_WORDS_BIGENDIAN
1dce7c3c
FB
407 uint32_t high, low;
408#else
409 uint32_t low, high;
3b46e624 410#endif
1dce7c3c
FB
411 } l;
412 } u, res;
413 uint64_t rl, rh;
0824d6fc 414
1dce7c3c
FB
415 u.ll = a;
416 rl = (uint64_t)u.l.low * (uint64_t)b;
417 rh = (uint64_t)u.l.high * (uint64_t)b;
418 rh += (rl >> 32);
419 res.l.high = rh / c;
420 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
421 return res.ll;
34865134
FB
422}
423
21d5d12b
JK
424static int64_t get_clock_realtime(void)
425{
426 struct timeval tv;
427
428 gettimeofday(&tv, NULL);
429 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
430}
431
1dce7c3c 432#ifdef WIN32
0824d6fc 433
1dce7c3c 434static int64_t clock_freq;
1115dde7 435
1dce7c3c 436static void init_get_clock(void)
1115dde7 437{
a8e5ac33
FB
438 LARGE_INTEGER freq;
439 int ret;
1dce7c3c
FB
440 ret = QueryPerformanceFrequency(&freq);
441 if (ret == 0) {
442 fprintf(stderr, "Could not calibrate ticks\n");
443 exit(1);
444 }
445 clock_freq = freq.QuadPart;
1115dde7
FB
446}
447
1dce7c3c 448static int64_t get_clock(void)
b8076a74 449{
1dce7c3c
FB
450 LARGE_INTEGER ti;
451 QueryPerformanceCounter(&ti);
274dfed8 452 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
b8076a74
FB
453}
454
1dce7c3c 455#else
90cb9493 456
1dce7c3c
FB
457static int use_rt_clock;
458
459static void init_get_clock(void)
90cb9493 460{
1dce7c3c 461 use_rt_clock = 0;
c5e97233 462#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
a167ba50 463 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
1dce7c3c
FB
464 {
465 struct timespec ts;
466 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
467 use_rt_clock = 1;
468 }
469 }
470#endif
90cb9493
FB
471}
472
1dce7c3c 473static int64_t get_clock(void)
fdbb4691 474{
c5e97233 475#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
a167ba50 476 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
1dce7c3c
FB
477 if (use_rt_clock) {
478 struct timespec ts;
479 clock_gettime(CLOCK_MONOTONIC, &ts);
480 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
5fafdf24 481 } else
fdbb4691 482#endif
1dce7c3c
FB
483 {
484 /* XXX: using gettimeofday leads to problems if the date
485 changes, so it should be avoided. */
21d5d12b 486 return get_clock_realtime();
1dce7c3c 487 }
fdbb4691 488}
34865134
FB
489#endif
490
2e70f6ef
PB
491/* Return the virtual CPU time, based on the instruction counter. */
492static int64_t cpu_get_icount(void)
493{
494 int64_t icount;
495 CPUState *env = cpu_single_env;;
496 icount = qemu_icount;
497 if (env) {
498 if (!can_do_io(env))
499 fprintf(stderr, "Bad clock read\n");
500 icount -= (env->icount_decr.u16.low + env->icount_extra);
501 }
502 return qemu_icount_bias + (icount << icount_time_shift);
503}
504
1dce7c3c
FB
505/***********************************************************/
506/* guest cycle counter */
507
6f68e33e
JQ
508typedef struct TimersState {
509 int64_t cpu_ticks_prev;
510 int64_t cpu_ticks_offset;
511 int64_t cpu_clock_offset;
512 int32_t cpu_ticks_enabled;
274dfed8 513 int64_t dummy;
6f68e33e
JQ
514} TimersState;
515
516TimersState timers_state;
34865134 517
1dce7c3c
FB
518/* return the host CPU cycle counter and handle stop/restart */
519int64_t cpu_get_ticks(void)
34865134 520{
2e70f6ef
PB
521 if (use_icount) {
522 return cpu_get_icount();
523 }
6f68e33e
JQ
524 if (!timers_state.cpu_ticks_enabled) {
525 return timers_state.cpu_ticks_offset;
8a7ddc38 526 } else {
eade0f19
FB
527 int64_t ticks;
528 ticks = cpu_get_real_ticks();
6f68e33e 529 if (timers_state.cpu_ticks_prev > ticks) {
eade0f19
FB
530 /* Note: non increasing ticks may happen if the host uses
531 software suspend */
6f68e33e 532 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
eade0f19 533 }
6f68e33e
JQ
534 timers_state.cpu_ticks_prev = ticks;
535 return ticks + timers_state.cpu_ticks_offset;
8a7ddc38 536 }
34865134
FB
537}
538
1dce7c3c
FB
539/* return the host CPU monotonic timer and handle stop/restart */
540static int64_t cpu_get_clock(void)
541{
542 int64_t ti;
6f68e33e
JQ
543 if (!timers_state.cpu_ticks_enabled) {
544 return timers_state.cpu_clock_offset;
1dce7c3c
FB
545 } else {
546 ti = get_clock();
6f68e33e 547 return ti + timers_state.cpu_clock_offset;
1dce7c3c
FB
548 }
549}
550
34865134
FB
551/* enable cpu_get_ticks() */
552void cpu_enable_ticks(void)
553{
6f68e33e
JQ
554 if (!timers_state.cpu_ticks_enabled) {
555 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
556 timers_state.cpu_clock_offset -= get_clock();
557 timers_state.cpu_ticks_enabled = 1;
8a7ddc38 558 }
34865134
FB
559}
560
561/* disable cpu_get_ticks() : the clock is stopped. You must not call
562 cpu_get_ticks() after that. */
563void cpu_disable_ticks(void)
564{
6f68e33e
JQ
565 if (timers_state.cpu_ticks_enabled) {
566 timers_state.cpu_ticks_offset = cpu_get_ticks();
567 timers_state.cpu_clock_offset = cpu_get_clock();
568 timers_state.cpu_ticks_enabled = 0;
8a7ddc38 569 }
34865134
FB
570}
571
1dce7c3c
FB
572/***********************************************************/
573/* timers */
5fafdf24 574
0fdddf80
JK
575#define QEMU_CLOCK_REALTIME 0
576#define QEMU_CLOCK_VIRTUAL 1
21d5d12b 577#define QEMU_CLOCK_HOST 2
8a7ddc38
FB
578
579struct QEMUClock {
580 int type;
581 /* XXX: add frequency */
582};
583
584struct QEMUTimer {
585 QEMUClock *clock;
586 int64_t expire_time;
587 QEMUTimerCB *cb;
588 void *opaque;
589 struct QEMUTimer *next;
590};
591
c8994013
TS
592struct qemu_alarm_timer {
593 char const *name;
c8994013
TS
594 int (*start)(struct qemu_alarm_timer *t);
595 void (*stop)(struct qemu_alarm_timer *t);
efe75411 596 void (*rearm)(struct qemu_alarm_timer *t);
c8994013 597 void *priv;
c8994013 598
1828be31
PB
599 char expired;
600 char pending;
cd48d7e8 601};
efe75411
TS
602
603static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
604{
1828be31 605 return !!t->rearm;
efe75411
TS
606}
607
608static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
609{
610 if (!alarm_has_dynticks(t))
611 return;
612
613 t->rearm(t);
614}
615
616/* TODO: MIN_TIMER_REARM_US should be optimized */
617#define MIN_TIMER_REARM_US 250
618
c8994013 619static struct qemu_alarm_timer *alarm_timer;
8a7ddc38 620
40c3bac3 621#ifdef _WIN32
c8994013
TS
622
623struct qemu_alarm_win32 {
624 MMRESULT timerId;
c8994013 625 unsigned int period;
9aea1029 626} alarm_win32_data = {0, 0};
c8994013
TS
627
628static int win32_start_timer(struct qemu_alarm_timer *t);
629static void win32_stop_timer(struct qemu_alarm_timer *t);
efe75411 630static void win32_rearm_timer(struct qemu_alarm_timer *t);
c8994013 631
40c3bac3 632#else
c8994013
TS
633
634static int unix_start_timer(struct qemu_alarm_timer *t);
635static void unix_stop_timer(struct qemu_alarm_timer *t);
636
231c6586
TS
637#ifdef __linux__
638
efe75411
TS
639static int dynticks_start_timer(struct qemu_alarm_timer *t);
640static void dynticks_stop_timer(struct qemu_alarm_timer *t);
641static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
642
c40ec5a9
TS
643static int hpet_start_timer(struct qemu_alarm_timer *t);
644static void hpet_stop_timer(struct qemu_alarm_timer *t);
645
c8994013
TS
646static int rtc_start_timer(struct qemu_alarm_timer *t);
647static void rtc_stop_timer(struct qemu_alarm_timer *t);
648
efe75411 649#endif /* __linux__ */
8a7ddc38 650
c8994013
TS
651#endif /* _WIN32 */
652
2e70f6ef 653/* Correlation between real and virtual time is always going to be
bf20dc07 654 fairly approximate, so ignore small variation.
2e70f6ef
PB
655 When the guest is idle real and virtual time will be aligned in
656 the IO wait loop. */
274dfed8 657#define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
2e70f6ef
PB
658
659static void icount_adjust(void)
660{
661 int64_t cur_time;
662 int64_t cur_icount;
663 int64_t delta;
664 static int64_t last_delta;
665 /* If the VM is not running, then do nothing. */
666 if (!vm_running)
667 return;
668
669 cur_time = cpu_get_clock();
670 cur_icount = qemu_get_clock(vm_clock);
671 delta = cur_icount - cur_time;
672 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
673 if (delta > 0
674 && last_delta + ICOUNT_WOBBLE < delta * 2
675 && icount_time_shift > 0) {
676 /* The guest is getting too far ahead. Slow time down. */
677 icount_time_shift--;
678 }
679 if (delta < 0
680 && last_delta - ICOUNT_WOBBLE > delta * 2
681 && icount_time_shift < MAX_ICOUNT_SHIFT) {
682 /* The guest is getting too far behind. Speed time up. */
683 icount_time_shift++;
684 }
685 last_delta = delta;
686 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
687}
688
689static void icount_adjust_rt(void * opaque)
690{
691 qemu_mod_timer(icount_rt_timer,
692 qemu_get_clock(rt_clock) + 1000);
693 icount_adjust();
694}
695
696static void icount_adjust_vm(void * opaque)
697{
698 qemu_mod_timer(icount_vm_timer,
274dfed8 699 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
2e70f6ef
PB
700 icount_adjust();
701}
702
703static void init_icount_adjust(void)
704{
705 /* Have both realtime and virtual time triggers for speed adjustment.
706 The realtime trigger catches emulated time passing too slowly,
707 the virtual time trigger catches emulated time passing too fast.
708 Realtime triggers occur even when idle, so use them less frequently
709 than VM triggers. */
710 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
711 qemu_mod_timer(icount_rt_timer,
712 qemu_get_clock(rt_clock) + 1000);
713 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
714 qemu_mod_timer(icount_vm_timer,
274dfed8 715 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
2e70f6ef
PB
716}
717
c8994013 718static struct qemu_alarm_timer alarm_timers[] = {
efe75411 719#ifndef _WIN32
231c6586 720#ifdef __linux__
cd48d7e8 721 {"dynticks", dynticks_start_timer,
efe75411 722 dynticks_stop_timer, dynticks_rearm_timer, NULL},
c40ec5a9 723 /* HPET - if available - is preferred */
cd48d7e8 724 {"hpet", hpet_start_timer, hpet_stop_timer, NULL, NULL},
c40ec5a9 725 /* ...otherwise try RTC */
cd48d7e8 726 {"rtc", rtc_start_timer, rtc_stop_timer, NULL, NULL},
c8994013 727#endif
cd48d7e8 728 {"unix", unix_start_timer, unix_stop_timer, NULL, NULL},
c8994013 729#else
cd48d7e8 730 {"dynticks", win32_start_timer,
efe75411 731 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
cd48d7e8 732 {"win32", win32_start_timer,
efe75411 733 win32_stop_timer, NULL, &alarm_win32_data},
c8994013
TS
734#endif
735 {NULL, }
736};
737
3f47aa8c 738static void show_available_alarms(void)
f3dcfada
TS
739{
740 int i;
741
742 printf("Available alarm timers, in order of precedence:\n");
743 for (i = 0; alarm_timers[i].name; i++)
744 printf("%s\n", alarm_timers[i].name);
745}
746
747static void configure_alarms(char const *opt)
748{
749 int i;
750 int cur = 0;
b1503cda 751 int count = ARRAY_SIZE(alarm_timers) - 1;
f3dcfada
TS
752 char *arg;
753 char *name;
2e70f6ef 754 struct qemu_alarm_timer tmp;
f3dcfada 755
3adda04c 756 if (!strcmp(opt, "?")) {
f3dcfada
TS
757 show_available_alarms();
758 exit(0);
759 }
760
73ffc805 761 arg = qemu_strdup(opt);
f3dcfada
TS
762
763 /* Reorder the array */
764 name = strtok(arg, ",");
765 while (name) {
e2b577e5 766 for (i = 0; i < count && alarm_timers[i].name; i++) {
f3dcfada
TS
767 if (!strcmp(alarm_timers[i].name, name))
768 break;
769 }
770
771 if (i == count) {
772 fprintf(stderr, "Unknown clock %s\n", name);
773 goto next;
774 }
775
776 if (i < cur)
777 /* Ignore */
778 goto next;
779
780 /* Swap */
781 tmp = alarm_timers[i];
782 alarm_timers[i] = alarm_timers[cur];
783 alarm_timers[cur] = tmp;
784
785 cur++;
786next:
787 name = strtok(NULL, ",");
788 }
789
73ffc805 790 qemu_free(arg);
f3dcfada
TS
791
792 if (cur) {
2e70f6ef 793 /* Disable remaining timers */
f3dcfada
TS
794 for (i = cur; i < count; i++)
795 alarm_timers[i].name = NULL;
3adda04c
AJ
796 } else {
797 show_available_alarms();
798 exit(1);
f3dcfada 799 }
f3dcfada
TS
800}
801
21d5d12b
JK
802#define QEMU_NUM_CLOCKS 3
803
c8994013
TS
804QEMUClock *rt_clock;
805QEMUClock *vm_clock;
21d5d12b 806QEMUClock *host_clock;
c8994013 807
21d5d12b 808static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
c8994013 809
9596ebb7 810static QEMUClock *qemu_new_clock(int type)
8a7ddc38
FB
811{
812 QEMUClock *clock;
813 clock = qemu_mallocz(sizeof(QEMUClock));
8a7ddc38
FB
814 clock->type = type;
815 return clock;
816}
817
818QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
819{
820 QEMUTimer *ts;
821
822 ts = qemu_mallocz(sizeof(QEMUTimer));
823 ts->clock = clock;
824 ts->cb = cb;
825 ts->opaque = opaque;
826 return ts;
827}
828
829void qemu_free_timer(QEMUTimer *ts)
830{
831 qemu_free(ts);
832}
833
834/* stop a timer, but do not dealloc it */
835void qemu_del_timer(QEMUTimer *ts)
836{
837 QEMUTimer **pt, *t;
838
839 /* NOTE: this code must be signal safe because
840 qemu_timer_expired() can be called from a signal. */
841 pt = &active_timers[ts->clock->type];
842 for(;;) {
843 t = *pt;
844 if (!t)
845 break;
846 if (t == ts) {
847 *pt = t->next;
848 break;
849 }
850 pt = &t->next;
851 }
852}
853
854/* modify the current timer so that it will be fired when current_time
855 >= expire_time. The corresponding callback will be called. */
856void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
857{
858 QEMUTimer **pt, *t;
859
860 qemu_del_timer(ts);
861
862 /* add the timer in the sorted list */
863 /* NOTE: this code must be signal safe because
864 qemu_timer_expired() can be called from a signal. */
865 pt = &active_timers[ts->clock->type];
866 for(;;) {
867 t = *pt;
868 if (!t)
869 break;
5fafdf24 870 if (t->expire_time > expire_time)
8a7ddc38
FB
871 break;
872 pt = &t->next;
873 }
874 ts->expire_time = expire_time;
875 ts->next = *pt;
876 *pt = ts;
d5d08334
AZ
877
878 /* Rearm if necessary */
2e70f6ef 879 if (pt == &active_timers[ts->clock->type]) {
1828be31 880 if (!alarm_timer->pending) {
2e70f6ef
PB
881 qemu_rearm_alarm_timer(alarm_timer);
882 }
883 /* Interrupt execution to force deadline recalculation. */
d9f75a4e
AL
884 if (use_icount)
885 qemu_notify_event();
2e70f6ef 886 }
8a7ddc38
FB
887}
888
889int qemu_timer_pending(QEMUTimer *ts)
890{
891 QEMUTimer *t;
892 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
893 if (t == ts)
894 return 1;
895 }
896 return 0;
897}
898
2430ffe4 899int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
8a7ddc38
FB
900{
901 if (!timer_head)
902 return 0;
903 return (timer_head->expire_time <= current_time);
904}
905
906static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
907{
908 QEMUTimer *ts;
3b46e624 909
8a7ddc38
FB
910 for(;;) {
911 ts = *ptimer_head;
e95c8d51 912 if (!ts || ts->expire_time > current_time)
8a7ddc38
FB
913 break;
914 /* remove timer from the list before calling the callback */
915 *ptimer_head = ts->next;
916 ts->next = NULL;
3b46e624 917
8a7ddc38
FB
918 /* run the callback (the timer list can be modified) */
919 ts->cb(ts->opaque);
920 }
921}
922
923int64_t qemu_get_clock(QEMUClock *clock)
924{
925 switch(clock->type) {
0fdddf80 926 case QEMU_CLOCK_REALTIME:
1dce7c3c 927 return get_clock() / 1000000;
8a7ddc38 928 default:
0fdddf80 929 case QEMU_CLOCK_VIRTUAL:
2e70f6ef
PB
930 if (use_icount) {
931 return cpu_get_icount();
932 } else {
933 return cpu_get_clock();
934 }
21d5d12b
JK
935 case QEMU_CLOCK_HOST:
936 return get_clock_realtime();
8a7ddc38
FB
937 }
938}
939
41c872b6
PB
940int64_t qemu_get_clock_ns(QEMUClock *clock)
941{
942 switch(clock->type) {
943 case QEMU_CLOCK_REALTIME:
944 return get_clock();
945 default:
946 case QEMU_CLOCK_VIRTUAL:
947 if (use_icount) {
948 return cpu_get_icount();
949 } else {
950 return cpu_get_clock();
951 }
952 case QEMU_CLOCK_HOST:
953 return get_clock_realtime();
954 }
955}
956
0fdddf80 957static void init_clocks(void)
1dce7c3c
FB
958{
959 init_get_clock();
0fdddf80
JK
960 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
961 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
21d5d12b 962 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
6875204c
JK
963
964 rtc_clock = host_clock;
1dce7c3c
FB
965}
966
8a7ddc38
FB
967/* save a timer */
968void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
969{
970 uint64_t expire_time;
971
972 if (qemu_timer_pending(ts)) {
973 expire_time = ts->expire_time;
974 } else {
975 expire_time = -1;
976 }
977 qemu_put_be64(f, expire_time);
978}
979
980void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
981{
982 uint64_t expire_time;
983
984 expire_time = qemu_get_be64(f);
985 if (expire_time != -1) {
986 qemu_mod_timer(ts, expire_time);
987 } else {
988 qemu_del_timer(ts);
989 }
990}
991
2faf58cd
JQ
992static const VMStateDescription vmstate_timers = {
993 .name = "timer",
994 .version_id = 2,
995 .minimum_version_id = 1,
996 .minimum_version_id_old = 1,
997 .fields = (VMStateField []) {
998 VMSTATE_INT64(cpu_ticks_offset, TimersState),
274dfed8 999 VMSTATE_INT64(dummy, TimersState),
2faf58cd
JQ
1000 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1001 VMSTATE_END_OF_LIST()
c88676f8 1002 }
2faf58cd 1003};
8a7ddc38 1004
50317c7f
AL
1005static void qemu_event_increment(void);
1006
67b915a5 1007#ifdef _WIN32
b9e82a59
BS
1008static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1009 DWORD_PTR dwUser, DWORD_PTR dw1,
1010 DWORD_PTR dw2)
67b915a5 1011#else
8a7ddc38 1012static void host_alarm_handler(int host_signum)
67b915a5 1013#endif
8a7ddc38 1014{
1828be31
PB
1015 struct qemu_alarm_timer *t = alarm_timer;
1016 if (!t)
1017 return;
1018
02ba45c5
FB
1019#if 0
1020#define DISP_FREQ 1000
1021 {
1022 static int64_t delta_min = INT64_MAX;
1023 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1024 static int count;
1025 ti = qemu_get_clock(vm_clock);
1026 if (last_clock != 0) {
1027 delta = ti - last_clock;
1028 if (delta < delta_min)
1029 delta_min = delta;
1030 if (delta > delta_max)
1031 delta_max = delta;
1032 delta_cum += delta;
1033 if (++count == DISP_FREQ) {
26a76461 1034 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
6ee093c9
JQ
1035 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1036 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1037 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1038 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
02ba45c5
FB
1039 count = 0;
1040 delta_min = INT64_MAX;
1041 delta_max = 0;
1042 delta_cum = 0;
1043 }
1044 }
1045 last_clock = ti;
1046 }
1047#endif
1828be31 1048 if (alarm_has_dynticks(t) ||
2e70f6ef 1049 (!use_icount &&
0fdddf80 1050 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
2e70f6ef 1051 qemu_get_clock(vm_clock))) ||
0fdddf80 1052 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
21d5d12b
JK
1053 qemu_get_clock(rt_clock)) ||
1054 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1055 qemu_get_clock(host_clock))) {
7a5e5838 1056
1828be31 1057 t->expired = alarm_has_dynticks(t);
d5d08334 1058
d6dc3d42
AL
1059#ifndef CONFIG_IOTHREAD
1060 if (next_cpu) {
4f8eb8da 1061 /* stop the currently executing cpu because a timer occured */
d6dc3d42 1062 cpu_exit(next_cpu);
4f8eb8da 1063 }
d6dc3d42 1064#endif
1828be31 1065 t->pending = 1;
d9f75a4e 1066 qemu_notify_event();
8a7ddc38
FB
1067 }
1068}
1069
2e70f6ef 1070static int64_t qemu_next_deadline(void)
efe75411 1071{
21d5d12b
JK
1072 /* To avoid problems with overflow limit this to 2^32. */
1073 int64_t delta = INT32_MAX;
efe75411 1074
0fdddf80
JK
1075 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1076 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
2e70f6ef 1077 qemu_get_clock(vm_clock);
21d5d12b
JK
1078 }
1079 if (active_timers[QEMU_CLOCK_HOST]) {
1080 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1081 qemu_get_clock(host_clock);
1082 if (hdelta < delta)
1083 delta = hdelta;
efe75411
TS
1084 }
1085
2e70f6ef
PB
1086 if (delta < 0)
1087 delta = 0;
efe75411 1088
2e70f6ef
PB
1089 return delta;
1090}
1091
f64382ba 1092#if defined(__linux__)
2e70f6ef
PB
1093static uint64_t qemu_next_deadline_dyntick(void)
1094{
1095 int64_t delta;
1096 int64_t rtdelta;
1097
1098 if (use_icount)
1099 delta = INT32_MAX;
1100 else
1101 delta = (qemu_next_deadline() + 999) / 1000;
1102
0fdddf80
JK
1103 if (active_timers[QEMU_CLOCK_REALTIME]) {
1104 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
2e70f6ef
PB
1105 qemu_get_clock(rt_clock))*1000;
1106 if (rtdelta < delta)
1107 delta = rtdelta;
1108 }
1109
1110 if (delta < MIN_TIMER_REARM_US)
1111 delta = MIN_TIMER_REARM_US;
1112
1113 return delta;
efe75411 1114}
8632fb9a 1115#endif
efe75411 1116
fd872598
FB
1117#ifndef _WIN32
1118
7183b4b4
AL
1119/* Sets a specific flag */
1120static int fcntl_setfl(int fd, int flag)
1121{
1122 int flags;
1123
1124 flags = fcntl(fd, F_GETFL);
1125 if (flags == -1)
1126 return -errno;
1127
1128 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1129 return -errno;
1130
1131 return 0;
1132}
1133
829309c7
FB
1134#if defined(__linux__)
1135
fd872598
FB
1136#define RTC_FREQ 1024
1137
de9a95f0 1138static void enable_sigio_timer(int fd)
c8994013
TS
1139{
1140 struct sigaction act;
1141
1142 /* timer signal */
1143 sigfillset(&act.sa_mask);
1144 act.sa_flags = 0;
c8994013
TS
1145 act.sa_handler = host_alarm_handler;
1146
1147 sigaction(SIGIO, &act, NULL);
7183b4b4 1148 fcntl_setfl(fd, O_ASYNC);
c8994013
TS
1149 fcntl(fd, F_SETOWN, getpid());
1150}
829309c7 1151
c40ec5a9
TS
1152static int hpet_start_timer(struct qemu_alarm_timer *t)
1153{
1154 struct hpet_info info;
1155 int r, fd;
1156
40ff6d7e 1157 fd = qemu_open("/dev/hpet", O_RDONLY);
c40ec5a9
TS
1158 if (fd < 0)
1159 return -1;
1160
1161 /* Set frequency */
1162 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1163 if (r < 0) {
1164 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1165 "error, but for better emulation accuracy type:\n"
1166 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1167 goto fail;
1168 }
1169
1170 /* Check capabilities */
1171 r = ioctl(fd, HPET_INFO, &info);
1172 if (r < 0)
1173 goto fail;
1174
1175 /* Enable periodic mode */
1176 r = ioctl(fd, HPET_EPI, 0);
1177 if (info.hi_flags && (r < 0))
1178 goto fail;
1179
1180 /* Enable interrupt */
1181 r = ioctl(fd, HPET_IE_ON, 0);
1182 if (r < 0)
1183 goto fail;
1184
1185 enable_sigio_timer(fd);
fcdc2129 1186 t->priv = (void *)(long)fd;
c40ec5a9
TS
1187
1188 return 0;
1189fail:
1190 close(fd);
1191 return -1;
1192}
1193
1194static void hpet_stop_timer(struct qemu_alarm_timer *t)
1195{
fcdc2129 1196 int fd = (long)t->priv;
c40ec5a9
TS
1197
1198 close(fd);
1199}
1200
c8994013 1201static int rtc_start_timer(struct qemu_alarm_timer *t)
fd872598 1202{
c8994013 1203 int rtc_fd;
b5a23ad4 1204 unsigned long current_rtc_freq = 0;
c8994013 1205
40ff6d7e 1206 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
fd872598
FB
1207 if (rtc_fd < 0)
1208 return -1;
b5a23ad4
AZ
1209 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1210 if (current_rtc_freq != RTC_FREQ &&
1211 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
fd872598
FB
1212 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1213 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1214 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1215 goto fail;
1216 }
1217 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1218 fail:
1219 close(rtc_fd);
1220 return -1;
1221 }
c8994013
TS
1222
1223 enable_sigio_timer(rtc_fd);
1224
fcdc2129 1225 t->priv = (void *)(long)rtc_fd;
c8994013 1226
fd872598
FB
1227 return 0;
1228}
1229
c8994013 1230static void rtc_stop_timer(struct qemu_alarm_timer *t)
829309c7 1231{
fcdc2129 1232 int rtc_fd = (long)t->priv;
c8994013
TS
1233
1234 close(rtc_fd);
829309c7
FB
1235}
1236
efe75411
TS
1237static int dynticks_start_timer(struct qemu_alarm_timer *t)
1238{
1239 struct sigevent ev;
1240 timer_t host_timer;
1241 struct sigaction act;
1242
1243 sigfillset(&act.sa_mask);
1244 act.sa_flags = 0;
efe75411
TS
1245 act.sa_handler = host_alarm_handler;
1246
1247 sigaction(SIGALRM, &act, NULL);
1248
9ed415b2
JCD
1249 /*
1250 * Initialize ev struct to 0 to avoid valgrind complaining
1251 * about uninitialized data in timer_create call
1252 */
1253 memset(&ev, 0, sizeof(ev));
efe75411
TS
1254 ev.sigev_value.sival_int = 0;
1255 ev.sigev_notify = SIGEV_SIGNAL;
1256 ev.sigev_signo = SIGALRM;
1257
1258 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1259 perror("timer_create");
1260
1261 /* disable dynticks */
1262 fprintf(stderr, "Dynamic Ticks disabled\n");
1263
1264 return -1;
1265 }
1266
0399bfe0 1267 t->priv = (void *)(long)host_timer;
efe75411
TS
1268
1269 return 0;
1270}
1271
1272static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1273{
0399bfe0 1274 timer_t host_timer = (timer_t)(long)t->priv;
efe75411
TS
1275
1276 timer_delete(host_timer);
1277}
1278
1279static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1280{
0399bfe0 1281 timer_t host_timer = (timer_t)(long)t->priv;
efe75411
TS
1282 struct itimerspec timeout;
1283 int64_t nearest_delta_us = INT64_MAX;
1284 int64_t current_us;
1285
cd48d7e8 1286 assert(alarm_has_dynticks(t));
0fdddf80 1287 if (!active_timers[QEMU_CLOCK_REALTIME] &&
21d5d12b
JK
1288 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1289 !active_timers[QEMU_CLOCK_HOST])
d5d08334 1290 return;
efe75411 1291
2e70f6ef 1292 nearest_delta_us = qemu_next_deadline_dyntick();
efe75411
TS
1293
1294 /* check whether a timer is already running */
1295 if (timer_gettime(host_timer, &timeout)) {
1296 perror("gettime");
1297 fprintf(stderr, "Internal timer error: aborting\n");
1298 exit(1);
1299 }
1300 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1301 if (current_us && current_us <= nearest_delta_us)
1302 return;
1303
1304 timeout.it_interval.tv_sec = 0;
1305 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1306 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1307 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1308 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1309 perror("settime");
1310 fprintf(stderr, "Internal timer error: aborting\n");
1311 exit(1);
1312 }
1313}
1314
70744b3a 1315#endif /* defined(__linux__) */
231c6586 1316
c8994013
TS
1317static int unix_start_timer(struct qemu_alarm_timer *t)
1318{
1319 struct sigaction act;
1320 struct itimerval itv;
1321 int err;
1322
1323 /* timer signal */
1324 sigfillset(&act.sa_mask);
1325 act.sa_flags = 0;
c8994013
TS
1326 act.sa_handler = host_alarm_handler;
1327
1328 sigaction(SIGALRM, &act, NULL);
1329
1330 itv.it_interval.tv_sec = 0;
1331 /* for i386 kernel 2.6 to get 1 ms */
1332 itv.it_interval.tv_usec = 999;
1333 itv.it_value.tv_sec = 0;
1334 itv.it_value.tv_usec = 10 * 1000;
1335
1336 err = setitimer(ITIMER_REAL, &itv, NULL);
1337 if (err)
1338 return -1;
1339
1340 return 0;
1341}
1342
1343static void unix_stop_timer(struct qemu_alarm_timer *t)
1344{
1345 struct itimerval itv;
1346
1347 memset(&itv, 0, sizeof(itv));
1348 setitimer(ITIMER_REAL, &itv, NULL);
1349}
1350
829309c7 1351#endif /* !defined(_WIN32) */
fd872598 1352
f49e58dc 1353
c8994013
TS
1354#ifdef _WIN32
1355
1356static int win32_start_timer(struct qemu_alarm_timer *t)
1357{
1358 TIMECAPS tc;
1359 struct qemu_alarm_win32 *data = t->priv;
efe75411 1360 UINT flags;
c8994013 1361
c8994013
TS
1362 memset(&tc, 0, sizeof(tc));
1363 timeGetDevCaps(&tc, sizeof(tc));
1364
9aea1029 1365 data->period = tc.wPeriodMin;
c8994013
TS
1366 timeBeginPeriod(data->period);
1367
efe75411
TS
1368 flags = TIME_CALLBACK_FUNCTION;
1369 if (alarm_has_dynticks(t))
1370 flags |= TIME_ONESHOT;
1371 else
1372 flags |= TIME_PERIODIC;
1373
c8994013
TS
1374 data->timerId = timeSetEvent(1, // interval (ms)
1375 data->period, // resolution
1376 host_alarm_handler, // function
1377 (DWORD)t, // parameter
efe75411 1378 flags);
c8994013
TS
1379
1380 if (!data->timerId) {
20889d4e 1381 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
705e83f6 1382 GetLastError());
c8994013 1383 timeEndPeriod(data->period);
c8994013
TS
1384 return -1;
1385 }
1386
c8994013
TS
1387 return 0;
1388}
1389
1390static void win32_stop_timer(struct qemu_alarm_timer *t)
1391{
1392 struct qemu_alarm_win32 *data = t->priv;
1393
1394 timeKillEvent(data->timerId);
1395 timeEndPeriod(data->period);
c8994013
TS
1396}
1397
efe75411
TS
1398static void win32_rearm_timer(struct qemu_alarm_timer *t)
1399{
1400 struct qemu_alarm_win32 *data = t->priv;
efe75411 1401
cd48d7e8 1402 assert(alarm_has_dynticks(t));
0fdddf80 1403 if (!active_timers[QEMU_CLOCK_REALTIME] &&
21d5d12b
JK
1404 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1405 !active_timers[QEMU_CLOCK_HOST])
d5d08334 1406 return;
efe75411 1407
efe75411
TS
1408 timeKillEvent(data->timerId);
1409
1410 data->timerId = timeSetEvent(1,
1411 data->period,
1412 host_alarm_handler,
1413 (DWORD)t,
291defbc 1414 TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
efe75411
TS
1415
1416 if (!data->timerId) {
20889d4e 1417 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
705e83f6 1418 GetLastError());
efe75411
TS
1419
1420 timeEndPeriod(data->period);
efe75411
TS
1421 exit(1);
1422 }
1423}
1424
c8994013
TS
1425#endif /* _WIN32 */
1426
7183b4b4 1427static int init_timer_alarm(void)
8a7ddc38 1428{
223f0d72 1429 struct qemu_alarm_timer *t = NULL;
c8994013 1430 int i, err = -1;
f49e58dc 1431
c8994013
TS
1432 for (i = 0; alarm_timers[i].name; i++) {
1433 t = &alarm_timers[i];
1434
c8994013
TS
1435 err = t->start(t);
1436 if (!err)
1437 break;
67b915a5 1438 }
fd872598 1439
c8994013 1440 if (err) {
7183b4b4
AL
1441 err = -ENOENT;
1442 goto fail;
67b915a5 1443 }
c8994013 1444
1828be31
PB
1445 /* first event is at time 0 */
1446 t->pending = 1;
c8994013 1447 alarm_timer = t;
7183b4b4 1448
6abfbd79 1449 return 0;
7183b4b4
AL
1450
1451fail:
7183b4b4 1452 return err;
8a7ddc38
FB
1453}
1454
9596ebb7 1455static void quit_timers(void)
40c3bac3 1456{
1828be31 1457 struct qemu_alarm_timer *t = alarm_timer;
c8994013 1458 alarm_timer = NULL;
1828be31 1459 t->stop(t);
40c3bac3
FB
1460}
1461
f6503059
AZ
1462/***********************************************************/
1463/* host time/date access */
1464void qemu_get_timedate(struct tm *tm, int offset)
1465{
1466 time_t ti;
1467 struct tm *ret;
1468
1469 time(&ti);
1470 ti += offset;
1471 if (rtc_date_offset == -1) {
1472 if (rtc_utc)
1473 ret = gmtime(&ti);
1474 else
1475 ret = localtime(&ti);
1476 } else {
1477 ti -= rtc_date_offset;
1478 ret = gmtime(&ti);
1479 }
1480
1481 memcpy(tm, ret, sizeof(struct tm));
1482}
1483
1484int qemu_timedate_diff(struct tm *tm)
1485{
1486 time_t seconds;
1487
1488 if (rtc_date_offset == -1)
1489 if (rtc_utc)
1490 seconds = mktimegm(tm);
1491 else
1492 seconds = mktime(tm);
1493 else
1494 seconds = mktimegm(tm) + rtc_date_offset;
1495
1496 return seconds - time(NULL);
1497}
1498
80cd3478
LC
1499void rtc_change_mon_event(struct tm *tm)
1500{
1501 QObject *data;
1502
1503 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
1504 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
1505 qobject_decref(data);
1506}
1507
1ed2fc1f
JK
1508static void configure_rtc_date_offset(const char *startdate, int legacy)
1509{
1510 time_t rtc_start_date;
1511 struct tm tm;
1512
1513 if (!strcmp(startdate, "now") && legacy) {
1514 rtc_date_offset = -1;
1515 } else {
1516 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1517 &tm.tm_year,
1518 &tm.tm_mon,
1519 &tm.tm_mday,
1520 &tm.tm_hour,
1521 &tm.tm_min,
1522 &tm.tm_sec) == 6) {
1523 /* OK */
1524 } else if (sscanf(startdate, "%d-%d-%d",
1525 &tm.tm_year,
1526 &tm.tm_mon,
1527 &tm.tm_mday) == 3) {
1528 tm.tm_hour = 0;
1529 tm.tm_min = 0;
1530 tm.tm_sec = 0;
1531 } else {
1532 goto date_fail;
1533 }
1534 tm.tm_year -= 1900;
1535 tm.tm_mon--;
1536 rtc_start_date = mktimegm(&tm);
1537 if (rtc_start_date == -1) {
1538 date_fail:
1539 fprintf(stderr, "Invalid date format. Valid formats are:\n"
1540 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1541 exit(1);
1542 }
1543 rtc_date_offset = time(NULL) - rtc_start_date;
1544 }
1545}
1546
1547static void configure_rtc(QemuOpts *opts)
1548{
1549 const char *value;
1550
1551 value = qemu_opt_get(opts, "base");
1552 if (value) {
1553 if (!strcmp(value, "utc")) {
1554 rtc_utc = 1;
1555 } else if (!strcmp(value, "localtime")) {
1556 rtc_utc = 0;
1557 } else {
1558 configure_rtc_date_offset(value, 0);
1559 }
1560 }
6875204c
JK
1561 value = qemu_opt_get(opts, "clock");
1562 if (value) {
1563 if (!strcmp(value, "host")) {
1564 rtc_clock = host_clock;
1565 } else if (!strcmp(value, "vm")) {
1566 rtc_clock = vm_clock;
1567 } else {
1568 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1569 exit(1);
1570 }
1571 }
1ed2fc1f
JK
1572#ifdef CONFIG_TARGET_I386
1573 value = qemu_opt_get(opts, "driftfix");
1574 if (value) {
1575 if (!strcmp(buf, "slew")) {
1576 rtc_td_hack = 1;
1577 } else if (!strcmp(buf, "none")) {
1578 rtc_td_hack = 0;
1579 } else {
1580 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1581 exit(1);
1582 }
1583 }
1584#endif
1585}
1586
fd1dff4b 1587#ifdef _WIN32
fd1dff4b
FB
1588static void socket_cleanup(void)
1589{
1590 WSACleanup();
1591}
82c643ff 1592
fd1dff4b
FB
1593static int socket_init(void)
1594{
1595 WSADATA Data;
1596 int ret, err;
1597
1598 ret = WSAStartup(MAKEWORD(2,2), &Data);
1599 if (ret != 0) {
1600 err = WSAGetLastError();
1601 fprintf(stderr, "WSAStartup: %d\n", err);
1602 return -1;
1603 }
1604 atexit(socket_cleanup);
1605 return 0;
1606}
64b7b733
AJ
1607#endif
1608
1ae26a18
AZ
1609/***********************************************************/
1610/* Bluetooth support */
1611static int nb_hcis;
1612static int cur_hci;
1613static struct HCIInfo *hci_table[MAX_NICS];
dc72ac14 1614
1ae26a18
AZ
1615static struct bt_vlan_s {
1616 struct bt_scatternet_s net;
1617 int id;
1618 struct bt_vlan_s *next;
1619} *first_bt_vlan;
1620
1621/* find or alloc a new bluetooth "VLAN" */
674bb261 1622static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1ae26a18
AZ
1623{
1624 struct bt_vlan_s **pvlan, *vlan;
1625 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1626 if (vlan->id == id)
1627 return &vlan->net;
1628 }
1629 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1630 vlan->id = id;
1631 pvlan = &first_bt_vlan;
1632 while (*pvlan != NULL)
1633 pvlan = &(*pvlan)->next;
1634 *pvlan = vlan;
1635 return &vlan->net;
1636}
1637
1638static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1639{
1640}
1641
1642static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1643{
1644 return -ENOTSUP;
1645}
1646
1647static struct HCIInfo null_hci = {
1648 .cmd_send = null_hci_send,
1649 .sco_send = null_hci_send,
1650 .acl_send = null_hci_send,
1651 .bdaddr_set = null_hci_addr_set,
1652};
1653
1654struct HCIInfo *qemu_next_hci(void)
1655{
1656 if (cur_hci == nb_hcis)
1657 return &null_hci;
1658
1659 return hci_table[cur_hci++];
1660}
1661
dc72ac14
AZ
1662static struct HCIInfo *hci_init(const char *str)
1663{
1664 char *endp;
1665 struct bt_scatternet_s *vlan = 0;
1666
1667 if (!strcmp(str, "null"))
1668 /* null */
1669 return &null_hci;
1670 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1671 /* host[:hciN] */
1672 return bt_host_hci(str[4] ? str + 5 : "hci0");
1673 else if (!strncmp(str, "hci", 3)) {
1674 /* hci[,vlan=n] */
1675 if (str[3]) {
1676 if (!strncmp(str + 3, ",vlan=", 6)) {
1677 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1678 if (*endp)
1679 vlan = 0;
1680 }
1681 } else
1682 vlan = qemu_find_bt_vlan(0);
1683 if (vlan)
1684 return bt_new_hci(vlan);
1685 }
1686
1687 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1688
1689 return 0;
1690}
1691
1692static int bt_hci_parse(const char *str)
1693{
1694 struct HCIInfo *hci;
c227f099 1695 bdaddr_t bdaddr;
dc72ac14
AZ
1696
1697 if (nb_hcis >= MAX_NICS) {
1698 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1699 return -1;
1700 }
1701
1702 hci = hci_init(str);
1703 if (!hci)
1704 return -1;
1705
1706 bdaddr.b[0] = 0x52;
1707 bdaddr.b[1] = 0x54;
1708 bdaddr.b[2] = 0x00;
1709 bdaddr.b[3] = 0x12;
1710 bdaddr.b[4] = 0x34;
1711 bdaddr.b[5] = 0x56 + nb_hcis;
1712 hci->bdaddr_set(hci, bdaddr.b);
1713
1714 hci_table[nb_hcis++] = hci;
1715
1716 return 0;
1717}
1718
1719static void bt_vhci_add(int vlan_id)
1720{
1721 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1722
1723 if (!vlan->slave)
1724 fprintf(stderr, "qemu: warning: adding a VHCI to "
1725 "an empty scatternet %i\n", vlan_id);
1726
1727 bt_vhci_init(bt_new_hci(vlan));
1728}
1729
1730static struct bt_device_s *bt_device_add(const char *opt)
1731{
1732 struct bt_scatternet_s *vlan;
1733 int vlan_id = 0;
1734 char *endp = strstr(opt, ",vlan=");
1735 int len = (endp ? endp - opt : strlen(opt)) + 1;
1736 char devname[10];
1737
1738 pstrcpy(devname, MIN(sizeof(devname), len), opt);
1739
1740 if (endp) {
1741 vlan_id = strtol(endp + 6, &endp, 0);
1742 if (*endp) {
1743 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1744 return 0;
1745 }
1746 }
1747
1748 vlan = qemu_find_bt_vlan(vlan_id);
1749
1750 if (!vlan->slave)
1751 fprintf(stderr, "qemu: warning: adding a slave device to "
1752 "an empty scatternet %i\n", vlan_id);
1753
1754 if (!strcmp(devname, "keyboard"))
1755 return bt_keyboard_init(vlan);
1756
1757 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1758 return 0;
1759}
1760
1761static int bt_parse(const char *opt)
1762{
1763 const char *endp, *p;
1764 int vlan;
1765
1766 if (strstart(opt, "hci", &endp)) {
1767 if (!*endp || *endp == ',') {
1768 if (*endp)
1769 if (!strstart(endp, ",vlan=", 0))
1770 opt = endp + 1;
1771
1772 return bt_hci_parse(opt);
1773 }
1774 } else if (strstart(opt, "vhci", &endp)) {
1775 if (!*endp || *endp == ',') {
1776 if (*endp) {
1777 if (strstart(endp, ",vlan=", &p)) {
1778 vlan = strtol(p, (char **) &endp, 0);
1779 if (*endp) {
1780 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1781 return 1;
1782 }
1783 } else {
1784 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1785 return 1;
1786 }
1787 } else
1788 vlan = 0;
1789
1790 bt_vhci_add(vlan);
1791 return 0;
1792 }
1793 } else if (strstart(opt, "device:", &endp))
1794 return !bt_device_add(endp);
1795
1796 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1797 return 1;
1798}
1799
1ae26a18
AZ
1800/***********************************************************/
1801/* QEMU Block devices */
1802
609497ab 1803#define HD_ALIAS "index=%d,media=disk"
e4bcb14c 1804#define CDROM_ALIAS "index=2,media=cdrom"
e4bcb14c 1805#define FD_ALIAS "index=%d,if=floppy"
609497ab
AZ
1806#define PFLASH_ALIAS "if=pflash"
1807#define MTD_ALIAS "if=mtd"
9d413d1d 1808#define SD_ALIAS "index=0,if=sd"
e4bcb14c 1809
9dfd7c7a 1810QemuOpts *drive_add(const char *file, const char *fmt, ...)
e4bcb14c
TS
1811{
1812 va_list ap;
9dfd7c7a
GH
1813 char optstr[1024];
1814 QemuOpts *opts;
e4bcb14c 1815
e4bcb14c 1816 va_start(ap, fmt);
9dfd7c7a 1817 vsnprintf(optstr, sizeof(optstr), fmt, ap);
e4bcb14c
TS
1818 va_end(ap);
1819
8212c64f 1820 opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
9dfd7c7a
GH
1821 if (!opts) {
1822 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1823 __FUNCTION__, optstr);
1824 return NULL;
1825 }
1826 if (file)
1827 qemu_opt_set(opts, "file", file);
1828 return opts;
b01b1111
AL
1829}
1830
751c6a17 1831DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
e4bcb14c 1832{
751c6a17 1833 DriveInfo *dinfo;
e4bcb14c
TS
1834
1835 /* seek interface, bus and unit */
1836
72cf2d4f 1837 QTAILQ_FOREACH(dinfo, &drives, next) {
751c6a17
GH
1838 if (dinfo->type == type &&
1839 dinfo->bus == bus &&
1840 dinfo->unit == unit)
1841 return dinfo;
1842 }
e4bcb14c 1843
751c6a17 1844 return NULL;
e4bcb14c
TS
1845}
1846
2e810b36 1847DriveInfo *drive_get_by_id(const char *id)
1dae12e6
GH
1848{
1849 DriveInfo *dinfo;
1850
72cf2d4f 1851 QTAILQ_FOREACH(dinfo, &drives, next) {
1dae12e6
GH
1852 if (strcmp(id, dinfo->id))
1853 continue;
1854 return dinfo;
1855 }
1856 return NULL;
1857}
1858
f60d39bc 1859int drive_get_max_bus(BlockInterfaceType type)
e4bcb14c
TS
1860{
1861 int max_bus;
751c6a17 1862 DriveInfo *dinfo;
e4bcb14c
TS
1863
1864 max_bus = -1;
72cf2d4f 1865 QTAILQ_FOREACH(dinfo, &drives, next) {
751c6a17
GH
1866 if(dinfo->type == type &&
1867 dinfo->bus > max_bus)
1868 max_bus = dinfo->bus;
e4bcb14c
TS
1869 }
1870 return max_bus;
1871}
1872
fa879c64
AL
1873const char *drive_get_serial(BlockDriverState *bdrv)
1874{
751c6a17 1875 DriveInfo *dinfo;
fa879c64 1876
72cf2d4f 1877 QTAILQ_FOREACH(dinfo, &drives, next) {
751c6a17
GH
1878 if (dinfo->bdrv == bdrv)
1879 return dinfo->serial;
1880 }
fa879c64
AL
1881
1882 return "\0";
1883}
1884
f7850099
KW
1885BlockInterfaceErrorAction drive_get_on_error(
1886 BlockDriverState *bdrv, int is_read)
428c5705 1887{
751c6a17 1888 DriveInfo *dinfo;
428c5705 1889
72cf2d4f 1890 QTAILQ_FOREACH(dinfo, &drives, next) {
751c6a17 1891 if (dinfo->bdrv == bdrv)
e9b2e818 1892 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
751c6a17 1893 }
428c5705 1894
e9b2e818 1895 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
428c5705
AL
1896}
1897
a1620fac
AJ
1898static void bdrv_format_print(void *opaque, const char *name)
1899{
1900 fprintf(stderr, " %s", name);
1901}
1902
56a14938 1903void drive_uninit(DriveInfo *dinfo)
b01b1111 1904{
56a14938
GH
1905 qemu_opts_del(dinfo->opts);
1906 bdrv_delete(dinfo->bdrv);
1907 QTAILQ_REMOVE(&drives, dinfo, next);
1908 qemu_free(dinfo);
b01b1111
AL
1909}
1910
e9b2e818
KW
1911static int parse_block_error_action(const char *buf, int is_read)
1912{
1913 if (!strcmp(buf, "ignore")) {
1914 return BLOCK_ERR_IGNORE;
1915 } else if (!is_read && !strcmp(buf, "enospc")) {
1916 return BLOCK_ERR_STOP_ENOSPC;
1917 } else if (!strcmp(buf, "stop")) {
1918 return BLOCK_ERR_STOP_ANY;
1919 } else if (!strcmp(buf, "report")) {
1920 return BLOCK_ERR_REPORT;
1921 } else {
1922 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1923 buf, is_read ? "read" : "write");
1924 return -1;
1925 }
1926}
1927
9dfd7c7a 1928DriveInfo *drive_init(QemuOpts *opts, void *opaque,
751c6a17 1929 int *fatal_error)
e4bcb14c 1930{
9dfd7c7a
GH
1931 const char *buf;
1932 const char *file = NULL;
c8522bdf 1933 char devname[128];
9dfd7c7a 1934 const char *serial;
c8522bdf 1935 const char *mediastr = "";
f60d39bc 1936 BlockInterfaceType type;
e4bcb14c
TS
1937 enum { MEDIA_DISK, MEDIA_CDROM } media;
1938 int bus_id, unit_id;
1939 int cyls, heads, secs, translation;
1e72d3b7 1940 BlockDriver *drv = NULL;
4d73cd3b 1941 QEMUMachine *machine = opaque;
e4bcb14c
TS
1942 int max_devs;
1943 int index;
33f00271 1944 int cache;
5c6c3a6c 1945 int aio = 0;
59f2689d 1946 int ro = 0;
e9b2e818
KW
1947 int bdrv_flags;
1948 int on_read_error, on_write_error;
c2cc47a4 1949 const char *devaddr;
751c6a17 1950 DriveInfo *dinfo;
9dfd7c7a 1951 int snapshot = 0;
e4bcb14c 1952
9dfd7c7a 1953 *fatal_error = 1;
e4bcb14c 1954
e4bcb14c 1955 translation = BIOS_ATA_TRANSLATION_AUTO;
0aa217e4 1956 cache = 1;
e4bcb14c 1957
4d007814 1958 if (machine && machine->use_scsi) {
f60d39bc 1959 type = IF_SCSI;
e4bcb14c 1960 max_devs = MAX_SCSI_DEVS;
363a37d5 1961 pstrcpy(devname, sizeof(devname), "scsi");
e4bcb14c 1962 } else {
f60d39bc 1963 type = IF_IDE;
e4bcb14c 1964 max_devs = MAX_IDE_DEVS;
363a37d5 1965 pstrcpy(devname, sizeof(devname), "ide");
e4bcb14c
TS
1966 }
1967 media = MEDIA_DISK;
1968
1969 /* extract parameters */
9dfd7c7a
GH
1970 bus_id = qemu_opt_get_number(opts, "bus", 0);
1971 unit_id = qemu_opt_get_number(opts, "unit", -1);
1972 index = qemu_opt_get_number(opts, "index", -1);
e4bcb14c 1973
9dfd7c7a
GH
1974 cyls = qemu_opt_get_number(opts, "cyls", 0);
1975 heads = qemu_opt_get_number(opts, "heads", 0);
1976 secs = qemu_opt_get_number(opts, "secs", 0);
e4bcb14c 1977
9dfd7c7a 1978 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
59f2689d 1979 ro = qemu_opt_get_bool(opts, "readonly", 0);
e4bcb14c 1980
9dfd7c7a
GH
1981 file = qemu_opt_get(opts, "file");
1982 serial = qemu_opt_get(opts, "serial");
1983
1984 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
ae45d369 1985 pstrcpy(devname, sizeof(devname), buf);
e4bcb14c 1986 if (!strcmp(buf, "ide")) {
f60d39bc 1987 type = IF_IDE;
e4bcb14c
TS
1988 max_devs = MAX_IDE_DEVS;
1989 } else if (!strcmp(buf, "scsi")) {
f60d39bc 1990 type = IF_SCSI;
e4bcb14c
TS
1991 max_devs = MAX_SCSI_DEVS;
1992 } else if (!strcmp(buf, "floppy")) {
f60d39bc 1993 type = IF_FLOPPY;
e4bcb14c
TS
1994 max_devs = 0;
1995 } else if (!strcmp(buf, "pflash")) {
f60d39bc 1996 type = IF_PFLASH;
e4bcb14c
TS
1997 max_devs = 0;
1998 } else if (!strcmp(buf, "mtd")) {
f60d39bc 1999 type = IF_MTD;
e4bcb14c
TS
2000 max_devs = 0;
2001 } else if (!strcmp(buf, "sd")) {
f60d39bc 2002 type = IF_SD;
e4bcb14c 2003 max_devs = 0;
6e02c38d
AL
2004 } else if (!strcmp(buf, "virtio")) {
2005 type = IF_VIRTIO;
2006 max_devs = 0;
62d23efa
AL
2007 } else if (!strcmp(buf, "xen")) {
2008 type = IF_XEN;
2009 max_devs = 0;
a8659e90
GH
2010 } else if (!strcmp(buf, "none")) {
2011 type = IF_NONE;
2012 max_devs = 0;
62d23efa 2013 } else {
9dfd7c7a 2014 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
751c6a17 2015 return NULL;
e4bcb14c
TS
2016 }
2017 }
2018
e4bcb14c 2019 if (cyls || heads || secs) {
5afe3f04 2020 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
9dfd7c7a 2021 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
751c6a17 2022 return NULL;
e4bcb14c 2023 }
5afe3f04 2024 if (heads < 1 || (type == IF_IDE && heads > 16)) {
9dfd7c7a 2025 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
751c6a17 2026 return NULL;
e4bcb14c 2027 }
5afe3f04 2028 if (secs < 1 || (type == IF_IDE && secs > 63)) {
9dfd7c7a 2029 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
751c6a17 2030 return NULL;
e4bcb14c
TS
2031 }
2032 }
2033
9dfd7c7a 2034 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
e4bcb14c
TS
2035 if (!cyls) {
2036 fprintf(stderr,
2037 "qemu: '%s' trans must be used with cyls,heads and secs\n",
9dfd7c7a 2038 buf);
751c6a17 2039 return NULL;
e4bcb14c
TS
2040 }
2041 if (!strcmp(buf, "none"))
2042 translation = BIOS_ATA_TRANSLATION_NONE;
2043 else if (!strcmp(buf, "lba"))
2044 translation = BIOS_ATA_TRANSLATION_LBA;
2045 else if (!strcmp(buf, "auto"))
2046 translation = BIOS_ATA_TRANSLATION_AUTO;
2047 else {
9dfd7c7a 2048 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
751c6a17 2049 return NULL;
e4bcb14c
TS
2050 }
2051 }
2052
9dfd7c7a 2053 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
e4bcb14c
TS
2054 if (!strcmp(buf, "disk")) {
2055 media = MEDIA_DISK;
2056 } else if (!strcmp(buf, "cdrom")) {
2057 if (cyls || secs || heads) {
2058 fprintf(stderr,
9dfd7c7a 2059 "qemu: '%s' invalid physical CHS format\n", buf);
751c6a17 2060 return NULL;
e4bcb14c
TS
2061 }
2062 media = MEDIA_CDROM;
2063 } else {
9dfd7c7a 2064 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
751c6a17 2065 return NULL;
e4bcb14c
TS
2066 }
2067 }
2068
9dfd7c7a 2069 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
9f7965c7 2070 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
33f00271 2071 cache = 0;
9f7965c7 2072 else if (!strcmp(buf, "writethrough"))
33f00271 2073 cache = 1;
9f7965c7
AL
2074 else if (!strcmp(buf, "writeback"))
2075 cache = 2;
33f00271
AZ
2076 else {
2077 fprintf(stderr, "qemu: invalid cache option\n");
751c6a17 2078 return NULL;
33f00271
AZ
2079 }
2080 }
2081
5c6c3a6c
CH
2082#ifdef CONFIG_LINUX_AIO
2083 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2084 if (!strcmp(buf, "threads"))
2085 aio = 0;
2086 else if (!strcmp(buf, "native"))
2087 aio = 1;
2088 else {
2089 fprintf(stderr, "qemu: invalid aio option\n");
2090 return NULL;
2091 }
2092 }
2093#endif
2094
9dfd7c7a 2095 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
a1620fac
AJ
2096 if (strcmp(buf, "?") == 0) {
2097 fprintf(stderr, "qemu: Supported formats:");
2098 bdrv_iterate_format(bdrv_format_print, NULL);
2099 fprintf(stderr, "\n");
751c6a17 2100 return NULL;
a1620fac 2101 }
eb852011 2102 drv = bdrv_find_whitelisted_format(buf);
1e72d3b7
AJ
2103 if (!drv) {
2104 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
751c6a17 2105 return NULL;
1e72d3b7
AJ
2106 }
2107 }
2108
e9b2e818 2109 on_write_error = BLOCK_ERR_STOP_ENOSPC;
9dfd7c7a 2110 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
869a5c6d 2111 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
ea8a5d7f 2112 fprintf(stderr, "werror is no supported by this format\n");
751c6a17 2113 return NULL;
428c5705 2114 }
e9b2e818
KW
2115
2116 on_write_error = parse_block_error_action(buf, 0);
2117 if (on_write_error < 0) {
2118 return NULL;
2119 }
2120 }
2121
2122 on_read_error = BLOCK_ERR_REPORT;
2123 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
f35d68f0 2124 if (type != IF_IDE && type != IF_VIRTIO) {
e9b2e818
KW
2125 fprintf(stderr, "rerror is no supported by this format\n");
2126 return NULL;
2127 }
2128
2129 on_read_error = parse_block_error_action(buf, 1);
2130 if (on_read_error < 0) {
751c6a17 2131 return NULL;
428c5705
AL
2132 }
2133 }
2134
9dfd7c7a 2135 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
c2cc47a4 2136 if (type != IF_VIRTIO) {
9dfd7c7a 2137 fprintf(stderr, "addr is not supported\n");
751c6a17 2138 return NULL;
c2cc47a4 2139 }
c2cc47a4
MA
2140 }
2141
e4bcb14c
TS
2142 /* compute bus and unit according index */
2143
2144 if (index != -1) {
2145 if (bus_id != 0 || unit_id != -1) {
2146 fprintf(stderr,
9dfd7c7a 2147 "qemu: index cannot be used with bus and unit\n");
751c6a17 2148 return NULL;
e4bcb14c
TS
2149 }
2150 if (max_devs == 0)
2151 {
2152 unit_id = index;
2153 bus_id = 0;
2154 } else {
2155 unit_id = index % max_devs;
2156 bus_id = index / max_devs;
2157 }
2158 }
2159
2160 /* if user doesn't specify a unit_id,
2161 * try to find the first free
2162 */
2163
2164 if (unit_id == -1) {
2165 unit_id = 0;
751c6a17 2166 while (drive_get(type, bus_id, unit_id) != NULL) {
e4bcb14c
TS
2167 unit_id++;
2168 if (max_devs && unit_id >= max_devs) {
2169 unit_id -= max_devs;
2170 bus_id++;
2171 }
2172 }
2173 }
2174
2175 /* check unit id */
2176
2177 if (max_devs && unit_id >= max_devs) {
9dfd7c7a
GH
2178 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2179 unit_id, max_devs - 1);
751c6a17 2180 return NULL;
e4bcb14c
TS
2181 }
2182
2183 /*
2184 * ignore multiple definitions
2185 */
2186
751c6a17
GH
2187 if (drive_get(type, bus_id, unit_id) != NULL) {
2188 *fatal_error = 0;
2189 return NULL;
2190 }
e4bcb14c
TS
2191
2192 /* init */
2193
751c6a17 2194 dinfo = qemu_mallocz(sizeof(*dinfo));
e23d9c4d 2195 if ((buf = qemu_opts_id(opts)) != NULL) {
9dfd7c7a
GH
2196 dinfo->id = qemu_strdup(buf);
2197 } else {
1dae12e6 2198 /* no id supplied -> create one */
9dfd7c7a 2199 dinfo->id = qemu_mallocz(32);
1dae12e6
GH
2200 if (type == IF_IDE || type == IF_SCSI)
2201 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2202 if (max_devs)
9dfd7c7a 2203 snprintf(dinfo->id, 32, "%s%i%s%i",
1dae12e6
GH
2204 devname, bus_id, mediastr, unit_id);
2205 else
9dfd7c7a 2206 snprintf(dinfo->id, 32, "%s%s%i",
1dae12e6
GH
2207 devname, mediastr, unit_id);
2208 }
1dae12e6 2209 dinfo->bdrv = bdrv_new(dinfo->id);
751c6a17
GH
2210 dinfo->devaddr = devaddr;
2211 dinfo->type = type;
2212 dinfo->bus = bus_id;
2213 dinfo->unit = unit_id;
e9b2e818
KW
2214 dinfo->on_read_error = on_read_error;
2215 dinfo->on_write_error = on_write_error;
9dfd7c7a
GH
2216 dinfo->opts = opts;
2217 if (serial)
2218 strncpy(dinfo->serial, serial, sizeof(serial));
72cf2d4f 2219 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
e4bcb14c 2220
f60d39bc 2221 switch(type) {
e4bcb14c
TS
2222 case IF_IDE:
2223 case IF_SCSI:
62d23efa 2224 case IF_XEN:
c219331e 2225 case IF_NONE:
e4bcb14c
TS
2226 switch(media) {
2227 case MEDIA_DISK:
2228 if (cyls != 0) {
1dae12e6
GH
2229 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2230 bdrv_set_translation_hint(dinfo->bdrv, translation);
e4bcb14c
TS
2231 }
2232 break;
2233 case MEDIA_CDROM:
1dae12e6 2234 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
e4bcb14c
TS
2235 break;
2236 }
2237 break;
2238 case IF_SD:
2239 /* FIXME: This isn't really a floppy, but it's a reasonable
2240 approximation. */
2241 case IF_FLOPPY:
1dae12e6 2242 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
e4bcb14c
TS
2243 break;
2244 case IF_PFLASH:
2245 case IF_MTD:
2246 break;
d176c495
GH
2247 case IF_VIRTIO:
2248 /* add virtio block device */
2249 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2250 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2251 qemu_opt_set(opts, "drive", dinfo->id);
2252 if (devaddr)
2253 qemu_opt_set(opts, "addr", devaddr);
2254 break;
aae9460e
PB
2255 case IF_COUNT:
2256 abort();
e4bcb14c 2257 }
9dfd7c7a 2258 if (!file) {
751c6a17
GH
2259 *fatal_error = 0;
2260 return NULL;
2261 }
33f00271 2262 bdrv_flags = 0;
9f7965c7 2263 if (snapshot) {
33f00271 2264 bdrv_flags |= BDRV_O_SNAPSHOT;
9f7965c7
AL
2265 cache = 2; /* always use write-back with snapshot */
2266 }
2267 if (cache == 0) /* no caching */
2268 bdrv_flags |= BDRV_O_NOCACHE;
2269 else if (cache == 2) /* write-back */
2270 bdrv_flags |= BDRV_O_CACHE_WB;
5c6c3a6c
CH
2271
2272 if (aio == 1) {
2273 bdrv_flags |= BDRV_O_NATIVE_AIO;
2274 } else {
2275 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2276 }
2277
59f2689d 2278 if (ro == 1) {
f5edb014
NS
2279 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2280 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
59f2689d
NS
2281 return NULL;
2282 }
b196b153
NS
2283 }
2284 /*
2285 * cdrom is read-only. Set it now, after above interface checking
2286 * since readonly attribute not explicitly required, so no error.
2287 */
2288 if (media == MEDIA_CDROM) {
f5edb014 2289 ro = 1;
59f2689d 2290 }
f5edb014 2291 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
59f2689d 2292
1dae12e6 2293 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
850810d0
JF
2294 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2295 file, strerror(errno));
751c6a17 2296 return NULL;
e4bcb14c 2297 }
5c6c3a6c 2298
1dae12e6 2299 if (bdrv_key_required(dinfo->bdrv))
c0f4ce77 2300 autostart = 0;
751c6a17
GH
2301 *fatal_error = 0;
2302 return dinfo;
e4bcb14c
TS
2303}
2304
9dfd7c7a
GH
2305static int drive_init_func(QemuOpts *opts, void *opaque)
2306{
2307 QEMUMachine *machine = opaque;
2308 int fatal_error = 0;
2309
2310 if (drive_init(opts, machine, &fatal_error) == NULL) {
2311 if (fatal_error)
2312 return 1;
2313 }
2314 return 0;
2315}
2316
2317static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2318{
2319 if (NULL == qemu_opt_get(opts, "snapshot")) {
2320 qemu_opt_set(opts, "snapshot", "on");
2321 }
2322 return 0;
2323}
2324
76e30d0f
JK
2325void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2326{
2327 boot_set_handler = func;
2328 boot_set_opaque = opaque;
2329}
2330
2331int qemu_boot_set(const char *boot_devices)
2332{
2333 if (!boot_set_handler) {
2334 return -EINVAL;
2335 }
2336 return boot_set_handler(boot_set_opaque, boot_devices);
2337}
2338
ef3adf68
JK
2339static int parse_bootdevices(char *devices)
2340{
2341 /* We just do some generic consistency checks */
2342 const char *p;
2343 int bitmap = 0;
2344
2345 for (p = devices; *p != '\0'; p++) {
2346 /* Allowed boot devices are:
2347 * a-b: floppy disk drives
2348 * c-f: IDE disk drives
2349 * g-m: machine implementation dependant drives
2350 * n-p: network devices
2351 * It's up to each machine implementation to check if the given boot
2352 * devices match the actual hardware implementation and firmware
2353 * features.
2354 */
2355 if (*p < 'a' || *p > 'p') {
2356 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2357 exit(1);
2358 }
2359 if (bitmap & (1 << (*p - 'a'))) {
2360 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2361 exit(1);
2362 }
2363 bitmap |= 1 << (*p - 'a');
2364 }
2365 return bitmap;
2366}
2367
e0f084bf
JK
2368static void restore_boot_devices(void *opaque)
2369{
2370 char *standard_boot_devices = opaque;
2371
2372 qemu_boot_set(standard_boot_devices);
2373
2374 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2375 qemu_free(standard_boot_devices);
2376}
2377
268a362c
AL
2378static void numa_add(const char *optarg)
2379{
2380 char option[128];
2381 char *endptr;
2382 unsigned long long value, endvalue;
2383 int nodenr;
2384
2385 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2386 if (!strcmp(option, "node")) {
2387 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2388 nodenr = nb_numa_nodes;
2389 } else {
2390 nodenr = strtoull(option, NULL, 10);
2391 }
2392
2393 if (get_param_value(option, 128, "mem", optarg) == 0) {
2394 node_mem[nodenr] = 0;
2395 } else {
2396 value = strtoull(option, &endptr, 0);
2397 switch (*endptr) {
2398 case 0: case 'M': case 'm':
2399 value <<= 20;
2400 break;
2401 case 'G': case 'g':
2402 value <<= 30;
2403 break;
2404 }
2405 node_mem[nodenr] = value;
2406 }
2407 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2408 node_cpumask[nodenr] = 0;
2409 } else {
2410 value = strtoull(option, &endptr, 10);
2411 if (value >= 64) {
2412 value = 63;
2413 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2414 } else {
2415 if (*endptr == '-') {
2416 endvalue = strtoull(endptr+1, &endptr, 10);
2417 if (endvalue >= 63) {
2418 endvalue = 62;
2419 fprintf(stderr,
2420 "only 63 CPUs in NUMA mode supported.\n");
2421 }
0dfbd514 2422 value = (2ULL << endvalue) - (1ULL << value);
268a362c 2423 } else {
0dfbd514 2424 value = 1ULL << value;
268a362c
AL
2425 }
2426 }
2427 node_cpumask[nodenr] = value;
2428 }
2429 nb_numa_nodes++;
2430 }
2431 return;
2432}
2433
dc6b1c09
AP
2434static void smp_parse(const char *optarg)
2435{
2436 int smp, sockets = 0, threads = 0, cores = 0;
2437 char *endptr;
2438 char option[128];
2439
2440 smp = strtoul(optarg, &endptr, 10);
2441 if (endptr != optarg) {
2442 if (*endptr == ',') {
2443 endptr++;
2444 }
2445 }
2446 if (get_param_value(option, 128, "sockets", endptr) != 0)
2447 sockets = strtoull(option, NULL, 10);
2448 if (get_param_value(option, 128, "cores", endptr) != 0)
2449 cores = strtoull(option, NULL, 10);
2450 if (get_param_value(option, 128, "threads", endptr) != 0)
2451 threads = strtoull(option, NULL, 10);
2452 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2453 max_cpus = strtoull(option, NULL, 10);
2454
2455 /* compute missing values, prefer sockets over cores over threads */
2456 if (smp == 0 || sockets == 0) {
2457 sockets = sockets > 0 ? sockets : 1;
2458 cores = cores > 0 ? cores : 1;
2459 threads = threads > 0 ? threads : 1;
2460 if (smp == 0) {
2461 smp = cores * threads * sockets;
dc6b1c09
AP
2462 }
2463 } else {
2464 if (cores == 0) {
2465 threads = threads > 0 ? threads : 1;
2466 cores = smp / (sockets * threads);
2467 } else {
5cdc9b76 2468 if (sockets) {
dc6b1c09
AP
2469 threads = smp / (cores * sockets);
2470 }
2471 }
2472 }
2473 smp_cpus = smp;
2474 smp_cores = cores > 0 ? cores : 1;
2475 smp_threads = threads > 0 ? threads : 1;
2476 if (max_cpus == 0)
2477 max_cpus = smp_cpus;
2478}
2479
a594cfbf
FB
2480/***********************************************************/
2481/* USB devices */
2482
c0f4ce77 2483static int usb_device_add(const char *devname, int is_hotplug)
a594cfbf
FB
2484{
2485 const char *p;
a5d2f727 2486 USBDevice *dev = NULL;
a594cfbf 2487
a5d2f727 2488 if (!usb_enabled)
a594cfbf
FB
2489 return -1;
2490
0958b4cc
GH
2491 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2492 dev = usbdevice_create(devname);
2493 if (dev)
2494 goto done;
2495
a5d2f727 2496 /* the other ones */
a594cfbf
FB
2497 if (strstart(devname, "host:", &p)) {
2498 dev = usb_host_device_open(p);
dc72ac14
AZ
2499 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2500 dev = usb_bt_init(devname[2] ? hci_init(p) :
2501 bt_new_hci(qemu_find_bt_vlan(0)));
a594cfbf
FB
2502 } else {
2503 return -1;
2504 }
0d92ed30
PB
2505 if (!dev)
2506 return -1;
2507
a5d2f727 2508done:
a594cfbf
FB
2509 return 0;
2510}
2511
1f3870ab
AL
2512static int usb_device_del(const char *devname)
2513{
2514 int bus_num, addr;
2515 const char *p;
2516
5d0c5750
AL
2517 if (strstart(devname, "host:", &p))
2518 return usb_host_device_close(p);
2519
a5d2f727 2520 if (!usb_enabled)
1f3870ab
AL
2521 return -1;
2522
2523 p = strchr(devname, '.');
2524 if (!p)
2525 return -1;
2526 bus_num = strtoul(devname, NULL, 0);
2527 addr = strtoul(p + 1, NULL, 0);
2528
a5d2f727 2529 return usb_device_delete_addr(bus_num, addr);
1f3870ab
AL
2530}
2531
bd3c948d
GH
2532static int usb_parse(const char *cmdline)
2533{
59d1c1c2
ST
2534 int r;
2535 r = usb_device_add(cmdline, 0);
2536 if (r < 0) {
2537 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2538 }
2539 return r;
bd3c948d
GH
2540}
2541
d54908a5 2542void do_usb_add(Monitor *mon, const QDict *qdict)
a594cfbf 2543{
59d1c1c2
ST
2544 const char *devname = qdict_get_str(qdict, "devname");
2545 if (usb_device_add(devname, 1) < 0) {
1ecda02b 2546 error_report("could not add USB device '%s'", devname);
59d1c1c2 2547 }
a594cfbf
FB
2548}
2549
d54908a5 2550void do_usb_del(Monitor *mon, const QDict *qdict)
a594cfbf 2551{
59d1c1c2
ST
2552 const char *devname = qdict_get_str(qdict, "devname");
2553 if (usb_device_del(devname) < 0) {
1ecda02b 2554 error_report("could not delete USB device '%s'", devname);
59d1c1c2 2555 }
a594cfbf
FB
2556}
2557
201a51fc
AZ
2558/***********************************************************/
2559/* PCMCIA/Cardbus */
2560
2561static struct pcmcia_socket_entry_s {
bc24a225 2562 PCMCIASocket *socket;
201a51fc
AZ
2563 struct pcmcia_socket_entry_s *next;
2564} *pcmcia_sockets = 0;
2565
bc24a225 2566void pcmcia_socket_register(PCMCIASocket *socket)
201a51fc
AZ
2567{
2568 struct pcmcia_socket_entry_s *entry;
2569
2570 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2571 entry->socket = socket;
2572 entry->next = pcmcia_sockets;
2573 pcmcia_sockets = entry;
2574}
2575
bc24a225 2576void pcmcia_socket_unregister(PCMCIASocket *socket)
201a51fc
AZ
2577{
2578 struct pcmcia_socket_entry_s *entry, **ptr;
2579
2580 ptr = &pcmcia_sockets;
2581 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2582 if (entry->socket == socket) {
2583 *ptr = entry->next;
2584 qemu_free(entry);
2585 }
2586}
2587
376253ec 2588void pcmcia_info(Monitor *mon)
201a51fc
AZ
2589{
2590 struct pcmcia_socket_entry_s *iter;
376253ec 2591
201a51fc 2592 if (!pcmcia_sockets)
376253ec 2593 monitor_printf(mon, "No PCMCIA sockets\n");
201a51fc
AZ
2594
2595 for (iter = pcmcia_sockets; iter; iter = iter->next)
376253ec
AL
2596 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2597 iter->socket->attached ? iter->socket->card_string :
2598 "Empty");
201a51fc
AZ
2599}
2600
2ff89790 2601/***********************************************************/
8a7ddc38 2602/* I/O handling */
0824d6fc 2603
c4b1fcc0
FB
2604typedef struct IOHandlerRecord {
2605 int fd;
7c9d8e07
FB
2606 IOCanRWHandler *fd_read_poll;
2607 IOHandler *fd_read;
2608 IOHandler *fd_write;
cafffd40 2609 int deleted;
c4b1fcc0
FB
2610 void *opaque;
2611 /* temporary data */
2612 struct pollfd *ufd;
8a7ddc38 2613 struct IOHandlerRecord *next;
c4b1fcc0
FB
2614} IOHandlerRecord;
2615
8a7ddc38 2616static IOHandlerRecord *first_io_handler;
c4b1fcc0 2617
7c9d8e07
FB
2618/* XXX: fd_read_poll should be suppressed, but an API change is
2619 necessary in the character devices to suppress fd_can_read(). */
5fafdf24
TS
2620int qemu_set_fd_handler2(int fd,
2621 IOCanRWHandler *fd_read_poll,
2622 IOHandler *fd_read,
2623 IOHandler *fd_write,
7c9d8e07 2624 void *opaque)
c4b1fcc0 2625{
7c9d8e07 2626 IOHandlerRecord **pioh, *ioh;
c4b1fcc0 2627
7c9d8e07
FB
2628 if (!fd_read && !fd_write) {
2629 pioh = &first_io_handler;
2630 for(;;) {
2631 ioh = *pioh;
2632 if (ioh == NULL)
2633 break;
2634 if (ioh->fd == fd) {
cafffd40 2635 ioh->deleted = 1;
7c9d8e07
FB
2636 break;
2637 }
2638 pioh = &ioh->next;
2639 }
2640 } else {
2641 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2642 if (ioh->fd == fd)
2643 goto found;
2644 }
2645 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
7c9d8e07
FB
2646 ioh->next = first_io_handler;
2647 first_io_handler = ioh;
2648 found:
2649 ioh->fd = fd;
2650 ioh->fd_read_poll = fd_read_poll;
2651 ioh->fd_read = fd_read;
2652 ioh->fd_write = fd_write;
2653 ioh->opaque = opaque;
cafffd40 2654 ioh->deleted = 0;
7c9d8e07 2655 }
c4b1fcc0
FB
2656 return 0;
2657}
2658
5fafdf24
TS
2659int qemu_set_fd_handler(int fd,
2660 IOHandler *fd_read,
2661 IOHandler *fd_write,
7c9d8e07 2662 void *opaque)
8a7ddc38 2663{
7c9d8e07 2664 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
8a7ddc38
FB
2665}
2666
56f3a5d0 2667#ifdef _WIN32
f331110f
FB
2668/***********************************************************/
2669/* Polling handling */
2670
2671typedef struct PollingEntry {
2672 PollingFunc *func;
2673 void *opaque;
2674 struct PollingEntry *next;
2675} PollingEntry;
2676
2677static PollingEntry *first_polling_entry;
2678
2679int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2680{
2681 PollingEntry **ppe, *pe;
2682 pe = qemu_mallocz(sizeof(PollingEntry));
f331110f
FB
2683 pe->func = func;
2684 pe->opaque = opaque;
2685 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2686 *ppe = pe;
2687 return 0;
2688}
2689
2690void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2691{
2692 PollingEntry **ppe, *pe;
2693 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2694 pe = *ppe;
2695 if (pe->func == func && pe->opaque == opaque) {
2696 *ppe = pe->next;
2697 qemu_free(pe);
2698 break;
2699 }
2700 }
2701}
2702
a18e524a
FB
2703/***********************************************************/
2704/* Wait objects support */
2705typedef struct WaitObjects {
2706 int num;
2707 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2708 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2709 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2710} WaitObjects;
2711
2712static WaitObjects wait_objects = {0};
3b46e624 2713
a18e524a
FB
2714int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2715{
2716 WaitObjects *w = &wait_objects;
2717
2718 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2719 return -1;
2720 w->events[w->num] = handle;
2721 w->func[w->num] = func;
2722 w->opaque[w->num] = opaque;
2723 w->num++;
2724 return 0;
2725}
2726
2727void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2728{
2729 int i, found;
2730 WaitObjects *w = &wait_objects;
2731
2732 found = 0;
2733 for (i = 0; i < w->num; i++) {
2734 if (w->events[i] == handle)
2735 found = 1;
2736 if (found) {
2737 w->events[i] = w->events[i + 1];
2738 w->func[i] = w->func[i + 1];
2739 w->opaque[i] = w->opaque[i + 1];
3b46e624 2740 }
a18e524a
FB
2741 }
2742 if (found)
2743 w->num--;
2744}
2745#endif
2746
8a7ddc38
FB
2747/***********************************************************/
2748/* ram save/restore */
2749
94fb0909 2750#define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
475e4277
AL
2751#define RAM_SAVE_FLAG_COMPRESS 0x02
2752#define RAM_SAVE_FLAG_MEM_SIZE 0x04
2753#define RAM_SAVE_FLAG_PAGE 0x08
2754#define RAM_SAVE_FLAG_EOS 0x10
2755
2756static int is_dup_page(uint8_t *page, uint8_t ch)
8a7ddc38 2757{
475e4277
AL
2758 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2759 uint32_t *array = (uint32_t *)page;
2760 int i;
3b46e624 2761
475e4277
AL
2762 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2763 if (array[i] != val)
2764 return 0;
2765 }
2766
2767 return 1;
2768}
2769
2770static int ram_save_block(QEMUFile *f)
2771{
c227f099
AL
2772 static ram_addr_t current_addr = 0;
2773 ram_addr_t saved_addr = current_addr;
2774 ram_addr_t addr = 0;
475e4277
AL
2775 int found = 0;
2776
94a6b54f 2777 while (addr < last_ram_offset) {
475e4277 2778 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
5579c7f3 2779 uint8_t *p;
475e4277
AL
2780
2781 cpu_physical_memory_reset_dirty(current_addr,
2782 current_addr + TARGET_PAGE_SIZE,
2783 MIGRATION_DIRTY_FLAG);
2784
5579c7f3 2785 p = qemu_get_ram_ptr(current_addr);
475e4277 2786
5579c7f3 2787 if (is_dup_page(p, *p)) {
475e4277 2788 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
5579c7f3 2789 qemu_put_byte(f, *p);
475e4277
AL
2790 } else {
2791 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
5579c7f3 2792 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
c88676f8 2793 }
475e4277
AL
2794
2795 found = 1;
2796 break;
c88676f8 2797 }
475e4277 2798 addr += TARGET_PAGE_SIZE;
94a6b54f 2799 current_addr = (saved_addr + addr) % last_ram_offset;
8a7ddc38 2800 }
475e4277
AL
2801
2802 return found;
8a7ddc38
FB
2803}
2804
84307938 2805static uint64_t bytes_transferred;
475e4277 2806
c227f099 2807static ram_addr_t ram_save_remaining(void)
475e4277 2808{
c227f099
AL
2809 ram_addr_t addr;
2810 ram_addr_t count = 0;
475e4277 2811
94a6b54f 2812 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
475e4277
AL
2813 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2814 count++;
2815 }
2816
2817 return count;
2818}
2819
9f9e28cd
GC
2820uint64_t ram_bytes_remaining(void)
2821{
2822 return ram_save_remaining() * TARGET_PAGE_SIZE;
2823}
2824
2825uint64_t ram_bytes_transferred(void)
2826{
2827 return bytes_transferred;
2828}
2829
2830uint64_t ram_bytes_total(void)
2831{
2832 return last_ram_offset;
2833}
2834
f327aa0c 2835static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
475e4277 2836{
c227f099 2837 ram_addr_t addr;
a0a3fd60
GC
2838 uint64_t bytes_transferred_last;
2839 double bwidth = 0;
2840 uint64_t expected_time = 0;
475e4277 2841
4ec7fcc7
JK
2842 if (stage < 0) {
2843 cpu_physical_memory_set_dirty_tracking(0);
2844 return 0;
2845 }
2846
9fa06385 2847 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
b0a46a33
JK
2848 qemu_file_set_error(f);
2849 return 0;
2850 }
2851
475e4277 2852 if (stage == 1) {
84307938
JK
2853 bytes_transferred = 0;
2854
475e4277 2855 /* Make sure all dirty bits are set */
94a6b54f 2856 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
475e4277
AL
2857 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2858 cpu_physical_memory_set_dirty(addr);
2859 }
b0a46a33 2860
475e4277
AL
2861 /* Enable dirty memory tracking */
2862 cpu_physical_memory_set_dirty_tracking(1);
2863
94a6b54f 2864 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
475e4277
AL
2865 }
2866
a0a3fd60 2867 bytes_transferred_last = bytes_transferred;
41c872b6 2868 bwidth = qemu_get_clock_ns(rt_clock);
a0a3fd60 2869
475e4277
AL
2870 while (!qemu_file_rate_limit(f)) {
2871 int ret;
2872
2873 ret = ram_save_block(f);
9f9e28cd 2874 bytes_transferred += ret * TARGET_PAGE_SIZE;
475e4277
AL
2875 if (ret == 0) /* no more blocks */
2876 break;
2877 }
2878
41c872b6 2879 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
a0a3fd60
GC
2880 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2881
2882 /* if we haven't transferred anything this round, force expected_time to a
2883 * a very high value, but without crashing */
2884 if (bwidth == 0)
2885 bwidth = 0.000001;
2886
475e4277 2887 /* try transferring iterative blocks of memory */
475e4277 2888 if (stage == 3) {
475e4277 2889 /* flush all remaining blocks regardless of rate limiting */
9f9e28cd
GC
2890 while (ram_save_block(f) != 0) {
2891 bytes_transferred += TARGET_PAGE_SIZE;
2892 }
8215e914 2893 cpu_physical_memory_set_dirty_tracking(0);
475e4277
AL
2894 }
2895
2896 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2897
a0a3fd60
GC
2898 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2899
2900 return (stage == 2) && (expected_time <= migrate_max_downtime());
475e4277
AL
2901}
2902
475e4277
AL
2903static int ram_load(QEMUFile *f, void *opaque, int version_id)
2904{
c227f099 2905 ram_addr_t addr;
475e4277
AL
2906 int flags;
2907
475e4277
AL
2908 if (version_id != 3)
2909 return -EINVAL;
2910
2911 do {
2912 addr = qemu_get_be64(f);
2913
2914 flags = addr & ~TARGET_PAGE_MASK;
2915 addr &= TARGET_PAGE_MASK;
2916
2917 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
94a6b54f 2918 if (addr != last_ram_offset)
475e4277
AL
2919 return -EINVAL;
2920 }
2921
475e4277
AL
2922 if (flags & RAM_SAVE_FLAG_COMPRESS) {
2923 uint8_t ch = qemu_get_byte(f);
779c6bef
AL
2924 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2925#ifndef _WIN32
30868442
AL
2926 if (ch == 0 &&
2927 (!kvm_enabled() || kvm_has_sync_mmu())) {
2928 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
779c6bef 2929 }
30868442 2930#endif
9a743e5b 2931 } else if (flags & RAM_SAVE_FLAG_PAGE) {
5579c7f3 2932 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
9a743e5b
JK
2933 }
2934 if (qemu_file_has_error(f)) {
2935 return -EIO;
2936 }
475e4277
AL
2937 } while (!(flags & RAM_SAVE_FLAG_EOS));
2938
8a7ddc38
FB
2939 return 0;
2940}
2941
9e472e10
AL
2942void qemu_service_io(void)
2943{
d9f75a4e 2944 qemu_notify_event();
9e472e10
AL
2945}
2946
cc1daa40
FB
2947/***********************************************************/
2948/* machine registration */
2949
bdaf78e0 2950static QEMUMachine *first_machine = NULL;
6f338c34 2951QEMUMachine *current_machine = NULL;
cc1daa40
FB
2952
2953int qemu_register_machine(QEMUMachine *m)
2954{
2955 QEMUMachine **pm;
2956 pm = &first_machine;
2957 while (*pm != NULL)
2958 pm = &(*pm)->next;
2959 m->next = NULL;
2960 *pm = m;
2961 return 0;
2962}
2963
9596ebb7 2964static QEMUMachine *find_machine(const char *name)
cc1daa40
FB
2965{
2966 QEMUMachine *m;
2967
2968 for(m = first_machine; m != NULL; m = m->next) {
2969 if (!strcmp(m->name, name))
2970 return m;
3f6599e6
MM
2971 if (m->alias && !strcmp(m->alias, name))
2972 return m;
cc1daa40
FB
2973 }
2974 return NULL;
2975}
2976
0c257437
AL
2977static QEMUMachine *find_default_machine(void)
2978{
2979 QEMUMachine *m;
2980
2981 for(m = first_machine; m != NULL; m = m->next) {
2982 if (m->is_default) {
2983 return m;
2984 }
2985 }
2986 return NULL;
2987}
2988
8a7ddc38
FB
2989/***********************************************************/
2990/* main execution loop */
2991
9596ebb7 2992static void gui_update(void *opaque)
8a7ddc38 2993{
7d957bd8 2994 uint64_t interval = GUI_REFRESH_INTERVAL;
740733bb 2995 DisplayState *ds = opaque;
7d957bd8
AL
2996 DisplayChangeListener *dcl = ds->listeners;
2997
62a2744c 2998 qemu_flush_coalesced_mmio_buffer();
7d957bd8
AL
2999 dpy_refresh(ds);
3000
3001 while (dcl != NULL) {
3002 if (dcl->gui_timer_interval &&
3003 dcl->gui_timer_interval < interval)
3004 interval = dcl->gui_timer_interval;
3005 dcl = dcl->next;
3006 }
3007 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
8a7ddc38
FB
3008}
3009
9043b62d
BS
3010static void nographic_update(void *opaque)
3011{
3012 uint64_t interval = GUI_REFRESH_INTERVAL;
3013
62a2744c 3014 qemu_flush_coalesced_mmio_buffer();
9043b62d
BS
3015 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3016}
3017
ea375f9a
JK
3018void cpu_synchronize_all_states(void)
3019{
3020 CPUState *cpu;
3021
3022 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3023 cpu_synchronize_state(cpu);
3024 }
3025}
3026
3027void cpu_synchronize_all_post_reset(void)
3028{
3029 CPUState *cpu;
3030
3031 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3032 cpu_synchronize_post_reset(cpu);
3033 }
3034}
3035
3036void cpu_synchronize_all_post_init(void)
3037{
3038 CPUState *cpu;
3039
3040 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3041 cpu_synchronize_post_init(cpu);
3042 }
3043}
3044
0bd48850
FB
3045struct vm_change_state_entry {
3046 VMChangeStateHandler *cb;
3047 void *opaque;
72cf2d4f 3048 QLIST_ENTRY (vm_change_state_entry) entries;
0bd48850
FB
3049};
3050
72cf2d4f 3051static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
0bd48850
FB
3052
3053VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3054 void *opaque)
3055{
3056 VMChangeStateEntry *e;
3057
3058 e = qemu_mallocz(sizeof (*e));
0bd48850
FB
3059
3060 e->cb = cb;
3061 e->opaque = opaque;
72cf2d4f 3062 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
0bd48850
FB
3063 return e;
3064}
3065
3066void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3067{
72cf2d4f 3068 QLIST_REMOVE (e, entries);
0bd48850
FB
3069 qemu_free (e);
3070}
3071
9781e040 3072static void vm_state_notify(int running, int reason)
0bd48850
FB
3073{
3074 VMChangeStateEntry *e;
3075
3076 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
9781e040 3077 e->cb(e->opaque, running, reason);
0bd48850
FB
3078 }
3079}
3080
d6dc3d42
AL
3081static void resume_all_vcpus(void);
3082static void pause_all_vcpus(void);
3083
8a7ddc38
FB
3084void vm_start(void)
3085{
3086 if (!vm_running) {
3087 cpu_enable_ticks();
3088 vm_running = 1;
9781e040 3089 vm_state_notify(1, 0);
efe75411 3090 qemu_rearm_alarm_timer(alarm_timer);
d6dc3d42 3091 resume_all_vcpus();
8a7ddc38
FB
3092 }
3093}
3094
bb0c6722
FB
3095/* reset/shutdown handler */
3096
3097typedef struct QEMUResetEntry {
72cf2d4f 3098 QTAILQ_ENTRY(QEMUResetEntry) entry;
bb0c6722
FB
3099 QEMUResetHandler *func;
3100 void *opaque;
bb0c6722
FB
3101} QEMUResetEntry;
3102
72cf2d4f
BS
3103static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3104 QTAILQ_HEAD_INITIALIZER(reset_handlers);
bb0c6722
FB
3105static int reset_requested;
3106static int shutdown_requested;
3475187d 3107static int powerdown_requested;
e568902a 3108static int debug_requested;
6e29f5da 3109static int vmstop_requested;
bb0c6722 3110
cf7a2fe2
AJ
3111int qemu_shutdown_requested(void)
3112{
3113 int r = shutdown_requested;
3114 shutdown_requested = 0;
3115 return r;
3116}
3117
3118int qemu_reset_requested(void)
3119{
3120 int r = reset_requested;
3121 reset_requested = 0;
3122 return r;
3123}
3124
3125int qemu_powerdown_requested(void)
3126{
3127 int r = powerdown_requested;
3128 powerdown_requested = 0;
3129 return r;
3130}
3131
e568902a
AL
3132static int qemu_debug_requested(void)
3133{
3134 int r = debug_requested;
3135 debug_requested = 0;
3136 return r;
3137}
3138
6e29f5da
AL
3139static int qemu_vmstop_requested(void)
3140{
3141 int r = vmstop_requested;
3142 vmstop_requested = 0;
3143 return r;
3144}
3145
3146static void do_vm_stop(int reason)
3147{
3148 if (vm_running) {
3149 cpu_disable_ticks();
3150 vm_running = 0;
d6dc3d42 3151 pause_all_vcpus();
6e29f5da 3152 vm_state_notify(0, reason);
6b8f8fff 3153 monitor_protocol_event(QEVENT_STOP, NULL);
6e29f5da
AL
3154 }
3155}
3156
a08d4367 3157void qemu_register_reset(QEMUResetHandler *func, void *opaque)
bb0c6722 3158{
55ddfe8e 3159 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
bb0c6722 3160
bb0c6722
FB
3161 re->func = func;
3162 re->opaque = opaque;
72cf2d4f 3163 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
bb0c6722
FB
3164}
3165
dda9b29f 3166void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
bb0c6722
FB
3167{
3168 QEMUResetEntry *re;
3169
72cf2d4f 3170 QTAILQ_FOREACH(re, &reset_handlers, entry) {
dda9b29f 3171 if (re->func == func && re->opaque == opaque) {
72cf2d4f 3172 QTAILQ_REMOVE(&reset_handlers, re, entry);
dda9b29f
JK
3173 qemu_free(re);
3174 return;
3175 }
3176 }
3177}
3178
3179void qemu_system_reset(void)
3180{
3181 QEMUResetEntry *re, *nre;
3182
3183 /* reset all devices */
72cf2d4f 3184 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
bb0c6722
FB
3185 re->func(re->opaque);
3186 }
81d9b784 3187 monitor_protocol_event(QEVENT_RESET, NULL);
ea375f9a 3188 cpu_synchronize_all_post_reset();
bb0c6722
FB
3189}
3190
3191void qemu_system_reset_request(void)
3192{
d1beab82
FB
3193 if (no_reboot) {
3194 shutdown_requested = 1;
3195 } else {
3196 reset_requested = 1;
3197 }
d9f75a4e 3198 qemu_notify_event();
bb0c6722
FB
3199}
3200
3201void qemu_system_shutdown_request(void)
3202{
3203 shutdown_requested = 1;
d9f75a4e 3204 qemu_notify_event();
bb0c6722
FB
3205}
3206
3475187d
FB
3207void qemu_system_powerdown_request(void)
3208{
3209 powerdown_requested = 1;
d9f75a4e
AL
3210 qemu_notify_event();
3211}
3212
d6dc3d42
AL
3213#ifdef CONFIG_IOTHREAD
3214static void qemu_system_vmstop_request(int reason)
d9f75a4e 3215{
d6dc3d42
AL
3216 vmstop_requested = reason;
3217 qemu_notify_event();
bb0c6722 3218}
d6dc3d42 3219#endif
bb0c6722 3220
50317c7f
AL
3221#ifndef _WIN32
3222static int io_thread_fd = -1;
3223
3224static void qemu_event_increment(void)
3fcf7b6b 3225{
f3dfda61
PB
3226 /* Write 8 bytes to be compatible with eventfd. */
3227 static uint64_t val = 1;
dc330e28 3228 ssize_t ret;
50317c7f
AL
3229
3230 if (io_thread_fd == -1)
3231 return;
3232
652ce2d4 3233 do {
f3dfda61 3234 ret = write(io_thread_fd, &val, sizeof(val));
652ce2d4
PB
3235 } while (ret < 0 && errno == EINTR);
3236
3237 /* EAGAIN is fine, a read must be pending. */
3238 if (ret < 0 && errno != EAGAIN) {
dc330e28
KS
3239 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
3240 strerror(errno));
3241 exit (1);
3242 }
50317c7f
AL
3243}
3244
3245static void qemu_event_read(void *opaque)
3246{
3247 int fd = (unsigned long)opaque;
3248 ssize_t len;
1d0f0d91 3249 char buffer[512];
50317c7f 3250
f3dfda61 3251 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
50317c7f 3252 do {
50317c7f 3253 len = read(fd, buffer, sizeof(buffer));
1d0f0d91 3254 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
50317c7f
AL
3255}
3256
3257static int qemu_event_init(void)
3258{
3259 int err;
3260 int fds[2];
3261
f3dfda61 3262 err = qemu_eventfd(fds);
50317c7f
AL
3263 if (err == -1)
3264 return -errno;
3265
3266 err = fcntl_setfl(fds[0], O_NONBLOCK);
3267 if (err < 0)
3268 goto fail;
3269
3270 err = fcntl_setfl(fds[1], O_NONBLOCK);
3271 if (err < 0)
3272 goto fail;
3273
3274 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3275 (void *)(unsigned long)fds[0]);
3276
3277 io_thread_fd = fds[1];
a7e21219
JK
3278 return 0;
3279
50317c7f
AL
3280fail:
3281 close(fds[0]);
3282 close(fds[1]);
3283 return err;
3284}
3285#else
3286HANDLE qemu_event_handle;
3287
3288static void dummy_event_handler(void *opaque)
3289{
3290}
3291
3292static int qemu_event_init(void)
3293{
3294 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3295 if (!qemu_event_handle) {
20889d4e 3296 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
50317c7f
AL
3297 return -1;
3298 }
3299 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3fcf7b6b
AL
3300 return 0;
3301}
3302
50317c7f
AL
3303static void qemu_event_increment(void)
3304{
de1c90cf 3305 if (!SetEvent(qemu_event_handle)) {
20889d4e 3306 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
de1c90cf 3307 GetLastError());
3308 exit (1);
3309 }
50317c7f
AL
3310}
3311#endif
3312
d6dc3d42
AL
3313static int cpu_can_run(CPUState *env)
3314{
3315 if (env->stop)
3316 return 0;
3317 if (env->stopped)
3318 return 0;
c5f32c99
MT
3319 if (!vm_running)
3320 return 0;
d6dc3d42
AL
3321 return 1;
3322}
3323
3324#ifndef CONFIG_IOTHREAD
50317c7f
AL
3325static int qemu_init_main_loop(void)
3326{
3327 return qemu_event_init();
3328}
3329
0bf46a40
AL
3330void qemu_init_vcpu(void *_env)
3331{
3332 CPUState *env = _env;
3333
dc6b1c09
AP
3334 env->nr_cores = smp_cores;
3335 env->nr_threads = smp_threads;
3f7638ec
JD
3336 if (kvm_enabled())
3337 kvm_init_vcpu(env);
0bf46a40
AL
3338 return;
3339}
3340
8edac960
AL
3341int qemu_cpu_self(void *env)
3342{
3343 return 1;
3344}
3345
d6dc3d42
AL
3346static void resume_all_vcpus(void)
3347{
3348}
3349
3350static void pause_all_vcpus(void)
3351{
3352}
3353
8edac960
AL
3354void qemu_cpu_kick(void *env)
3355{
3356 return;
3357}
3358
d6dc3d42
AL
3359void qemu_notify_event(void)
3360{
3361 CPUState *env = cpu_single_env;
3362
7a5e5838 3363 qemu_event_increment ();
d6dc3d42
AL
3364 if (env) {
3365 cpu_exit(env);
4a1418e0 3366 }
d6dc3d42
AL
3367}
3368
d549db5a
GC
3369void qemu_mutex_lock_iothread(void) {}
3370void qemu_mutex_unlock_iothread(void) {}
4870852c 3371
6e29f5da
AL
3372void vm_stop(int reason)
3373{
3374 do_vm_stop(reason);
3375}
3376
d6dc3d42
AL
3377#else /* CONFIG_IOTHREAD */
3378
3379#include "qemu-thread.h"
3380
3381QemuMutex qemu_global_mutex;
3382static QemuMutex qemu_fair_mutex;
3383
3384static QemuThread io_thread;
3385
3386static QemuThread *tcg_cpu_thread;
3387static QemuCond *tcg_halt_cond;
3388
3389static int qemu_system_ready;
3390/* cpu creation */
3391static QemuCond qemu_cpu_cond;
3392/* system init */
3393static QemuCond qemu_system_cond;
3394static QemuCond qemu_pause_cond;
3395
cc84de95
MT
3396static void tcg_block_io_signals(void);
3397static void kvm_block_io_signals(CPUState *env);
d6dc3d42
AL
3398static void unblock_io_signals(void);
3399static int tcg_has_work(void);
fed6c344 3400static int cpu_has_work(CPUState *env);
d6dc3d42
AL
3401
3402static int qemu_init_main_loop(void)
3403{
3404 int ret;
3405
3406 ret = qemu_event_init();
3407 if (ret)
3408 return ret;
3409
3410 qemu_cond_init(&qemu_pause_cond);
3411 qemu_mutex_init(&qemu_fair_mutex);
3412 qemu_mutex_init(&qemu_global_mutex);
3413 qemu_mutex_lock(&qemu_global_mutex);
3414
3415 unblock_io_signals();
3416 qemu_thread_self(&io_thread);
3417
3418 return 0;
3419}
3420
fed6c344
MT
3421static void qemu_wait_io_event_common(CPUState *env)
3422{
3423 if (env->stop) {
3424 env->stop = 0;
3425 env->stopped = 1;
3426 qemu_cond_signal(&qemu_pause_cond);
3427 }
3428}
3429
d6dc3d42
AL
3430static void qemu_wait_io_event(CPUState *env)
3431{
3432 while (!tcg_has_work())
3433 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3434
3435 qemu_mutex_unlock(&qemu_global_mutex);
3436
3437 /*
3438 * Users of qemu_global_mutex can be starved, having no chance
3439 * to acquire it since this path will get to it first.
3440 * So use another lock to provide fairness.
3441 */
3442 qemu_mutex_lock(&qemu_fair_mutex);
3443 qemu_mutex_unlock(&qemu_fair_mutex);
3444
3445 qemu_mutex_lock(&qemu_global_mutex);
fed6c344
MT
3446 qemu_wait_io_event_common(env);
3447}
3448
cc84de95
MT
3449static void qemu_kvm_eat_signal(CPUState *env, int timeout)
3450{
3451 struct timespec ts;
3452 int r, e;
3453 siginfo_t siginfo;
3454 sigset_t waitset;
3455
3456 ts.tv_sec = timeout / 1000;
3457 ts.tv_nsec = (timeout % 1000) * 1000000;
3458
3459 sigemptyset(&waitset);
3460 sigaddset(&waitset, SIG_IPI);
3461
3462 qemu_mutex_unlock(&qemu_global_mutex);
3463 r = sigtimedwait(&waitset, &siginfo, &ts);
3464 e = errno;
3465 qemu_mutex_lock(&qemu_global_mutex);
3466
3467 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
3468 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
3469 exit(1);
d6dc3d42
AL
3470 }
3471}
3472
fed6c344
MT
3473static void qemu_kvm_wait_io_event(CPUState *env)
3474{
3475 while (!cpu_has_work(env))
3476 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3477
cc84de95 3478 qemu_kvm_eat_signal(env, 0);
fed6c344 3479 qemu_wait_io_event_common(env);
d6dc3d42
AL
3480}
3481
3482static int qemu_cpu_exec(CPUState *env);
3483
3484static void *kvm_cpu_thread_fn(void *arg)
3485{
3486 CPUState *env = arg;
3487
d6dc3d42 3488 qemu_thread_self(env->thread);
321c1cb1
JCD
3489 if (kvm_enabled())
3490 kvm_init_vcpu(env);
d6dc3d42 3491
cc84de95
MT
3492 kvm_block_io_signals(env);
3493
d6dc3d42
AL
3494 /* signal CPU creation */
3495 qemu_mutex_lock(&qemu_global_mutex);
3496 env->created = 1;
3497 qemu_cond_signal(&qemu_cpu_cond);
3498
3499 /* and wait for machine initialization */
3500 while (!qemu_system_ready)
3501 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3502
3503 while (1) {
3504 if (cpu_can_run(env))
3505 qemu_cpu_exec(env);
fed6c344 3506 qemu_kvm_wait_io_event(env);
d6dc3d42
AL
3507 }
3508
3509 return NULL;
3510}
3511
3512static void tcg_cpu_exec(void);
3513
3514static void *tcg_cpu_thread_fn(void *arg)
3515{
3516 CPUState *env = arg;
3517
cc84de95 3518 tcg_block_io_signals();
d6dc3d42
AL
3519 qemu_thread_self(env->thread);
3520
3521 /* signal CPU creation */
3522 qemu_mutex_lock(&qemu_global_mutex);
3523 for (env = first_cpu; env != NULL; env = env->next_cpu)
3524 env->created = 1;
3525 qemu_cond_signal(&qemu_cpu_cond);
3526
3527 /* and wait for machine initialization */
3528 while (!qemu_system_ready)
3529 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3530
3531 while (1) {
3532 tcg_cpu_exec();
3533 qemu_wait_io_event(cur_cpu);
3534 }
3535
3536 return NULL;
3537}
3538
3539void qemu_cpu_kick(void *_env)
3540{
3541 CPUState *env = _env;
3542 qemu_cond_broadcast(env->halt_cond);
3543 if (kvm_enabled())
cc84de95 3544 qemu_thread_signal(env->thread, SIG_IPI);
d6dc3d42
AL
3545}
3546
e5bc201d 3547int qemu_cpu_self(void *_env)
d6dc3d42 3548{
e5bc201d
GC
3549 CPUState *env = _env;
3550 QemuThread this;
3551
3552 qemu_thread_self(&this);
3553
3554 return qemu_thread_equal(&this, env->thread);
d6dc3d42
AL
3555}
3556
3557static void cpu_signal(int sig)
3558{
3559 if (cpu_single_env)
3560 cpu_exit(cpu_single_env);
3561}
3562
cc84de95 3563static void tcg_block_io_signals(void)
d6dc3d42
AL
3564{
3565 sigset_t set;
3566 struct sigaction sigact;
3567
3568 sigemptyset(&set);
3569 sigaddset(&set, SIGUSR2);
3570 sigaddset(&set, SIGIO);
3571 sigaddset(&set, SIGALRM);
adc8c965 3572 sigaddset(&set, SIGCHLD);
d6dc3d42
AL
3573 pthread_sigmask(SIG_BLOCK, &set, NULL);
3574
3575 sigemptyset(&set);
cc84de95 3576 sigaddset(&set, SIG_IPI);
d6dc3d42
AL
3577 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3578
3579 memset(&sigact, 0, sizeof(sigact));
3580 sigact.sa_handler = cpu_signal;
cc84de95
MT
3581 sigaction(SIG_IPI, &sigact, NULL);
3582}
3583
3584static void dummy_signal(int sig)
3585{
3586}
3587
3588static void kvm_block_io_signals(CPUState *env)
3589{
3590 int r;
3591 sigset_t set;
3592 struct sigaction sigact;
3593
3594 sigemptyset(&set);
3595 sigaddset(&set, SIGUSR2);
3596 sigaddset(&set, SIGIO);
3597 sigaddset(&set, SIGALRM);
3598 sigaddset(&set, SIGCHLD);
3599 sigaddset(&set, SIG_IPI);
3600 pthread_sigmask(SIG_BLOCK, &set, NULL);
3601
3602 pthread_sigmask(SIG_BLOCK, NULL, &set);
3603 sigdelset(&set, SIG_IPI);
3604
3605 memset(&sigact, 0, sizeof(sigact));
3606 sigact.sa_handler = dummy_signal;
3607 sigaction(SIG_IPI, &sigact, NULL);
3608
3609 r = kvm_set_signal_mask(env, &set);
3610 if (r) {
3611 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
3612 exit(1);
3613 }
d6dc3d42
AL
3614}
3615
3616static void unblock_io_signals(void)
3617{
3618 sigset_t set;
3619
3620 sigemptyset(&set);
3621 sigaddset(&set, SIGUSR2);
3622 sigaddset(&set, SIGIO);
3623 sigaddset(&set, SIGALRM);
3624 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3625
3626 sigemptyset(&set);
cc84de95 3627 sigaddset(&set, SIG_IPI);
d6dc3d42
AL
3628 pthread_sigmask(SIG_BLOCK, &set, NULL);
3629}
3630
3631static void qemu_signal_lock(unsigned int msecs)
3632{
3633 qemu_mutex_lock(&qemu_fair_mutex);
3634
3635 while (qemu_mutex_trylock(&qemu_global_mutex)) {
cc84de95 3636 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
d6dc3d42
AL
3637 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3638 break;
3639 }
3640 qemu_mutex_unlock(&qemu_fair_mutex);
3641}
3642
d549db5a 3643void qemu_mutex_lock_iothread(void)
d6dc3d42
AL
3644{
3645 if (kvm_enabled()) {
3646 qemu_mutex_lock(&qemu_fair_mutex);
3647 qemu_mutex_lock(&qemu_global_mutex);
3648 qemu_mutex_unlock(&qemu_fair_mutex);
3649 } else
3650 qemu_signal_lock(100);
3651}
3652
d549db5a 3653void qemu_mutex_unlock_iothread(void)
d6dc3d42
AL
3654{
3655 qemu_mutex_unlock(&qemu_global_mutex);
3656}
3657
3658static int all_vcpus_paused(void)
3659{
3660 CPUState *penv = first_cpu;
3661
3662 while (penv) {
3663 if (!penv->stopped)
3664 return 0;
3665 penv = (CPUState *)penv->next_cpu;
3666 }
3667
3668 return 1;
3669}
3670
3671static void pause_all_vcpus(void)
3672{
3673 CPUState *penv = first_cpu;
3674
3675 while (penv) {
3676 penv->stop = 1;
cc84de95 3677 qemu_thread_signal(penv->thread, SIG_IPI);
d6dc3d42
AL
3678 qemu_cpu_kick(penv);
3679 penv = (CPUState *)penv->next_cpu;
3680 }
3681
3682 while (!all_vcpus_paused()) {
3683 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3684 penv = first_cpu;
3685 while (penv) {
cc84de95 3686 qemu_thread_signal(penv->thread, SIG_IPI);
d6dc3d42
AL
3687 penv = (CPUState *)penv->next_cpu;
3688 }
3689 }
3690}
3691
3692static void resume_all_vcpus(void)
3693{
3694 CPUState *penv = first_cpu;
3695
3696 while (penv) {
3697 penv->stop = 0;
3698 penv->stopped = 0;
cc84de95 3699 qemu_thread_signal(penv->thread, SIG_IPI);
d6dc3d42
AL
3700 qemu_cpu_kick(penv);
3701 penv = (CPUState *)penv->next_cpu;
3702 }
3703}
3704
3705static void tcg_init_vcpu(void *_env)
3706{
3707 CPUState *env = _env;
3708 /* share a single thread for all cpus with TCG */
3709 if (!tcg_cpu_thread) {
3710 env->thread = qemu_mallocz(sizeof(QemuThread));
3711 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3712 qemu_cond_init(env->halt_cond);
3713 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3714 while (env->created == 0)
3715 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3716 tcg_cpu_thread = env->thread;
3717 tcg_halt_cond = env->halt_cond;
3718 } else {
3719 env->thread = tcg_cpu_thread;
3720 env->halt_cond = tcg_halt_cond;
3721 }
3722}
3723
3724static void kvm_start_vcpu(CPUState *env)
3725{
d6dc3d42
AL
3726 env->thread = qemu_mallocz(sizeof(QemuThread));
3727 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3728 qemu_cond_init(env->halt_cond);
3729 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3730 while (env->created == 0)
3731 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3732}
3733
3734void qemu_init_vcpu(void *_env)
3735{
3736 CPUState *env = _env;
3737
3f7638ec
JD
3738 env->nr_cores = smp_cores;
3739 env->nr_threads = smp_threads;
d6dc3d42
AL
3740 if (kvm_enabled())
3741 kvm_start_vcpu(env);
3742 else
3743 tcg_init_vcpu(env);
3744}
3745
3746void qemu_notify_event(void)
3747{
3748 qemu_event_increment();
3749}
3750
3751void vm_stop(int reason)
3752{
3753 QemuThread me;
3754 qemu_thread_self(&me);
3755
3756 if (!qemu_thread_equal(&me, &io_thread)) {
3757 qemu_system_vmstop_request(reason);
3758 /*
3759 * FIXME: should not return to device code in case
3760 * vm_stop() has been requested.
3761 */
3762 if (cpu_single_env) {
3763 cpu_exit(cpu_single_env);
3764 cpu_single_env->stop = 1;
3765 }
3766 return;
3767 }
3768 do_vm_stop(reason);
3769}
3770
3771#endif
3772
3773
877cf882 3774#ifdef _WIN32
69d6451c 3775static void host_main_loop_wait(int *timeout)
56f3a5d0
AL
3776{
3777 int ret, ret2, i;
f331110f
FB
3778 PollingEntry *pe;
3779
c4b1fcc0 3780
f331110f
FB
3781 /* XXX: need to suppress polling by better using win32 events */
3782 ret = 0;
3783 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3784 ret |= pe->func(pe->opaque);
3785 }
e6b1e558 3786 if (ret == 0) {
a18e524a
FB
3787 int err;
3788 WaitObjects *w = &wait_objects;
3b46e624 3789
56f3a5d0 3790 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
a18e524a
FB
3791 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3792 if (w->func[ret - WAIT_OBJECT_0])
3793 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3b46e624 3794
5fafdf24 3795 /* Check for additional signaled events */
e6b1e558 3796 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3b46e624 3797
e6b1e558
TS
3798 /* Check if event is signaled */
3799 ret2 = WaitForSingleObject(w->events[i], 0);
3800 if(ret2 == WAIT_OBJECT_0) {
3801 if (w->func[i])
3802 w->func[i](w->opaque[i]);
3803 } else if (ret2 == WAIT_TIMEOUT) {
3804 } else {
3805 err = GetLastError();
3806 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3b46e624
TS
3807 }
3808 }
a18e524a
FB
3809 } else if (ret == WAIT_TIMEOUT) {
3810 } else {
3811 err = GetLastError();
e6b1e558 3812 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
a18e524a 3813 }
f331110f 3814 }
56f3a5d0
AL
3815
3816 *timeout = 0;
3817}
3818#else
69d6451c 3819static void host_main_loop_wait(int *timeout)
56f3a5d0
AL
3820{
3821}
fd1dff4b 3822#endif
56f3a5d0
AL
3823
3824void main_loop_wait(int timeout)
3825{
3826 IOHandlerRecord *ioh;
3827 fd_set rfds, wfds, xfds;
3828 int ret, nfds;
3829 struct timeval tv;
3830
3831 qemu_bh_update_timeout(&timeout);
3832
3833 host_main_loop_wait(&timeout);
3834
fd1dff4b
FB
3835 /* poll any events */
3836 /* XXX: separate device handlers from system ones */
6abfbd79 3837 nfds = -1;
fd1dff4b
FB
3838 FD_ZERO(&rfds);
3839 FD_ZERO(&wfds);
e035649e 3840 FD_ZERO(&xfds);
fd1dff4b 3841 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
cafffd40
TS
3842 if (ioh->deleted)
3843 continue;
fd1dff4b
FB
3844 if (ioh->fd_read &&
3845 (!ioh->fd_read_poll ||
3846 ioh->fd_read_poll(ioh->opaque) != 0)) {
3847 FD_SET(ioh->fd, &rfds);
3848 if (ioh->fd > nfds)
3849 nfds = ioh->fd;
3850 }
3851 if (ioh->fd_write) {
3852 FD_SET(ioh->fd, &wfds);
3853 if (ioh->fd > nfds)
3854 nfds = ioh->fd;
3855 }
3856 }
3b46e624 3857
56f3a5d0
AL
3858 tv.tv_sec = timeout / 1000;
3859 tv.tv_usec = (timeout % 1000) * 1000;
3860
d918f23e
JK
3861 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3862
4870852c 3863 qemu_mutex_unlock_iothread();
e035649e 3864 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4870852c 3865 qemu_mutex_lock_iothread();
fd1dff4b 3866 if (ret > 0) {
cafffd40
TS
3867 IOHandlerRecord **pioh;
3868
3869 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6ab43fdc 3870 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
fd1dff4b 3871 ioh->fd_read(ioh->opaque);
7c9d8e07 3872 }
6ab43fdc 3873 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
fd1dff4b 3874 ioh->fd_write(ioh->opaque);
c4b1fcc0 3875 }
b4608c04 3876 }
cafffd40
TS
3877
3878 /* remove deleted IO handlers */
3879 pioh = &first_io_handler;
3880 while (*pioh) {
3881 ioh = *pioh;
3882 if (ioh->deleted) {
3883 *pioh = ioh->next;
3884 qemu_free(ioh);
5fafdf24 3885 } else
cafffd40
TS
3886 pioh = &ioh->next;
3887 }
fd1dff4b 3888 }
d918f23e
JK
3889
3890 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
b4608c04 3891
50317c7f 3892 /* rearm timer, if not periodic */
cd48d7e8
PB
3893 if (alarm_timer->expired) {
3894 alarm_timer->expired = 0;
50317c7f
AL
3895 qemu_rearm_alarm_timer(alarm_timer);
3896 }
3897
1828be31
PB
3898 alarm_timer->pending = 0;
3899
357c692c 3900 /* vm time timers */
d6dc3d42
AL
3901 if (vm_running) {
3902 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
0fdddf80
JK
3903 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3904 qemu_get_clock(vm_clock));
d6dc3d42 3905 }
357c692c
AL
3906
3907 /* real time timers */
0fdddf80 3908 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
357c692c
AL
3909 qemu_get_clock(rt_clock));
3910
21d5d12b
JK
3911 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3912 qemu_get_clock(host_clock));
3913
423f0742
PB
3914 /* Check bottom-halves last in case any of the earlier events triggered
3915 them. */
3916 qemu_bh_poll();
3b46e624 3917
5905b2e5
FB
3918}
3919
43b96858 3920static int qemu_cpu_exec(CPUState *env)
5905b2e5 3921{
43b96858 3922 int ret;
89bfc105
FB
3923#ifdef CONFIG_PROFILER
3924 int64_t ti;
3925#endif
5905b2e5 3926
89bfc105 3927#ifdef CONFIG_PROFILER
43b96858 3928 ti = profile_getclock();
89bfc105 3929#endif
43b96858
AL
3930 if (use_icount) {
3931 int64_t count;
3932 int decr;
3933 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3934 env->icount_decr.u16.low = 0;
3935 env->icount_extra = 0;
3936 count = qemu_next_deadline();
3937 count = (count + (1 << icount_time_shift) - 1)
3938 >> icount_time_shift;
3939 qemu_icount += count;
3940 decr = (count > 0xffff) ? 0xffff : count;
3941 count -= decr;
3942 env->icount_decr.u16.low = decr;
3943 env->icount_extra = count;
3944 }
3945 ret = cpu_exec(env);
89bfc105 3946#ifdef CONFIG_PROFILER
43b96858 3947 qemu_time += profile_getclock() - ti;
89bfc105 3948#endif
43b96858
AL
3949 if (use_icount) {
3950 /* Fold pending instructions back into the
3951 instruction counter, and clear the interrupt flag. */
3952 qemu_icount -= (env->icount_decr.u16.low
3953 + env->icount_extra);
3954 env->icount_decr.u32 = 0;
3955 env->icount_extra = 0;
3956 }
3957 return ret;
3958}
3959
e6e35b1e
AL
3960static void tcg_cpu_exec(void)
3961{
d6dc3d42 3962 int ret = 0;
e6e35b1e
AL
3963
3964 if (next_cpu == NULL)
3965 next_cpu = first_cpu;
3966 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3967 CPUState *env = cur_cpu = next_cpu;
3968
1828be31 3969 if (alarm_timer->pending)
e6e35b1e 3970 break;
d6dc3d42
AL
3971 if (cpu_can_run(env))
3972 ret = qemu_cpu_exec(env);
c37cc7b0
MT
3973 else if (env->stop)
3974 break;
3975
e6e35b1e
AL
3976 if (ret == EXCP_DEBUG) {
3977 gdb_set_stop_cpu(env);
3978 debug_requested = 1;
3979 break;
3980 }
3981 }
3982}
3983
43b96858
AL
3984static int cpu_has_work(CPUState *env)
3985{
d6dc3d42
AL
3986 if (env->stop)
3987 return 1;
3988 if (env->stopped)
3989 return 0;
43b96858
AL
3990 if (!env->halted)
3991 return 1;
3992 if (qemu_cpu_has_work(env))
3993 return 1;
3994 return 0;
3995}
3996
3997static int tcg_has_work(void)
3998{
3999 CPUState *env;
4000
4001 for (env = first_cpu; env != NULL; env = env->next_cpu)
4002 if (cpu_has_work(env))
4003 return 1;
4004 return 0;
4005}
4006
4007static int qemu_calculate_timeout(void)
4008{
b319820d 4009#ifndef CONFIG_IOTHREAD
43b96858
AL
4010 int timeout;
4011
4012 if (!vm_running)
4013 timeout = 5000;
4014 else if (tcg_has_work())
4015 timeout = 0;
4016 else if (!use_icount)
4017 timeout = 5000;
4018 else {
4019 /* XXX: use timeout computed from timers */
4020 int64_t add;
4021 int64_t delta;
4022 /* Advance virtual time to the next event. */
4023 if (use_icount == 1) {
4024 /* When not using an adaptive execution frequency
4025 we tend to get badly out of sync with real time,
4026 so just delay for a reasonable amount of time. */
4027 delta = 0;
4028 } else {
4029 delta = cpu_get_icount() - cpu_get_clock();
4030 }
4031 if (delta > 0) {
4032 /* If virtual time is ahead of real time then just
4033 wait for IO. */
4034 timeout = (delta / 1000000) + 1;
4035 } else {
4036 /* Wait for either IO to occur or the next
4037 timer event. */
4038 add = qemu_next_deadline();
4039 /* We advance the timer before checking for IO.
4040 Limit the amount we advance so that early IO
4041 activity won't get the guest too far ahead. */
4042 if (add > 10000000)
4043 add = 10000000;
4044 delta += add;
4045 add = (add + (1 << icount_time_shift) - 1)
4046 >> icount_time_shift;
4047 qemu_icount += add;
4048 timeout = delta / 1000000;
4049 if (timeout < 0)
4050 timeout = 0;
4051 }
4052 }
4053
4054 return timeout;
b319820d
LC
4055#else /* CONFIG_IOTHREAD */
4056 return 1000;
4057#endif
43b96858
AL
4058}
4059
4060static int vm_can_run(void)
4061{
4062 if (powerdown_requested)
4063 return 0;
4064 if (reset_requested)
4065 return 0;
4066 if (shutdown_requested)
4067 return 0;
e568902a
AL
4068 if (debug_requested)
4069 return 0;
43b96858
AL
4070 return 1;
4071}
4072
d9c32310
BS
4073qemu_irq qemu_system_powerdown;
4074
43b96858
AL
4075static void main_loop(void)
4076{
6e29f5da 4077 int r;
e6e35b1e 4078
d6dc3d42
AL
4079#ifdef CONFIG_IOTHREAD
4080 qemu_system_ready = 1;
4081 qemu_cond_broadcast(&qemu_system_cond);
4082#endif
4083
6e29f5da 4084 for (;;) {
43b96858 4085 do {
e6e35b1e
AL
4086#ifdef CONFIG_PROFILER
4087 int64_t ti;
4088#endif
d6dc3d42 4089#ifndef CONFIG_IOTHREAD
e6e35b1e 4090 tcg_cpu_exec();
d6dc3d42 4091#endif
89bfc105 4092#ifdef CONFIG_PROFILER
43b96858 4093 ti = profile_getclock();
89bfc105 4094#endif
43b96858 4095 main_loop_wait(qemu_calculate_timeout());
89bfc105 4096#ifdef CONFIG_PROFILER
43b96858 4097 dev_time += profile_getclock() - ti;
89bfc105 4098#endif
e568902a 4099 } while (vm_can_run());
43b96858 4100
b1a15e7e 4101 if (qemu_debug_requested()) {
e568902a 4102 vm_stop(EXCP_DEBUG);
b1a15e7e 4103 }
43b96858 4104 if (qemu_shutdown_requested()) {
242cd003 4105 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
43b96858
AL
4106 if (no_shutdown) {
4107 vm_stop(0);
4108 no_shutdown = 0;
4109 } else
4110 break;
4111 }
d6dc3d42
AL
4112 if (qemu_reset_requested()) {
4113 pause_all_vcpus();
43b96858 4114 qemu_system_reset();
d6dc3d42
AL
4115 resume_all_vcpus();
4116 }
d9c32310 4117 if (qemu_powerdown_requested()) {
242cd003 4118 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
d9c32310
BS
4119 qemu_irq_raise(qemu_system_powerdown);
4120 }
b1a15e7e 4121 if ((r = qemu_vmstop_requested())) {
6e29f5da 4122 vm_stop(r);
b1a15e7e 4123 }
b4608c04 4124 }
d6dc3d42 4125 pause_all_vcpus();
b4608c04
FB
4126}
4127
9bd7e6d9
PB
4128static void version(void)
4129{
4a19f1ec 4130 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
9bd7e6d9
PB
4131}
4132
15f82208 4133static void help(int exitcode)
0824d6fc 4134{
e8105ebb 4135 const char *options_help =
5824d651
BS
4136#define DEF(option, opt_arg, opt_enum, opt_help) \
4137 opt_help
4138#define DEFHEADING(text) stringify(text) "\n"
4139#include "qemu-options.h"
4140#undef DEF
4141#undef DEFHEADING
4142#undef GEN_DOCS
e8105ebb
PB
4143 ;
4144 version();
4145 printf("usage: %s [options] [disk_image]\n"
4146 "\n"
4147 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3f020d70 4148 "\n"
e8105ebb 4149 "%s\n"
3f020d70 4150 "During emulation, the following keys are useful:\n"
4151 "ctrl-alt-f toggle full screen\n"
4152 "ctrl-alt-n switch to virtual console 'n'\n"
4153 "ctrl-alt toggle mouse and keyboard grab\n"
4154 "\n"
e8105ebb
PB
4155 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4156 "qemu",
4157 options_help);
15f82208 4158 exit(exitcode);
0824d6fc
FB
4159}
4160
cd6f1169
FB
4161#define HAS_ARG 0x0001
4162
4163enum {
5824d651
BS
4164#define DEF(option, opt_arg, opt_enum, opt_help) \
4165 opt_enum,
4166#define DEFHEADING(text)
4167#include "qemu-options.h"
4168#undef DEF
4169#undef DEFHEADING
4170#undef GEN_DOCS
cd6f1169
FB
4171};
4172
4173typedef struct QEMUOption {
4174 const char *name;
4175 int flags;
4176 int index;
4177} QEMUOption;
4178
dbed7e40 4179static const QEMUOption qemu_options[] = {
cd6f1169 4180 { "h", 0, QEMU_OPTION_h },
5824d651
BS
4181#define DEF(option, opt_arg, opt_enum, opt_help) \
4182 { option, opt_arg, opt_enum },
4183#define DEFHEADING(text)
4184#include "qemu-options.h"
4185#undef DEF
4186#undef DEFHEADING
4187#undef GEN_DOCS
cd6f1169 4188 { NULL },
fc01f7e7
FB
4189};
4190
1d14ffa9 4191#ifdef HAS_AUDIO
6a36d84e 4192struct soundhw soundhw[] = {
b00052e4 4193#ifdef HAS_AUDIO_CHOICE
4ce7ff6e 4194#if defined(TARGET_I386) || defined(TARGET_MIPS)
fd06c375
FB
4195 {
4196 "pcspk",
4197 "PC speaker",
4198 0,
4199 1,
4200 { .init_isa = pcspk_audio_init }
4201 },
4202#endif
4c9b53e3 4203
4204#ifdef CONFIG_SB16
6a36d84e
FB
4205 {
4206 "sb16",
4207 "Creative Sound Blaster 16",
4208 0,
4209 1,
4210 { .init_isa = SB16_init }
4211 },
4c9b53e3 4212#endif
6a36d84e 4213
cc53d26d 4214#ifdef CONFIG_CS4231A
4215 {
4216 "cs4231a",
4217 "CS4231A",
4218 0,
4219 1,
4220 { .init_isa = cs4231a_init }
4221 },
4222#endif
4223
1d14ffa9 4224#ifdef CONFIG_ADLIB
6a36d84e
FB
4225 {
4226 "adlib",
1d14ffa9 4227#ifdef HAS_YMF262
6a36d84e 4228 "Yamaha YMF262 (OPL3)",
1d14ffa9 4229#else
6a36d84e 4230 "Yamaha YM3812 (OPL2)",
1d14ffa9 4231#endif
6a36d84e
FB
4232 0,
4233 1,
4234 { .init_isa = Adlib_init }
4235 },
1d14ffa9 4236#endif
6a36d84e 4237
1d14ffa9 4238#ifdef CONFIG_GUS
6a36d84e
FB
4239 {
4240 "gus",
4241 "Gravis Ultrasound GF1",
4242 0,
4243 1,
4244 { .init_isa = GUS_init }
4245 },
1d14ffa9 4246#endif
6a36d84e 4247
4c9b53e3 4248#ifdef CONFIG_AC97
e5c9a13e
AZ
4249 {
4250 "ac97",
4251 "Intel 82801AA AC97 Audio",
4252 0,
4253 0,
4254 { .init_pci = ac97_init }
4255 },
4c9b53e3 4256#endif
e5c9a13e 4257
4c9b53e3 4258#ifdef CONFIG_ES1370
6a36d84e
FB
4259 {
4260 "es1370",
4261 "ENSONIQ AudioPCI ES1370",
4262 0,
4263 0,
4264 { .init_pci = es1370_init }
4265 },
b00052e4 4266#endif
6a36d84e 4267
4c9b53e3 4268#endif /* HAS_AUDIO_CHOICE */
4269
6a36d84e
FB
4270 { NULL, NULL, 0, 0, { NULL } }
4271};
4272
4273static void select_soundhw (const char *optarg)
4274{
4275 struct soundhw *c;
4276
4277 if (*optarg == '?') {
4278 show_valid_cards:
4279
4280 printf ("Valid sound card names (comma separated):\n");
4281 for (c = soundhw; c->name; ++c) {
4282 printf ("%-11s %s\n", c->name, c->descr);
4283 }
4284 printf ("\n-soundhw all will enable all of the above\n");
1d14ffa9
FB
4285 exit (*optarg != '?');
4286 }
4287 else {
6a36d84e 4288 size_t l;
1d14ffa9
FB
4289 const char *p;
4290 char *e;
4291 int bad_card = 0;
4292
6a36d84e
FB
4293 if (!strcmp (optarg, "all")) {
4294 for (c = soundhw; c->name; ++c) {
4295 c->enabled = 1;
4296 }
4297 return;
4298 }
1d14ffa9 4299
6a36d84e 4300 p = optarg;
1d14ffa9
FB
4301 while (*p) {
4302 e = strchr (p, ',');
4303 l = !e ? strlen (p) : (size_t) (e - p);
6a36d84e
FB
4304
4305 for (c = soundhw; c->name; ++c) {
b3d6fb4a 4306 if (!strncmp (c->name, p, l) && !c->name[l]) {
6a36d84e 4307 c->enabled = 1;
1d14ffa9
FB
4308 break;
4309 }
4310 }
6a36d84e
FB
4311
4312 if (!c->name) {
1d14ffa9
FB
4313 if (l > 80) {
4314 fprintf (stderr,
4315 "Unknown sound card name (too big to show)\n");
4316 }
4317 else {
4318 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4319 (int) l, p);
4320 }
4321 bad_card = 1;
4322 }
4323 p += l + (e != NULL);
4324 }
4325
4326 if (bad_card)
4327 goto show_valid_cards;
4328 }
4329}
4330#endif
4331
3893c124 4332static void select_vgahw (const char *p)
4333{
4334 const char *opts;
4335
64465297 4336 default_vga = 0;
86176759 4337 vga_interface_type = VGA_NONE;
3893c124 4338 if (strstart(p, "std", &opts)) {
86176759 4339 vga_interface_type = VGA_STD;
3893c124 4340 } else if (strstart(p, "cirrus", &opts)) {
86176759 4341 vga_interface_type = VGA_CIRRUS;
3893c124 4342 } else if (strstart(p, "vmware", &opts)) {
86176759 4343 vga_interface_type = VGA_VMWARE;
94909d9f 4344 } else if (strstart(p, "xenfb", &opts)) {
86176759 4345 vga_interface_type = VGA_XENFB;
28b85ed8 4346 } else if (!strstart(p, "none", &opts)) {
3893c124 4347 invalid_vga:
4348 fprintf(stderr, "Unknown vga type: %s\n", p);
4349 exit(1);
4350 }
cb5a7aa8 4351 while (*opts) {
4352 const char *nextopt;
4353
4354 if (strstart(opts, ",retrace=", &nextopt)) {
4355 opts = nextopt;
4356 if (strstart(opts, "dumb", &nextopt))
4357 vga_retrace_method = VGA_RETRACE_DUMB;
4358 else if (strstart(opts, "precise", &nextopt))
4359 vga_retrace_method = VGA_RETRACE_PRECISE;
4360 else goto invalid_vga;
4361 } else goto invalid_vga;
4362 opts = nextopt;
4363 }
3893c124 4364}
4365
7d4c3d53
MA
4366#ifdef TARGET_I386
4367static int balloon_parse(const char *arg)
4368{
382f0743 4369 QemuOpts *opts;
7d4c3d53 4370
382f0743
GH
4371 if (strcmp(arg, "none") == 0) {
4372 return 0;
4373 }
4374
4375 if (!strncmp(arg, "virtio", 6)) {
4376 if (arg[6] == ',') {
4377 /* have params -> parse them */
8212c64f 4378 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
382f0743
GH
4379 if (!opts)
4380 return -1;
4381 } else {
4382 /* create empty opts */
4383 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
7d4c3d53 4384 }
382f0743
GH
4385 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4386 return 0;
7d4c3d53 4387 }
382f0743
GH
4388
4389 return -1;
7d4c3d53
MA
4390}
4391#endif
4392
3587d7e6
FB
4393#ifdef _WIN32
4394static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4395{
4396 exit(STATUS_CONTROL_C_EXIT);
4397 return TRUE;
4398}
4399#endif
4400
c4be29ff 4401int qemu_uuid_parse(const char *str, uint8_t *uuid)
8fcb1b90
BS
4402{
4403 int ret;
4404
4405 if(strlen(str) != 36)
4406 return -1;
4407
4408 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4409 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4410 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4411
4412 if(ret != 16)
4413 return -1;
4414
b6f6e3d3
AL
4415#ifdef TARGET_I386
4416 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4417#endif
4418
8fcb1b90
BS
4419 return 0;
4420}
4421
5b08fc10
AL
4422#ifndef _WIN32
4423
4424static void termsig_handler(int signal)
4425{
4426 qemu_system_shutdown_request();
4427}
4428
7c3370d4
JK
4429static void sigchld_handler(int signal)
4430{
4431 waitpid(-1, NULL, WNOHANG);
4432}
4433
4434static void sighandler_setup(void)
5b08fc10
AL
4435{
4436 struct sigaction act;
4437
4438 memset(&act, 0, sizeof(act));
4439 act.sa_handler = termsig_handler;
4440 sigaction(SIGINT, &act, NULL);
4441 sigaction(SIGHUP, &act, NULL);
4442 sigaction(SIGTERM, &act, NULL);
7c3370d4
JK
4443
4444 act.sa_handler = sigchld_handler;
4445 act.sa_flags = SA_NOCLDSTOP;
4446 sigaction(SIGCHLD, &act, NULL);
5b08fc10
AL
4447}
4448
4449#endif
4450
5cea8590
PB
4451#ifdef _WIN32
4452/* Look for support files in the same directory as the executable. */
4453static char *find_datadir(const char *argv0)
4454{
4455 char *p;
4456 char buf[MAX_PATH];
4457 DWORD len;
4458
4459 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4460 if (len == 0) {
c5947808 4461 return NULL;
5cea8590
PB
4462 }
4463
4464 buf[len] = 0;
4465 p = buf + len - 1;
4466 while (p != buf && *p != '\\')
4467 p--;
4468 *p = 0;
4469 if (access(buf, R_OK) == 0) {
4470 return qemu_strdup(buf);
4471 }
4472 return NULL;
4473}
4474#else /* !_WIN32 */
4475
4476/* Find a likely location for support files using the location of the binary.
4477 For installed binaries this will be "$bindir/../share/qemu". When
4478 running from the build tree this will be "$bindir/../pc-bios". */
4479#define SHARE_SUFFIX "/share/qemu"
4480#define BUILD_SUFFIX "/pc-bios"
4481static char *find_datadir(const char *argv0)
4482{
4483 char *dir;
4484 char *p = NULL;
4485 char *res;
5cea8590 4486 char buf[PATH_MAX];
3a41759d 4487 size_t max_len;
5cea8590
PB
4488
4489#if defined(__linux__)
4490 {
4491 int len;
4492 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4493 if (len > 0) {
4494 buf[len] = 0;
4495 p = buf;
4496 }
4497 }
4498#elif defined(__FreeBSD__)
4499 {
4500 int len;
4501 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4502 if (len > 0) {
4503 buf[len] = 0;
4504 p = buf;
4505 }
4506 }
4507#endif
4508 /* If we don't have any way of figuring out the actual executable
4509 location then try argv[0]. */
4510 if (!p) {
4d224196 4511 p = realpath(argv0, buf);
5cea8590
PB
4512 if (!p) {
4513 return NULL;
4514 }
4515 }
4516 dir = dirname(p);
4517 dir = dirname(dir);
4518
3a41759d
BS
4519 max_len = strlen(dir) +
4520 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4521 res = qemu_mallocz(max_len);
4522 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
5cea8590 4523 if (access(res, R_OK)) {
3a41759d 4524 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
5cea8590
PB
4525 if (access(res, R_OK)) {
4526 qemu_free(res);
4527 res = NULL;
4528 }
4529 }
4d224196 4530
5cea8590
PB
4531 return res;
4532}
4533#undef SHARE_SUFFIX
4534#undef BUILD_SUFFIX
4535#endif
4536
4537char *qemu_find_file(int type, const char *name)
4538{
4539 int len;
4540 const char *subdir;
4541 char *buf;
4542
4543 /* If name contains path separators then try it as a straight path. */
4544 if ((strchr(name, '/') || strchr(name, '\\'))
4545 && access(name, R_OK) == 0) {
73ffc805 4546 return qemu_strdup(name);
5cea8590
PB
4547 }
4548 switch (type) {
4549 case QEMU_FILE_TYPE_BIOS:
4550 subdir = "";
4551 break;
4552 case QEMU_FILE_TYPE_KEYMAP:
4553 subdir = "keymaps/";
4554 break;
4555 default:
4556 abort();
4557 }
4558 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4559 buf = qemu_mallocz(len);
3a41759d 4560 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
5cea8590
PB
4561 if (access(buf, R_OK)) {
4562 qemu_free(buf);
4563 return NULL;
4564 }
4565 return buf;
4566}
4567
ff952ba2
MA
4568static int device_help_func(QemuOpts *opts, void *opaque)
4569{
4570 return qdev_device_help(opts);
4571}
4572
f31d07d1
GH
4573static int device_init_func(QemuOpts *opts, void *opaque)
4574{
4575 DeviceState *dev;
4576
4577 dev = qdev_device_add(opts);
4578 if (!dev)
4579 return -1;
4580 return 0;
4581}
4582
1a688d3b
GH
4583static int chardev_init_func(QemuOpts *opts, void *opaque)
4584{
4585 CharDriverState *chr;
4586
4587 chr = qemu_chr_open_opts(opts, NULL);
4588 if (!chr)
4589 return -1;
4590 return 0;
4591}
4592
88589343
GH
4593static int mon_init_func(QemuOpts *opts, void *opaque)
4594{
4595 CharDriverState *chr;
4596 const char *chardev;
4597 const char *mode;
4598 int flags;
4599
4600 mode = qemu_opt_get(opts, "mode");
4601 if (mode == NULL) {
4602 mode = "readline";
4603 }
4604 if (strcmp(mode, "readline") == 0) {
4605 flags = MONITOR_USE_READLINE;
4606 } else if (strcmp(mode, "control") == 0) {
4607 flags = MONITOR_USE_CONTROL;
4608 } else {
4609 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4610 exit(1);
4611 }
4612
4613 if (qemu_opt_get_bool(opts, "default", 0))
4614 flags |= MONITOR_IS_DEFAULT;
4615
4616 chardev = qemu_opt_get(opts, "chardev");
4617 chr = qemu_chr_find(chardev);
4618 if (chr == NULL) {
4619 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4620 exit(1);
4621 }
4622
4623 monitor_init(chr, flags);
4624 return 0;
4625}
4626
6ca5582d 4627static void monitor_parse(const char *optarg, const char *mode)
88589343
GH
4628{
4629 static int monitor_device_index = 0;
4630 QemuOpts *opts;
4631 const char *p;
4632 char label[32];
4633 int def = 0;
4634
4635 if (strstart(optarg, "chardev:", &p)) {
4636 snprintf(label, sizeof(label), "%s", p);
4637 } else {
4638 if (monitor_device_index) {
4639 snprintf(label, sizeof(label), "monitor%d",
4640 monitor_device_index);
4641 } else {
4642 snprintf(label, sizeof(label), "monitor");
4643 def = 1;
4644 }
4645 opts = qemu_chr_parse_compat(label, optarg);
4646 if (!opts) {
4647 fprintf(stderr, "parse error: %s\n", optarg);
4648 exit(1);
4649 }
4650 }
4651
4652 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4653 if (!opts) {
4654 fprintf(stderr, "duplicate chardev: %s\n", label);
4655 exit(1);
4656 }
6ca5582d 4657 qemu_opt_set(opts, "mode", mode);
88589343
GH
4658 qemu_opt_set(opts, "chardev", label);
4659 if (def)
4660 qemu_opt_set(opts, "default", "on");
4661 monitor_device_index++;
4662}
4663
bd3c948d
GH
4664struct device_config {
4665 enum {
aee1b935
GH
4666 DEV_USB, /* -usbdevice */
4667 DEV_BT, /* -bt */
4668 DEV_SERIAL, /* -serial */
4669 DEV_PARALLEL, /* -parallel */
4670 DEV_VIRTCON, /* -virtioconsole */
c9f398e5 4671 DEV_DEBUGCON, /* -debugcon */
bd3c948d
GH
4672 } type;
4673 const char *cmdline;
72cf2d4f 4674 QTAILQ_ENTRY(device_config) next;
bd3c948d 4675};
72cf2d4f 4676QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
bd3c948d
GH
4677
4678static void add_device_config(int type, const char *cmdline)
4679{
4680 struct device_config *conf;
4681
4682 conf = qemu_mallocz(sizeof(*conf));
4683 conf->type = type;
4684 conf->cmdline = cmdline;
72cf2d4f 4685 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
bd3c948d
GH
4686}
4687
4688static int foreach_device_config(int type, int (*func)(const char *cmdline))
4689{
4690 struct device_config *conf;
4691 int rc;
4692
72cf2d4f 4693 QTAILQ_FOREACH(conf, &device_configs, next) {
bd3c948d
GH
4694 if (conf->type != type)
4695 continue;
4696 rc = func(conf->cmdline);
4697 if (0 != rc)
4698 return rc;
4699 }
4700 return 0;
4701}
4702
998bbd74
GH
4703static int serial_parse(const char *devname)
4704{
4705 static int index = 0;
4706 char label[32];
4707
4708 if (strcmp(devname, "none") == 0)
4709 return 0;
4710 if (index == MAX_SERIAL_PORTS) {
4711 fprintf(stderr, "qemu: too many serial ports\n");
4712 exit(1);
4713 }
4714 snprintf(label, sizeof(label), "serial%d", index);
4715 serial_hds[index] = qemu_chr_open(label, devname, NULL);
4716 if (!serial_hds[index]) {
4717 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4718 devname, strerror(errno));
4719 return -1;
4720 }
4721 index++;
4722 return 0;
4723}
4724
6a5e8b0e
GH
4725static int parallel_parse(const char *devname)
4726{
4727 static int index = 0;
4728 char label[32];
4729
4730 if (strcmp(devname, "none") == 0)
4731 return 0;
4732 if (index == MAX_PARALLEL_PORTS) {
4733 fprintf(stderr, "qemu: too many parallel ports\n");
4734 exit(1);
4735 }
4736 snprintf(label, sizeof(label), "parallel%d", index);
4737 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4738 if (!parallel_hds[index]) {
4739 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4740 devname, strerror(errno));
4741 return -1;
4742 }
4743 index++;
4744 return 0;
4745}
4746
aee1b935
GH
4747static int virtcon_parse(const char *devname)
4748{
4749 static int index = 0;
4750 char label[32];
392ecf54 4751 QemuOpts *bus_opts, *dev_opts;
aee1b935
GH
4752
4753 if (strcmp(devname, "none") == 0)
4754 return 0;
4755 if (index == MAX_VIRTIO_CONSOLES) {
4756 fprintf(stderr, "qemu: too many virtio consoles\n");
4757 exit(1);
4758 }
392ecf54
AS
4759
4760 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4761 qemu_opt_set(bus_opts, "driver", "virtio-serial");
4762
4763 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4764 qemu_opt_set(dev_opts, "driver", "virtconsole");
4765
aee1b935
GH
4766 snprintf(label, sizeof(label), "virtcon%d", index);
4767 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4768 if (!virtcon_hds[index]) {
4769 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4770 devname, strerror(errno));
4771 return -1;
4772 }
392ecf54
AS
4773 qemu_opt_set(dev_opts, "chardev", label);
4774
aee1b935
GH
4775 index++;
4776 return 0;
4777}
4778
c9f398e5
PA
4779static int debugcon_parse(const char *devname)
4780{
4781 QemuOpts *opts;
4782
4783 if (!qemu_chr_open("debugcon", devname, NULL)) {
4784 exit(1);
4785 }
4786 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4787 if (!opts) {
4788 fprintf(stderr, "qemu: already have a debugcon device\n");
4789 exit(1);
4790 }
4791 qemu_opt_set(opts, "driver", "isa-debugcon");
4792 qemu_opt_set(opts, "chardev", "debugcon");
4793 return 0;
4794}
4795
6530a97b
AL
4796static const QEMUOption *lookup_opt(int argc, char **argv,
4797 const char **poptarg, int *poptind)
4798{
4799 const QEMUOption *popt;
4800 int optind = *poptind;
4801 char *r = argv[optind];
4802 const char *optarg;
4803
0f0bc3f1 4804 loc_set_cmdline(argv, optind, 1);
6530a97b
AL
4805 optind++;
4806 /* Treat --foo the same as -foo. */
4807 if (r[1] == '-')
4808 r++;
4809 popt = qemu_options;
4810 for(;;) {
4811 if (!popt->name) {
0f0bc3f1 4812 error_report("invalid option");
6530a97b
AL
4813 exit(1);
4814 }
4815 if (!strcmp(popt->name, r + 1))
4816 break;
4817 popt++;
4818 }
4819 if (popt->flags & HAS_ARG) {
4820 if (optind >= argc) {
0f0bc3f1 4821 error_report("requires an argument");
6530a97b
AL
4822 exit(1);
4823 }
4824 optarg = argv[optind++];
0f0bc3f1 4825 loc_set_cmdline(argv, optind - 2, 2);
6530a97b
AL
4826 } else {
4827 optarg = NULL;
4828 }
4829
4830 *poptarg = optarg;
4831 *poptind = optind;
4832
4833 return popt;
4834}
4835
902b3d5c 4836int main(int argc, char **argv, char **envp)
0824d6fc 4837{
59030a8c 4838 const char *gdbstub_dev = NULL;
28c5af54 4839 uint32_t boot_devices_bitmap = 0;
e4bcb14c 4840 int i;
28c5af54 4841 int snapshot, linux_boot, net_boot;
7f7f9873 4842 const char *initrd_filename;
a20dd508 4843 const char *kernel_filename, *kernel_cmdline;
195325a4 4844 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3023f332 4845 DisplayState *ds;
7d957bd8 4846 DisplayChangeListener *dcl;
46d4767d 4847 int cyls, heads, secs, translation;
f31d07d1 4848 QemuOpts *hda_opts = NULL, *opts;
cd6f1169 4849 int optind;
6530a97b 4850 const char *optarg;
d63d307f 4851 const char *loadvm = NULL;
cc1daa40 4852 QEMUMachine *machine;
94fc95cd 4853 const char *cpu_model;
b9e82a59 4854#ifndef _WIN32
71e3ceb8 4855 int fds[2];
b9e82a59 4856#endif
26a5f13b 4857 int tb_size;
93815bc2 4858 const char *pid_file = NULL;
5bb7910a 4859 const char *incoming = NULL;
b9e82a59 4860#ifndef _WIN32
54042bcf
AL
4861 int fd = 0;
4862 struct passwd *pwd = NULL;
0858532e
AL
4863 const char *chroot_dir = NULL;
4864 const char *run_as = NULL;
b9e82a59 4865#endif
268a362c 4866 CPUState *env;
993fbfdb 4867 int show_vnc_port = 0;
292444cb 4868 int defconfig = 1;
0bd48850 4869
65abca0a
MA
4870 error_set_progname(argv[0]);
4871
6875204c
JK
4872 init_clocks();
4873
902b3d5c 4874 qemu_cache_utils_init(envp);
4875
72cf2d4f 4876 QLIST_INIT (&vm_change_state_head);
be995c27
FB
4877#ifndef _WIN32
4878 {
4879 struct sigaction act;
4880 sigfillset(&act.sa_mask);
4881 act.sa_flags = 0;
4882 act.sa_handler = SIG_IGN;
4883 sigaction(SIGPIPE, &act, NULL);
4884 }
3587d7e6
FB
4885#else
4886 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
a8e5ac33
FB
4887 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4888 QEMU to run on a single CPU */
4889 {
4890 HANDLE h;
4891 DWORD mask, smask;
4892 int i;
4893 h = GetCurrentProcess();
4894 if (GetProcessAffinityMask(h, &mask, &smask)) {
4895 for(i = 0; i < 32; i++) {
4896 if (mask & (1 << i))
4897 break;
4898 }
4899 if (i != 32) {
4900 mask = 1 << i;
4901 SetProcessAffinityMask(h, mask);
4902 }
4903 }
4904 }
67b915a5 4905#endif
be995c27 4906
f80f9ec9 4907 module_call_init(MODULE_INIT_MACHINE);
0c257437 4908 machine = find_default_machine();
94fc95cd 4909 cpu_model = NULL;
fc01f7e7 4910 initrd_filename = NULL;
4fc5d071 4911 ram_size = 0;
33e3963e 4912 snapshot = 0;
a20dd508
FB
4913 kernel_filename = NULL;
4914 kernel_cmdline = "";
c4b1fcc0 4915 cyls = heads = secs = 0;
46d4767d 4916 translation = BIOS_ATA_TRANSLATION_AUTO;
c4b1fcc0 4917
268a362c
AL
4918 for (i = 0; i < MAX_NODES; i++) {
4919 node_mem[i] = 0;
4920 node_cpumask[i] = 0;
4921 }
4922
268a362c 4923 nb_numa_nodes = 0;
7c9d8e07 4924 nb_nics = 0;
3b46e624 4925
26a5f13b 4926 tb_size = 0;
41bd639b
BS
4927 autostart= 1;
4928
292444cb
AL
4929 /* first pass of option parsing */
4930 optind = 1;
4931 while (optind < argc) {
4932 if (argv[optind][0] != '-') {
4933 /* disk image */
28e68d68 4934 optind++;
292444cb
AL
4935 continue;
4936 } else {
4937 const QEMUOption *popt;
4938
4939 popt = lookup_opt(argc, argv, &optarg, &optind);
4940 switch (popt->index) {
4941 case QEMU_OPTION_nodefconfig:
4942 defconfig=0;
4943 break;
4944 }
4945 }
4946 }
4947
4948 if (defconfig) {
cf5a65aa 4949 const char *fname;
292444cb 4950 FILE *fp;
cf5a65aa
MA
4951
4952 fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
4953 fp = fopen(fname, "r");
292444cb 4954 if (fp) {
cf5a65aa 4955 if (qemu_config_parse(fp, fname) != 0) {
292444cb
AL
4956 exit(1);
4957 }
4958 fclose(fp);
4959 }
4960
cf5a65aa
MA
4961 fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
4962 fp = fopen(fname, "r");
292444cb 4963 if (fp) {
cf5a65aa 4964 if (qemu_config_parse(fp, fname) != 0) {
292444cb
AL
4965 exit(1);
4966 }
4967 fclose(fp);
4968 }
4969 }
b5ec5ce0 4970#if defined(cpudef_setup)
4971 cpudef_setup(); /* parse cpu definitions in target config file */
4972#endif
292444cb
AL
4973
4974 /* second pass of option parsing */
cd6f1169 4975 optind = 1;
0824d6fc 4976 for(;;) {
cd6f1169 4977 if (optind >= argc)
0824d6fc 4978 break;
6530a97b 4979 if (argv[optind][0] != '-') {
9dfd7c7a 4980 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
cd6f1169
FB
4981 } else {
4982 const QEMUOption *popt;
4983
6530a97b 4984 popt = lookup_opt(argc, argv, &optarg, &optind);
cd6f1169 4985 switch(popt->index) {
cc1daa40
FB
4986 case QEMU_OPTION_M:
4987 machine = find_machine(optarg);
4988 if (!machine) {
4989 QEMUMachine *m;
4990 printf("Supported machines are:\n");
4991 for(m = first_machine; m != NULL; m = m->next) {
3f6599e6
MM
4992 if (m->alias)
4993 printf("%-10s %s (alias of %s)\n",
4994 m->alias, m->desc, m->name);
cc1daa40 4995 printf("%-10s %s%s\n",
5fafdf24 4996 m->name, m->desc,
0c257437 4997 m->is_default ? " (default)" : "");
cc1daa40 4998 }
15f82208 4999 exit(*optarg != '?');
cc1daa40
FB
5000 }
5001 break;
94fc95cd
JM
5002 case QEMU_OPTION_cpu:
5003 /* hw initialization will check this */
15f82208 5004 if (*optarg == '?') {
c732abe2 5005/* XXX: implement xxx_cpu_list for targets that still miss it */
b5ec5ce0 5006#if defined(cpu_list_id)
5007 cpu_list_id(stdout, &fprintf, optarg);
5008#elif defined(cpu_list)
5009 cpu_list(stdout, &fprintf); /* deprecated */
94fc95cd 5010#endif
15f82208 5011 exit(0);
94fc95cd
JM
5012 } else {
5013 cpu_model = optarg;
5014 }
5015 break;
cd6f1169 5016 case QEMU_OPTION_initrd:
fc01f7e7
FB
5017 initrd_filename = optarg;
5018 break;
cd6f1169 5019 case QEMU_OPTION_hda:
e4bcb14c 5020 if (cyls == 0)
9dfd7c7a 5021 hda_opts = drive_add(optarg, HD_ALIAS, 0);
e4bcb14c 5022 else
9dfd7c7a 5023 hda_opts = drive_add(optarg, HD_ALIAS
e4bcb14c 5024 ",cyls=%d,heads=%d,secs=%d%s",
609497ab 5025 0, cyls, heads, secs,
e4bcb14c
TS
5026 translation == BIOS_ATA_TRANSLATION_LBA ?
5027 ",trans=lba" :
5028 translation == BIOS_ATA_TRANSLATION_NONE ?
5029 ",trans=none" : "");
5030 break;
cd6f1169 5031 case QEMU_OPTION_hdb:
cc1daa40
FB
5032 case QEMU_OPTION_hdc:
5033 case QEMU_OPTION_hdd:
609497ab 5034 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
fc01f7e7 5035 break;
e4bcb14c 5036 case QEMU_OPTION_drive:
609497ab 5037 drive_add(NULL, "%s", optarg);
e4bcb14c 5038 break;
d058fe03
GH
5039 case QEMU_OPTION_set:
5040 if (qemu_set_option(optarg) != 0)
5041 exit(1);
5042 break;
d0fef6fb
GH
5043 case QEMU_OPTION_global:
5044 if (qemu_global_option(optarg) != 0)
5045 exit(1);
5046 break;
3e3d5815 5047 case QEMU_OPTION_mtdblock:
609497ab 5048 drive_add(optarg, MTD_ALIAS);
3e3d5815 5049 break;
a1bb27b1 5050 case QEMU_OPTION_sd:
609497ab 5051 drive_add(optarg, SD_ALIAS);
a1bb27b1 5052 break;
86f55663 5053 case QEMU_OPTION_pflash:
609497ab 5054 drive_add(optarg, PFLASH_ALIAS);
86f55663 5055 break;
cd6f1169 5056 case QEMU_OPTION_snapshot:
33e3963e
FB
5057 snapshot = 1;
5058 break;
cd6f1169 5059 case QEMU_OPTION_hdachs:
330d0414 5060 {
330d0414
FB
5061 const char *p;
5062 p = optarg;
5063 cyls = strtol(p, (char **)&p, 0);
46d4767d
FB
5064 if (cyls < 1 || cyls > 16383)
5065 goto chs_fail;
330d0414
FB
5066 if (*p != ',')
5067 goto chs_fail;
5068 p++;
5069 heads = strtol(p, (char **)&p, 0);
46d4767d
FB
5070 if (heads < 1 || heads > 16)
5071 goto chs_fail;
330d0414
FB
5072 if (*p != ',')
5073 goto chs_fail;
5074 p++;
5075 secs = strtol(p, (char **)&p, 0);
46d4767d
FB
5076 if (secs < 1 || secs > 63)
5077 goto chs_fail;
5078 if (*p == ',') {
5079 p++;
5080 if (!strcmp(p, "none"))
5081 translation = BIOS_ATA_TRANSLATION_NONE;
5082 else if (!strcmp(p, "lba"))
5083 translation = BIOS_ATA_TRANSLATION_LBA;
5084 else if (!strcmp(p, "auto"))
5085 translation = BIOS_ATA_TRANSLATION_AUTO;
5086 else
5087 goto chs_fail;
5088 } else if (*p != '\0') {
c4b1fcc0 5089 chs_fail:
46d4767d
FB
5090 fprintf(stderr, "qemu: invalid physical CHS format\n");
5091 exit(1);
c4b1fcc0 5092 }
9dfd7c7a
GH
5093 if (hda_opts != NULL) {
5094 char num[16];
5095 snprintf(num, sizeof(num), "%d", cyls);
5096 qemu_opt_set(hda_opts, "cyls", num);
5097 snprintf(num, sizeof(num), "%d", heads);
5098 qemu_opt_set(hda_opts, "heads", num);
5099 snprintf(num, sizeof(num), "%d", secs);
5100 qemu_opt_set(hda_opts, "secs", num);
5101 if (translation == BIOS_ATA_TRANSLATION_LBA)
5102 qemu_opt_set(hda_opts, "trans", "lba");
5103 if (translation == BIOS_ATA_TRANSLATION_NONE)
5104 qemu_opt_set(hda_opts, "trans", "none");
5105 }
330d0414
FB
5106 }
5107 break;
268a362c
AL
5108 case QEMU_OPTION_numa:
5109 if (nb_numa_nodes >= MAX_NODES) {
5110 fprintf(stderr, "qemu: too many NUMA nodes\n");
5111 exit(1);
5112 }
5113 numa_add(optarg);
5114 break;
cd6f1169 5115 case QEMU_OPTION_nographic:
993fbfdb 5116 display_type = DT_NOGRAPHIC;
a20dd508 5117 break;
4d3b6f6e
AZ
5118#ifdef CONFIG_CURSES
5119 case QEMU_OPTION_curses:
993fbfdb 5120 display_type = DT_CURSES;
4d3b6f6e
AZ
5121 break;
5122#endif
a171fe39
AZ
5123 case QEMU_OPTION_portrait:
5124 graphic_rotate = 1;
5125 break;
cd6f1169 5126 case QEMU_OPTION_kernel:
a20dd508
FB
5127 kernel_filename = optarg;
5128 break;
cd6f1169 5129 case QEMU_OPTION_append:
a20dd508 5130 kernel_cmdline = optarg;
313aa567 5131 break;
cd6f1169 5132 case QEMU_OPTION_cdrom:
609497ab 5133 drive_add(optarg, CDROM_ALIAS);
36b486bb 5134 break;
cd6f1169 5135 case QEMU_OPTION_boot:
28c5af54 5136 {
ef3adf68 5137 static const char * const params[] = {
95387491 5138 "order", "once", "menu", NULL
ef3adf68
JK
5139 };
5140 char buf[sizeof(boot_devices)];
e0f084bf 5141 char *standard_boot_devices;
ef3adf68
JK
5142 int legacy = 0;
5143
5144 if (!strchr(optarg, '=')) {
5145 legacy = 1;
5146 pstrcpy(buf, sizeof(buf), optarg);
5147 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5148 fprintf(stderr,
5149 "qemu: unknown boot parameter '%s' in '%s'\n",
5150 buf, optarg);
5151 exit(1);
5152 }
5153
5154 if (legacy ||
5155 get_param_value(buf, sizeof(buf), "order", optarg)) {
5156 boot_devices_bitmap = parse_bootdevices(buf);
5157 pstrcpy(boot_devices, sizeof(boot_devices), buf);
28c5af54 5158 }
e0f084bf
JK
5159 if (!legacy) {
5160 if (get_param_value(buf, sizeof(buf),
5161 "once", optarg)) {
5162 boot_devices_bitmap |= parse_bootdevices(buf);
5163 standard_boot_devices = qemu_strdup(boot_devices);
5164 pstrcpy(boot_devices, sizeof(boot_devices), buf);
5165 qemu_register_reset(restore_boot_devices,
5166 standard_boot_devices);
5167 }
95387491
JK
5168 if (get_param_value(buf, sizeof(buf),
5169 "menu", optarg)) {
5170 if (!strcmp(buf, "on")) {
5171 boot_menu = 1;
5172 } else if (!strcmp(buf, "off")) {
5173 boot_menu = 0;
5174 } else {
5175 fprintf(stderr,
5176 "qemu: invalid option value '%s'\n",
5177 buf);
5178 exit(1);
5179 }
5180 }
e0f084bf 5181 }
36b486bb
FB
5182 }
5183 break;
cd6f1169 5184 case QEMU_OPTION_fda:
cd6f1169 5185 case QEMU_OPTION_fdb:
609497ab 5186 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
c45886db 5187 break;
52ca8d6a
FB
5188#ifdef TARGET_I386
5189 case QEMU_OPTION_no_fd_bootchk:
5190 fd_bootchk = 0;
5191 break;
5192#endif
a1ea458f
MM
5193 case QEMU_OPTION_netdev:
5194 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5195 exit(1);
5196 }
5197 break;
7c9d8e07 5198 case QEMU_OPTION_net:
7f161aae 5199 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
c4b1fcc0
FB
5200 exit(1);
5201 }
702c651c 5202 break;
c7f74643
FB
5203#ifdef CONFIG_SLIRP
5204 case QEMU_OPTION_tftp:
ad196a9d 5205 legacy_tftp_prefix = optarg;
9bf05444 5206 break;
47d5d01a 5207 case QEMU_OPTION_bootp:
ad196a9d 5208 legacy_bootp_filename = optarg;
47d5d01a 5209 break;
c94c8d64 5210#ifndef _WIN32
9d728e8c 5211 case QEMU_OPTION_smb:
0752706d
MA
5212 if (net_slirp_smb(optarg) < 0)
5213 exit(1);
9d728e8c 5214 break;
c94c8d64 5215#endif
9bf05444 5216 case QEMU_OPTION_redir:
0752706d
MA
5217 if (net_slirp_redir(optarg) < 0)
5218 exit(1);
9bf05444 5219 break;
c7f74643 5220#endif
dc72ac14 5221 case QEMU_OPTION_bt:
bd3c948d 5222 add_device_config(DEV_BT, optarg);
dc72ac14 5223 break;
1d14ffa9 5224#ifdef HAS_AUDIO
1d14ffa9
FB
5225 case QEMU_OPTION_audio_help:
5226 AUD_help ();
5227 exit (0);
5228 break;
5229 case QEMU_OPTION_soundhw:
5230 select_soundhw (optarg);
5231 break;
5232#endif
cd6f1169 5233 case QEMU_OPTION_h:
15f82208 5234 help(0);
cd6f1169 5235 break;
9bd7e6d9
PB
5236 case QEMU_OPTION_version:
5237 version();
5238 exit(0);
5239 break;
00f82b8a
AJ
5240 case QEMU_OPTION_m: {
5241 uint64_t value;
5242 char *ptr;
5243
5244 value = strtoul(optarg, &ptr, 10);
5245 switch (*ptr) {
5246 case 0: case 'M': case 'm':
5247 value <<= 20;
5248 break;
5249 case 'G': case 'g':
5250 value <<= 30;
5251 break;
5252 default:
5253 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
cd6f1169
FB
5254 exit(1);
5255 }
00f82b8a
AJ
5256
5257 /* On 32-bit hosts, QEMU is limited by virtual address space */
4a1418e0 5258 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
00f82b8a
AJ
5259 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5260 exit(1);
5261 }
c227f099 5262 if (value != (uint64_t)(ram_addr_t)value) {
00f82b8a
AJ
5263 fprintf(stderr, "qemu: ram size too large\n");
5264 exit(1);
5265 }
5266 ram_size = value;
cd6f1169 5267 break;
00f82b8a 5268 }
c902760f
MT
5269 case QEMU_OPTION_mempath:
5270 mem_path = optarg;
5271 break;
5272#ifdef MAP_POPULATE
5273 case QEMU_OPTION_mem_prealloc:
5274 mem_prealloc = 1;
5275 break;
5276#endif
cd6f1169
FB
5277 case QEMU_OPTION_d:
5278 {
5279 int mask;
c7cd6a37 5280 const CPULogItem *item;
3b46e624 5281
cd6f1169
FB
5282 mask = cpu_str_to_log_mask(optarg);
5283 if (!mask) {
5284 printf("Log items (comma separated):\n");
f193c797
FB
5285 for(item = cpu_log_items; item->mask != 0; item++) {
5286 printf("%-10s %s\n", item->name, item->help);
5287 }
5288 exit(1);
cd6f1169
FB
5289 }
5290 cpu_set_log(mask);
f193c797 5291 }
cd6f1169 5292 break;
cd6f1169 5293 case QEMU_OPTION_s:
59030a8c 5294 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
cd6f1169 5295 break;
59030a8c
AL
5296 case QEMU_OPTION_gdb:
5297 gdbstub_dev = optarg;
cd6f1169 5298 break;
cd6f1169 5299 case QEMU_OPTION_L:
5cea8590 5300 data_dir = optarg;
cd6f1169 5301 break;
1192dad8
JM
5302 case QEMU_OPTION_bios:
5303 bios_name = optarg;
5304 break;
1b530a6d
AJ
5305 case QEMU_OPTION_singlestep:
5306 singlestep = 1;
5307 break;
cd6f1169 5308 case QEMU_OPTION_S:
3c07f8e8 5309 autostart = 0;
cd6f1169 5310 break;
3d11d0eb
FB
5311 case QEMU_OPTION_k:
5312 keyboard_layout = optarg;
5313 break;
ee22c2f7
FB
5314 case QEMU_OPTION_localtime:
5315 rtc_utc = 0;
5316 break;
3893c124 5317 case QEMU_OPTION_vga:
5318 select_vgahw (optarg);
1bfe856e 5319 break;
5824d651 5320#if defined(TARGET_PPC) || defined(TARGET_SPARC)
e9b137c2
FB
5321 case QEMU_OPTION_g:
5322 {
5323 const char *p;
5324 int w, h, depth;
5325 p = optarg;
5326 w = strtol(p, (char **)&p, 10);
5327 if (w <= 0) {
5328 graphic_error:
5329 fprintf(stderr, "qemu: invalid resolution or depth\n");
5330 exit(1);
5331 }
5332 if (*p != 'x')
5333 goto graphic_error;
5334 p++;
5335 h = strtol(p, (char **)&p, 10);
5336 if (h <= 0)
5337 goto graphic_error;
5338 if (*p == 'x') {
5339 p++;
5340 depth = strtol(p, (char **)&p, 10);
5fafdf24 5341 if (depth != 8 && depth != 15 && depth != 16 &&
e9b137c2
FB
5342 depth != 24 && depth != 32)
5343 goto graphic_error;
5344 } else if (*p == '\0') {
5345 depth = graphic_depth;
5346 } else {
5347 goto graphic_error;
5348 }
3b46e624 5349
e9b137c2
FB
5350 graphic_width = w;
5351 graphic_height = h;
5352 graphic_depth = depth;
5353 }
5354 break;
5824d651 5355#endif
20d8a3ed
TS
5356 case QEMU_OPTION_echr:
5357 {
5358 char *r;
5359 term_escape_char = strtol(optarg, &r, 0);
5360 if (r == optarg)
5361 printf("Bad argument to echr\n");
5362 break;
5363 }
82c643ff 5364 case QEMU_OPTION_monitor:
6ca5582d
GH
5365 monitor_parse(optarg, "readline");
5366 default_monitor = 0;
5367 break;
5368 case QEMU_OPTION_qmp:
5369 monitor_parse(optarg, "control");
abdeed06 5370 default_monitor = 0;
82c643ff 5371 break;
22a0e04b 5372 case QEMU_OPTION_mon:
8212c64f 5373 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
22a0e04b
GH
5374 if (!opts) {
5375 fprintf(stderr, "parse error: %s\n", optarg);
5376 exit(1);
5377 }
5378 default_monitor = 0;
5379 break;
191bc01b 5380 case QEMU_OPTION_chardev:
8212c64f 5381 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
191bc01b
GH
5382 if (!opts) {
5383 fprintf(stderr, "parse error: %s\n", optarg);
5384 exit(1);
5385 }
191bc01b 5386 break;
82c643ff 5387 case QEMU_OPTION_serial:
998bbd74
GH
5388 add_device_config(DEV_SERIAL, optarg);
5389 default_serial = 0;
18141ed6
JK
5390 if (strncmp(optarg, "mon:", 4) == 0) {
5391 default_monitor = 0;
5392 }
82c643ff 5393 break;
9dd986cc 5394 case QEMU_OPTION_watchdog:
09aaa160
MA
5395 if (watchdog) {
5396 fprintf(stderr,
5397 "qemu: only one watchdog option may be given\n");
5398 return 1;
5399 }
5400 watchdog = optarg;
9dd986cc
RJ
5401 break;
5402 case QEMU_OPTION_watchdog_action:
5403 if (select_watchdog_action(optarg) == -1) {
5404 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5405 exit(1);
5406 }
5407 break;
51ecf136 5408 case QEMU_OPTION_virtiocon:
aee1b935
GH
5409 add_device_config(DEV_VIRTCON, optarg);
5410 default_virtcon = 0;
18141ed6
JK
5411 if (strncmp(optarg, "mon:", 4) == 0) {
5412 default_monitor = 0;
5413 }
51ecf136 5414 break;
6508fe59 5415 case QEMU_OPTION_parallel:
6a5e8b0e
GH
5416 add_device_config(DEV_PARALLEL, optarg);
5417 default_parallel = 0;
18141ed6
JK
5418 if (strncmp(optarg, "mon:", 4) == 0) {
5419 default_monitor = 0;
5420 }
6508fe59 5421 break;
c9f398e5
PA
5422 case QEMU_OPTION_debugcon:
5423 add_device_config(DEV_DEBUGCON, optarg);
5424 break;
d63d307f
FB
5425 case QEMU_OPTION_loadvm:
5426 loadvm = optarg;
5427 break;
5428 case QEMU_OPTION_full_screen:
5429 full_screen = 1;
5430 break;
667accab 5431#ifdef CONFIG_SDL
43523e93
TS
5432 case QEMU_OPTION_no_frame:
5433 no_frame = 1;
5434 break;
3780e197
TS
5435 case QEMU_OPTION_alt_grab:
5436 alt_grab = 1;
5437 break;
0ca9f8a4
DK
5438 case QEMU_OPTION_ctrl_grab:
5439 ctrl_grab = 1;
5440 break;
667accab
TS
5441 case QEMU_OPTION_no_quit:
5442 no_quit = 1;
5443 break;
7d957bd8 5444 case QEMU_OPTION_sdl:
993fbfdb 5445 display_type = DT_SDL;
7d957bd8 5446 break;
667accab 5447#endif
f7cce898 5448 case QEMU_OPTION_pidfile:
93815bc2 5449 pid_file = optarg;
f7cce898 5450 break;
a09db21f
FB
5451#ifdef TARGET_I386
5452 case QEMU_OPTION_win2k_hack:
5453 win2k_install_hack = 1;
5454 break;
73822ec8
AL
5455 case QEMU_OPTION_rtc_td_hack:
5456 rtc_td_hack = 1;
5457 break;
8a92ea2f
AL
5458 case QEMU_OPTION_acpitable:
5459 if(acpi_table_add(optarg) < 0) {
5460 fprintf(stderr, "Wrong acpi table provided\n");
5461 exit(1);
5462 }
5463 break;
b6f6e3d3
AL
5464 case QEMU_OPTION_smbios:
5465 if(smbios_entry_add(optarg) < 0) {
5466 fprintf(stderr, "Wrong smbios provided\n");
5467 exit(1);
5468 }
5469 break;
a09db21f 5470#endif
7ba1e619
AL
5471#ifdef CONFIG_KVM
5472 case QEMU_OPTION_enable_kvm:
5473 kvm_allowed = 1;
7ba1e619 5474 break;
d993e026 5475#endif
bb36d470
FB
5476 case QEMU_OPTION_usb:
5477 usb_enabled = 1;
5478 break;
a594cfbf
FB
5479 case QEMU_OPTION_usbdevice:
5480 usb_enabled = 1;
bd3c948d
GH
5481 add_device_config(DEV_USB, optarg);
5482 break;
5483 case QEMU_OPTION_device:
8212c64f 5484 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
f31d07d1
GH
5485 exit(1);
5486 }
a594cfbf 5487 break;
6a00d601 5488 case QEMU_OPTION_smp:
dc6b1c09 5489 smp_parse(optarg);
b2097003 5490 if (smp_cpus < 1) {
6a00d601
FB
5491 fprintf(stderr, "Invalid number of CPUs\n");
5492 exit(1);
5493 }
6be68d7e
JS
5494 if (max_cpus < smp_cpus) {
5495 fprintf(stderr, "maxcpus must be equal to or greater than "
5496 "smp\n");
5497 exit(1);
5498 }
5499 if (max_cpus > 255) {
5500 fprintf(stderr, "Unsupported number of maxcpus\n");
5501 exit(1);
5502 }
6a00d601 5503 break;
24236869 5504 case QEMU_OPTION_vnc:
993fbfdb 5505 display_type = DT_VNC;
73fc9742 5506 vnc_display = optarg;
24236869 5507 break;
5824d651 5508#ifdef TARGET_I386
6515b203
FB
5509 case QEMU_OPTION_no_acpi:
5510 acpi_enabled = 0;
5511 break;
16b29ae1
AL
5512 case QEMU_OPTION_no_hpet:
5513 no_hpet = 1;
5514 break;
7d4c3d53
MA
5515 case QEMU_OPTION_balloon:
5516 if (balloon_parse(optarg) < 0) {
5517 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5518 exit(1);
5519 }
df97b920 5520 break;
5824d651 5521#endif
d1beab82
FB
5522 case QEMU_OPTION_no_reboot:
5523 no_reboot = 1;
5524 break;
b2f76161
AJ
5525 case QEMU_OPTION_no_shutdown:
5526 no_shutdown = 1;
5527 break;
9467cd46
AZ
5528 case QEMU_OPTION_show_cursor:
5529 cursor_hide = 0;
5530 break;
8fcb1b90
BS
5531 case QEMU_OPTION_uuid:
5532 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5533 fprintf(stderr, "Fail to parse UUID string."
5534 " Wrong format.\n");
5535 exit(1);
5536 }
5537 break;
5824d651 5538#ifndef _WIN32
71e3ceb8
TS
5539 case QEMU_OPTION_daemonize:
5540 daemonize = 1;
5541 break;
5824d651 5542#endif
9ae02555
TS
5543 case QEMU_OPTION_option_rom:
5544 if (nb_option_roms >= MAX_OPTION_ROMS) {
5545 fprintf(stderr, "Too many option ROMs\n");
5546 exit(1);
5547 }
5548 option_rom[nb_option_roms] = optarg;
5549 nb_option_roms++;
5550 break;
5824d651 5551#if defined(TARGET_ARM) || defined(TARGET_M68K)
8e71621f
PB
5552 case QEMU_OPTION_semihosting:
5553 semihosting_enabled = 1;
5554 break;
5824d651 5555#endif
c35734b2 5556 case QEMU_OPTION_name:
1889465a
AK
5557 qemu_name = qemu_strdup(optarg);
5558 {
5559 char *p = strchr(qemu_name, ',');
5560 if (p != NULL) {
5561 *p++ = 0;
5562 if (strncmp(p, "process=", 8)) {
5563 fprintf(stderr, "Unknown subargument %s to -name", p);
5564 exit(1);
5565 }
5566 p += 8;
5567 set_proc_name(p);
5568 }
5569 }
c35734b2 5570 break;
95efd11c 5571#if defined(TARGET_SPARC) || defined(TARGET_PPC)
66508601
BS
5572 case QEMU_OPTION_prom_env:
5573 if (nb_prom_envs >= MAX_PROM_ENVS) {
5574 fprintf(stderr, "Too many prom variables\n");
5575 exit(1);
5576 }
5577 prom_envs[nb_prom_envs] = optarg;
5578 nb_prom_envs++;
5579 break;
2b8f2d41
AZ
5580#endif
5581#ifdef TARGET_ARM
5582 case QEMU_OPTION_old_param:
5583 old_param = 1;
05ebd537 5584 break;
66508601 5585#endif
f3dcfada
TS
5586 case QEMU_OPTION_clock:
5587 configure_alarms(optarg);
5588 break;
7e0af5d0 5589 case QEMU_OPTION_startdate:
1ed2fc1f
JK
5590 configure_rtc_date_offset(optarg, 1);
5591 break;
5592 case QEMU_OPTION_rtc:
8212c64f 5593 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
1ed2fc1f
JK
5594 if (!opts) {
5595 fprintf(stderr, "parse error: %s\n", optarg);
5596 exit(1);
7e0af5d0 5597 }
1ed2fc1f 5598 configure_rtc(opts);
7e0af5d0 5599 break;
26a5f13b
FB
5600 case QEMU_OPTION_tb_size:
5601 tb_size = strtol(optarg, NULL, 0);
5602 if (tb_size < 0)
5603 tb_size = 0;
5604 break;
2e70f6ef
PB
5605 case QEMU_OPTION_icount:
5606 use_icount = 1;
5607 if (strcmp(optarg, "auto") == 0) {
5608 icount_time_shift = -1;
5609 } else {
5610 icount_time_shift = strtol(optarg, NULL, 0);
5611 }
5612 break;
5bb7910a
AL
5613 case QEMU_OPTION_incoming:
5614 incoming = optarg;
5615 break;
d8c208dd
GH
5616 case QEMU_OPTION_nodefaults:
5617 default_serial = 0;
5618 default_parallel = 0;
aee1b935 5619 default_virtcon = 0;
d8c208dd
GH
5620 default_monitor = 0;
5621 default_vga = 0;
cb4522cc 5622 default_net = 0;
ac33f8fa
GH
5623 default_floppy = 0;
5624 default_cdrom = 0;
5625 default_sdcard = 0;
d8c208dd 5626 break;
5824d651 5627#ifndef _WIN32
0858532e
AL
5628 case QEMU_OPTION_chroot:
5629 chroot_dir = optarg;
5630 break;
5631 case QEMU_OPTION_runas:
5632 run_as = optarg;
5633 break;
e37630ca
AL
5634#endif
5635#ifdef CONFIG_XEN
5636 case QEMU_OPTION_xen_domid:
5637 xen_domid = atoi(optarg);
5638 break;
5639 case QEMU_OPTION_xen_create:
5640 xen_mode = XEN_CREATE;
5641 break;
5642 case QEMU_OPTION_xen_attach:
5643 xen_mode = XEN_ATTACH;
5644 break;
5824d651 5645#endif
715a664a
GH
5646 case QEMU_OPTION_readconfig:
5647 {
5648 FILE *fp;
5649 fp = fopen(optarg, "r");
5650 if (fp == NULL) {
5651 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5652 exit(1);
5653 }
cf5a65aa 5654 if (qemu_config_parse(fp, optarg) != 0) {
715a664a
GH
5655 exit(1);
5656 }
5657 fclose(fp);
5658 break;
5659 }
5660 case QEMU_OPTION_writeconfig:
5661 {
5662 FILE *fp;
5663 if (strcmp(optarg, "-") == 0) {
5664 fp = stdout;
5665 } else {
5666 fp = fopen(optarg, "w");
5667 if (fp == NULL) {
5668 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5669 exit(1);
5670 }
5671 }
5672 qemu_config_write(fp);
5673 fclose(fp);
5674 break;
5675 }
cd6f1169 5676 }
0824d6fc
FB
5677 }
5678 }
0f0bc3f1 5679 loc_set_none();
330d0414 5680
5cea8590
PB
5681 /* If no data_dir is specified then try to find it relative to the
5682 executable path. */
5683 if (!data_dir) {
5684 data_dir = find_datadir(argv[0]);
5685 }
5686 /* If all else fails use the install patch specified when building. */
5687 if (!data_dir) {
5688 data_dir = CONFIG_QEMU_SHAREDIR;
5689 }
5690
6be68d7e
JS
5691 /*
5692 * Default to max_cpus = smp_cpus, in case the user doesn't
5693 * specify a max_cpus value.
5694 */
5695 if (!max_cpus)
5696 max_cpus = smp_cpus;
5697
3d878caa 5698 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
b2097003
AL
5699 if (smp_cpus > machine->max_cpus) {
5700 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5701 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5702 machine->max_cpus);
5703 exit(1);
5704 }
5705
998bbd74 5706 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
d8bcbabf 5707 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
998bbd74 5708
986c5f78
GH
5709 if (machine->no_serial) {
5710 default_serial = 0;
5711 }
5712 if (machine->no_parallel) {
5713 default_parallel = 0;
5714 }
5715 if (!machine->use_virtcon) {
5716 default_virtcon = 0;
5717 }
5718 if (machine->no_vga) {
5719 default_vga = 0;
5720 }
ac33f8fa
GH
5721 if (machine->no_floppy) {
5722 default_floppy = 0;
5723 }
5724 if (machine->no_cdrom) {
5725 default_cdrom = 0;
5726 }
5727 if (machine->no_sdcard) {
5728 default_sdcard = 0;
5729 }
986c5f78 5730
993fbfdb 5731 if (display_type == DT_NOGRAPHIC) {
6a5e8b0e
GH
5732 if (default_parallel)
5733 add_device_config(DEV_PARALLEL, "null");
e1c09175
GH
5734 if (default_serial && default_monitor) {
5735 add_device_config(DEV_SERIAL, "mon:stdio");
986c5f78
GH
5736 } else if (default_virtcon && default_monitor) {
5737 add_device_config(DEV_VIRTCON, "mon:stdio");
e1c09175
GH
5738 } else {
5739 if (default_serial)
5740 add_device_config(DEV_SERIAL, "stdio");
986c5f78
GH
5741 if (default_virtcon)
5742 add_device_config(DEV_VIRTCON, "stdio");
e1c09175 5743 if (default_monitor)
6ca5582d 5744 monitor_parse("stdio", "readline");
e1c09175 5745 }
998bbd74
GH
5746 } else {
5747 if (default_serial)
5748 add_device_config(DEV_SERIAL, "vc:80Cx24C");
6a5e8b0e
GH
5749 if (default_parallel)
5750 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
abdeed06 5751 if (default_monitor)
6ca5582d 5752 monitor_parse("vc:80Cx24C", "readline");
38536da1
AG
5753 if (default_virtcon)
5754 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
bc0129d9 5755 }
64465297
GH
5756 if (default_vga)
5757 vga_interface_type = VGA_CIRRUS;
bc0129d9 5758
1a688d3b
GH
5759 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5760 exit(1);
5761
71e3ceb8 5762#ifndef _WIN32
71e3ceb8
TS
5763 if (daemonize) {
5764 pid_t pid;
5765
5766 if (pipe(fds) == -1)
5767 exit(1);
5768
5769 pid = fork();
5770 if (pid > 0) {
5771 uint8_t status;
5772 ssize_t len;
5773
5774 close(fds[1]);
5775
5776 again:
93815bc2
TS
5777 len = read(fds[0], &status, 1);
5778 if (len == -1 && (errno == EINTR))
5779 goto again;
5780
5781 if (len != 1)
5782 exit(1);
5783 else if (status == 1) {
850810d0 5784 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
93815bc2
TS
5785 exit(1);
5786 } else
5787 exit(0);
71e3ceb8 5788 } else if (pid < 0)
93815bc2 5789 exit(1);
71e3ceb8 5790
40ff6d7e
KW
5791 close(fds[0]);
5792 qemu_set_cloexec(fds[1]);
5793
71e3ceb8
TS
5794 setsid();
5795
5796 pid = fork();
5797 if (pid > 0)
5798 exit(0);
5799 else if (pid < 0)
5800 exit(1);
5801
5802 umask(027);
71e3ceb8
TS
5803
5804 signal(SIGTSTP, SIG_IGN);
5805 signal(SIGTTOU, SIG_IGN);
5806 signal(SIGTTIN, SIG_IGN);
5807 }
099fe236 5808#endif
71e3ceb8 5809
aa26bb2d 5810 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
099fe236 5811#ifndef _WIN32
93815bc2
TS
5812 if (daemonize) {
5813 uint8_t status = 1;
dc330e28
KS
5814 if (write(fds[1], &status, 1) != 1) {
5815 perror("daemonize. Writing to pipe\n");
5816 }
93815bc2 5817 } else
099fe236 5818#endif
850810d0 5819 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
93815bc2
TS
5820 exit(1);
5821 }
5822
214910a7
MT
5823 if (kvm_enabled()) {
5824 int ret;
5825
5826 ret = kvm_init(smp_cpus);
5827 if (ret < 0) {
5828 fprintf(stderr, "failed to initialize KVM\n");
5829 exit(1);
5830 }
5831 }
5832
3fcf7b6b
AL
5833 if (qemu_init_main_loop()) {
5834 fprintf(stderr, "qemu_init_main_loop failed\n");
5835 exit(1);
5836 }
a20dd508 5837 linux_boot = (kernel_filename != NULL);
6c41b272 5838
f8d39c01
TS
5839 if (!linux_boot && *kernel_cmdline != '\0') {
5840 fprintf(stderr, "-append only allowed with -kernel option\n");
5841 exit(1);
5842 }
5843
5844 if (!linux_boot && initrd_filename != NULL) {
5845 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5846 exit(1);
5847 }
5848
bf65f53f
FN
5849#ifndef _WIN32
5850 /* Win32 doesn't support line-buffering and requires size >= 2 */
b118d61e 5851 setvbuf(stdout, NULL, _IOLBF, 0);
bf65f53f 5852#endif
3b46e624 5853
7183b4b4
AL
5854 if (init_timer_alarm() < 0) {
5855 fprintf(stderr, "could not initialize alarm timer\n");
5856 exit(1);
5857 }
2e70f6ef
PB
5858 if (use_icount && icount_time_shift < 0) {
5859 use_icount = 2;
5860 /* 125MIPS seems a reasonable initial guess at the guest speed.
5861 It will be corrected fairly quickly anyway. */
5862 icount_time_shift = 3;
5863 init_icount_adjust();
5864 }
634fce96 5865
fd1dff4b
FB
5866#ifdef _WIN32
5867 socket_init();
5868#endif
5869
dc1c9fe8
MM
5870 if (net_init_clients() < 0) {
5871 exit(1);
702c651c 5872 }
f1510b2c 5873
406c8df3
GC
5874 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5875 net_set_boot_mask(net_boot);
5876
dc72ac14 5877 /* init the bluetooth world */
bd3c948d
GH
5878 if (foreach_device_config(DEV_BT, bt_parse))
5879 exit(1);
dc72ac14 5880
0824d6fc 5881 /* init the memory */
94a6b54f
PB
5882 if (ram_size == 0)
5883 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9ae02555 5884
26a5f13b
FB
5885 /* init the dynamic translator */
5886 cpu_exec_init_all(tb_size * 1024 * 1024);
5887
eb852011 5888 bdrv_init_with_whitelist();
c4b1fcc0 5889
c163b5ca
LS
5890 blk_mig_init();
5891
ac33f8fa 5892 if (default_cdrom) {
aa40fc9c
GH
5893 /* we always create the cdrom drive, even if no disk is there */
5894 drive_add(NULL, CDROM_ALIAS);
ac33f8fa 5895 }
c4b1fcc0 5896
ac33f8fa 5897 if (default_floppy) {
aa40fc9c
GH
5898 /* we always create at least one floppy */
5899 drive_add(NULL, FD_ALIAS, 0);
ac33f8fa 5900 }
86f55663 5901
ac33f8fa 5902 if (default_sdcard) {
aa40fc9c
GH
5903 /* we always create one sd slot, even if no card is in it */
5904 drive_add(NULL, SD_ALIAS);
5905 }
9d413d1d 5906
e4bcb14c 5907 /* open the virtual block devices */
9dfd7c7a 5908 if (snapshot)
7282a033
GH
5909 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5910 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
9dfd7c7a 5911 exit(1);
3e3d5815 5912
2faf58cd 5913 vmstate_register(0, &vmstate_timers ,&timers_state);
c163b5ca
LS
5914 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5915 ram_load, NULL);
8a7ddc38 5916
268a362c
AL
5917 if (nb_numa_nodes > 0) {
5918 int i;
5919
5920 if (nb_numa_nodes > smp_cpus) {
5921 nb_numa_nodes = smp_cpus;
5922 }
5923
5924 /* If no memory size if given for any node, assume the default case
5925 * and distribute the available memory equally across all nodes
5926 */
5927 for (i = 0; i < nb_numa_nodes; i++) {
5928 if (node_mem[i] != 0)
5929 break;
5930 }
5931 if (i == nb_numa_nodes) {
5932 uint64_t usedmem = 0;
5933
5934 /* On Linux, the each node's border has to be 8MB aligned,
5935 * the final node gets the rest.
5936 */
5937 for (i = 0; i < nb_numa_nodes - 1; i++) {
5938 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5939 usedmem += node_mem[i];
5940 }
5941 node_mem[i] = ram_size - usedmem;
5942 }
5943
5944 for (i = 0; i < nb_numa_nodes; i++) {
5945 if (node_cpumask[i] != 0)
5946 break;
5947 }
5948 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5949 * must cope with this anyway, because there are BIOSes out there in
5950 * real machines which also use this scheme.
5951 */
5952 if (i == nb_numa_nodes) {
5953 for (i = 0; i < smp_cpus; i++) {
5954 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5955 }
5956 }
5957 }
5958
998bbd74
GH
5959 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5960 exit(1);
6a5e8b0e
GH
5961 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5962 exit(1);
aee1b935
GH
5963 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5964 exit(1);
c9f398e5
PA
5965 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5966 exit(1);
2796dae0 5967
aae9460e
PB
5968 module_call_init(MODULE_INIT_DEVICE);
5969
ff952ba2
MA
5970 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
5971 exit(0);
5972
09aaa160
MA
5973 if (watchdog) {
5974 i = select_watchdog(watchdog);
5975 if (i > 0)
5976 exit (i == 1 ? 1 : 0);
5977 }
5978
b6b61144 5979 if (machine->compat_props) {
458fb679 5980 qdev_prop_register_global_list(machine->compat_props);
b6b61144 5981 }
d0fef6fb
GH
5982 qemu_add_globals();
5983
fbe1b595 5984 machine->init(ram_size, boot_devices,
3023f332
AL
5985 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5986
ea375f9a 5987 cpu_synchronize_all_post_init();
268a362c 5988
67b3b71d
JQ
5989#ifndef _WIN32
5990 /* must be after terminal init, SDL library changes signal handlers */
5991 sighandler_setup();
5992#endif
5993
268a362c
AL
5994 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5995 for (i = 0; i < nb_numa_nodes; i++) {
5996 if (node_cpumask[i] & (1 << env->cpu_index)) {
5997 env->numa_node = i;
5998 }
5999 }
6000 }
6001
6f338c34
AL
6002 current_machine = machine;
6003
3023f332
AL
6004 /* init USB devices */
6005 if (usb_enabled) {
0752706d
MA
6006 if (foreach_device_config(DEV_USB, usb_parse) < 0)
6007 exit(1);
3023f332
AL
6008 }
6009
bd3c948d 6010 /* init generic devices */
f31d07d1 6011 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
bd3c948d
GH
6012 exit(1);
6013
668680f7
MA
6014 net_check_clients();
6015
3023f332 6016 /* just use the first displaystate for the moment */
b473df6e 6017 ds = get_displaystate();
993fbfdb
AL
6018
6019 if (display_type == DT_DEFAULT) {
6020#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6021 display_type = DT_SDL;
6022#else
6023 display_type = DT_VNC;
6024 vnc_display = "localhost:0,to=99";
6025 show_vnc_port = 1;
6026#endif
6027 }
6028
6029
6030 switch (display_type) {
6031 case DT_NOGRAPHIC:
6032 break;
4d3b6f6e 6033#if defined(CONFIG_CURSES)
993fbfdb
AL
6034 case DT_CURSES:
6035 curses_display_init(ds, full_screen);
6036 break;
4d3b6f6e 6037#endif
5b0753e0 6038#if defined(CONFIG_SDL)
993fbfdb
AL
6039 case DT_SDL:
6040 sdl_display_init(ds, full_screen, no_frame);
6041 break;
5b0753e0 6042#elif defined(CONFIG_COCOA)
993fbfdb
AL
6043 case DT_SDL:
6044 cocoa_display_init(ds, full_screen);
6045 break;
313aa567 6046#endif
993fbfdb
AL
6047 case DT_VNC:
6048 vnc_display_init(ds);
6049 if (vnc_display_open(ds, vnc_display) < 0)
6050 exit(1);
f92f8afe 6051
993fbfdb
AL
6052 if (show_vnc_port) {
6053 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
f92f8afe 6054 }
993fbfdb
AL
6055 break;
6056 default:
6057 break;
313aa567 6058 }
7d957bd8 6059 dpy_resize(ds);
5b08fc10 6060
3023f332
AL
6061 dcl = ds->listeners;
6062 while (dcl != NULL) {
6063 if (dcl->dpy_refresh != NULL) {
6064 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6065 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
20d8a3ed 6066 }
3023f332 6067 dcl = dcl->next;
20d8a3ed 6068 }
3023f332 6069
993fbfdb 6070 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
9043b62d
BS
6071 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6072 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6073 }
6074
b473df6e 6075 text_consoles_set_display(ds);
2796dae0 6076
88589343
GH
6077 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6078 exit(1);
82c643ff 6079
59030a8c
AL
6080 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6081 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6082 gdbstub_dev);
6083 exit(1);
45669e00 6084 }
45669e00 6085
3418bd25
GH
6086 qdev_machine_creation_done();
6087
15ff7705
GH
6088 if (rom_load_all() != 0) {
6089 fprintf(stderr, "rom loading failed\n");
6090 exit(1);
6091 }
45a50b16 6092
504c2948 6093 qemu_system_reset();
05f2401e 6094 if (loadvm) {
03cd4655 6095 if (load_vmstate(loadvm) < 0) {
05f2401e
JQ
6096 autostart = 0;
6097 }
6098 }
d63d307f 6099
2bb8c10c 6100 if (incoming) {
5bb7910a 6101 qemu_start_incoming_migration(incoming);
6b99dadc 6102 } else if (autostart) {
c0f4ce77 6103 vm_start();
6b99dadc 6104 }
ffd843bc 6105
b9e82a59 6106#ifndef _WIN32
71e3ceb8
TS
6107 if (daemonize) {
6108 uint8_t status = 0;
6109 ssize_t len;
71e3ceb8
TS
6110
6111 again1:
6112 len = write(fds[1], &status, 1);
6113 if (len == -1 && (errno == EINTR))
6114 goto again1;
6115
6116 if (len != 1)
6117 exit(1);
6118
dc330e28
KS
6119 if (chdir("/")) {
6120 perror("not able to chdir to /");
6121 exit(1);
6122 }
40ff6d7e 6123 TFR(fd = qemu_open("/dev/null", O_RDWR));
71e3ceb8
TS
6124 if (fd == -1)
6125 exit(1);
0858532e 6126 }
71e3ceb8 6127
0858532e
AL
6128 if (run_as) {
6129 pwd = getpwnam(run_as);
6130 if (!pwd) {
6131 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6132 exit(1);
6133 }
6134 }
6135
6136 if (chroot_dir) {
6137 if (chroot(chroot_dir) < 0) {
6138 fprintf(stderr, "chroot failed\n");
6139 exit(1);
6140 }
dc330e28
KS
6141 if (chdir("/")) {
6142 perror("not able to chdir to /");
6143 exit(1);
6144 }
0858532e
AL
6145 }
6146
6147 if (run_as) {
6148 if (setgid(pwd->pw_gid) < 0) {
6149 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6150 exit(1);
6151 }
6152 if (setuid(pwd->pw_uid) < 0) {
6153 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6154 exit(1);
6155 }
6156 if (setuid(0) != -1) {
6157 fprintf(stderr, "Dropping privileges failed\n");
6158 exit(1);
6159 }
6160 }
0858532e
AL
6161
6162 if (daemonize) {
6163 dup2(fd, 0);
6164 dup2(fd, 1);
6165 dup2(fd, 2);
71e3ceb8 6166
0858532e 6167 close(fd);
71e3ceb8 6168 }
b9e82a59 6169#endif
71e3ceb8 6170
8a7ddc38 6171 main_loop();
40c3bac3 6172 quit_timers();
63a01ef8 6173 net_cleanup();
b46a8906 6174
0824d6fc
FB
6175 return 0;
6176}