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