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