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