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