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