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