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