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