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