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