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