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