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