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