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