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