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