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