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