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