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