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