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