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