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