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