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