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