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