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