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