]> git.proxmox.com Git - mirror_qemu.git/blame - vl.c
qdev: also match bus name for global properties
[mirror_qemu.git] / vl.c
CommitLineData
0824d6fc 1/*
80cabfad 2 * QEMU System Emulator
5fafdf24 3 *
68d0f70e 4 * Copyright (c) 2003-2008 Fabrice Bellard
5fafdf24 5 *
1df912cf
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
0824d6fc 23 */
0824d6fc 24#include <unistd.h>
0824d6fc
FB
25#include <fcntl.h>
26#include <signal.h>
27#include <time.h>
0824d6fc 28#include <errno.h>
67b915a5 29#include <sys/time.h>
c88676f8 30#include <zlib.h>
67b915a5 31
71e72a19 32/* Needed early for CONFIG_BSD etc. */
d40cdb10
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
LS
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
40ff6d7e 1246 fd = qemu_open("/dev/hpet", O_RDONLY);
c40ec5a9
TS
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
40ff6d7e 1295 TFR(rtc_fd = qemu_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
f7850099
KW
1962BlockInterfaceErrorAction drive_get_on_error(
1963 BlockDriverState *bdrv, int is_read)
428c5705 1964{
751c6a17 1965 DriveInfo *dinfo;
428c5705 1966
fc072ec4
KW
1967 if (is_read) {
1968 return BLOCK_ERR_REPORT;
1969 }
1970
72cf2d4f 1971 QTAILQ_FOREACH(dinfo, &drives, next) {
751c6a17 1972 if (dinfo->bdrv == bdrv)
e9b2e818 1973 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
751c6a17 1974 }
428c5705 1975
e9b2e818 1976 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
428c5705
AL
1977}
1978
a1620fac
AJ
1979static void bdrv_format_print(void *opaque, const char *name)
1980{
1981 fprintf(stderr, " %s", name);
1982}
1983
56a14938 1984void drive_uninit(DriveInfo *dinfo)
b01b1111 1985{
56a14938
GH
1986 qemu_opts_del(dinfo->opts);
1987 bdrv_delete(dinfo->bdrv);
1988 QTAILQ_REMOVE(&drives, dinfo, next);
1989 qemu_free(dinfo);
b01b1111
AL
1990}
1991
e9b2e818
KW
1992static int parse_block_error_action(const char *buf, int is_read)
1993{
1994 if (!strcmp(buf, "ignore")) {
1995 return BLOCK_ERR_IGNORE;
1996 } else if (!is_read && !strcmp(buf, "enospc")) {
1997 return BLOCK_ERR_STOP_ENOSPC;
1998 } else if (!strcmp(buf, "stop")) {
1999 return BLOCK_ERR_STOP_ANY;
2000 } else if (!strcmp(buf, "report")) {
2001 return BLOCK_ERR_REPORT;
2002 } else {
2003 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
2004 buf, is_read ? "read" : "write");
2005 return -1;
2006 }
2007}
2008
9dfd7c7a 2009DriveInfo *drive_init(QemuOpts *opts, void *opaque,
751c6a17 2010 int *fatal_error)
e4bcb14c 2011{
9dfd7c7a
GH
2012 const char *buf;
2013 const char *file = NULL;
c8522bdf 2014 char devname[128];
9dfd7c7a 2015 const char *serial;
c8522bdf 2016 const char *mediastr = "";
f60d39bc 2017 BlockInterfaceType type;
e4bcb14c
TS
2018 enum { MEDIA_DISK, MEDIA_CDROM } media;
2019 int bus_id, unit_id;
2020 int cyls, heads, secs, translation;
1e72d3b7 2021 BlockDriver *drv = NULL;
4d73cd3b 2022 QEMUMachine *machine = opaque;
e4bcb14c
TS
2023 int max_devs;
2024 int index;
33f00271 2025 int cache;
5c6c3a6c 2026 int aio = 0;
59f2689d 2027 int ro = 0;
e9b2e818
KW
2028 int bdrv_flags;
2029 int on_read_error, on_write_error;
c2cc47a4 2030 const char *devaddr;
751c6a17 2031 DriveInfo *dinfo;
9dfd7c7a 2032 int snapshot = 0;
e4bcb14c 2033
9dfd7c7a 2034 *fatal_error = 1;
e4bcb14c 2035
e4bcb14c 2036 translation = BIOS_ATA_TRANSLATION_AUTO;
0aa217e4 2037 cache = 1;
e4bcb14c 2038
4d007814 2039 if (machine && machine->use_scsi) {
f60d39bc 2040 type = IF_SCSI;
e4bcb14c 2041 max_devs = MAX_SCSI_DEVS;
363a37d5 2042 pstrcpy(devname, sizeof(devname), "scsi");
e4bcb14c 2043 } else {
f60d39bc 2044 type = IF_IDE;
e4bcb14c 2045 max_devs = MAX_IDE_DEVS;
363a37d5 2046 pstrcpy(devname, sizeof(devname), "ide");
e4bcb14c
TS
2047 }
2048 media = MEDIA_DISK;
2049
2050 /* extract parameters */
9dfd7c7a
GH
2051 bus_id = qemu_opt_get_number(opts, "bus", 0);
2052 unit_id = qemu_opt_get_number(opts, "unit", -1);
2053 index = qemu_opt_get_number(opts, "index", -1);
e4bcb14c 2054
9dfd7c7a
GH
2055 cyls = qemu_opt_get_number(opts, "cyls", 0);
2056 heads = qemu_opt_get_number(opts, "heads", 0);
2057 secs = qemu_opt_get_number(opts, "secs", 0);
e4bcb14c 2058
9dfd7c7a 2059 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
59f2689d 2060 ro = qemu_opt_get_bool(opts, "readonly", 0);
e4bcb14c 2061
9dfd7c7a
GH
2062 file = qemu_opt_get(opts, "file");
2063 serial = qemu_opt_get(opts, "serial");
2064
2065 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
ae45d369 2066 pstrcpy(devname, sizeof(devname), buf);
e4bcb14c 2067 if (!strcmp(buf, "ide")) {
f60d39bc 2068 type = IF_IDE;
e4bcb14c
TS
2069 max_devs = MAX_IDE_DEVS;
2070 } else if (!strcmp(buf, "scsi")) {
f60d39bc 2071 type = IF_SCSI;
e4bcb14c
TS
2072 max_devs = MAX_SCSI_DEVS;
2073 } else if (!strcmp(buf, "floppy")) {
f60d39bc 2074 type = IF_FLOPPY;
e4bcb14c
TS
2075 max_devs = 0;
2076 } else if (!strcmp(buf, "pflash")) {
f60d39bc 2077 type = IF_PFLASH;
e4bcb14c
TS
2078 max_devs = 0;
2079 } else if (!strcmp(buf, "mtd")) {
f60d39bc 2080 type = IF_MTD;
e4bcb14c
TS
2081 max_devs = 0;
2082 } else if (!strcmp(buf, "sd")) {
f60d39bc 2083 type = IF_SD;
e4bcb14c 2084 max_devs = 0;
6e02c38d
AL
2085 } else if (!strcmp(buf, "virtio")) {
2086 type = IF_VIRTIO;
2087 max_devs = 0;
62d23efa
AL
2088 } else if (!strcmp(buf, "xen")) {
2089 type = IF_XEN;
2090 max_devs = 0;
a8659e90
GH
2091 } else if (!strcmp(buf, "none")) {
2092 type = IF_NONE;
2093 max_devs = 0;
62d23efa 2094 } else {
9dfd7c7a 2095 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
751c6a17 2096 return NULL;
e4bcb14c
TS
2097 }
2098 }
2099
e4bcb14c 2100 if (cyls || heads || secs) {
5afe3f04 2101 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
9dfd7c7a 2102 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
751c6a17 2103 return NULL;
e4bcb14c 2104 }
5afe3f04 2105 if (heads < 1 || (type == IF_IDE && heads > 16)) {
9dfd7c7a 2106 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
751c6a17 2107 return NULL;
e4bcb14c 2108 }
5afe3f04 2109 if (secs < 1 || (type == IF_IDE && secs > 63)) {
9dfd7c7a 2110 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
751c6a17 2111 return NULL;
e4bcb14c
TS
2112 }
2113 }
2114
9dfd7c7a 2115 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
e4bcb14c
TS
2116 if (!cyls) {
2117 fprintf(stderr,
2118 "qemu: '%s' trans must be used with cyls,heads and secs\n",
9dfd7c7a 2119 buf);
751c6a17 2120 return NULL;
e4bcb14c
TS
2121 }
2122 if (!strcmp(buf, "none"))
2123 translation = BIOS_ATA_TRANSLATION_NONE;
2124 else if (!strcmp(buf, "lba"))
2125 translation = BIOS_ATA_TRANSLATION_LBA;
2126 else if (!strcmp(buf, "auto"))
2127 translation = BIOS_ATA_TRANSLATION_AUTO;
2128 else {
9dfd7c7a 2129 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
751c6a17 2130 return NULL;
e4bcb14c
TS
2131 }
2132 }
2133
9dfd7c7a 2134 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
e4bcb14c
TS
2135 if (!strcmp(buf, "disk")) {
2136 media = MEDIA_DISK;
2137 } else if (!strcmp(buf, "cdrom")) {
2138 if (cyls || secs || heads) {
2139 fprintf(stderr,
9dfd7c7a 2140 "qemu: '%s' invalid physical CHS format\n", buf);
751c6a17 2141 return NULL;
e4bcb14c
TS
2142 }
2143 media = MEDIA_CDROM;
2144 } else {
9dfd7c7a 2145 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
751c6a17 2146 return NULL;
e4bcb14c
TS
2147 }
2148 }
2149
9dfd7c7a 2150 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
9f7965c7 2151 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
33f00271 2152 cache = 0;
9f7965c7 2153 else if (!strcmp(buf, "writethrough"))
33f00271 2154 cache = 1;
9f7965c7
AL
2155 else if (!strcmp(buf, "writeback"))
2156 cache = 2;
33f00271
AZ
2157 else {
2158 fprintf(stderr, "qemu: invalid cache option\n");
751c6a17 2159 return NULL;
33f00271
AZ
2160 }
2161 }
2162
5c6c3a6c
CH
2163#ifdef CONFIG_LINUX_AIO
2164 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2165 if (!strcmp(buf, "threads"))
2166 aio = 0;
2167 else if (!strcmp(buf, "native"))
2168 aio = 1;
2169 else {
2170 fprintf(stderr, "qemu: invalid aio option\n");
2171 return NULL;
2172 }
2173 }
2174#endif
2175
9dfd7c7a 2176 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
a1620fac
AJ
2177 if (strcmp(buf, "?") == 0) {
2178 fprintf(stderr, "qemu: Supported formats:");
2179 bdrv_iterate_format(bdrv_format_print, NULL);
2180 fprintf(stderr, "\n");
751c6a17 2181 return NULL;
a1620fac 2182 }
eb852011 2183 drv = bdrv_find_whitelisted_format(buf);
1e72d3b7
AJ
2184 if (!drv) {
2185 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
751c6a17 2186 return NULL;
1e72d3b7
AJ
2187 }
2188 }
2189
e9b2e818 2190 on_write_error = BLOCK_ERR_STOP_ENOSPC;
9dfd7c7a 2191 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
869a5c6d 2192 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
ea8a5d7f 2193 fprintf(stderr, "werror is no supported by this format\n");
751c6a17 2194 return NULL;
428c5705 2195 }
e9b2e818
KW
2196
2197 on_write_error = parse_block_error_action(buf, 0);
2198 if (on_write_error < 0) {
2199 return NULL;
2200 }
2201 }
2202
2203 on_read_error = BLOCK_ERR_REPORT;
2204 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
f35d68f0 2205 if (type != IF_IDE && type != IF_VIRTIO) {
e9b2e818
KW
2206 fprintf(stderr, "rerror is no supported by this format\n");
2207 return NULL;
2208 }
2209
2210 on_read_error = parse_block_error_action(buf, 1);
2211 if (on_read_error < 0) {
751c6a17 2212 return NULL;
428c5705
AL
2213 }
2214 }
2215
9dfd7c7a 2216 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
c2cc47a4 2217 if (type != IF_VIRTIO) {
9dfd7c7a 2218 fprintf(stderr, "addr is not supported\n");
751c6a17 2219 return NULL;
c2cc47a4 2220 }
c2cc47a4
MA
2221 }
2222
e4bcb14c
TS
2223 /* compute bus and unit according index */
2224
2225 if (index != -1) {
2226 if (bus_id != 0 || unit_id != -1) {
2227 fprintf(stderr,
9dfd7c7a 2228 "qemu: index cannot be used with bus and unit\n");
751c6a17 2229 return NULL;
e4bcb14c
TS
2230 }
2231 if (max_devs == 0)
2232 {
2233 unit_id = index;
2234 bus_id = 0;
2235 } else {
2236 unit_id = index % max_devs;
2237 bus_id = index / max_devs;
2238 }
2239 }
2240
2241 /* if user doesn't specify a unit_id,
2242 * try to find the first free
2243 */
2244
2245 if (unit_id == -1) {
2246 unit_id = 0;
751c6a17 2247 while (drive_get(type, bus_id, unit_id) != NULL) {
e4bcb14c
TS
2248 unit_id++;
2249 if (max_devs && unit_id >= max_devs) {
2250 unit_id -= max_devs;
2251 bus_id++;
2252 }
2253 }
2254 }
2255
2256 /* check unit id */
2257
2258 if (max_devs && unit_id >= max_devs) {
9dfd7c7a
GH
2259 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2260 unit_id, max_devs - 1);
751c6a17 2261 return NULL;
e4bcb14c
TS
2262 }
2263
2264 /*
2265 * ignore multiple definitions
2266 */
2267
751c6a17
GH
2268 if (drive_get(type, bus_id, unit_id) != NULL) {
2269 *fatal_error = 0;
2270 return NULL;
2271 }
e4bcb14c
TS
2272
2273 /* init */
2274
751c6a17 2275 dinfo = qemu_mallocz(sizeof(*dinfo));
e23d9c4d 2276 if ((buf = qemu_opts_id(opts)) != NULL) {
9dfd7c7a
GH
2277 dinfo->id = qemu_strdup(buf);
2278 } else {
1dae12e6 2279 /* no id supplied -> create one */
9dfd7c7a 2280 dinfo->id = qemu_mallocz(32);
1dae12e6
GH
2281 if (type == IF_IDE || type == IF_SCSI)
2282 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2283 if (max_devs)
9dfd7c7a 2284 snprintf(dinfo->id, 32, "%s%i%s%i",
1dae12e6
GH
2285 devname, bus_id, mediastr, unit_id);
2286 else
9dfd7c7a 2287 snprintf(dinfo->id, 32, "%s%s%i",
1dae12e6
GH
2288 devname, mediastr, unit_id);
2289 }
1dae12e6 2290 dinfo->bdrv = bdrv_new(dinfo->id);
751c6a17
GH
2291 dinfo->devaddr = devaddr;
2292 dinfo->type = type;
2293 dinfo->bus = bus_id;
2294 dinfo->unit = unit_id;
e9b2e818
KW
2295 dinfo->on_read_error = on_read_error;
2296 dinfo->on_write_error = on_write_error;
9dfd7c7a
GH
2297 dinfo->opts = opts;
2298 if (serial)
2299 strncpy(dinfo->serial, serial, sizeof(serial));
72cf2d4f 2300 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
e4bcb14c 2301
f60d39bc 2302 switch(type) {
e4bcb14c
TS
2303 case IF_IDE:
2304 case IF_SCSI:
62d23efa 2305 case IF_XEN:
c219331e 2306 case IF_NONE:
e4bcb14c
TS
2307 switch(media) {
2308 case MEDIA_DISK:
2309 if (cyls != 0) {
1dae12e6
GH
2310 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2311 bdrv_set_translation_hint(dinfo->bdrv, translation);
e4bcb14c
TS
2312 }
2313 break;
2314 case MEDIA_CDROM:
1dae12e6 2315 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
e4bcb14c
TS
2316 break;
2317 }
2318 break;
2319 case IF_SD:
2320 /* FIXME: This isn't really a floppy, but it's a reasonable
2321 approximation. */
2322 case IF_FLOPPY:
1dae12e6 2323 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
e4bcb14c
TS
2324 break;
2325 case IF_PFLASH:
2326 case IF_MTD:
2327 break;
d176c495
GH
2328 case IF_VIRTIO:
2329 /* add virtio block device */
2330 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2331 qemu_opt_set(opts, "driver", "virtio-blk-pci");
2332 qemu_opt_set(opts, "drive", dinfo->id);
2333 if (devaddr)
2334 qemu_opt_set(opts, "addr", devaddr);
2335 break;
aae9460e
PB
2336 case IF_COUNT:
2337 abort();
e4bcb14c 2338 }
9dfd7c7a 2339 if (!file) {
751c6a17
GH
2340 *fatal_error = 0;
2341 return NULL;
2342 }
33f00271 2343 bdrv_flags = 0;
9f7965c7 2344 if (snapshot) {
33f00271 2345 bdrv_flags |= BDRV_O_SNAPSHOT;
9f7965c7
AL
2346 cache = 2; /* always use write-back with snapshot */
2347 }
2348 if (cache == 0) /* no caching */
2349 bdrv_flags |= BDRV_O_NOCACHE;
2350 else if (cache == 2) /* write-back */
2351 bdrv_flags |= BDRV_O_CACHE_WB;
5c6c3a6c
CH
2352
2353 if (aio == 1) {
2354 bdrv_flags |= BDRV_O_NATIVE_AIO;
2355 } else {
2356 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2357 }
2358
59f2689d
NS
2359 if (ro == 1) {
2360 if (type == IF_IDE) {
2361 fprintf(stderr, "qemu: readonly flag not supported for drive with ide interface\n");
2362 return NULL;
2363 }
2364 (void)bdrv_set_read_only(dinfo->bdrv, 1);
2365 }
2366
1dae12e6 2367 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
850810d0
JF
2368 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2369 file, strerror(errno));
751c6a17 2370 return NULL;
e4bcb14c 2371 }
5c6c3a6c 2372
1dae12e6 2373 if (bdrv_key_required(dinfo->bdrv))
c0f4ce77 2374 autostart = 0;
751c6a17
GH
2375 *fatal_error = 0;
2376 return dinfo;
e4bcb14c
TS
2377}
2378
9dfd7c7a
GH
2379static int drive_init_func(QemuOpts *opts, void *opaque)
2380{
2381 QEMUMachine *machine = opaque;
2382 int fatal_error = 0;
2383
2384 if (drive_init(opts, machine, &fatal_error) == NULL) {
2385 if (fatal_error)
2386 return 1;
2387 }
2388 return 0;
2389}
2390
2391static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2392{
2393 if (NULL == qemu_opt_get(opts, "snapshot")) {
2394 qemu_opt_set(opts, "snapshot", "on");
2395 }
2396 return 0;
2397}
2398
76e30d0f
JK
2399void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2400{
2401 boot_set_handler = func;
2402 boot_set_opaque = opaque;
2403}
2404
2405int qemu_boot_set(const char *boot_devices)
2406{
2407 if (!boot_set_handler) {
2408 return -EINVAL;
2409 }
2410 return boot_set_handler(boot_set_opaque, boot_devices);
2411}
2412
ef3adf68
JK
2413static int parse_bootdevices(char *devices)
2414{
2415 /* We just do some generic consistency checks */
2416 const char *p;
2417 int bitmap = 0;
2418
2419 for (p = devices; *p != '\0'; p++) {
2420 /* Allowed boot devices are:
2421 * a-b: floppy disk drives
2422 * c-f: IDE disk drives
2423 * g-m: machine implementation dependant drives
2424 * n-p: network devices
2425 * It's up to each machine implementation to check if the given boot
2426 * devices match the actual hardware implementation and firmware
2427 * features.
2428 */
2429 if (*p < 'a' || *p > 'p') {
2430 fprintf(stderr, "Invalid boot device '%c'\n", *p);
2431 exit(1);
2432 }
2433 if (bitmap & (1 << (*p - 'a'))) {
2434 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2435 exit(1);
2436 }
2437 bitmap |= 1 << (*p - 'a');
2438 }
2439 return bitmap;
2440}
2441
e0f084bf
JK
2442static void restore_boot_devices(void *opaque)
2443{
2444 char *standard_boot_devices = opaque;
2445
2446 qemu_boot_set(standard_boot_devices);
2447
2448 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2449 qemu_free(standard_boot_devices);
2450}
2451
268a362c
AL
2452static void numa_add(const char *optarg)
2453{
2454 char option[128];
2455 char *endptr;
2456 unsigned long long value, endvalue;
2457 int nodenr;
2458
2459 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2460 if (!strcmp(option, "node")) {
2461 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2462 nodenr = nb_numa_nodes;
2463 } else {
2464 nodenr = strtoull(option, NULL, 10);
2465 }
2466
2467 if (get_param_value(option, 128, "mem", optarg) == 0) {
2468 node_mem[nodenr] = 0;
2469 } else {
2470 value = strtoull(option, &endptr, 0);
2471 switch (*endptr) {
2472 case 0: case 'M': case 'm':
2473 value <<= 20;
2474 break;
2475 case 'G': case 'g':
2476 value <<= 30;
2477 break;
2478 }
2479 node_mem[nodenr] = value;
2480 }
2481 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2482 node_cpumask[nodenr] = 0;
2483 } else {
2484 value = strtoull(option, &endptr, 10);
2485 if (value >= 64) {
2486 value = 63;
2487 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2488 } else {
2489 if (*endptr == '-') {
2490 endvalue = strtoull(endptr+1, &endptr, 10);
2491 if (endvalue >= 63) {
2492 endvalue = 62;
2493 fprintf(stderr,
2494 "only 63 CPUs in NUMA mode supported.\n");
2495 }
2496 value = (1 << (endvalue + 1)) - (1 << value);
2497 } else {
2498 value = 1 << value;
2499 }
2500 }
2501 node_cpumask[nodenr] = value;
2502 }
2503 nb_numa_nodes++;
2504 }
2505 return;
2506}
2507
dc6b1c09
AP
2508static void smp_parse(const char *optarg)
2509{
2510 int smp, sockets = 0, threads = 0, cores = 0;
2511 char *endptr;
2512 char option[128];
2513
2514 smp = strtoul(optarg, &endptr, 10);
2515 if (endptr != optarg) {
2516 if (*endptr == ',') {
2517 endptr++;
2518 }
2519 }
2520 if (get_param_value(option, 128, "sockets", endptr) != 0)
2521 sockets = strtoull(option, NULL, 10);
2522 if (get_param_value(option, 128, "cores", endptr) != 0)
2523 cores = strtoull(option, NULL, 10);
2524 if (get_param_value(option, 128, "threads", endptr) != 0)
2525 threads = strtoull(option, NULL, 10);
2526 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2527 max_cpus = strtoull(option, NULL, 10);
2528
2529 /* compute missing values, prefer sockets over cores over threads */
2530 if (smp == 0 || sockets == 0) {
2531 sockets = sockets > 0 ? sockets : 1;
2532 cores = cores > 0 ? cores : 1;
2533 threads = threads > 0 ? threads : 1;
2534 if (smp == 0) {
2535 smp = cores * threads * sockets;
2536 } else {
2537 sockets = smp / (cores * threads);
2538 }
2539 } else {
2540 if (cores == 0) {
2541 threads = threads > 0 ? threads : 1;
2542 cores = smp / (sockets * threads);
2543 } else {
2544 if (sockets == 0) {
2545 sockets = smp / (cores * threads);
2546 } else {
2547 threads = smp / (cores * sockets);
2548 }
2549 }
2550 }
2551 smp_cpus = smp;
2552 smp_cores = cores > 0 ? cores : 1;
2553 smp_threads = threads > 0 ? threads : 1;
2554 if (max_cpus == 0)
2555 max_cpus = smp_cpus;
2556}
2557
a594cfbf
FB
2558/***********************************************************/
2559/* USB devices */
2560
c0f4ce77 2561static int usb_device_add(const char *devname, int is_hotplug)
a594cfbf
FB
2562{
2563 const char *p;
a5d2f727 2564 USBDevice *dev = NULL;
a594cfbf 2565
a5d2f727 2566 if (!usb_enabled)
a594cfbf
FB
2567 return -1;
2568
0958b4cc
GH
2569 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2570 dev = usbdevice_create(devname);
2571 if (dev)
2572 goto done;
2573
a5d2f727 2574 /* the other ones */
a594cfbf
FB
2575 if (strstart(devname, "host:", &p)) {
2576 dev = usb_host_device_open(p);
6c9f886c 2577 } else if (strstart(devname, "net:", &p)) {
13cf8f21
MM
2578 QemuOpts *opts;
2579 int idx;
6c9f886c 2580
13cf8f21
MM
2581 opts = qemu_opts_parse(&qemu_net_opts, p, NULL);
2582 if (!opts) {
6c9f886c 2583 return -1;
13cf8f21
MM
2584 }
2585
2586 qemu_opt_set(opts, "type", "nic");
2587 qemu_opt_set(opts, "model", "usb");
2588
f6b134ac 2589 idx = net_client_init(NULL, opts, 0);
13cf8f21
MM
2590 if (idx == -1) {
2591 return -1;
2592 }
2593
2594 dev = usb_net_init(&nd_table[idx]);
dc72ac14
AZ
2595 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2596 dev = usb_bt_init(devname[2] ? hci_init(p) :
2597 bt_new_hci(qemu_find_bt_vlan(0)));
a594cfbf
FB
2598 } else {
2599 return -1;
2600 }
0d92ed30
PB
2601 if (!dev)
2602 return -1;
2603
a5d2f727 2604done:
a594cfbf
FB
2605 return 0;
2606}
2607
1f3870ab
AL
2608static int usb_device_del(const char *devname)
2609{
2610 int bus_num, addr;
2611 const char *p;
2612
5d0c5750
AL
2613 if (strstart(devname, "host:", &p))
2614 return usb_host_device_close(p);
2615
a5d2f727 2616 if (!usb_enabled)
1f3870ab
AL
2617 return -1;
2618
2619 p = strchr(devname, '.');
2620 if (!p)
2621 return -1;
2622 bus_num = strtoul(devname, NULL, 0);
2623 addr = strtoul(p + 1, NULL, 0);
2624
a5d2f727 2625 return usb_device_delete_addr(bus_num, addr);
1f3870ab
AL
2626}
2627
bd3c948d
GH
2628static int usb_parse(const char *cmdline)
2629{
2630 return usb_device_add(cmdline, 0);
2631}
2632
d54908a5 2633void do_usb_add(Monitor *mon, const QDict *qdict)
a594cfbf 2634{
d54908a5 2635 usb_device_add(qdict_get_str(qdict, "devname"), 1);
a594cfbf
FB
2636}
2637
d54908a5 2638void do_usb_del(Monitor *mon, const QDict *qdict)
a594cfbf 2639{
d54908a5 2640 usb_device_del(qdict_get_str(qdict, "devname"));
a594cfbf
FB
2641}
2642
201a51fc
AZ
2643/***********************************************************/
2644/* PCMCIA/Cardbus */
2645
2646static struct pcmcia_socket_entry_s {
bc24a225 2647 PCMCIASocket *socket;
201a51fc
AZ
2648 struct pcmcia_socket_entry_s *next;
2649} *pcmcia_sockets = 0;
2650
bc24a225 2651void pcmcia_socket_register(PCMCIASocket *socket)
201a51fc
AZ
2652{
2653 struct pcmcia_socket_entry_s *entry;
2654
2655 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2656 entry->socket = socket;
2657 entry->next = pcmcia_sockets;
2658 pcmcia_sockets = entry;
2659}
2660
bc24a225 2661void pcmcia_socket_unregister(PCMCIASocket *socket)
201a51fc
AZ
2662{
2663 struct pcmcia_socket_entry_s *entry, **ptr;
2664
2665 ptr = &pcmcia_sockets;
2666 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2667 if (entry->socket == socket) {
2668 *ptr = entry->next;
2669 qemu_free(entry);
2670 }
2671}
2672
376253ec 2673void pcmcia_info(Monitor *mon)
201a51fc
AZ
2674{
2675 struct pcmcia_socket_entry_s *iter;
376253ec 2676
201a51fc 2677 if (!pcmcia_sockets)
376253ec 2678 monitor_printf(mon, "No PCMCIA sockets\n");
201a51fc
AZ
2679
2680 for (iter = pcmcia_sockets; iter; iter = iter->next)
376253ec
AL
2681 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2682 iter->socket->attached ? iter->socket->card_string :
2683 "Empty");
201a51fc
AZ
2684}
2685
2ff89790 2686/***********************************************************/
3023f332
AL
2687/* register display */
2688
7b5d76da
AL
2689struct DisplayAllocator default_allocator = {
2690 defaultallocator_create_displaysurface,
2691 defaultallocator_resize_displaysurface,
2692 defaultallocator_free_displaysurface
2693};
2694
3023f332
AL
2695void register_displaystate(DisplayState *ds)
2696{
2697 DisplayState **s;
2698 s = &display_state;
2699 while (*s != NULL)
2700 s = &(*s)->next;
2701 ds->next = NULL;
2702 *s = ds;
2703}
2704
2705DisplayState *get_displaystate(void)
2706{
2707 return display_state;
2708}
2709
7b5d76da
AL
2710DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2711{
2712 if(ds->allocator == &default_allocator) ds->allocator = da;
2713 return ds->allocator;
2714}
2715
2ff89790
TS
2716/* dumb display */
2717
8f391ab4 2718static void dumb_display_init(void)
2ff89790 2719{
8f391ab4 2720 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
7b5d76da
AL
2721 ds->allocator = &default_allocator;
2722 ds->surface = qemu_create_displaysurface(ds, 640, 480);
8f391ab4 2723 register_displaystate(ds);
2ff89790
TS
2724}
2725
8a7ddc38
FB
2726/***********************************************************/
2727/* I/O handling */
0824d6fc 2728
c4b1fcc0
FB
2729typedef struct IOHandlerRecord {
2730 int fd;
7c9d8e07
FB
2731 IOCanRWHandler *fd_read_poll;
2732 IOHandler *fd_read;
2733 IOHandler *fd_write;
cafffd40 2734 int deleted;
c4b1fcc0
FB
2735 void *opaque;
2736 /* temporary data */
2737 struct pollfd *ufd;
8a7ddc38 2738 struct IOHandlerRecord *next;
c4b1fcc0
FB
2739} IOHandlerRecord;
2740
8a7ddc38 2741static IOHandlerRecord *first_io_handler;
c4b1fcc0 2742
7c9d8e07
FB
2743/* XXX: fd_read_poll should be suppressed, but an API change is
2744 necessary in the character devices to suppress fd_can_read(). */
5fafdf24
TS
2745int qemu_set_fd_handler2(int fd,
2746 IOCanRWHandler *fd_read_poll,
2747 IOHandler *fd_read,
2748 IOHandler *fd_write,
7c9d8e07 2749 void *opaque)
c4b1fcc0 2750{
7c9d8e07 2751 IOHandlerRecord **pioh, *ioh;
c4b1fcc0 2752
7c9d8e07
FB
2753 if (!fd_read && !fd_write) {
2754 pioh = &first_io_handler;
2755 for(;;) {
2756 ioh = *pioh;
2757 if (ioh == NULL)
2758 break;
2759 if (ioh->fd == fd) {
cafffd40 2760 ioh->deleted = 1;
7c9d8e07
FB
2761 break;
2762 }
2763 pioh = &ioh->next;
2764 }
2765 } else {
2766 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2767 if (ioh->fd == fd)
2768 goto found;
2769 }
2770 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
7c9d8e07
FB
2771 ioh->next = first_io_handler;
2772 first_io_handler = ioh;
2773 found:
2774 ioh->fd = fd;
2775 ioh->fd_read_poll = fd_read_poll;
2776 ioh->fd_read = fd_read;
2777 ioh->fd_write = fd_write;
2778 ioh->opaque = opaque;
cafffd40 2779 ioh->deleted = 0;
7c9d8e07 2780 }
c4b1fcc0
FB
2781 return 0;
2782}
2783
5fafdf24
TS
2784int qemu_set_fd_handler(int fd,
2785 IOHandler *fd_read,
2786 IOHandler *fd_write,
7c9d8e07 2787 void *opaque)
8a7ddc38 2788{
7c9d8e07 2789 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
8a7ddc38
FB
2790}
2791
56f3a5d0 2792#ifdef _WIN32
f331110f
FB
2793/***********************************************************/
2794/* Polling handling */
2795
2796typedef struct PollingEntry {
2797 PollingFunc *func;
2798 void *opaque;
2799 struct PollingEntry *next;
2800} PollingEntry;
2801
2802static PollingEntry *first_polling_entry;
2803
2804int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2805{
2806 PollingEntry **ppe, *pe;
2807 pe = qemu_mallocz(sizeof(PollingEntry));
f331110f
FB
2808 pe->func = func;
2809 pe->opaque = opaque;
2810 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2811 *ppe = pe;
2812 return 0;
2813}
2814
2815void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2816{
2817 PollingEntry **ppe, *pe;
2818 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2819 pe = *ppe;
2820 if (pe->func == func && pe->opaque == opaque) {
2821 *ppe = pe->next;
2822 qemu_free(pe);
2823 break;
2824 }
2825 }
2826}
2827
a18e524a
FB
2828/***********************************************************/
2829/* Wait objects support */
2830typedef struct WaitObjects {
2831 int num;
2832 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2833 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2834 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2835} WaitObjects;
2836
2837static WaitObjects wait_objects = {0};
3b46e624 2838
a18e524a
FB
2839int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2840{
2841 WaitObjects *w = &wait_objects;
2842
2843 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2844 return -1;
2845 w->events[w->num] = handle;
2846 w->func[w->num] = func;
2847 w->opaque[w->num] = opaque;
2848 w->num++;
2849 return 0;
2850}
2851
2852void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2853{
2854 int i, found;
2855 WaitObjects *w = &wait_objects;
2856
2857 found = 0;
2858 for (i = 0; i < w->num; i++) {
2859 if (w->events[i] == handle)
2860 found = 1;
2861 if (found) {
2862 w->events[i] = w->events[i + 1];
2863 w->func[i] = w->func[i + 1];
2864 w->opaque[i] = w->opaque[i + 1];
3b46e624 2865 }
a18e524a
FB
2866 }
2867 if (found)
2868 w->num--;
2869}
2870#endif
2871
8a7ddc38
FB
2872/***********************************************************/
2873/* ram save/restore */
2874
94fb0909 2875#define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
475e4277
AL
2876#define RAM_SAVE_FLAG_COMPRESS 0x02
2877#define RAM_SAVE_FLAG_MEM_SIZE 0x04
2878#define RAM_SAVE_FLAG_PAGE 0x08
2879#define RAM_SAVE_FLAG_EOS 0x10
2880
2881static int is_dup_page(uint8_t *page, uint8_t ch)
8a7ddc38 2882{
475e4277
AL
2883 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2884 uint32_t *array = (uint32_t *)page;
2885 int i;
3b46e624 2886
475e4277
AL
2887 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2888 if (array[i] != val)
2889 return 0;
2890 }
2891
2892 return 1;
2893}
2894
2895static int ram_save_block(QEMUFile *f)
2896{
c227f099
AL
2897 static ram_addr_t current_addr = 0;
2898 ram_addr_t saved_addr = current_addr;
2899 ram_addr_t addr = 0;
475e4277
AL
2900 int found = 0;
2901
94a6b54f 2902 while (addr < last_ram_offset) {
475e4277 2903 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
5579c7f3 2904 uint8_t *p;
475e4277
AL
2905
2906 cpu_physical_memory_reset_dirty(current_addr,
2907 current_addr + TARGET_PAGE_SIZE,
2908 MIGRATION_DIRTY_FLAG);
2909
5579c7f3 2910 p = qemu_get_ram_ptr(current_addr);
475e4277 2911
5579c7f3 2912 if (is_dup_page(p, *p)) {
475e4277 2913 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
5579c7f3 2914 qemu_put_byte(f, *p);
475e4277
AL
2915 } else {
2916 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
5579c7f3 2917 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
c88676f8 2918 }
475e4277
AL
2919
2920 found = 1;
2921 break;
c88676f8 2922 }
475e4277 2923 addr += TARGET_PAGE_SIZE;
94a6b54f 2924 current_addr = (saved_addr + addr) % last_ram_offset;
8a7ddc38 2925 }
475e4277
AL
2926
2927 return found;
8a7ddc38
FB
2928}
2929
84307938 2930static uint64_t bytes_transferred;
475e4277 2931
c227f099 2932static ram_addr_t ram_save_remaining(void)
475e4277 2933{
c227f099
AL
2934 ram_addr_t addr;
2935 ram_addr_t count = 0;
475e4277 2936
94a6b54f 2937 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
475e4277
AL
2938 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2939 count++;
2940 }
2941
2942 return count;
2943}
2944
9f9e28cd
GC
2945uint64_t ram_bytes_remaining(void)
2946{
2947 return ram_save_remaining() * TARGET_PAGE_SIZE;
2948}
2949
2950uint64_t ram_bytes_transferred(void)
2951{
2952 return bytes_transferred;
2953}
2954
2955uint64_t ram_bytes_total(void)
2956{
2957 return last_ram_offset;
2958}
2959
f327aa0c 2960static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
475e4277 2961{
c227f099 2962 ram_addr_t addr;
a0a3fd60
GC
2963 uint64_t bytes_transferred_last;
2964 double bwidth = 0;
2965 uint64_t expected_time = 0;
475e4277 2966
4ec7fcc7
JK
2967 if (stage < 0) {
2968 cpu_physical_memory_set_dirty_tracking(0);
2969 return 0;
2970 }
2971
9fa06385 2972 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
b0a46a33
JK
2973 qemu_file_set_error(f);
2974 return 0;
2975 }
2976
475e4277 2977 if (stage == 1) {
84307938
JK
2978 bytes_transferred = 0;
2979
475e4277 2980 /* Make sure all dirty bits are set */
94a6b54f 2981 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
475e4277
AL
2982 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2983 cpu_physical_memory_set_dirty(addr);
2984 }
b0a46a33 2985
475e4277
AL
2986 /* Enable dirty memory tracking */
2987 cpu_physical_memory_set_dirty_tracking(1);
2988
94a6b54f 2989 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
475e4277
AL
2990 }
2991
a0a3fd60
GC
2992 bytes_transferred_last = bytes_transferred;
2993 bwidth = get_clock();
2994
475e4277
AL
2995 while (!qemu_file_rate_limit(f)) {
2996 int ret;
2997
2998 ret = ram_save_block(f);
9f9e28cd 2999 bytes_transferred += ret * TARGET_PAGE_SIZE;
475e4277
AL
3000 if (ret == 0) /* no more blocks */
3001 break;
3002 }
3003
a0a3fd60
GC
3004 bwidth = get_clock() - bwidth;
3005 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3006
3007 /* if we haven't transferred anything this round, force expected_time to a
3008 * a very high value, but without crashing */
3009 if (bwidth == 0)
3010 bwidth = 0.000001;
3011
475e4277 3012 /* try transferring iterative blocks of memory */
475e4277 3013 if (stage == 3) {
475e4277 3014 /* flush all remaining blocks regardless of rate limiting */
9f9e28cd
GC
3015 while (ram_save_block(f) != 0) {
3016 bytes_transferred += TARGET_PAGE_SIZE;
3017 }
8215e914 3018 cpu_physical_memory_set_dirty_tracking(0);
475e4277
AL
3019 }
3020
3021 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3022
a0a3fd60
GC
3023 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3024
3025 return (stage == 2) && (expected_time <= migrate_max_downtime());
475e4277
AL
3026}
3027
475e4277
AL
3028static int ram_load(QEMUFile *f, void *opaque, int version_id)
3029{
c227f099 3030 ram_addr_t addr;
475e4277
AL
3031 int flags;
3032
475e4277
AL
3033 if (version_id != 3)
3034 return -EINVAL;
3035
3036 do {
3037 addr = qemu_get_be64(f);
3038
3039 flags = addr & ~TARGET_PAGE_MASK;
3040 addr &= TARGET_PAGE_MASK;
3041
3042 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
94a6b54f 3043 if (addr != last_ram_offset)
475e4277
AL
3044 return -EINVAL;
3045 }
3046
475e4277
AL
3047 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3048 uint8_t ch = qemu_get_byte(f);
779c6bef
AL
3049 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3050#ifndef _WIN32
30868442
AL
3051 if (ch == 0 &&
3052 (!kvm_enabled() || kvm_has_sync_mmu())) {
3053 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
779c6bef 3054 }
30868442 3055#endif
9a743e5b 3056 } else if (flags & RAM_SAVE_FLAG_PAGE) {
5579c7f3 3057 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
9a743e5b
JK
3058 }
3059 if (qemu_file_has_error(f)) {
3060 return -EIO;
3061 }
475e4277
AL
3062 } while (!(flags & RAM_SAVE_FLAG_EOS));
3063
8a7ddc38
FB
3064 return 0;
3065}
3066
9e472e10
AL
3067void qemu_service_io(void)
3068{
d9f75a4e 3069 qemu_notify_event();
9e472e10
AL
3070}
3071
cc1daa40
FB
3072/***********************************************************/
3073/* machine registration */
3074
bdaf78e0 3075static QEMUMachine *first_machine = NULL;
6f338c34 3076QEMUMachine *current_machine = NULL;
cc1daa40
FB
3077
3078int qemu_register_machine(QEMUMachine *m)
3079{
3080 QEMUMachine **pm;
3081 pm = &first_machine;
3082 while (*pm != NULL)
3083 pm = &(*pm)->next;
3084 m->next = NULL;
3085 *pm = m;
3086 return 0;
3087}
3088
9596ebb7 3089static QEMUMachine *find_machine(const char *name)
cc1daa40
FB
3090{
3091 QEMUMachine *m;
3092
3093 for(m = first_machine; m != NULL; m = m->next) {
3094 if (!strcmp(m->name, name))
3095 return m;
3f6599e6
MM
3096 if (m->alias && !strcmp(m->alias, name))
3097 return m;
cc1daa40
FB
3098 }
3099 return NULL;
3100}
3101
0c257437
AL
3102static QEMUMachine *find_default_machine(void)
3103{
3104 QEMUMachine *m;
3105
3106 for(m = first_machine; m != NULL; m = m->next) {
3107 if (m->is_default) {
3108 return m;
3109 }
3110 }
3111 return NULL;
3112}
3113
8a7ddc38
FB
3114/***********************************************************/
3115/* main execution loop */
3116
9596ebb7 3117static void gui_update(void *opaque)
8a7ddc38 3118{
7d957bd8 3119 uint64_t interval = GUI_REFRESH_INTERVAL;
740733bb 3120 DisplayState *ds = opaque;
7d957bd8
AL
3121 DisplayChangeListener *dcl = ds->listeners;
3122
3123 dpy_refresh(ds);
3124
3125 while (dcl != NULL) {
3126 if (dcl->gui_timer_interval &&
3127 dcl->gui_timer_interval < interval)
3128 interval = dcl->gui_timer_interval;
3129 dcl = dcl->next;
3130 }
3131 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
8a7ddc38
FB
3132}
3133
9043b62d
BS
3134static void nographic_update(void *opaque)
3135{
3136 uint64_t interval = GUI_REFRESH_INTERVAL;
3137
3138 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3139}
3140
0bd48850
FB
3141struct vm_change_state_entry {
3142 VMChangeStateHandler *cb;
3143 void *opaque;
72cf2d4f 3144 QLIST_ENTRY (vm_change_state_entry) entries;
0bd48850
FB
3145};
3146
72cf2d4f 3147static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
0bd48850
FB
3148
3149VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3150 void *opaque)
3151{
3152 VMChangeStateEntry *e;
3153
3154 e = qemu_mallocz(sizeof (*e));
0bd48850
FB
3155
3156 e->cb = cb;
3157 e->opaque = opaque;
72cf2d4f 3158 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
0bd48850
FB
3159 return e;
3160}
3161
3162void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3163{
72cf2d4f 3164 QLIST_REMOVE (e, entries);
0bd48850
FB
3165 qemu_free (e);
3166}
3167
9781e040 3168static void vm_state_notify(int running, int reason)
0bd48850
FB
3169{
3170 VMChangeStateEntry *e;
3171
3172 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
9781e040 3173 e->cb(e->opaque, running, reason);
0bd48850
FB
3174 }
3175}
3176
d6dc3d42
AL
3177static void resume_all_vcpus(void);
3178static void pause_all_vcpus(void);
3179
8a7ddc38
FB
3180void vm_start(void)
3181{
3182 if (!vm_running) {
3183 cpu_enable_ticks();
3184 vm_running = 1;
9781e040 3185 vm_state_notify(1, 0);
efe75411 3186 qemu_rearm_alarm_timer(alarm_timer);
d6dc3d42 3187 resume_all_vcpus();
8a7ddc38
FB
3188 }
3189}
3190
bb0c6722
FB
3191/* reset/shutdown handler */
3192
3193typedef struct QEMUResetEntry {
72cf2d4f 3194 QTAILQ_ENTRY(QEMUResetEntry) entry;
bb0c6722
FB
3195 QEMUResetHandler *func;
3196 void *opaque;
bb0c6722
FB
3197} QEMUResetEntry;
3198
72cf2d4f
BS
3199static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3200 QTAILQ_HEAD_INITIALIZER(reset_handlers);
bb0c6722
FB
3201static int reset_requested;
3202static int shutdown_requested;
3475187d 3203static int powerdown_requested;
e568902a 3204static int debug_requested;
6e29f5da 3205static int vmstop_requested;
bb0c6722 3206
cf7a2fe2
AJ
3207int qemu_shutdown_requested(void)
3208{
3209 int r = shutdown_requested;
3210 shutdown_requested = 0;
3211 return r;
3212}
3213
3214int qemu_reset_requested(void)
3215{
3216 int r = reset_requested;
3217 reset_requested = 0;
3218 return r;
3219}
3220
3221int qemu_powerdown_requested(void)
3222{
3223 int r = powerdown_requested;
3224 powerdown_requested = 0;
3225 return r;
3226}
3227
e568902a
AL
3228static int qemu_debug_requested(void)
3229{
3230 int r = debug_requested;
3231 debug_requested = 0;
3232 return r;
3233}
3234
6e29f5da
AL
3235static int qemu_vmstop_requested(void)
3236{
3237 int r = vmstop_requested;
3238 vmstop_requested = 0;
3239 return r;
3240}
3241
3242static void do_vm_stop(int reason)
3243{
3244 if (vm_running) {
3245 cpu_disable_ticks();
3246 vm_running = 0;
d6dc3d42 3247 pause_all_vcpus();
6e29f5da
AL
3248 vm_state_notify(0, reason);
3249 }
3250}
3251
a08d4367 3252void qemu_register_reset(QEMUResetHandler *func, void *opaque)
bb0c6722 3253{
55ddfe8e 3254 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
bb0c6722 3255
bb0c6722
FB
3256 re->func = func;
3257 re->opaque = opaque;
72cf2d4f 3258 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
bb0c6722
FB
3259}
3260
dda9b29f 3261void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
bb0c6722
FB
3262{
3263 QEMUResetEntry *re;
3264
72cf2d4f 3265 QTAILQ_FOREACH(re, &reset_handlers, entry) {
dda9b29f 3266 if (re->func == func && re->opaque == opaque) {
72cf2d4f 3267 QTAILQ_REMOVE(&reset_handlers, re, entry);
dda9b29f
JK
3268 qemu_free(re);
3269 return;
3270 }
3271 }
3272}
3273
3274void qemu_system_reset(void)
3275{
3276 QEMUResetEntry *re, *nre;
3277
3278 /* reset all devices */
72cf2d4f 3279 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
bb0c6722
FB
3280 re->func(re->opaque);
3281 }
3282}
3283
3284void qemu_system_reset_request(void)
3285{
d1beab82
FB
3286 if (no_reboot) {
3287 shutdown_requested = 1;
3288 } else {
3289 reset_requested = 1;
3290 }
d9f75a4e 3291 qemu_notify_event();
bb0c6722
FB
3292}
3293
3294void qemu_system_shutdown_request(void)
3295{
3296 shutdown_requested = 1;
d9f75a4e 3297 qemu_notify_event();
bb0c6722
FB
3298}
3299
3475187d
FB
3300void qemu_system_powerdown_request(void)
3301{
3302 powerdown_requested = 1;
d9f75a4e
AL
3303 qemu_notify_event();
3304}
3305
d6dc3d42
AL
3306#ifdef CONFIG_IOTHREAD
3307static void qemu_system_vmstop_request(int reason)
d9f75a4e 3308{
d6dc3d42
AL
3309 vmstop_requested = reason;
3310 qemu_notify_event();
bb0c6722 3311}
d6dc3d42 3312#endif
bb0c6722 3313
50317c7f
AL
3314#ifndef _WIN32
3315static int io_thread_fd = -1;
3316
3317static void qemu_event_increment(void)
3fcf7b6b 3318{
50317c7f
AL
3319 static const char byte = 0;
3320
3321 if (io_thread_fd == -1)
3322 return;
3323
3324 write(io_thread_fd, &byte, sizeof(byte));
3325}
3326
3327static void qemu_event_read(void *opaque)
3328{
3329 int fd = (unsigned long)opaque;
3330 ssize_t len;
3331
3332 /* Drain the notify pipe */
3333 do {
3334 char buffer[512];
3335 len = read(fd, buffer, sizeof(buffer));
3336 } while ((len == -1 && errno == EINTR) || len > 0);
3337}
3338
3339static int qemu_event_init(void)
3340{
3341 int err;
3342 int fds[2];
3343
40ff6d7e 3344 err = qemu_pipe(fds);
50317c7f
AL
3345 if (err == -1)
3346 return -errno;
3347
3348 err = fcntl_setfl(fds[0], O_NONBLOCK);
3349 if (err < 0)
3350 goto fail;
3351
3352 err = fcntl_setfl(fds[1], O_NONBLOCK);
3353 if (err < 0)
3354 goto fail;
3355
3356 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3357 (void *)(unsigned long)fds[0]);
3358
3359 io_thread_fd = fds[1];
a7e21219
JK
3360 return 0;
3361
50317c7f
AL
3362fail:
3363 close(fds[0]);
3364 close(fds[1]);
3365 return err;
3366}
3367#else
3368HANDLE qemu_event_handle;
3369
3370static void dummy_event_handler(void *opaque)
3371{
3372}
3373
3374static int qemu_event_init(void)
3375{
3376 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3377 if (!qemu_event_handle) {
20889d4e 3378 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
50317c7f
AL
3379 return -1;
3380 }
3381 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3fcf7b6b
AL
3382 return 0;
3383}
3384
50317c7f
AL
3385static void qemu_event_increment(void)
3386{
de1c90cf 3387 if (!SetEvent(qemu_event_handle)) {
20889d4e 3388 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
de1c90cf 3389 GetLastError());
3390 exit (1);
3391 }
50317c7f
AL
3392}
3393#endif
3394
d6dc3d42
AL
3395static int cpu_can_run(CPUState *env)
3396{
3397 if (env->stop)
3398 return 0;
3399 if (env->stopped)
3400 return 0;
3401 return 1;
3402}
3403
3404#ifndef CONFIG_IOTHREAD
50317c7f
AL
3405static int qemu_init_main_loop(void)
3406{
3407 return qemu_event_init();
3408}
3409
0bf46a40
AL
3410void qemu_init_vcpu(void *_env)
3411{
3412 CPUState *env = _env;
3413
3414 if (kvm_enabled())
3415 kvm_init_vcpu(env);
dc6b1c09
AP
3416 env->nr_cores = smp_cores;
3417 env->nr_threads = smp_threads;
0bf46a40
AL
3418 return;
3419}
3420
8edac960
AL
3421int qemu_cpu_self(void *env)
3422{
3423 return 1;
3424}
3425
d6dc3d42
AL
3426static void resume_all_vcpus(void)
3427{
3428}
3429
3430static void pause_all_vcpus(void)
3431{
3432}
3433
8edac960
AL
3434void qemu_cpu_kick(void *env)
3435{
3436 return;
3437}
3438
d6dc3d42
AL
3439void qemu_notify_event(void)
3440{
3441 CPUState *env = cpu_single_env;
3442
3443 if (env) {
3444 cpu_exit(env);
4a1418e0 3445 }
d6dc3d42
AL
3446}
3447
d549db5a
GC
3448void qemu_mutex_lock_iothread(void) {}
3449void qemu_mutex_unlock_iothread(void) {}
4870852c 3450
6e29f5da
AL
3451void vm_stop(int reason)
3452{
3453 do_vm_stop(reason);
3454}
3455
d6dc3d42
AL
3456#else /* CONFIG_IOTHREAD */
3457
3458#include "qemu-thread.h"
3459
3460QemuMutex qemu_global_mutex;
3461static QemuMutex qemu_fair_mutex;
3462
3463static QemuThread io_thread;
3464
3465static QemuThread *tcg_cpu_thread;
3466static QemuCond *tcg_halt_cond;
3467
3468static int qemu_system_ready;
3469/* cpu creation */
3470static QemuCond qemu_cpu_cond;
3471/* system init */
3472static QemuCond qemu_system_cond;
3473static QemuCond qemu_pause_cond;
3474
3475static void block_io_signals(void);
3476static void unblock_io_signals(void);
3477static int tcg_has_work(void);
3478
3479static int qemu_init_main_loop(void)
3480{
3481 int ret;
3482
3483 ret = qemu_event_init();
3484 if (ret)
3485 return ret;
3486
3487 qemu_cond_init(&qemu_pause_cond);
3488 qemu_mutex_init(&qemu_fair_mutex);
3489 qemu_mutex_init(&qemu_global_mutex);
3490 qemu_mutex_lock(&qemu_global_mutex);
3491
3492 unblock_io_signals();
3493 qemu_thread_self(&io_thread);
3494
3495 return 0;
3496}
3497
3498static void qemu_wait_io_event(CPUState *env)
3499{
3500 while (!tcg_has_work())
3501 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3502
3503 qemu_mutex_unlock(&qemu_global_mutex);
3504
3505 /*
3506 * Users of qemu_global_mutex can be starved, having no chance
3507 * to acquire it since this path will get to it first.
3508 * So use another lock to provide fairness.
3509 */
3510 qemu_mutex_lock(&qemu_fair_mutex);
3511 qemu_mutex_unlock(&qemu_fair_mutex);
3512
3513 qemu_mutex_lock(&qemu_global_mutex);
3514 if (env->stop) {
3515 env->stop = 0;
3516 env->stopped = 1;
3517 qemu_cond_signal(&qemu_pause_cond);
3518 }
3519}
3520
3521static int qemu_cpu_exec(CPUState *env);
3522
3523static void *kvm_cpu_thread_fn(void *arg)
3524{
3525 CPUState *env = arg;
3526
3527 block_io_signals();
3528 qemu_thread_self(env->thread);
321c1cb1
JCD
3529 if (kvm_enabled())
3530 kvm_init_vcpu(env);
d6dc3d42
AL
3531
3532 /* signal CPU creation */
3533 qemu_mutex_lock(&qemu_global_mutex);
3534 env->created = 1;
3535 qemu_cond_signal(&qemu_cpu_cond);
3536
3537 /* and wait for machine initialization */
3538 while (!qemu_system_ready)
3539 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3540
3541 while (1) {
3542 if (cpu_can_run(env))
3543 qemu_cpu_exec(env);
1c3173b9 3544 qemu_wait_io_event(env);
d6dc3d42
AL
3545 }
3546
3547 return NULL;
3548}
3549
3550static void tcg_cpu_exec(void);
3551
3552static void *tcg_cpu_thread_fn(void *arg)
3553{
3554 CPUState *env = arg;
3555
3556 block_io_signals();
3557 qemu_thread_self(env->thread);
3558
3559 /* signal CPU creation */
3560 qemu_mutex_lock(&qemu_global_mutex);
3561 for (env = first_cpu; env != NULL; env = env->next_cpu)
3562 env->created = 1;
3563 qemu_cond_signal(&qemu_cpu_cond);
3564
3565 /* and wait for machine initialization */
3566 while (!qemu_system_ready)
3567 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3568
3569 while (1) {
3570 tcg_cpu_exec();
3571 qemu_wait_io_event(cur_cpu);
3572 }
3573
3574 return NULL;
3575}
3576
3577void qemu_cpu_kick(void *_env)
3578{
3579 CPUState *env = _env;
3580 qemu_cond_broadcast(env->halt_cond);
3581 if (kvm_enabled())
3582 qemu_thread_signal(env->thread, SIGUSR1);
3583}
3584
e5bc201d 3585int qemu_cpu_self(void *_env)
d6dc3d42 3586{
e5bc201d
GC
3587 CPUState *env = _env;
3588 QemuThread this;
3589
3590 qemu_thread_self(&this);
3591
3592 return qemu_thread_equal(&this, env->thread);
d6dc3d42
AL
3593}
3594
3595static void cpu_signal(int sig)
3596{
3597 if (cpu_single_env)
3598 cpu_exit(cpu_single_env);
3599}
3600
3601static void block_io_signals(void)
3602{
3603 sigset_t set;
3604 struct sigaction sigact;
3605
3606 sigemptyset(&set);
3607 sigaddset(&set, SIGUSR2);
3608 sigaddset(&set, SIGIO);
3609 sigaddset(&set, SIGALRM);
3610 pthread_sigmask(SIG_BLOCK, &set, NULL);
3611
3612 sigemptyset(&set);
3613 sigaddset(&set, SIGUSR1);
3614 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3615
3616 memset(&sigact, 0, sizeof(sigact));
3617 sigact.sa_handler = cpu_signal;
3618 sigaction(SIGUSR1, &sigact, NULL);
3619}
3620
3621static void unblock_io_signals(void)
3622{
3623 sigset_t set;
3624
3625 sigemptyset(&set);
3626 sigaddset(&set, SIGUSR2);
3627 sigaddset(&set, SIGIO);
3628 sigaddset(&set, SIGALRM);
3629 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3630
3631 sigemptyset(&set);
3632 sigaddset(&set, SIGUSR1);
3633 pthread_sigmask(SIG_BLOCK, &set, NULL);
3634}
3635
3636static void qemu_signal_lock(unsigned int msecs)
3637{
3638 qemu_mutex_lock(&qemu_fair_mutex);
3639
3640 while (qemu_mutex_trylock(&qemu_global_mutex)) {
3641 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3642 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3643 break;
3644 }
3645 qemu_mutex_unlock(&qemu_fair_mutex);
3646}
3647
d549db5a 3648void qemu_mutex_lock_iothread(void)
d6dc3d42
AL
3649{
3650 if (kvm_enabled()) {
3651 qemu_mutex_lock(&qemu_fair_mutex);
3652 qemu_mutex_lock(&qemu_global_mutex);
3653 qemu_mutex_unlock(&qemu_fair_mutex);
3654 } else
3655 qemu_signal_lock(100);
3656}
3657
d549db5a 3658void qemu_mutex_unlock_iothread(void)
d6dc3d42
AL
3659{
3660 qemu_mutex_unlock(&qemu_global_mutex);
3661}
3662
3663static int all_vcpus_paused(void)
3664{
3665 CPUState *penv = first_cpu;
3666
3667 while (penv) {
3668 if (!penv->stopped)
3669 return 0;
3670 penv = (CPUState *)penv->next_cpu;
3671 }
3672
3673 return 1;
3674}
3675
3676static void pause_all_vcpus(void)
3677{
3678 CPUState *penv = first_cpu;
3679
3680 while (penv) {
3681 penv->stop = 1;
3682 qemu_thread_signal(penv->thread, SIGUSR1);
3683 qemu_cpu_kick(penv);
3684 penv = (CPUState *)penv->next_cpu;
3685 }
3686
3687 while (!all_vcpus_paused()) {
3688 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3689 penv = first_cpu;
3690 while (penv) {
3691 qemu_thread_signal(penv->thread, SIGUSR1);
3692 penv = (CPUState *)penv->next_cpu;
3693 }
3694 }
3695}
3696
3697static void resume_all_vcpus(void)
3698{
3699 CPUState *penv = first_cpu;
3700
3701 while (penv) {
3702 penv->stop = 0;
3703 penv->stopped = 0;
3704 qemu_thread_signal(penv->thread, SIGUSR1);
3705 qemu_cpu_kick(penv);
3706 penv = (CPUState *)penv->next_cpu;
3707 }
3708}
3709
3710static void tcg_init_vcpu(void *_env)
3711{
3712 CPUState *env = _env;
3713 /* share a single thread for all cpus with TCG */
3714 if (!tcg_cpu_thread) {
3715 env->thread = qemu_mallocz(sizeof(QemuThread));
3716 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3717 qemu_cond_init(env->halt_cond);
3718 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3719 while (env->created == 0)
3720 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3721 tcg_cpu_thread = env->thread;
3722 tcg_halt_cond = env->halt_cond;
3723 } else {
3724 env->thread = tcg_cpu_thread;
3725 env->halt_cond = tcg_halt_cond;
3726 }
3727}
3728
3729static void kvm_start_vcpu(CPUState *env)
3730{
d6dc3d42
AL
3731 env->thread = qemu_mallocz(sizeof(QemuThread));
3732 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3733 qemu_cond_init(env->halt_cond);
3734 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3735 while (env->created == 0)
3736 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3737}
3738
3739void qemu_init_vcpu(void *_env)
3740{
3741 CPUState *env = _env;
3742
3743 if (kvm_enabled())
3744 kvm_start_vcpu(env);
3745 else
3746 tcg_init_vcpu(env);
dc6b1c09
AP
3747 env->nr_cores = smp_cores;
3748 env->nr_threads = smp_threads;
d6dc3d42
AL
3749}
3750
3751void qemu_notify_event(void)
3752{
3753 qemu_event_increment();
3754}
3755
3756void vm_stop(int reason)
3757{
3758 QemuThread me;
3759 qemu_thread_self(&me);
3760
3761 if (!qemu_thread_equal(&me, &io_thread)) {
3762 qemu_system_vmstop_request(reason);
3763 /*
3764 * FIXME: should not return to device code in case
3765 * vm_stop() has been requested.
3766 */
3767 if (cpu_single_env) {
3768 cpu_exit(cpu_single_env);
3769 cpu_single_env->stop = 1;
3770 }
3771 return;
3772 }
3773 do_vm_stop(reason);
3774}
3775
3776#endif
3777
3778
877cf882 3779#ifdef _WIN32
69d6451c 3780static void host_main_loop_wait(int *timeout)
56f3a5d0
AL
3781{
3782 int ret, ret2, i;
f331110f
FB
3783 PollingEntry *pe;
3784
c4b1fcc0 3785
f331110f
FB
3786 /* XXX: need to suppress polling by better using win32 events */
3787 ret = 0;
3788 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3789 ret |= pe->func(pe->opaque);
3790 }
e6b1e558 3791 if (ret == 0) {
a18e524a
FB
3792 int err;
3793 WaitObjects *w = &wait_objects;
3b46e624 3794
56f3a5d0 3795 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
a18e524a
FB
3796 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3797 if (w->func[ret - WAIT_OBJECT_0])
3798 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3b46e624 3799
5fafdf24 3800 /* Check for additional signaled events */
e6b1e558 3801 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3b46e624 3802
e6b1e558
TS
3803 /* Check if event is signaled */
3804 ret2 = WaitForSingleObject(w->events[i], 0);
3805 if(ret2 == WAIT_OBJECT_0) {
3806 if (w->func[i])
3807 w->func[i](w->opaque[i]);
3808 } else if (ret2 == WAIT_TIMEOUT) {
3809 } else {
3810 err = GetLastError();
3811 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3b46e624
TS
3812 }
3813 }
a18e524a
FB
3814 } else if (ret == WAIT_TIMEOUT) {
3815 } else {
3816 err = GetLastError();
e6b1e558 3817 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
a18e524a 3818 }
f331110f 3819 }
56f3a5d0
AL
3820
3821 *timeout = 0;
3822}
3823#else
69d6451c 3824static void host_main_loop_wait(int *timeout)
56f3a5d0
AL
3825{
3826}
fd1dff4b 3827#endif
56f3a5d0
AL
3828
3829void main_loop_wait(int timeout)
3830{
3831 IOHandlerRecord *ioh;
3832 fd_set rfds, wfds, xfds;
3833 int ret, nfds;
3834 struct timeval tv;
3835
3836 qemu_bh_update_timeout(&timeout);
3837
3838 host_main_loop_wait(&timeout);
3839
fd1dff4b
FB
3840 /* poll any events */
3841 /* XXX: separate device handlers from system ones */
6abfbd79 3842 nfds = -1;
fd1dff4b
FB
3843 FD_ZERO(&rfds);
3844 FD_ZERO(&wfds);
e035649e 3845 FD_ZERO(&xfds);
fd1dff4b 3846 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
cafffd40
TS
3847 if (ioh->deleted)
3848 continue;
fd1dff4b
FB
3849 if (ioh->fd_read &&
3850 (!ioh->fd_read_poll ||
3851 ioh->fd_read_poll(ioh->opaque) != 0)) {
3852 FD_SET(ioh->fd, &rfds);
3853 if (ioh->fd > nfds)
3854 nfds = ioh->fd;
3855 }
3856 if (ioh->fd_write) {
3857 FD_SET(ioh->fd, &wfds);
3858 if (ioh->fd > nfds)
3859 nfds = ioh->fd;
3860 }
3861 }
3b46e624 3862
56f3a5d0
AL
3863 tv.tv_sec = timeout / 1000;
3864 tv.tv_usec = (timeout % 1000) * 1000;
3865
d918f23e
JK
3866 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3867
4870852c 3868 qemu_mutex_unlock_iothread();
e035649e 3869 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4870852c 3870 qemu_mutex_lock_iothread();
fd1dff4b 3871 if (ret > 0) {
cafffd40
TS
3872 IOHandlerRecord **pioh;
3873
3874 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6ab43fdc 3875 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
fd1dff4b 3876 ioh->fd_read(ioh->opaque);
7c9d8e07 3877 }
6ab43fdc 3878 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
fd1dff4b 3879 ioh->fd_write(ioh->opaque);
c4b1fcc0 3880 }
b4608c04 3881 }
cafffd40
TS
3882
3883 /* remove deleted IO handlers */
3884 pioh = &first_io_handler;
3885 while (*pioh) {
3886 ioh = *pioh;
3887 if (ioh->deleted) {
3888 *pioh = ioh->next;
3889 qemu_free(ioh);
5fafdf24 3890 } else
cafffd40
TS
3891 pioh = &ioh->next;
3892 }
fd1dff4b 3893 }
d918f23e
JK
3894
3895 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
b4608c04 3896
50317c7f
AL
3897 /* rearm timer, if not periodic */
3898 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3899 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3900 qemu_rearm_alarm_timer(alarm_timer);
3901 }
3902
357c692c 3903 /* vm time timers */
d6dc3d42
AL
3904 if (vm_running) {
3905 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
0fdddf80
JK
3906 qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3907 qemu_get_clock(vm_clock));
d6dc3d42 3908 }
357c692c
AL
3909
3910 /* real time timers */
0fdddf80 3911 qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
357c692c
AL
3912 qemu_get_clock(rt_clock));
3913
21d5d12b
JK
3914 qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3915 qemu_get_clock(host_clock));
3916
423f0742
PB
3917 /* Check bottom-halves last in case any of the earlier events triggered
3918 them. */
3919 qemu_bh_poll();
3b46e624 3920
5905b2e5
FB
3921}
3922
43b96858 3923static int qemu_cpu_exec(CPUState *env)
5905b2e5 3924{
43b96858 3925 int ret;
89bfc105
FB
3926#ifdef CONFIG_PROFILER
3927 int64_t ti;
3928#endif
5905b2e5 3929
89bfc105 3930#ifdef CONFIG_PROFILER
43b96858 3931 ti = profile_getclock();
89bfc105 3932#endif
43b96858
AL
3933 if (use_icount) {
3934 int64_t count;
3935 int decr;
3936 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3937 env->icount_decr.u16.low = 0;
3938 env->icount_extra = 0;
3939 count = qemu_next_deadline();
3940 count = (count + (1 << icount_time_shift) - 1)
3941 >> icount_time_shift;
3942 qemu_icount += count;
3943 decr = (count > 0xffff) ? 0xffff : count;
3944 count -= decr;
3945 env->icount_decr.u16.low = decr;
3946 env->icount_extra = count;
3947 }
3948 ret = cpu_exec(env);
89bfc105 3949#ifdef CONFIG_PROFILER
43b96858 3950 qemu_time += profile_getclock() - ti;
89bfc105 3951#endif
43b96858
AL
3952 if (use_icount) {
3953 /* Fold pending instructions back into the
3954 instruction counter, and clear the interrupt flag. */
3955 qemu_icount -= (env->icount_decr.u16.low
3956 + env->icount_extra);
3957 env->icount_decr.u32 = 0;
3958 env->icount_extra = 0;
3959 }
3960 return ret;
3961}
3962
e6e35b1e
AL
3963static void tcg_cpu_exec(void)
3964{
d6dc3d42 3965 int ret = 0;
e6e35b1e
AL
3966
3967 if (next_cpu == NULL)
3968 next_cpu = first_cpu;
3969 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3970 CPUState *env = cur_cpu = next_cpu;
3971
3972 if (!vm_running)
3973 break;
3974 if (timer_alarm_pending) {
3975 timer_alarm_pending = 0;
3976 break;
3977 }
d6dc3d42
AL
3978 if (cpu_can_run(env))
3979 ret = qemu_cpu_exec(env);
e6e35b1e
AL
3980 if (ret == EXCP_DEBUG) {
3981 gdb_set_stop_cpu(env);
3982 debug_requested = 1;
3983 break;
3984 }
3985 }
3986}
3987
43b96858
AL
3988static int cpu_has_work(CPUState *env)
3989{
d6dc3d42
AL
3990 if (env->stop)
3991 return 1;
3992 if (env->stopped)
3993 return 0;
43b96858
AL
3994 if (!env->halted)
3995 return 1;
3996 if (qemu_cpu_has_work(env))
3997 return 1;
3998 return 0;
3999}
4000
4001static int tcg_has_work(void)
4002{
4003 CPUState *env;
4004
4005 for (env = first_cpu; env != NULL; env = env->next_cpu)
4006 if (cpu_has_work(env))
4007 return 1;
4008 return 0;
4009}
4010
4011static int qemu_calculate_timeout(void)
4012{
b319820d 4013#ifndef CONFIG_IOTHREAD
43b96858
AL
4014 int timeout;
4015
4016 if (!vm_running)
4017 timeout = 5000;
4018 else if (tcg_has_work())
4019 timeout = 0;
4020 else if (!use_icount)
4021 timeout = 5000;
4022 else {
4023 /* XXX: use timeout computed from timers */
4024 int64_t add;
4025 int64_t delta;
4026 /* Advance virtual time to the next event. */
4027 if (use_icount == 1) {
4028 /* When not using an adaptive execution frequency
4029 we tend to get badly out of sync with real time,
4030 so just delay for a reasonable amount of time. */
4031 delta = 0;
4032 } else {
4033 delta = cpu_get_icount() - cpu_get_clock();
4034 }
4035 if (delta > 0) {
4036 /* If virtual time is ahead of real time then just
4037 wait for IO. */
4038 timeout = (delta / 1000000) + 1;
4039 } else {
4040 /* Wait for either IO to occur or the next
4041 timer event. */
4042 add = qemu_next_deadline();
4043 /* We advance the timer before checking for IO.
4044 Limit the amount we advance so that early IO
4045 activity won't get the guest too far ahead. */
4046 if (add > 10000000)
4047 add = 10000000;
4048 delta += add;
4049 add = (add + (1 << icount_time_shift) - 1)
4050 >> icount_time_shift;
4051 qemu_icount += add;
4052 timeout = delta / 1000000;
4053 if (timeout < 0)
4054 timeout = 0;
4055 }
4056 }
4057
4058 return timeout;
b319820d
LC
4059#else /* CONFIG_IOTHREAD */
4060 return 1000;
4061#endif
43b96858
AL
4062}
4063
4064static int vm_can_run(void)
4065{
4066 if (powerdown_requested)
4067 return 0;
4068 if (reset_requested)
4069 return 0;
4070 if (shutdown_requested)
4071 return 0;
e568902a
AL
4072 if (debug_requested)
4073 return 0;
43b96858
AL
4074 return 1;
4075}
4076
d9c32310
BS
4077qemu_irq qemu_system_powerdown;
4078
43b96858
AL
4079static void main_loop(void)
4080{
6e29f5da 4081 int r;
e6e35b1e 4082
d6dc3d42
AL
4083#ifdef CONFIG_IOTHREAD
4084 qemu_system_ready = 1;
4085 qemu_cond_broadcast(&qemu_system_cond);
4086#endif
4087
6e29f5da 4088 for (;;) {
43b96858 4089 do {
e6e35b1e
AL
4090#ifdef CONFIG_PROFILER
4091 int64_t ti;
4092#endif
d6dc3d42 4093#ifndef CONFIG_IOTHREAD
e6e35b1e 4094 tcg_cpu_exec();
d6dc3d42 4095#endif
89bfc105 4096#ifdef CONFIG_PROFILER
43b96858 4097 ti = profile_getclock();
89bfc105 4098#endif
43b96858 4099 main_loop_wait(qemu_calculate_timeout());
89bfc105 4100#ifdef CONFIG_PROFILER
43b96858 4101 dev_time += profile_getclock() - ti;
89bfc105 4102#endif
e568902a 4103 } while (vm_can_run());
43b96858 4104
b1a15e7e 4105 if (qemu_debug_requested()) {
242cd003 4106 monitor_protocol_event(QEVENT_DEBUG, NULL);
e568902a 4107 vm_stop(EXCP_DEBUG);
b1a15e7e 4108 }
43b96858 4109 if (qemu_shutdown_requested()) {
242cd003 4110 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
43b96858
AL
4111 if (no_shutdown) {
4112 vm_stop(0);
4113 no_shutdown = 0;
4114 } else
4115 break;
4116 }
d6dc3d42 4117 if (qemu_reset_requested()) {
242cd003 4118 monitor_protocol_event(QEVENT_RESET, NULL);
d6dc3d42 4119 pause_all_vcpus();
43b96858 4120 qemu_system_reset();
d6dc3d42
AL
4121 resume_all_vcpus();
4122 }
d9c32310 4123 if (qemu_powerdown_requested()) {
242cd003 4124 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
d9c32310
BS
4125 qemu_irq_raise(qemu_system_powerdown);
4126 }
b1a15e7e 4127 if ((r = qemu_vmstop_requested())) {
242cd003 4128 monitor_protocol_event(QEVENT_STOP, NULL);
6e29f5da 4129 vm_stop(r);
b1a15e7e 4130 }
b4608c04 4131 }
d6dc3d42 4132 pause_all_vcpus();
b4608c04
FB
4133}
4134
9bd7e6d9
PB
4135static void version(void)
4136{
4a19f1ec 4137 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
9bd7e6d9
PB
4138}
4139
15f82208 4140static void help(int exitcode)
0824d6fc 4141{
9bd7e6d9
PB
4142 version();
4143 printf("usage: %s [options] [disk_image]\n"
0824d6fc 4144 "\n"
a20dd508 4145 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
fc01f7e7 4146 "\n"
5824d651
BS
4147#define DEF(option, opt_arg, opt_enum, opt_help) \
4148 opt_help
4149#define DEFHEADING(text) stringify(text) "\n"
4150#include "qemu-options.h"
4151#undef DEF
4152#undef DEFHEADING
4153#undef GEN_DOCS
0824d6fc 4154 "\n"
82c643ff 4155 "During emulation, the following keys are useful:\n"
032a8c9e
FB
4156 "ctrl-alt-f toggle full screen\n"
4157 "ctrl-alt-n switch to virtual console 'n'\n"
4158 "ctrl-alt toggle mouse and keyboard grab\n"
82c643ff
FB
4159 "\n"
4160 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4161 ,
0db63474 4162 "qemu",
a00bad7e 4163 DEFAULT_RAM_SIZE,
7c9d8e07 4164#ifndef _WIN32
a00bad7e 4165 DEFAULT_NETWORK_SCRIPT,
b46a8906 4166 DEFAULT_NETWORK_DOWN_SCRIPT,
7c9d8e07 4167#endif
6e44ba7f 4168 DEFAULT_GDBSTUB_PORT,
bce61846 4169 "/tmp/qemu.log");
15f82208 4170 exit(exitcode);
0824d6fc
FB
4171}
4172
cd6f1169
FB
4173#define HAS_ARG 0x0001
4174
4175enum {
5824d651
BS
4176#define DEF(option, opt_arg, opt_enum, opt_help) \
4177 opt_enum,
4178#define DEFHEADING(text)
4179#include "qemu-options.h"
4180#undef DEF
4181#undef DEFHEADING
4182#undef GEN_DOCS
cd6f1169
FB
4183};
4184
4185typedef struct QEMUOption {
4186 const char *name;
4187 int flags;
4188 int index;
4189} QEMUOption;
4190
dbed7e40 4191static const QEMUOption qemu_options[] = {
cd6f1169 4192 { "h", 0, QEMU_OPTION_h },
5824d651
BS
4193#define DEF(option, opt_arg, opt_enum, opt_help) \
4194 { option, opt_arg, opt_enum },
4195#define DEFHEADING(text)
4196#include "qemu-options.h"
4197#undef DEF
4198#undef DEFHEADING
4199#undef GEN_DOCS
cd6f1169 4200 { NULL },
fc01f7e7
FB
4201};
4202
1d14ffa9 4203#ifdef HAS_AUDIO
6a36d84e 4204struct soundhw soundhw[] = {
b00052e4 4205#ifdef HAS_AUDIO_CHOICE
4ce7ff6e 4206#if defined(TARGET_I386) || defined(TARGET_MIPS)
fd06c375
FB
4207 {
4208 "pcspk",
4209 "PC speaker",
4210 0,
4211 1,
4212 { .init_isa = pcspk_audio_init }
4213 },
4214#endif
4c9b53e3 4215
4216#ifdef CONFIG_SB16
6a36d84e
FB
4217 {
4218 "sb16",
4219 "Creative Sound Blaster 16",
4220 0,
4221 1,
4222 { .init_isa = SB16_init }
4223 },
4c9b53e3 4224#endif
6a36d84e 4225
cc53d26d 4226#ifdef CONFIG_CS4231A
4227 {
4228 "cs4231a",
4229 "CS4231A",
4230 0,
4231 1,
4232 { .init_isa = cs4231a_init }
4233 },
4234#endif
4235
1d14ffa9 4236#ifdef CONFIG_ADLIB
6a36d84e
FB
4237 {
4238 "adlib",
1d14ffa9 4239#ifdef HAS_YMF262
6a36d84e 4240 "Yamaha YMF262 (OPL3)",
1d14ffa9 4241#else
6a36d84e 4242 "Yamaha YM3812 (OPL2)",
1d14ffa9 4243#endif
6a36d84e
FB
4244 0,
4245 1,
4246 { .init_isa = Adlib_init }
4247 },
1d14ffa9 4248#endif
6a36d84e 4249
1d14ffa9 4250#ifdef CONFIG_GUS
6a36d84e
FB
4251 {
4252 "gus",
4253 "Gravis Ultrasound GF1",
4254 0,
4255 1,
4256 { .init_isa = GUS_init }
4257 },
1d14ffa9 4258#endif
6a36d84e 4259
4c9b53e3 4260#ifdef CONFIG_AC97
e5c9a13e
AZ
4261 {
4262 "ac97",
4263 "Intel 82801AA AC97 Audio",
4264 0,
4265 0,
4266 { .init_pci = ac97_init }
4267 },
4c9b53e3 4268#endif
e5c9a13e 4269
4c9b53e3 4270#ifdef CONFIG_ES1370
6a36d84e
FB
4271 {
4272 "es1370",
4273 "ENSONIQ AudioPCI ES1370",
4274 0,
4275 0,
4276 { .init_pci = es1370_init }
4277 },
b00052e4 4278#endif
6a36d84e 4279
4c9b53e3 4280#endif /* HAS_AUDIO_CHOICE */
4281
6a36d84e
FB
4282 { NULL, NULL, 0, 0, { NULL } }
4283};
4284
4285static void select_soundhw (const char *optarg)
4286{
4287 struct soundhw *c;
4288
4289 if (*optarg == '?') {
4290 show_valid_cards:
4291
4292 printf ("Valid sound card names (comma separated):\n");
4293 for (c = soundhw; c->name; ++c) {
4294 printf ("%-11s %s\n", c->name, c->descr);
4295 }
4296 printf ("\n-soundhw all will enable all of the above\n");
1d14ffa9
FB
4297 exit (*optarg != '?');
4298 }
4299 else {
6a36d84e 4300 size_t l;
1d14ffa9
FB
4301 const char *p;
4302 char *e;
4303 int bad_card = 0;
4304
6a36d84e
FB
4305 if (!strcmp (optarg, "all")) {
4306 for (c = soundhw; c->name; ++c) {
4307 c->enabled = 1;
4308 }
4309 return;
4310 }
1d14ffa9 4311
6a36d84e 4312 p = optarg;
1d14ffa9
FB
4313 while (*p) {
4314 e = strchr (p, ',');
4315 l = !e ? strlen (p) : (size_t) (e - p);
6a36d84e
FB
4316
4317 for (c = soundhw; c->name; ++c) {
b3d6fb4a 4318 if (!strncmp (c->name, p, l) && !c->name[l]) {
6a36d84e 4319 c->enabled = 1;
1d14ffa9
FB
4320 break;
4321 }
4322 }
6a36d84e
FB
4323
4324 if (!c->name) {
1d14ffa9
FB
4325 if (l > 80) {
4326 fprintf (stderr,
4327 "Unknown sound card name (too big to show)\n");
4328 }
4329 else {
4330 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4331 (int) l, p);
4332 }
4333 bad_card = 1;
4334 }
4335 p += l + (e != NULL);
4336 }
4337
4338 if (bad_card)
4339 goto show_valid_cards;
4340 }
4341}
4342#endif
4343
3893c124 4344static void select_vgahw (const char *p)
4345{
4346 const char *opts;
4347
86176759 4348 vga_interface_type = VGA_NONE;
3893c124 4349 if (strstart(p, "std", &opts)) {
86176759 4350 vga_interface_type = VGA_STD;
3893c124 4351 } else if (strstart(p, "cirrus", &opts)) {
86176759 4352 vga_interface_type = VGA_CIRRUS;
3893c124 4353 } else if (strstart(p, "vmware", &opts)) {
86176759 4354 vga_interface_type = VGA_VMWARE;
94909d9f 4355 } else if (strstart(p, "xenfb", &opts)) {
86176759 4356 vga_interface_type = VGA_XENFB;
28b85ed8 4357 } else if (!strstart(p, "none", &opts)) {
3893c124 4358 invalid_vga:
4359 fprintf(stderr, "Unknown vga type: %s\n", p);
4360 exit(1);
4361 }
cb5a7aa8 4362 while (*opts) {
4363 const char *nextopt;
4364
4365 if (strstart(opts, ",retrace=", &nextopt)) {
4366 opts = nextopt;
4367 if (strstart(opts, "dumb", &nextopt))
4368 vga_retrace_method = VGA_RETRACE_DUMB;
4369 else if (strstart(opts, "precise", &nextopt))
4370 vga_retrace_method = VGA_RETRACE_PRECISE;
4371 else goto invalid_vga;
4372 } else goto invalid_vga;
4373 opts = nextopt;
4374 }
3893c124 4375}
4376
7d4c3d53
MA
4377#ifdef TARGET_I386
4378static int balloon_parse(const char *arg)
4379{
382f0743 4380 QemuOpts *opts;
7d4c3d53 4381
382f0743
GH
4382 if (strcmp(arg, "none") == 0) {
4383 return 0;
4384 }
4385
4386 if (!strncmp(arg, "virtio", 6)) {
4387 if (arg[6] == ',') {
4388 /* have params -> parse them */
4389 opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4390 if (!opts)
4391 return -1;
4392 } else {
4393 /* create empty opts */
4394 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
7d4c3d53 4395 }
382f0743
GH
4396 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4397 return 0;
7d4c3d53 4398 }
382f0743
GH
4399
4400 return -1;
7d4c3d53
MA
4401}
4402#endif
4403
3587d7e6
FB
4404#ifdef _WIN32
4405static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4406{
4407 exit(STATUS_CONTROL_C_EXIT);
4408 return TRUE;
4409}
4410#endif
4411
c4be29ff 4412int qemu_uuid_parse(const char *str, uint8_t *uuid)
8fcb1b90
BS
4413{
4414 int ret;
4415
4416 if(strlen(str) != 36)
4417 return -1;
4418
4419 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4420 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4421 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4422
4423 if(ret != 16)
4424 return -1;
4425
b6f6e3d3
AL
4426#ifdef TARGET_I386
4427 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4428#endif
4429
8fcb1b90
BS
4430 return 0;
4431}
4432
5b08fc10
AL
4433#ifndef _WIN32
4434
4435static void termsig_handler(int signal)
4436{
4437 qemu_system_shutdown_request();
4438}
4439
7c3370d4
JK
4440static void sigchld_handler(int signal)
4441{
4442 waitpid(-1, NULL, WNOHANG);
4443}
4444
4445static void sighandler_setup(void)
5b08fc10
AL
4446{
4447 struct sigaction act;
4448
4449 memset(&act, 0, sizeof(act));
4450 act.sa_handler = termsig_handler;
4451 sigaction(SIGINT, &act, NULL);
4452 sigaction(SIGHUP, &act, NULL);
4453 sigaction(SIGTERM, &act, NULL);
7c3370d4
JK
4454
4455 act.sa_handler = sigchld_handler;
4456 act.sa_flags = SA_NOCLDSTOP;
4457 sigaction(SIGCHLD, &act, NULL);
5b08fc10
AL
4458}
4459
4460#endif
4461
5cea8590
PB
4462#ifdef _WIN32
4463/* Look for support files in the same directory as the executable. */
4464static char *find_datadir(const char *argv0)
4465{
4466 char *p;
4467 char buf[MAX_PATH];
4468 DWORD len;
4469
4470 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4471 if (len == 0) {
c5947808 4472 return NULL;
5cea8590
PB
4473 }
4474
4475 buf[len] = 0;
4476 p = buf + len - 1;
4477 while (p != buf && *p != '\\')
4478 p--;
4479 *p = 0;
4480 if (access(buf, R_OK) == 0) {
4481 return qemu_strdup(buf);
4482 }
4483 return NULL;
4484}
4485#else /* !_WIN32 */
4486
4487/* Find a likely location for support files using the location of the binary.
4488 For installed binaries this will be "$bindir/../share/qemu". When
4489 running from the build tree this will be "$bindir/../pc-bios". */
4490#define SHARE_SUFFIX "/share/qemu"
4491#define BUILD_SUFFIX "/pc-bios"
4492static char *find_datadir(const char *argv0)
4493{
4494 char *dir;
4495 char *p = NULL;
4496 char *res;
5cea8590 4497 char buf[PATH_MAX];
3a41759d 4498 size_t max_len;
5cea8590
PB
4499
4500#if defined(__linux__)
4501 {
4502 int len;
4503 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4504 if (len > 0) {
4505 buf[len] = 0;
4506 p = buf;
4507 }
4508 }
4509#elif defined(__FreeBSD__)
4510 {
4511 int len;
4512 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4513 if (len > 0) {
4514 buf[len] = 0;
4515 p = buf;
4516 }
4517 }
4518#endif
4519 /* If we don't have any way of figuring out the actual executable
4520 location then try argv[0]. */
4521 if (!p) {
4d224196 4522 p = realpath(argv0, buf);
5cea8590
PB
4523 if (!p) {
4524 return NULL;
4525 }
4526 }
4527 dir = dirname(p);
4528 dir = dirname(dir);
4529
3a41759d
BS
4530 max_len = strlen(dir) +
4531 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4532 res = qemu_mallocz(max_len);
4533 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
5cea8590 4534 if (access(res, R_OK)) {
3a41759d 4535 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
5cea8590
PB
4536 if (access(res, R_OK)) {
4537 qemu_free(res);
4538 res = NULL;
4539 }
4540 }
4d224196 4541
5cea8590
PB
4542 return res;
4543}
4544#undef SHARE_SUFFIX
4545#undef BUILD_SUFFIX
4546#endif
4547
4548char *qemu_find_file(int type, const char *name)
4549{
4550 int len;
4551 const char *subdir;
4552 char *buf;
4553
4554 /* If name contains path separators then try it as a straight path. */
4555 if ((strchr(name, '/') || strchr(name, '\\'))
4556 && access(name, R_OK) == 0) {
73ffc805 4557 return qemu_strdup(name);
5cea8590
PB
4558 }
4559 switch (type) {
4560 case QEMU_FILE_TYPE_BIOS:
4561 subdir = "";
4562 break;
4563 case QEMU_FILE_TYPE_KEYMAP:
4564 subdir = "keymaps/";
4565 break;
4566 default:
4567 abort();
4568 }
4569 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4570 buf = qemu_mallocz(len);
3a41759d 4571 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
5cea8590
PB
4572 if (access(buf, R_OK)) {
4573 qemu_free(buf);
4574 return NULL;
4575 }
4576 return buf;
4577}
4578
f31d07d1
GH
4579static int device_init_func(QemuOpts *opts, void *opaque)
4580{
4581 DeviceState *dev;
4582
4583 dev = qdev_device_add(opts);
4584 if (!dev)
4585 return -1;
4586 return 0;
4587}
4588
bd3c948d
GH
4589struct device_config {
4590 enum {
bd3c948d
GH
4591 DEV_USB, /* -usbdevice */
4592 DEV_BT, /* -bt */
4593 } type;
4594 const char *cmdline;
72cf2d4f 4595 QTAILQ_ENTRY(device_config) next;
bd3c948d 4596};
72cf2d4f 4597QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
bd3c948d
GH
4598
4599static void add_device_config(int type, const char *cmdline)
4600{
4601 struct device_config *conf;
4602
4603 conf = qemu_mallocz(sizeof(*conf));
4604 conf->type = type;
4605 conf->cmdline = cmdline;
72cf2d4f 4606 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
bd3c948d
GH
4607}
4608
4609static int foreach_device_config(int type, int (*func)(const char *cmdline))
4610{
4611 struct device_config *conf;
4612 int rc;
4613
72cf2d4f 4614 QTAILQ_FOREACH(conf, &device_configs, next) {
bd3c948d
GH
4615 if (conf->type != type)
4616 continue;
4617 rc = func(conf->cmdline);
4618 if (0 != rc)
4619 return rc;
4620 }
4621 return 0;
4622}
4623
902b3d5c 4624int main(int argc, char **argv, char **envp)
0824d6fc 4625{
59030a8c 4626 const char *gdbstub_dev = NULL;
28c5af54 4627 uint32_t boot_devices_bitmap = 0;
e4bcb14c 4628 int i;
28c5af54 4629 int snapshot, linux_boot, net_boot;
7f7f9873 4630 const char *initrd_filename;
a20dd508 4631 const char *kernel_filename, *kernel_cmdline;
195325a4 4632 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3023f332 4633 DisplayState *ds;
7d957bd8 4634 DisplayChangeListener *dcl;
46d4767d 4635 int cyls, heads, secs, translation;
f31d07d1 4636 QemuOpts *hda_opts = NULL, *opts;
cd6f1169
FB
4637 int optind;
4638 const char *r, *optarg;
ddd9bbd9
JK
4639 CharDriverState *monitor_hds[MAX_MONITOR_DEVICES];
4640 const char *monitor_devices[MAX_MONITOR_DEVICES];
adcb181a 4641 int monitor_flags[MAX_MONITOR_DEVICES];
ddd9bbd9 4642 int monitor_device_index;
fd5f393a 4643 const char *serial_devices[MAX_SERIAL_PORTS];
8d11df9e 4644 int serial_device_index;
fd5f393a 4645 const char *parallel_devices[MAX_PARALLEL_PORTS];
6508fe59 4646 int parallel_device_index;
9ede2fde
AL
4647 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4648 int virtio_console_index;
d63d307f 4649 const char *loadvm = NULL;
cc1daa40 4650 QEMUMachine *machine;
94fc95cd 4651 const char *cpu_model;
b9e82a59 4652#ifndef _WIN32
71e3ceb8 4653 int fds[2];
b9e82a59 4654#endif
26a5f13b 4655 int tb_size;
93815bc2 4656 const char *pid_file = NULL;
5bb7910a 4657 const char *incoming = NULL;
b9e82a59 4658#ifndef _WIN32
54042bcf
AL
4659 int fd = 0;
4660 struct passwd *pwd = NULL;
0858532e
AL
4661 const char *chroot_dir = NULL;
4662 const char *run_as = NULL;
b9e82a59 4663#endif
268a362c 4664 CPUState *env;
993fbfdb 4665 int show_vnc_port = 0;
0bd48850 4666
6875204c
JK
4667 init_clocks();
4668
ac7531ec 4669 qemu_errors_to_file(stderr);
902b3d5c 4670 qemu_cache_utils_init(envp);
4671
72cf2d4f 4672 QLIST_INIT (&vm_change_state_head);
be995c27
FB
4673#ifndef _WIN32
4674 {
4675 struct sigaction act;
4676 sigfillset(&act.sa_mask);
4677 act.sa_flags = 0;
4678 act.sa_handler = SIG_IGN;
4679 sigaction(SIGPIPE, &act, NULL);
4680 }
3587d7e6
FB
4681#else
4682 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
a8e5ac33
FB
4683 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4684 QEMU to run on a single CPU */
4685 {
4686 HANDLE h;
4687 DWORD mask, smask;
4688 int i;
4689 h = GetCurrentProcess();
4690 if (GetProcessAffinityMask(h, &mask, &smask)) {
4691 for(i = 0; i < 32; i++) {
4692 if (mask & (1 << i))
4693 break;
4694 }
4695 if (i != 32) {
4696 mask = 1 << i;
4697 SetProcessAffinityMask(h, mask);
4698 }
4699 }
4700 }
67b915a5 4701#endif
be995c27 4702
f80f9ec9 4703 module_call_init(MODULE_INIT_MACHINE);
0c257437 4704 machine = find_default_machine();
94fc95cd 4705 cpu_model = NULL;
fc01f7e7 4706 initrd_filename = NULL;
4fc5d071 4707 ram_size = 0;
33e3963e 4708 snapshot = 0;
a20dd508
FB
4709 kernel_filename = NULL;
4710 kernel_cmdline = "";
c4b1fcc0 4711 cyls = heads = secs = 0;
46d4767d 4712 translation = BIOS_ATA_TRANSLATION_AUTO;
c4b1fcc0 4713
93d434b4
AG
4714#ifdef TARGET_S390X
4715 for(i = 0; i < MAX_SERIAL_PORTS; i++)
4716 serial_devices[i] = NULL;
4717 serial_device_index = 0;
4718
4719 for(i = 0; i < MAX_PARALLEL_PORTS; i++)
4720 parallel_devices[i] = NULL;
4721 parallel_device_index = 0;
4722
4723 virtio_consoles[0] = "mon:stdio";
4724 for(i = 1; i < MAX_VIRTIO_CONSOLES; i++)
4725 virtio_consoles[i] = NULL;
4726 virtio_console_index = 0;
4727#else
c75a823c 4728 serial_devices[0] = "vc:80Cx24C";
8d11df9e 4729 for(i = 1; i < MAX_SERIAL_PORTS; i++)
fd5f393a 4730 serial_devices[i] = NULL;
8d11df9e 4731 serial_device_index = 0;
3b46e624 4732
8290edda 4733 parallel_devices[0] = "vc:80Cx24C";
6508fe59 4734 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
fd5f393a 4735 parallel_devices[i] = NULL;
6508fe59 4736 parallel_device_index = 0;
3b46e624 4737
1b8fc811 4738 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
9ede2fde
AL
4739 virtio_consoles[i] = NULL;
4740 virtio_console_index = 0;
93d434b4 4741#endif
9ede2fde 4742
ddd9bbd9 4743 monitor_devices[0] = "vc:80Cx24C";
adcb181a 4744 monitor_flags[0] = MONITOR_IS_DEFAULT | MONITOR_USE_READLINE;
ddd9bbd9
JK
4745 for (i = 1; i < MAX_MONITOR_DEVICES; i++) {
4746 monitor_devices[i] = NULL;
adcb181a 4747 monitor_flags[i] = MONITOR_USE_READLINE;
ddd9bbd9
JK
4748 }
4749 monitor_device_index = 0;
4750
268a362c
AL
4751 for (i = 0; i < MAX_NODES; i++) {
4752 node_mem[i] = 0;
4753 node_cpumask[i] = 0;
4754 }
4755
268a362c 4756 nb_numa_nodes = 0;
7c9d8e07 4757 nb_nics = 0;
3b46e624 4758
26a5f13b 4759 tb_size = 0;
41bd639b
BS
4760 autostart= 1;
4761
cd6f1169 4762 optind = 1;
0824d6fc 4763 for(;;) {
cd6f1169 4764 if (optind >= argc)
0824d6fc 4765 break;
cd6f1169
FB
4766 r = argv[optind];
4767 if (r[0] != '-') {
9dfd7c7a 4768 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
cd6f1169
FB
4769 } else {
4770 const QEMUOption *popt;
4771
4772 optind++;
dff5efc8
PB
4773 /* Treat --foo the same as -foo. */
4774 if (r[1] == '-')
4775 r++;
cd6f1169
FB
4776 popt = qemu_options;
4777 for(;;) {
4778 if (!popt->name) {
5fafdf24 4779 fprintf(stderr, "%s: invalid option -- '%s'\n",
cd6f1169
FB
4780 argv[0], r);
4781 exit(1);
4782 }
4783 if (!strcmp(popt->name, r + 1))
4784 break;
4785 popt++;
4786 }
4787 if (popt->flags & HAS_ARG) {
4788 if (optind >= argc) {
4789 fprintf(stderr, "%s: option '%s' requires an argument\n",
4790 argv[0], r);
4791 exit(1);
4792 }
4793 optarg = argv[optind++];
4794 } else {
4795 optarg = NULL;
4796 }
4797
4798 switch(popt->index) {
cc1daa40
FB
4799 case QEMU_OPTION_M:
4800 machine = find_machine(optarg);
4801 if (!machine) {
4802 QEMUMachine *m;
4803 printf("Supported machines are:\n");
4804 for(m = first_machine; m != NULL; m = m->next) {
3f6599e6
MM
4805 if (m->alias)
4806 printf("%-10s %s (alias of %s)\n",
4807 m->alias, m->desc, m->name);
cc1daa40 4808 printf("%-10s %s%s\n",
5fafdf24 4809 m->name, m->desc,
0c257437 4810 m->is_default ? " (default)" : "");
cc1daa40 4811 }
15f82208 4812 exit(*optarg != '?');
cc1daa40
FB
4813 }
4814 break;
94fc95cd
JM
4815 case QEMU_OPTION_cpu:
4816 /* hw initialization will check this */
15f82208 4817 if (*optarg == '?') {
c732abe2
JM
4818/* XXX: implement xxx_cpu_list for targets that still miss it */
4819#if defined(cpu_list)
4820 cpu_list(stdout, &fprintf);
94fc95cd 4821#endif
15f82208 4822 exit(0);
94fc95cd
JM
4823 } else {
4824 cpu_model = optarg;
4825 }
4826 break;
cd6f1169 4827 case QEMU_OPTION_initrd:
fc01f7e7
FB
4828 initrd_filename = optarg;
4829 break;
cd6f1169 4830 case QEMU_OPTION_hda:
e4bcb14c 4831 if (cyls == 0)
9dfd7c7a 4832 hda_opts = drive_add(optarg, HD_ALIAS, 0);
e4bcb14c 4833 else
9dfd7c7a 4834 hda_opts = drive_add(optarg, HD_ALIAS
e4bcb14c 4835 ",cyls=%d,heads=%d,secs=%d%s",
609497ab 4836 0, cyls, heads, secs,
e4bcb14c
TS
4837 translation == BIOS_ATA_TRANSLATION_LBA ?
4838 ",trans=lba" :
4839 translation == BIOS_ATA_TRANSLATION_NONE ?
4840 ",trans=none" : "");
4841 break;
cd6f1169 4842 case QEMU_OPTION_hdb:
cc1daa40
FB
4843 case QEMU_OPTION_hdc:
4844 case QEMU_OPTION_hdd:
609497ab 4845 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
fc01f7e7 4846 break;
e4bcb14c 4847 case QEMU_OPTION_drive:
609497ab 4848 drive_add(NULL, "%s", optarg);
e4bcb14c 4849 break;
d058fe03
GH
4850 case QEMU_OPTION_set:
4851 if (qemu_set_option(optarg) != 0)
4852 exit(1);
4853 break;
d0fef6fb
GH
4854 case QEMU_OPTION_global:
4855 if (qemu_global_option(optarg) != 0)
4856 exit(1);
4857 break;
3e3d5815 4858 case QEMU_OPTION_mtdblock:
609497ab 4859 drive_add(optarg, MTD_ALIAS);
3e3d5815 4860 break;
a1bb27b1 4861 case QEMU_OPTION_sd:
609497ab 4862 drive_add(optarg, SD_ALIAS);
a1bb27b1 4863 break;
86f55663 4864 case QEMU_OPTION_pflash:
609497ab 4865 drive_add(optarg, PFLASH_ALIAS);
86f55663 4866 break;
cd6f1169 4867 case QEMU_OPTION_snapshot:
33e3963e
FB
4868 snapshot = 1;
4869 break;
cd6f1169 4870 case QEMU_OPTION_hdachs:
330d0414 4871 {
330d0414
FB
4872 const char *p;
4873 p = optarg;
4874 cyls = strtol(p, (char **)&p, 0);
46d4767d
FB
4875 if (cyls < 1 || cyls > 16383)
4876 goto chs_fail;
330d0414
FB
4877 if (*p != ',')
4878 goto chs_fail;
4879 p++;
4880 heads = strtol(p, (char **)&p, 0);
46d4767d
FB
4881 if (heads < 1 || heads > 16)
4882 goto chs_fail;
330d0414
FB
4883 if (*p != ',')
4884 goto chs_fail;
4885 p++;
4886 secs = strtol(p, (char **)&p, 0);
46d4767d
FB
4887 if (secs < 1 || secs > 63)
4888 goto chs_fail;
4889 if (*p == ',') {
4890 p++;
4891 if (!strcmp(p, "none"))
4892 translation = BIOS_ATA_TRANSLATION_NONE;
4893 else if (!strcmp(p, "lba"))
4894 translation = BIOS_ATA_TRANSLATION_LBA;
4895 else if (!strcmp(p, "auto"))
4896 translation = BIOS_ATA_TRANSLATION_AUTO;
4897 else
4898 goto chs_fail;
4899 } else if (*p != '\0') {
c4b1fcc0 4900 chs_fail:
46d4767d
FB
4901 fprintf(stderr, "qemu: invalid physical CHS format\n");
4902 exit(1);
c4b1fcc0 4903 }
9dfd7c7a
GH
4904 if (hda_opts != NULL) {
4905 char num[16];
4906 snprintf(num, sizeof(num), "%d", cyls);
4907 qemu_opt_set(hda_opts, "cyls", num);
4908 snprintf(num, sizeof(num), "%d", heads);
4909 qemu_opt_set(hda_opts, "heads", num);
4910 snprintf(num, sizeof(num), "%d", secs);
4911 qemu_opt_set(hda_opts, "secs", num);
4912 if (translation == BIOS_ATA_TRANSLATION_LBA)
4913 qemu_opt_set(hda_opts, "trans", "lba");
4914 if (translation == BIOS_ATA_TRANSLATION_NONE)
4915 qemu_opt_set(hda_opts, "trans", "none");
4916 }
330d0414
FB
4917 }
4918 break;
268a362c
AL
4919 case QEMU_OPTION_numa:
4920 if (nb_numa_nodes >= MAX_NODES) {
4921 fprintf(stderr, "qemu: too many NUMA nodes\n");
4922 exit(1);
4923 }
4924 numa_add(optarg);
4925 break;
cd6f1169 4926 case QEMU_OPTION_nographic:
993fbfdb 4927 display_type = DT_NOGRAPHIC;
a20dd508 4928 break;
4d3b6f6e
AZ
4929#ifdef CONFIG_CURSES
4930 case QEMU_OPTION_curses:
993fbfdb 4931 display_type = DT_CURSES;
4d3b6f6e
AZ
4932 break;
4933#endif
a171fe39
AZ
4934 case QEMU_OPTION_portrait:
4935 graphic_rotate = 1;
4936 break;
cd6f1169 4937 case QEMU_OPTION_kernel:
a20dd508
FB
4938 kernel_filename = optarg;
4939 break;
cd6f1169 4940 case QEMU_OPTION_append:
a20dd508 4941 kernel_cmdline = optarg;
313aa567 4942 break;
cd6f1169 4943 case QEMU_OPTION_cdrom:
609497ab 4944 drive_add(optarg, CDROM_ALIAS);
36b486bb 4945 break;
cd6f1169 4946 case QEMU_OPTION_boot:
28c5af54 4947 {
ef3adf68 4948 static const char * const params[] = {
95387491 4949 "order", "once", "menu", NULL
ef3adf68
JK
4950 };
4951 char buf[sizeof(boot_devices)];
e0f084bf 4952 char *standard_boot_devices;
ef3adf68
JK
4953 int legacy = 0;
4954
4955 if (!strchr(optarg, '=')) {
4956 legacy = 1;
4957 pstrcpy(buf, sizeof(buf), optarg);
4958 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4959 fprintf(stderr,
4960 "qemu: unknown boot parameter '%s' in '%s'\n",
4961 buf, optarg);
4962 exit(1);
4963 }
4964
4965 if (legacy ||
4966 get_param_value(buf, sizeof(buf), "order", optarg)) {
4967 boot_devices_bitmap = parse_bootdevices(buf);
4968 pstrcpy(boot_devices, sizeof(boot_devices), buf);
28c5af54 4969 }
e0f084bf
JK
4970 if (!legacy) {
4971 if (get_param_value(buf, sizeof(buf),
4972 "once", optarg)) {
4973 boot_devices_bitmap |= parse_bootdevices(buf);
4974 standard_boot_devices = qemu_strdup(boot_devices);
4975 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4976 qemu_register_reset(restore_boot_devices,
4977 standard_boot_devices);
4978 }
95387491
JK
4979 if (get_param_value(buf, sizeof(buf),
4980 "menu", optarg)) {
4981 if (!strcmp(buf, "on")) {
4982 boot_menu = 1;
4983 } else if (!strcmp(buf, "off")) {
4984 boot_menu = 0;
4985 } else {
4986 fprintf(stderr,
4987 "qemu: invalid option value '%s'\n",
4988 buf);
4989 exit(1);
4990 }
4991 }
e0f084bf 4992 }
36b486bb
FB
4993 }
4994 break;
cd6f1169 4995 case QEMU_OPTION_fda:
cd6f1169 4996 case QEMU_OPTION_fdb:
609497ab 4997 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
c45886db 4998 break;
52ca8d6a
FB
4999#ifdef TARGET_I386
5000 case QEMU_OPTION_no_fd_bootchk:
5001 fd_bootchk = 0;
5002 break;
5003#endif
a1ea458f
MM
5004 case QEMU_OPTION_netdev:
5005 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5006 exit(1);
5007 }
5008 break;
7c9d8e07 5009 case QEMU_OPTION_net:
7f161aae 5010 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
c4b1fcc0
FB
5011 exit(1);
5012 }
702c651c 5013 break;
c7f74643
FB
5014#ifdef CONFIG_SLIRP
5015 case QEMU_OPTION_tftp:
ad196a9d 5016 legacy_tftp_prefix = optarg;
9bf05444 5017 break;
47d5d01a 5018 case QEMU_OPTION_bootp:
ad196a9d 5019 legacy_bootp_filename = optarg;
47d5d01a 5020 break;
c94c8d64 5021#ifndef _WIN32
9d728e8c 5022 case QEMU_OPTION_smb:
0752706d
MA
5023 if (net_slirp_smb(optarg) < 0)
5024 exit(1);
9d728e8c 5025 break;
c94c8d64 5026#endif
9bf05444 5027 case QEMU_OPTION_redir:
0752706d
MA
5028 if (net_slirp_redir(optarg) < 0)
5029 exit(1);
9bf05444 5030 break;
c7f74643 5031#endif
dc72ac14 5032 case QEMU_OPTION_bt:
bd3c948d 5033 add_device_config(DEV_BT, optarg);
dc72ac14 5034 break;
1d14ffa9 5035#ifdef HAS_AUDIO
1d14ffa9
FB
5036 case QEMU_OPTION_audio_help:
5037 AUD_help ();
5038 exit (0);
5039 break;
5040 case QEMU_OPTION_soundhw:
5041 select_soundhw (optarg);
5042 break;
5043#endif
cd6f1169 5044 case QEMU_OPTION_h:
15f82208 5045 help(0);
cd6f1169 5046 break;
9bd7e6d9
PB
5047 case QEMU_OPTION_version:
5048 version();
5049 exit(0);
5050 break;
00f82b8a
AJ
5051 case QEMU_OPTION_m: {
5052 uint64_t value;
5053 char *ptr;
5054
5055 value = strtoul(optarg, &ptr, 10);
5056 switch (*ptr) {
5057 case 0: case 'M': case 'm':
5058 value <<= 20;
5059 break;
5060 case 'G': case 'g':
5061 value <<= 30;
5062 break;
5063 default:
5064 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
cd6f1169
FB
5065 exit(1);
5066 }
00f82b8a
AJ
5067
5068 /* On 32-bit hosts, QEMU is limited by virtual address space */
4a1418e0 5069 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
00f82b8a
AJ
5070 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5071 exit(1);
5072 }
c227f099 5073 if (value != (uint64_t)(ram_addr_t)value) {
00f82b8a
AJ
5074 fprintf(stderr, "qemu: ram size too large\n");
5075 exit(1);
5076 }
5077 ram_size = value;
cd6f1169 5078 break;
00f82b8a 5079 }
cd6f1169
FB
5080 case QEMU_OPTION_d:
5081 {
5082 int mask;
c7cd6a37 5083 const CPULogItem *item;
3b46e624 5084
cd6f1169
FB
5085 mask = cpu_str_to_log_mask(optarg);
5086 if (!mask) {
5087 printf("Log items (comma separated):\n");
f193c797
FB
5088 for(item = cpu_log_items; item->mask != 0; item++) {
5089 printf("%-10s %s\n", item->name, item->help);
5090 }
5091 exit(1);
cd6f1169
FB
5092 }
5093 cpu_set_log(mask);
f193c797 5094 }
cd6f1169 5095 break;
cd6f1169 5096 case QEMU_OPTION_s:
59030a8c 5097 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
cd6f1169 5098 break;
59030a8c
AL
5099 case QEMU_OPTION_gdb:
5100 gdbstub_dev = optarg;
cd6f1169 5101 break;
cd6f1169 5102 case QEMU_OPTION_L:
5cea8590 5103 data_dir = optarg;
cd6f1169 5104 break;
1192dad8
JM
5105 case QEMU_OPTION_bios:
5106 bios_name = optarg;
5107 break;
1b530a6d
AJ
5108 case QEMU_OPTION_singlestep:
5109 singlestep = 1;
5110 break;
cd6f1169 5111 case QEMU_OPTION_S:
3c07f8e8 5112 autostart = 0;
cd6f1169 5113 break;
3d11d0eb
FB
5114 case QEMU_OPTION_k:
5115 keyboard_layout = optarg;
5116 break;
ee22c2f7
FB
5117 case QEMU_OPTION_localtime:
5118 rtc_utc = 0;
5119 break;
3893c124 5120 case QEMU_OPTION_vga:
5121 select_vgahw (optarg);
1bfe856e 5122 break;
5824d651 5123#if defined(TARGET_PPC) || defined(TARGET_SPARC)
e9b137c2
FB
5124 case QEMU_OPTION_g:
5125 {
5126 const char *p;
5127 int w, h, depth;
5128 p = optarg;
5129 w = strtol(p, (char **)&p, 10);
5130 if (w <= 0) {
5131 graphic_error:
5132 fprintf(stderr, "qemu: invalid resolution or depth\n");
5133 exit(1);
5134 }
5135 if (*p != 'x')
5136 goto graphic_error;
5137 p++;
5138 h = strtol(p, (char **)&p, 10);
5139 if (h <= 0)
5140 goto graphic_error;
5141 if (*p == 'x') {
5142 p++;
5143 depth = strtol(p, (char **)&p, 10);
5fafdf24 5144 if (depth != 8 && depth != 15 && depth != 16 &&
e9b137c2
FB
5145 depth != 24 && depth != 32)
5146 goto graphic_error;
5147 } else if (*p == '\0') {
5148 depth = graphic_depth;
5149 } else {
5150 goto graphic_error;
5151 }
3b46e624 5152
e9b137c2
FB
5153 graphic_width = w;
5154 graphic_height = h;
5155 graphic_depth = depth;
5156 }
5157 break;
5824d651 5158#endif
20d8a3ed
TS
5159 case QEMU_OPTION_echr:
5160 {
5161 char *r;
5162 term_escape_char = strtol(optarg, &r, 0);
5163 if (r == optarg)
5164 printf("Bad argument to echr\n");
5165 break;
5166 }
82c643ff 5167 case QEMU_OPTION_monitor:
ddd9bbd9
JK
5168 if (monitor_device_index >= MAX_MONITOR_DEVICES) {
5169 fprintf(stderr, "qemu: too many monitor devices\n");
5170 exit(1);
5171 }
adcb181a
LC
5172 monitor_devices[monitor_device_index] =
5173 monitor_cmdline_parse(optarg,
5174 &monitor_flags[monitor_device_index]);
ddd9bbd9 5175 monitor_device_index++;
82c643ff 5176 break;
191bc01b
GH
5177 case QEMU_OPTION_chardev:
5178 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5179 if (!opts) {
5180 fprintf(stderr, "parse error: %s\n", optarg);
5181 exit(1);
5182 }
3df04ac3 5183 if (qemu_chr_open_opts(opts, NULL) == NULL) {
191bc01b
GH
5184 exit(1);
5185 }
5186 break;
82c643ff 5187 case QEMU_OPTION_serial:
8d11df9e
FB
5188 if (serial_device_index >= MAX_SERIAL_PORTS) {
5189 fprintf(stderr, "qemu: too many serial ports\n");
5190 exit(1);
5191 }
fd5f393a 5192 serial_devices[serial_device_index] = optarg;
8d11df9e 5193 serial_device_index++;
82c643ff 5194 break;
9dd986cc 5195 case QEMU_OPTION_watchdog:
09aaa160
MA
5196 if (watchdog) {
5197 fprintf(stderr,
5198 "qemu: only one watchdog option may be given\n");
5199 return 1;
5200 }
5201 watchdog = optarg;
9dd986cc
RJ
5202 break;
5203 case QEMU_OPTION_watchdog_action:
5204 if (select_watchdog_action(optarg) == -1) {
5205 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5206 exit(1);
5207 }
5208 break;
51ecf136
AL
5209 case QEMU_OPTION_virtiocon:
5210 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5211 fprintf(stderr, "qemu: too many virtio consoles\n");
5212 exit(1);
5213 }
5214 virtio_consoles[virtio_console_index] = optarg;
5215 virtio_console_index++;
5216 break;
6508fe59
FB
5217 case QEMU_OPTION_parallel:
5218 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5219 fprintf(stderr, "qemu: too many parallel ports\n");
5220 exit(1);
5221 }
fd5f393a 5222 parallel_devices[parallel_device_index] = optarg;
6508fe59
FB
5223 parallel_device_index++;
5224 break;
d63d307f
FB
5225 case QEMU_OPTION_loadvm:
5226 loadvm = optarg;
5227 break;
5228 case QEMU_OPTION_full_screen:
5229 full_screen = 1;
5230 break;
667accab 5231#ifdef CONFIG_SDL
43523e93
TS
5232 case QEMU_OPTION_no_frame:
5233 no_frame = 1;
5234 break;
3780e197
TS
5235 case QEMU_OPTION_alt_grab:
5236 alt_grab = 1;
5237 break;
0ca9f8a4
DK
5238 case QEMU_OPTION_ctrl_grab:
5239 ctrl_grab = 1;
5240 break;
667accab
TS
5241 case QEMU_OPTION_no_quit:
5242 no_quit = 1;
5243 break;
7d957bd8 5244 case QEMU_OPTION_sdl:
993fbfdb 5245 display_type = DT_SDL;
7d957bd8 5246 break;
667accab 5247#endif
f7cce898 5248 case QEMU_OPTION_pidfile:
93815bc2 5249 pid_file = optarg;
f7cce898 5250 break;
a09db21f
FB
5251#ifdef TARGET_I386
5252 case QEMU_OPTION_win2k_hack:
5253 win2k_install_hack = 1;
5254 break;
73822ec8
AL
5255 case QEMU_OPTION_rtc_td_hack:
5256 rtc_td_hack = 1;
5257 break;
8a92ea2f
AL
5258 case QEMU_OPTION_acpitable:
5259 if(acpi_table_add(optarg) < 0) {
5260 fprintf(stderr, "Wrong acpi table provided\n");
5261 exit(1);
5262 }
5263 break;
b6f6e3d3
AL
5264 case QEMU_OPTION_smbios:
5265 if(smbios_entry_add(optarg) < 0) {
5266 fprintf(stderr, "Wrong smbios provided\n");
5267 exit(1);
5268 }
5269 break;
a09db21f 5270#endif
7ba1e619
AL
5271#ifdef CONFIG_KVM
5272 case QEMU_OPTION_enable_kvm:
5273 kvm_allowed = 1;
7ba1e619 5274 break;
d993e026 5275#endif
bb36d470
FB
5276 case QEMU_OPTION_usb:
5277 usb_enabled = 1;
5278 break;
a594cfbf
FB
5279 case QEMU_OPTION_usbdevice:
5280 usb_enabled = 1;
bd3c948d
GH
5281 add_device_config(DEV_USB, optarg);
5282 break;
5283 case QEMU_OPTION_device:
b386becf 5284 if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
f31d07d1
GH
5285 exit(1);
5286 }
a594cfbf 5287 break;
6a00d601 5288 case QEMU_OPTION_smp:
dc6b1c09 5289 smp_parse(optarg);
b2097003 5290 if (smp_cpus < 1) {
6a00d601
FB
5291 fprintf(stderr, "Invalid number of CPUs\n");
5292 exit(1);
5293 }
6be68d7e
JS
5294 if (max_cpus < smp_cpus) {
5295 fprintf(stderr, "maxcpus must be equal to or greater than "
5296 "smp\n");
5297 exit(1);
5298 }
5299 if (max_cpus > 255) {
5300 fprintf(stderr, "Unsupported number of maxcpus\n");
5301 exit(1);
5302 }
6a00d601 5303 break;
24236869 5304 case QEMU_OPTION_vnc:
993fbfdb 5305 display_type = DT_VNC;
73fc9742 5306 vnc_display = optarg;
24236869 5307 break;
5824d651 5308#ifdef TARGET_I386
6515b203
FB
5309 case QEMU_OPTION_no_acpi:
5310 acpi_enabled = 0;
5311 break;
16b29ae1
AL
5312 case QEMU_OPTION_no_hpet:
5313 no_hpet = 1;
5314 break;
7d4c3d53
MA
5315 case QEMU_OPTION_balloon:
5316 if (balloon_parse(optarg) < 0) {
5317 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5318 exit(1);
5319 }
df97b920 5320 break;
5824d651 5321#endif
d1beab82
FB
5322 case QEMU_OPTION_no_reboot:
5323 no_reboot = 1;
5324 break;
b2f76161
AJ
5325 case QEMU_OPTION_no_shutdown:
5326 no_shutdown = 1;
5327 break;
9467cd46
AZ
5328 case QEMU_OPTION_show_cursor:
5329 cursor_hide = 0;
5330 break;
8fcb1b90
BS
5331 case QEMU_OPTION_uuid:
5332 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5333 fprintf(stderr, "Fail to parse UUID string."
5334 " Wrong format.\n");
5335 exit(1);
5336 }
5337 break;
5824d651 5338#ifndef _WIN32
71e3ceb8
TS
5339 case QEMU_OPTION_daemonize:
5340 daemonize = 1;
5341 break;
5824d651 5342#endif
9ae02555
TS
5343 case QEMU_OPTION_option_rom:
5344 if (nb_option_roms >= MAX_OPTION_ROMS) {
5345 fprintf(stderr, "Too many option ROMs\n");
5346 exit(1);
5347 }
5348 option_rom[nb_option_roms] = optarg;
5349 nb_option_roms++;
5350 break;
5824d651 5351#if defined(TARGET_ARM) || defined(TARGET_M68K)
8e71621f
PB
5352 case QEMU_OPTION_semihosting:
5353 semihosting_enabled = 1;
5354 break;
5824d651 5355#endif
c35734b2 5356 case QEMU_OPTION_name:
1889465a
AK
5357 qemu_name = qemu_strdup(optarg);
5358 {
5359 char *p = strchr(qemu_name, ',');
5360 if (p != NULL) {
5361 *p++ = 0;
5362 if (strncmp(p, "process=", 8)) {
5363 fprintf(stderr, "Unknown subargument %s to -name", p);
5364 exit(1);
5365 }
5366 p += 8;
5367 set_proc_name(p);
5368 }
5369 }
c35734b2 5370 break;
95efd11c 5371#if defined(TARGET_SPARC) || defined(TARGET_PPC)
66508601
BS
5372 case QEMU_OPTION_prom_env:
5373 if (nb_prom_envs >= MAX_PROM_ENVS) {
5374 fprintf(stderr, "Too many prom variables\n");
5375 exit(1);
5376 }
5377 prom_envs[nb_prom_envs] = optarg;
5378 nb_prom_envs++;
5379 break;
2b8f2d41
AZ
5380#endif
5381#ifdef TARGET_ARM
5382 case QEMU_OPTION_old_param:
5383 old_param = 1;
05ebd537 5384 break;
66508601 5385#endif
f3dcfada
TS
5386 case QEMU_OPTION_clock:
5387 configure_alarms(optarg);
5388 break;
7e0af5d0 5389 case QEMU_OPTION_startdate:
1ed2fc1f
JK
5390 configure_rtc_date_offset(optarg, 1);
5391 break;
5392 case QEMU_OPTION_rtc:
5393 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5394 if (!opts) {
5395 fprintf(stderr, "parse error: %s\n", optarg);
5396 exit(1);
7e0af5d0 5397 }
1ed2fc1f 5398 configure_rtc(opts);
7e0af5d0 5399 break;
26a5f13b
FB
5400 case QEMU_OPTION_tb_size:
5401 tb_size = strtol(optarg, NULL, 0);
5402 if (tb_size < 0)
5403 tb_size = 0;
5404 break;
2e70f6ef
PB
5405 case QEMU_OPTION_icount:
5406 use_icount = 1;
5407 if (strcmp(optarg, "auto") == 0) {
5408 icount_time_shift = -1;
5409 } else {
5410 icount_time_shift = strtol(optarg, NULL, 0);
5411 }
5412 break;
5bb7910a
AL
5413 case QEMU_OPTION_incoming:
5414 incoming = optarg;
5415 break;
5824d651 5416#ifndef _WIN32
0858532e
AL
5417 case QEMU_OPTION_chroot:
5418 chroot_dir = optarg;
5419 break;
5420 case QEMU_OPTION_runas:
5421 run_as = optarg;
5422 break;
e37630ca
AL
5423#endif
5424#ifdef CONFIG_XEN
5425 case QEMU_OPTION_xen_domid:
5426 xen_domid = atoi(optarg);
5427 break;
5428 case QEMU_OPTION_xen_create:
5429 xen_mode = XEN_CREATE;
5430 break;
5431 case QEMU_OPTION_xen_attach:
5432 xen_mode = XEN_ATTACH;
5433 break;
5824d651 5434#endif
715a664a
GH
5435 case QEMU_OPTION_readconfig:
5436 {
5437 FILE *fp;
5438 fp = fopen(optarg, "r");
5439 if (fp == NULL) {
5440 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5441 exit(1);
5442 }
5443 if (qemu_config_parse(fp) != 0) {
5444 exit(1);
5445 }
5446 fclose(fp);
5447 break;
5448 }
5449 case QEMU_OPTION_writeconfig:
5450 {
5451 FILE *fp;
5452 if (strcmp(optarg, "-") == 0) {
5453 fp = stdout;
5454 } else {
5455 fp = fopen(optarg, "w");
5456 if (fp == NULL) {
5457 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5458 exit(1);
5459 }
5460 }
5461 qemu_config_write(fp);
5462 fclose(fp);
5463 break;
5464 }
cd6f1169 5465 }
0824d6fc
FB
5466 }
5467 }
330d0414 5468
5cea8590
PB
5469 /* If no data_dir is specified then try to find it relative to the
5470 executable path. */
5471 if (!data_dir) {
5472 data_dir = find_datadir(argv[0]);
5473 }
5474 /* If all else fails use the install patch specified when building. */
5475 if (!data_dir) {
5476 data_dir = CONFIG_QEMU_SHAREDIR;
5477 }
5478
6be68d7e
JS
5479 /*
5480 * Default to max_cpus = smp_cpus, in case the user doesn't
5481 * specify a max_cpus value.
5482 */
5483 if (!max_cpus)
5484 max_cpus = smp_cpus;
5485
3d878caa 5486 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
b2097003
AL
5487 if (smp_cpus > machine->max_cpus) {
5488 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5489 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5490 machine->max_cpus);
5491 exit(1);
5492 }
5493
993fbfdb 5494 if (display_type == DT_NOGRAPHIC) {
bc0129d9
AL
5495 if (serial_device_index == 0)
5496 serial_devices[0] = "stdio";
5497 if (parallel_device_index == 0)
5498 parallel_devices[0] = "null";
ddd9bbd9
JK
5499 if (strncmp(monitor_devices[0], "vc", 2) == 0) {
5500 monitor_devices[0] = "stdio";
5501 }
bc0129d9
AL
5502 }
5503
71e3ceb8 5504#ifndef _WIN32
71e3ceb8
TS
5505 if (daemonize) {
5506 pid_t pid;
5507
5508 if (pipe(fds) == -1)
5509 exit(1);
5510
5511 pid = fork();
5512 if (pid > 0) {
5513 uint8_t status;
5514 ssize_t len;
5515
5516 close(fds[1]);
5517
5518 again:
93815bc2
TS
5519 len = read(fds[0], &status, 1);
5520 if (len == -1 && (errno == EINTR))
5521 goto again;
5522
5523 if (len != 1)
5524 exit(1);
5525 else if (status == 1) {
850810d0 5526 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
93815bc2
TS
5527 exit(1);
5528 } else
5529 exit(0);
71e3ceb8 5530 } else if (pid < 0)
93815bc2 5531 exit(1);
71e3ceb8 5532
40ff6d7e
KW
5533 close(fds[0]);
5534 qemu_set_cloexec(fds[1]);
5535
71e3ceb8
TS
5536 setsid();
5537
5538 pid = fork();
5539 if (pid > 0)
5540 exit(0);
5541 else if (pid < 0)
5542 exit(1);
5543
5544 umask(027);
71e3ceb8
TS
5545
5546 signal(SIGTSTP, SIG_IGN);
5547 signal(SIGTTOU, SIG_IGN);
5548 signal(SIGTTIN, SIG_IGN);
5549 }
71e3ceb8 5550
aa26bb2d 5551 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
93815bc2
TS
5552 if (daemonize) {
5553 uint8_t status = 1;
5554 write(fds[1], &status, 1);
5555 } else
850810d0 5556 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
93815bc2
TS
5557 exit(1);
5558 }
b9e82a59 5559#endif
93815bc2 5560
214910a7
MT
5561 if (kvm_enabled()) {
5562 int ret;
5563
5564 ret = kvm_init(smp_cpus);
5565 if (ret < 0) {
5566 fprintf(stderr, "failed to initialize KVM\n");
5567 exit(1);
5568 }
5569 }
5570
3fcf7b6b
AL
5571 if (qemu_init_main_loop()) {
5572 fprintf(stderr, "qemu_init_main_loop failed\n");
5573 exit(1);
5574 }
a20dd508 5575 linux_boot = (kernel_filename != NULL);
6c41b272 5576
f8d39c01
TS
5577 if (!linux_boot && *kernel_cmdline != '\0') {
5578 fprintf(stderr, "-append only allowed with -kernel option\n");
5579 exit(1);
5580 }
5581
5582 if (!linux_boot && initrd_filename != NULL) {
5583 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5584 exit(1);
5585 }
5586
bf65f53f
FN
5587#ifndef _WIN32
5588 /* Win32 doesn't support line-buffering and requires size >= 2 */
b118d61e 5589 setvbuf(stdout, NULL, _IOLBF, 0);
bf65f53f 5590#endif
3b46e624 5591
7183b4b4
AL
5592 if (init_timer_alarm() < 0) {
5593 fprintf(stderr, "could not initialize alarm timer\n");
5594 exit(1);
5595 }
2e70f6ef
PB
5596 if (use_icount && icount_time_shift < 0) {
5597 use_icount = 2;
5598 /* 125MIPS seems a reasonable initial guess at the guest speed.
5599 It will be corrected fairly quickly anyway. */
5600 icount_time_shift = 3;
5601 init_icount_adjust();
5602 }
634fce96 5603
fd1dff4b
FB
5604#ifdef _WIN32
5605 socket_init();
5606#endif
5607
dc1c9fe8
MM
5608 if (net_init_clients() < 0) {
5609 exit(1);
702c651c 5610 }
f1510b2c 5611
406c8df3
GC
5612 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5613 net_set_boot_mask(net_boot);
5614
dc72ac14 5615 /* init the bluetooth world */
bd3c948d
GH
5616 if (foreach_device_config(DEV_BT, bt_parse))
5617 exit(1);
dc72ac14 5618
0824d6fc 5619 /* init the memory */
94a6b54f
PB
5620 if (ram_size == 0)
5621 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9ae02555 5622
26a5f13b
FB
5623 /* init the dynamic translator */
5624 cpu_exec_init_all(tb_size * 1024 * 1024);
5625
eb852011 5626 bdrv_init_with_whitelist();
c4b1fcc0 5627
c163b5ca
LS
5628 blk_mig_init();
5629
e4bcb14c 5630 /* we always create the cdrom drive, even if no disk is there */
3b0ba927 5631 drive_add(NULL, CDROM_ALIAS);
c4b1fcc0 5632
9d413d1d 5633 /* we always create at least one floppy */
3b0ba927 5634 drive_add(NULL, FD_ALIAS, 0);
86f55663 5635
9d413d1d 5636 /* we always create one sd slot, even if no card is in it */
3b0ba927 5637 drive_add(NULL, SD_ALIAS);
9d413d1d 5638
e4bcb14c 5639 /* open the virtual block devices */
9dfd7c7a 5640 if (snapshot)
7282a033
GH
5641 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5642 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
9dfd7c7a 5643 exit(1);
3e3d5815 5644
2faf58cd 5645 vmstate_register(0, &vmstate_timers ,&timers_state);
c163b5ca
LS
5646 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
5647 ram_load, NULL);
8a7ddc38 5648
3023f332 5649 /* Maintain compatibility with multiple stdio monitors */
ddd9bbd9 5650 if (!strcmp(monitor_devices[0],"stdio")) {
3023f332
AL
5651 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5652 const char *devname = serial_devices[i];
5653 if (devname && !strcmp(devname,"mon:stdio")) {
ddd9bbd9 5654 monitor_devices[0] = NULL;
3023f332
AL
5655 break;
5656 } else if (devname && !strcmp(devname,"stdio")) {
ddd9bbd9 5657 monitor_devices[0] = NULL;
3023f332
AL
5658 serial_devices[i] = "mon:stdio";
5659 break;
5660 }
5661 }
93d434b4
AG
5662 for (i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5663 const char *devname = virtio_consoles[i];
5664 if (devname && !strcmp(devname,"mon:stdio")) {
5665 monitor_devices[0] = NULL;
5666 break;
5667 } else if (devname && !strcmp(devname,"stdio")) {
5668 monitor_devices[0] = NULL;
5669 virtio_consoles[i] = "mon:stdio";
5670 break;
5671 }
5672 }
3023f332
AL
5673 }
5674
268a362c
AL
5675 if (nb_numa_nodes > 0) {
5676 int i;
5677
5678 if (nb_numa_nodes > smp_cpus) {
5679 nb_numa_nodes = smp_cpus;
5680 }
5681
5682 /* If no memory size if given for any node, assume the default case
5683 * and distribute the available memory equally across all nodes
5684 */
5685 for (i = 0; i < nb_numa_nodes; i++) {
5686 if (node_mem[i] != 0)
5687 break;
5688 }
5689 if (i == nb_numa_nodes) {
5690 uint64_t usedmem = 0;
5691
5692 /* On Linux, the each node's border has to be 8MB aligned,
5693 * the final node gets the rest.
5694 */
5695 for (i = 0; i < nb_numa_nodes - 1; i++) {
5696 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5697 usedmem += node_mem[i];
5698 }
5699 node_mem[i] = ram_size - usedmem;
5700 }
5701
5702 for (i = 0; i < nb_numa_nodes; i++) {
5703 if (node_cpumask[i] != 0)
5704 break;
5705 }
5706 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5707 * must cope with this anyway, because there are BIOSes out there in
5708 * real machines which also use this scheme.
5709 */
5710 if (i == nb_numa_nodes) {
5711 for (i = 0; i < smp_cpus; i++) {
5712 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5713 }
5714 }
5715 }
5716
ddd9bbd9
JK
5717 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5718 const char *devname = monitor_devices[i];
5719 if (devname && strcmp(devname, "none")) {
5720 char label[32];
5721 if (i == 0) {
5722 snprintf(label, sizeof(label), "monitor");
5723 } else {
5724 snprintf(label, sizeof(label), "monitor%d", i);
5725 }
5726 monitor_hds[i] = qemu_chr_open(label, devname, NULL);
5727 if (!monitor_hds[i]) {
5728 fprintf(stderr, "qemu: could not open monitor device '%s'\n",
5729 devname);
5730 exit(1);
5731 }
4c621805
AL
5732 }
5733 }
5734
2796dae0
AL
5735 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5736 const char *devname = serial_devices[i];
5737 if (devname && strcmp(devname, "none")) {
324a8021
AJ
5738 char label[32];
5739 snprintf(label, sizeof(label), "serial%d", i);
ceecf1d1 5740 serial_hds[i] = qemu_chr_open(label, devname, NULL);
324a8021 5741 if (!serial_hds[i]) {
850810d0
JF
5742 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
5743 devname, strerror(errno));
324a8021
AJ
5744 exit(1);
5745 }
2796dae0
AL
5746 }
5747 }
5748
5749 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5750 const char *devname = parallel_devices[i];
5751 if (devname && strcmp(devname, "none")) {
5752 char label[32];
5753 snprintf(label, sizeof(label), "parallel%d", i);
ceecf1d1 5754 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
2796dae0 5755 if (!parallel_hds[i]) {
850810d0
JF
5756 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
5757 devname, strerror(errno));
2796dae0
AL
5758 exit(1);
5759 }
5760 }
5761 }
5762
5763 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5764 const char *devname = virtio_consoles[i];
5765 if (devname && strcmp(devname, "none")) {
5766 char label[32];
5767 snprintf(label, sizeof(label), "virtcon%d", i);
ceecf1d1 5768 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
2796dae0 5769 if (!virtcon_hds[i]) {
850810d0
JF
5770 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
5771 devname, strerror(errno));
2796dae0
AL
5772 exit(1);
5773 }
5774 }
5775 }
5776
aae9460e
PB
5777 module_call_init(MODULE_INIT_DEVICE);
5778
09aaa160
MA
5779 if (watchdog) {
5780 i = select_watchdog(watchdog);
5781 if (i > 0)
5782 exit (i == 1 ? 1 : 0);
5783 }
5784
b6b61144 5785 if (machine->compat_props) {
458fb679 5786 qdev_prop_register_global_list(machine->compat_props);
b6b61144 5787 }
d0fef6fb
GH
5788 qemu_add_globals();
5789
fbe1b595 5790 machine->init(ram_size, boot_devices,
3023f332
AL
5791 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5792
268a362c 5793
67b3b71d
JQ
5794#ifndef _WIN32
5795 /* must be after terminal init, SDL library changes signal handlers */
5796 sighandler_setup();
5797#endif
5798
268a362c
AL
5799 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5800 for (i = 0; i < nb_numa_nodes; i++) {
5801 if (node_cpumask[i] & (1 << env->cpu_index)) {
5802 env->numa_node = i;
5803 }
5804 }
5805 }
5806
6f338c34
AL
5807 current_machine = machine;
5808
3023f332
AL
5809 /* init USB devices */
5810 if (usb_enabled) {
0752706d
MA
5811 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5812 exit(1);
3023f332
AL
5813 }
5814
bd3c948d 5815 /* init generic devices */
f31d07d1 5816 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
bd3c948d
GH
5817 exit(1);
5818
8f391ab4
AL
5819 if (!display_state)
5820 dumb_display_init();
3023f332
AL
5821 /* just use the first displaystate for the moment */
5822 ds = display_state;
993fbfdb
AL
5823
5824 if (display_type == DT_DEFAULT) {
5825#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5826 display_type = DT_SDL;
5827#else
5828 display_type = DT_VNC;
5829 vnc_display = "localhost:0,to=99";
5830 show_vnc_port = 1;
5831#endif
5832 }
5833
5834
5835 switch (display_type) {
5836 case DT_NOGRAPHIC:
5837 break;
4d3b6f6e 5838#if defined(CONFIG_CURSES)
993fbfdb
AL
5839 case DT_CURSES:
5840 curses_display_init(ds, full_screen);
5841 break;
4d3b6f6e 5842#endif
5b0753e0 5843#if defined(CONFIG_SDL)
993fbfdb
AL
5844 case DT_SDL:
5845 sdl_display_init(ds, full_screen, no_frame);
5846 break;
5b0753e0 5847#elif defined(CONFIG_COCOA)
993fbfdb
AL
5848 case DT_SDL:
5849 cocoa_display_init(ds, full_screen);
5850 break;
313aa567 5851#endif
993fbfdb
AL
5852 case DT_VNC:
5853 vnc_display_init(ds);
5854 if (vnc_display_open(ds, vnc_display) < 0)
5855 exit(1);
f92f8afe 5856
993fbfdb
AL
5857 if (show_vnc_port) {
5858 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
f92f8afe 5859 }
993fbfdb
AL
5860 break;
5861 default:
5862 break;
313aa567 5863 }
7d957bd8 5864 dpy_resize(ds);
5b08fc10 5865
3023f332
AL
5866 dcl = ds->listeners;
5867 while (dcl != NULL) {
5868 if (dcl->dpy_refresh != NULL) {
5869 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5870 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
20d8a3ed 5871 }
3023f332 5872 dcl = dcl->next;
20d8a3ed 5873 }
3023f332 5874
993fbfdb 5875 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
9043b62d
BS
5876 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5877 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5878 }
5879
2796dae0
AL
5880 text_consoles_set_display(display_state);
5881
ddd9bbd9
JK
5882 for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5883 if (monitor_devices[i] && monitor_hds[i]) {
adcb181a 5884 monitor_init(monitor_hds[i], monitor_flags[i]);
ddd9bbd9
JK
5885 }
5886 }
82c643ff 5887
8d11df9e 5888 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
c03b0f0f 5889 const char *devname = serial_devices[i];
fd5f393a 5890 if (devname && strcmp(devname, "none")) {
af3a9031 5891 if (strstart(devname, "vc", 0))
7ba1260a 5892 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8d11df9e 5893 }
82c643ff 5894 }
82c643ff 5895
6508fe59 5896 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
c03b0f0f 5897 const char *devname = parallel_devices[i];
fd5f393a 5898 if (devname && strcmp(devname, "none")) {
af3a9031 5899 if (strstart(devname, "vc", 0))
7ba1260a 5900 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6508fe59
FB
5901 }
5902 }
5903
9ede2fde
AL
5904 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5905 const char *devname = virtio_consoles[i];
2796dae0 5906 if (virtcon_hds[i] && devname) {
9ede2fde
AL
5907 if (strstart(devname, "vc", 0))
5908 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5909 }
5910 }
5911
59030a8c
AL
5912 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5913 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5914 gdbstub_dev);
5915 exit(1);
45669e00 5916 }
45669e00 5917
3418bd25
GH
5918 qdev_machine_creation_done();
5919
45a50b16
GH
5920 rom_load_all();
5921
504c2948 5922 qemu_system_reset();
05f2401e
JQ
5923 if (loadvm) {
5924 if (load_vmstate(cur_mon, loadvm) < 0) {
5925 autostart = 0;
5926 }
5927 }
d63d307f 5928
2bb8c10c 5929 if (incoming) {
5bb7910a 5930 qemu_start_incoming_migration(incoming);
6b99dadc 5931 } else if (autostart) {
c0f4ce77 5932 vm_start();
6b99dadc 5933 }
ffd843bc 5934
b9e82a59 5935#ifndef _WIN32
71e3ceb8
TS
5936 if (daemonize) {
5937 uint8_t status = 0;
5938 ssize_t len;
71e3ceb8
TS
5939
5940 again1:
5941 len = write(fds[1], &status, 1);
5942 if (len == -1 && (errno == EINTR))
5943 goto again1;
5944
5945 if (len != 1)
5946 exit(1);
5947
bd54b863 5948 chdir("/");
40ff6d7e 5949 TFR(fd = qemu_open("/dev/null", O_RDWR));
71e3ceb8
TS
5950 if (fd == -1)
5951 exit(1);
0858532e 5952 }
71e3ceb8 5953
0858532e
AL
5954 if (run_as) {
5955 pwd = getpwnam(run_as);
5956 if (!pwd) {
5957 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5958 exit(1);
5959 }
5960 }
5961
5962 if (chroot_dir) {
5963 if (chroot(chroot_dir) < 0) {
5964 fprintf(stderr, "chroot failed\n");
5965 exit(1);
5966 }
5967 chdir("/");
5968 }
5969
5970 if (run_as) {
5971 if (setgid(pwd->pw_gid) < 0) {
5972 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5973 exit(1);
5974 }
5975 if (setuid(pwd->pw_uid) < 0) {
5976 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5977 exit(1);
5978 }
5979 if (setuid(0) != -1) {
5980 fprintf(stderr, "Dropping privileges failed\n");
5981 exit(1);
5982 }
5983 }
0858532e
AL
5984
5985 if (daemonize) {
5986 dup2(fd, 0);
5987 dup2(fd, 1);
5988 dup2(fd, 2);
71e3ceb8 5989
0858532e 5990 close(fd);
71e3ceb8 5991 }
b9e82a59 5992#endif
71e3ceb8 5993
8a7ddc38 5994 main_loop();
40c3bac3 5995 quit_timers();
63a01ef8 5996 net_cleanup();
b46a8906 5997
0824d6fc
FB
5998 return 0;
5999}