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