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