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