Restore old stable branch
[qemu-kvm/fedora.git] / vl.c
blobaaeff23faff9da8982d530207249e6d7d09561b6
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "cache-utils.h"
40 #include "block.h"
41 #include "audio/audio.h"
42 #include "migration.h"
43 #include "kvm.h"
44 #include "balloon.h"
46 #include <unistd.h>
47 #include <fcntl.h>
48 #include <signal.h>
49 #include <time.h>
50 #include <errno.h>
51 #include <sys/time.h>
52 #include <zlib.h>
54 #ifndef _WIN32
55 #include <pwd.h>
56 #include <sys/times.h>
57 #include <sys/wait.h>
58 #include <termios.h>
59 #include <sys/mman.h>
60 #include <sys/ioctl.h>
61 #include <sys/resource.h>
62 #include <sys/socket.h>
63 #include <netinet/in.h>
64 #include <net/if.h>
65 #if defined(__NetBSD__)
66 #include <net/if_tap.h>
67 #endif
68 #ifdef __linux__
69 #include <linux/if_tun.h>
70 #endif
71 #include <arpa/inet.h>
72 #include <dirent.h>
73 #include <netdb.h>
74 #include <sys/select.h>
75 #ifdef _BSD
76 #include <sys/stat.h>
77 #ifdef __FreeBSD__
78 #include <libutil.h>
79 #else
80 #include <util.h>
81 #endif
82 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
83 #include <freebsd/stdlib.h>
84 #else
85 #ifdef __linux__
86 #include <pty.h>
87 #include <malloc.h>
88 #include <linux/rtc.h>
90 /* For the benefit of older linux systems which don't supply it,
91 we use a local copy of hpet.h. */
92 /* #include <linux/hpet.h> */
93 #include "hpet.h"
95 #include <linux/ppdev.h>
96 #include <linux/parport.h>
97 #endif
98 #ifdef __sun__
99 #include <sys/stat.h>
100 #include <sys/ethernet.h>
101 #include <sys/sockio.h>
102 #include <netinet/arp.h>
103 #include <netinet/in.h>
104 #include <netinet/in_systm.h>
105 #include <netinet/ip.h>
106 #include <netinet/ip_icmp.h> // must come after ip.h
107 #include <netinet/udp.h>
108 #include <netinet/tcp.h>
109 #include <net/if.h>
110 #include <syslog.h>
111 #include <stropts.h>
112 #endif
113 #endif
114 #endif
116 #include "qemu_socket.h"
118 #if defined(CONFIG_SLIRP)
119 #include "libslirp.h"
120 #endif
122 #if defined(__OpenBSD__)
123 #include <util.h>
124 #endif
126 #if defined(CONFIG_VDE)
127 #include <libvdeplug.h>
128 #endif
130 #ifdef _WIN32
131 #include <malloc.h>
132 #include <sys/timeb.h>
133 #include <mmsystem.h>
134 #define getopt_long_only getopt_long
135 #define memalign(align, size) malloc(size)
136 #endif
138 #ifdef CONFIG_SDL
139 #ifdef __APPLE__
140 #include <SDL/SDL.h>
141 int qemu_main(int argc, char **argv, char **envp);
142 int main(int argc, char **argv)
144 qemu_main(argc, argv, NULL);
146 #undef main
147 #define main qemu_main
148 #endif
149 #endif /* CONFIG_SDL */
151 #ifdef CONFIG_COCOA
152 #undef main
153 #define main qemu_main
154 #endif /* CONFIG_COCOA */
156 #include "disas.h"
158 #include "exec-all.h"
160 //#define DEBUG_UNUSED_IOPORT
161 //#define DEBUG_IOPORT
162 //#define DEBUG_NET
163 //#define DEBUG_SLIRP
166 #ifdef DEBUG_IOPORT
167 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
168 #else
169 # define LOG_IOPORT(...) do { } while (0)
170 #endif
172 #define DEFAULT_RAM_SIZE 128
174 /* Max number of USB devices that can be specified on the commandline. */
175 #define MAX_USB_CMDLINE 8
177 /* Max number of bluetooth switches on the commandline. */
178 #define MAX_BT_CMDLINE 10
180 /* XXX: use a two level table to limit memory usage */
181 #define MAX_IOPORTS 65536
183 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
184 const char *bios_name = NULL;
185 static void *ioport_opaque[MAX_IOPORTS];
186 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
187 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
188 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
189 to store the VM snapshots */
190 DriveInfo drives_table[MAX_DRIVES+1];
191 int nb_drives;
192 static int vga_ram_size;
193 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
194 static DisplayState *display_state;
195 int nographic;
196 static int curses;
197 static int sdl;
198 const char* keyboard_layout = NULL;
199 int64_t ticks_per_sec;
200 ram_addr_t ram_size;
201 int nb_nics;
202 NICInfo nd_table[MAX_NICS];
203 int vm_running;
204 static int autostart;
205 static int rtc_utc = 1;
206 static int rtc_date_offset = -1; /* -1 means no change */
207 int cirrus_vga_enabled = 1;
208 int std_vga_enabled = 0;
209 int vmsvga_enabled = 0;
210 #ifdef TARGET_SPARC
211 int graphic_width = 1024;
212 int graphic_height = 768;
213 int graphic_depth = 8;
214 #else
215 int graphic_width = 800;
216 int graphic_height = 600;
217 int graphic_depth = 15;
218 #endif
219 static int full_screen = 0;
220 #ifdef CONFIG_SDL
221 static int no_frame = 0;
222 #endif
223 int no_quit = 0;
224 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
225 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
226 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
227 #ifdef TARGET_I386
228 int win2k_install_hack = 0;
229 int rtc_td_hack = 0;
230 #endif
231 int usb_enabled = 0;
232 int smp_cpus = 1;
233 const char *vnc_display;
234 int acpi_enabled = 1;
235 int no_hpet = 0;
236 int fd_bootchk = 1;
237 int no_reboot = 0;
238 int no_shutdown = 0;
239 int cursor_hide = 1;
240 int graphic_rotate = 0;
241 int daemonize = 0;
242 const char *option_rom[MAX_OPTION_ROMS];
243 int nb_option_roms;
244 int semihosting_enabled = 0;
245 #ifdef TARGET_ARM
246 int old_param = 0;
247 #endif
248 const char *qemu_name;
249 int alt_grab = 0;
250 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
251 unsigned int nb_prom_envs = 0;
252 const char *prom_envs[MAX_PROM_ENVS];
253 #endif
254 int nb_drives_opt;
255 struct drive_opt drives_opt[MAX_DRIVES];
257 static CPUState *cur_cpu;
258 static CPUState *next_cpu;
259 static int event_pending = 1;
260 /* Conversion factor from emulated instructions to virtual clock ticks. */
261 static int icount_time_shift;
262 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
263 #define MAX_ICOUNT_SHIFT 10
264 /* Compensate for varying guest execution speed. */
265 static int64_t qemu_icount_bias;
266 static QEMUTimer *icount_rt_timer;
267 static QEMUTimer *icount_vm_timer;
268 static QEMUTimer *nographic_timer;
270 uint8_t qemu_uuid[16];
272 /***********************************************************/
273 /* x86 ISA bus support */
275 target_phys_addr_t isa_mem_base = 0;
276 PicState2 *isa_pic;
278 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
279 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
281 static uint32_t ioport_read(int index, uint32_t address)
283 static IOPortReadFunc *default_func[3] = {
284 default_ioport_readb,
285 default_ioport_readw,
286 default_ioport_readl
288 IOPortReadFunc *func = ioport_read_table[index][address];
289 if (!func)
290 func = default_func[index];
291 return func(ioport_opaque[address], address);
294 static void ioport_write(int index, uint32_t address, uint32_t data)
296 static IOPortWriteFunc *default_func[3] = {
297 default_ioport_writeb,
298 default_ioport_writew,
299 default_ioport_writel
301 IOPortWriteFunc *func = ioport_write_table[index][address];
302 if (!func)
303 func = default_func[index];
304 func(ioport_opaque[address], address, data);
307 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
309 #ifdef DEBUG_UNUSED_IOPORT
310 fprintf(stderr, "unused inb: port=0x%04x\n", address);
311 #endif
312 return 0xff;
315 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
317 #ifdef DEBUG_UNUSED_IOPORT
318 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
319 #endif
322 /* default is to make two byte accesses */
323 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
325 uint32_t data;
326 data = ioport_read(0, address);
327 address = (address + 1) & (MAX_IOPORTS - 1);
328 data |= ioport_read(0, address) << 8;
329 return data;
332 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
334 ioport_write(0, address, data & 0xff);
335 address = (address + 1) & (MAX_IOPORTS - 1);
336 ioport_write(0, address, (data >> 8) & 0xff);
339 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
341 #ifdef DEBUG_UNUSED_IOPORT
342 fprintf(stderr, "unused inl: port=0x%04x\n", address);
343 #endif
344 return 0xffffffff;
347 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
349 #ifdef DEBUG_UNUSED_IOPORT
350 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
351 #endif
354 /* size is the word size in byte */
355 int register_ioport_read(int start, int length, int size,
356 IOPortReadFunc *func, void *opaque)
358 int i, bsize;
360 if (size == 1) {
361 bsize = 0;
362 } else if (size == 2) {
363 bsize = 1;
364 } else if (size == 4) {
365 bsize = 2;
366 } else {
367 hw_error("register_ioport_read: invalid size");
368 return -1;
370 for(i = start; i < start + length; i += size) {
371 ioport_read_table[bsize][i] = func;
372 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
373 hw_error("register_ioport_read: invalid opaque");
374 ioport_opaque[i] = opaque;
376 return 0;
379 /* size is the word size in byte */
380 int register_ioport_write(int start, int length, int size,
381 IOPortWriteFunc *func, void *opaque)
383 int i, bsize;
385 if (size == 1) {
386 bsize = 0;
387 } else if (size == 2) {
388 bsize = 1;
389 } else if (size == 4) {
390 bsize = 2;
391 } else {
392 hw_error("register_ioport_write: invalid size");
393 return -1;
395 for(i = start; i < start + length; i += size) {
396 ioport_write_table[bsize][i] = func;
397 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
398 hw_error("register_ioport_write: invalid opaque");
399 ioport_opaque[i] = opaque;
401 return 0;
404 void isa_unassign_ioport(int start, int length)
406 int i;
408 for(i = start; i < start + length; i++) {
409 ioport_read_table[0][i] = default_ioport_readb;
410 ioport_read_table[1][i] = default_ioport_readw;
411 ioport_read_table[2][i] = default_ioport_readl;
413 ioport_write_table[0][i] = default_ioport_writeb;
414 ioport_write_table[1][i] = default_ioport_writew;
415 ioport_write_table[2][i] = default_ioport_writel;
417 ioport_opaque[i] = NULL;
421 /***********************************************************/
423 void cpu_outb(CPUState *env, int addr, int val)
425 LOG_IOPORT("outb: %04x %02x\n", addr, val);
426 ioport_write(0, addr, val);
427 #ifdef USE_KQEMU
428 if (env)
429 env->last_io_time = cpu_get_time_fast();
430 #endif
433 void cpu_outw(CPUState *env, int addr, int val)
435 LOG_IOPORT("outw: %04x %04x\n", addr, val);
436 ioport_write(1, addr, val);
437 #ifdef USE_KQEMU
438 if (env)
439 env->last_io_time = cpu_get_time_fast();
440 #endif
443 void cpu_outl(CPUState *env, int addr, int val)
445 LOG_IOPORT("outl: %04x %08x\n", addr, val);
446 ioport_write(2, addr, val);
447 #ifdef USE_KQEMU
448 if (env)
449 env->last_io_time = cpu_get_time_fast();
450 #endif
453 int cpu_inb(CPUState *env, int addr)
455 int val;
456 val = ioport_read(0, addr);
457 LOG_IOPORT("inb : %04x %02x\n", addr, val);
458 #ifdef USE_KQEMU
459 if (env)
460 env->last_io_time = cpu_get_time_fast();
461 #endif
462 return val;
465 int cpu_inw(CPUState *env, int addr)
467 int val;
468 val = ioport_read(1, addr);
469 LOG_IOPORT("inw : %04x %04x\n", addr, val);
470 #ifdef USE_KQEMU
471 if (env)
472 env->last_io_time = cpu_get_time_fast();
473 #endif
474 return val;
477 int cpu_inl(CPUState *env, int addr)
479 int val;
480 val = ioport_read(2, addr);
481 LOG_IOPORT("inl : %04x %08x\n", addr, val);
482 #ifdef USE_KQEMU
483 if (env)
484 env->last_io_time = cpu_get_time_fast();
485 #endif
486 return val;
489 /***********************************************************/
490 void hw_error(const char *fmt, ...)
492 va_list ap;
493 CPUState *env;
495 va_start(ap, fmt);
496 fprintf(stderr, "qemu: hardware error: ");
497 vfprintf(stderr, fmt, ap);
498 fprintf(stderr, "\n");
499 for(env = first_cpu; env != NULL; env = env->next_cpu) {
500 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
501 #ifdef TARGET_I386
502 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
503 #else
504 cpu_dump_state(env, stderr, fprintf, 0);
505 #endif
507 va_end(ap);
508 abort();
511 /***************/
512 /* ballooning */
514 static QEMUBalloonEvent *qemu_balloon_event;
515 void *qemu_balloon_event_opaque;
517 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
519 qemu_balloon_event = func;
520 qemu_balloon_event_opaque = opaque;
523 void qemu_balloon(ram_addr_t target)
525 if (qemu_balloon_event)
526 qemu_balloon_event(qemu_balloon_event_opaque, target);
529 ram_addr_t qemu_balloon_status(void)
531 if (qemu_balloon_event)
532 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
533 return 0;
536 /***********************************************************/
537 /* keyboard/mouse */
539 static QEMUPutKBDEvent *qemu_put_kbd_event;
540 static void *qemu_put_kbd_event_opaque;
541 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
542 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
544 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
546 qemu_put_kbd_event_opaque = opaque;
547 qemu_put_kbd_event = func;
550 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
551 void *opaque, int absolute,
552 const char *name)
554 QEMUPutMouseEntry *s, *cursor;
556 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
558 s->qemu_put_mouse_event = func;
559 s->qemu_put_mouse_event_opaque = opaque;
560 s->qemu_put_mouse_event_absolute = absolute;
561 s->qemu_put_mouse_event_name = qemu_strdup(name);
562 s->next = NULL;
564 if (!qemu_put_mouse_event_head) {
565 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
566 return s;
569 cursor = qemu_put_mouse_event_head;
570 while (cursor->next != NULL)
571 cursor = cursor->next;
573 cursor->next = s;
574 qemu_put_mouse_event_current = s;
576 return s;
579 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
581 QEMUPutMouseEntry *prev = NULL, *cursor;
583 if (!qemu_put_mouse_event_head || entry == NULL)
584 return;
586 cursor = qemu_put_mouse_event_head;
587 while (cursor != NULL && cursor != entry) {
588 prev = cursor;
589 cursor = cursor->next;
592 if (cursor == NULL) // does not exist or list empty
593 return;
594 else if (prev == NULL) { // entry is head
595 qemu_put_mouse_event_head = cursor->next;
596 if (qemu_put_mouse_event_current == entry)
597 qemu_put_mouse_event_current = cursor->next;
598 qemu_free(entry->qemu_put_mouse_event_name);
599 qemu_free(entry);
600 return;
603 prev->next = entry->next;
605 if (qemu_put_mouse_event_current == entry)
606 qemu_put_mouse_event_current = prev;
608 qemu_free(entry->qemu_put_mouse_event_name);
609 qemu_free(entry);
612 void kbd_put_keycode(int keycode)
614 if (qemu_put_kbd_event) {
615 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
619 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
621 QEMUPutMouseEvent *mouse_event;
622 void *mouse_event_opaque;
623 int width;
625 if (!qemu_put_mouse_event_current) {
626 return;
629 mouse_event =
630 qemu_put_mouse_event_current->qemu_put_mouse_event;
631 mouse_event_opaque =
632 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
634 if (mouse_event) {
635 if (graphic_rotate) {
636 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
637 width = 0x7fff;
638 else
639 width = graphic_width - 1;
640 mouse_event(mouse_event_opaque,
641 width - dy, dx, dz, buttons_state);
642 } else
643 mouse_event(mouse_event_opaque,
644 dx, dy, dz, buttons_state);
648 int kbd_mouse_is_absolute(void)
650 if (!qemu_put_mouse_event_current)
651 return 0;
653 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
656 void do_info_mice(void)
658 QEMUPutMouseEntry *cursor;
659 int index = 0;
661 if (!qemu_put_mouse_event_head) {
662 term_printf("No mouse devices connected\n");
663 return;
666 term_printf("Mouse devices available:\n");
667 cursor = qemu_put_mouse_event_head;
668 while (cursor != NULL) {
669 term_printf("%c Mouse #%d: %s\n",
670 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
671 index, cursor->qemu_put_mouse_event_name);
672 index++;
673 cursor = cursor->next;
677 void do_mouse_set(int index)
679 QEMUPutMouseEntry *cursor;
680 int i = 0;
682 if (!qemu_put_mouse_event_head) {
683 term_printf("No mouse devices connected\n");
684 return;
687 cursor = qemu_put_mouse_event_head;
688 while (cursor != NULL && index != i) {
689 i++;
690 cursor = cursor->next;
693 if (cursor != NULL)
694 qemu_put_mouse_event_current = cursor;
695 else
696 term_printf("Mouse at given index not found\n");
699 /* compute with 96 bit intermediate result: (a*b)/c */
700 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
702 union {
703 uint64_t ll;
704 struct {
705 #ifdef WORDS_BIGENDIAN
706 uint32_t high, low;
707 #else
708 uint32_t low, high;
709 #endif
710 } l;
711 } u, res;
712 uint64_t rl, rh;
714 u.ll = a;
715 rl = (uint64_t)u.l.low * (uint64_t)b;
716 rh = (uint64_t)u.l.high * (uint64_t)b;
717 rh += (rl >> 32);
718 res.l.high = rh / c;
719 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
720 return res.ll;
723 /***********************************************************/
724 /* real time host monotonic timer */
726 #define QEMU_TIMER_BASE 1000000000LL
728 #ifdef WIN32
730 static int64_t clock_freq;
732 static void init_get_clock(void)
734 LARGE_INTEGER freq;
735 int ret;
736 ret = QueryPerformanceFrequency(&freq);
737 if (ret == 0) {
738 fprintf(stderr, "Could not calibrate ticks\n");
739 exit(1);
741 clock_freq = freq.QuadPart;
744 static int64_t get_clock(void)
746 LARGE_INTEGER ti;
747 QueryPerformanceCounter(&ti);
748 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
751 #else
753 static int use_rt_clock;
755 static void init_get_clock(void)
757 use_rt_clock = 0;
758 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
760 struct timespec ts;
761 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
762 use_rt_clock = 1;
765 #endif
768 static int64_t get_clock(void)
770 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
771 if (use_rt_clock) {
772 struct timespec ts;
773 clock_gettime(CLOCK_MONOTONIC, &ts);
774 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
775 } else
776 #endif
778 /* XXX: using gettimeofday leads to problems if the date
779 changes, so it should be avoided. */
780 struct timeval tv;
781 gettimeofday(&tv, NULL);
782 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
785 #endif
787 /* Return the virtual CPU time, based on the instruction counter. */
788 static int64_t cpu_get_icount(void)
790 int64_t icount;
791 CPUState *env = cpu_single_env;;
792 icount = qemu_icount;
793 if (env) {
794 if (!can_do_io(env))
795 fprintf(stderr, "Bad clock read\n");
796 icount -= (env->icount_decr.u16.low + env->icount_extra);
798 return qemu_icount_bias + (icount << icount_time_shift);
801 /***********************************************************/
802 /* guest cycle counter */
804 static int64_t cpu_ticks_prev;
805 static int64_t cpu_ticks_offset;
806 static int64_t cpu_clock_offset;
807 static int cpu_ticks_enabled;
809 /* return the host CPU cycle counter and handle stop/restart */
810 int64_t cpu_get_ticks(void)
812 if (use_icount) {
813 return cpu_get_icount();
815 if (!cpu_ticks_enabled) {
816 return cpu_ticks_offset;
817 } else {
818 int64_t ticks;
819 ticks = cpu_get_real_ticks();
820 if (cpu_ticks_prev > ticks) {
821 /* Note: non increasing ticks may happen if the host uses
822 software suspend */
823 cpu_ticks_offset += cpu_ticks_prev - ticks;
825 cpu_ticks_prev = ticks;
826 return ticks + cpu_ticks_offset;
830 /* return the host CPU monotonic timer and handle stop/restart */
831 static int64_t cpu_get_clock(void)
833 int64_t ti;
834 if (!cpu_ticks_enabled) {
835 return cpu_clock_offset;
836 } else {
837 ti = get_clock();
838 return ti + cpu_clock_offset;
842 /* enable cpu_get_ticks() */
843 void cpu_enable_ticks(void)
845 if (!cpu_ticks_enabled) {
846 cpu_ticks_offset -= cpu_get_real_ticks();
847 cpu_clock_offset -= get_clock();
848 cpu_ticks_enabled = 1;
852 /* disable cpu_get_ticks() : the clock is stopped. You must not call
853 cpu_get_ticks() after that. */
854 void cpu_disable_ticks(void)
856 if (cpu_ticks_enabled) {
857 cpu_ticks_offset = cpu_get_ticks();
858 cpu_clock_offset = cpu_get_clock();
859 cpu_ticks_enabled = 0;
863 /***********************************************************/
864 /* timers */
866 #define QEMU_TIMER_REALTIME 0
867 #define QEMU_TIMER_VIRTUAL 1
869 struct QEMUClock {
870 int type;
871 /* XXX: add frequency */
874 struct QEMUTimer {
875 QEMUClock *clock;
876 int64_t expire_time;
877 QEMUTimerCB *cb;
878 void *opaque;
879 struct QEMUTimer *next;
882 struct qemu_alarm_timer {
883 char const *name;
884 unsigned int flags;
886 int (*start)(struct qemu_alarm_timer *t);
887 void (*stop)(struct qemu_alarm_timer *t);
888 void (*rearm)(struct qemu_alarm_timer *t);
889 void *priv;
892 #define ALARM_FLAG_DYNTICKS 0x1
893 #define ALARM_FLAG_EXPIRED 0x2
895 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
897 return t->flags & ALARM_FLAG_DYNTICKS;
900 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
902 if (!alarm_has_dynticks(t))
903 return;
905 t->rearm(t);
908 /* TODO: MIN_TIMER_REARM_US should be optimized */
909 #define MIN_TIMER_REARM_US 250
911 static struct qemu_alarm_timer *alarm_timer;
912 #ifndef _WIN32
913 static int alarm_timer_rfd, alarm_timer_wfd;
914 #endif
916 #ifdef _WIN32
918 struct qemu_alarm_win32 {
919 MMRESULT timerId;
920 HANDLE host_alarm;
921 unsigned int period;
922 } alarm_win32_data = {0, NULL, -1};
924 static int win32_start_timer(struct qemu_alarm_timer *t);
925 static void win32_stop_timer(struct qemu_alarm_timer *t);
926 static void win32_rearm_timer(struct qemu_alarm_timer *t);
928 #else
930 static int unix_start_timer(struct qemu_alarm_timer *t);
931 static void unix_stop_timer(struct qemu_alarm_timer *t);
933 #ifdef __linux__
935 static int dynticks_start_timer(struct qemu_alarm_timer *t);
936 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
937 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
939 static int hpet_start_timer(struct qemu_alarm_timer *t);
940 static void hpet_stop_timer(struct qemu_alarm_timer *t);
942 static int rtc_start_timer(struct qemu_alarm_timer *t);
943 static void rtc_stop_timer(struct qemu_alarm_timer *t);
945 #endif /* __linux__ */
947 #endif /* _WIN32 */
949 /* Correlation between real and virtual time is always going to be
950 fairly approximate, so ignore small variation.
951 When the guest is idle real and virtual time will be aligned in
952 the IO wait loop. */
953 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
955 static void icount_adjust(void)
957 int64_t cur_time;
958 int64_t cur_icount;
959 int64_t delta;
960 static int64_t last_delta;
961 /* If the VM is not running, then do nothing. */
962 if (!vm_running)
963 return;
965 cur_time = cpu_get_clock();
966 cur_icount = qemu_get_clock(vm_clock);
967 delta = cur_icount - cur_time;
968 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
969 if (delta > 0
970 && last_delta + ICOUNT_WOBBLE < delta * 2
971 && icount_time_shift > 0) {
972 /* The guest is getting too far ahead. Slow time down. */
973 icount_time_shift--;
975 if (delta < 0
976 && last_delta - ICOUNT_WOBBLE > delta * 2
977 && icount_time_shift < MAX_ICOUNT_SHIFT) {
978 /* The guest is getting too far behind. Speed time up. */
979 icount_time_shift++;
981 last_delta = delta;
982 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
985 static void icount_adjust_rt(void * opaque)
987 qemu_mod_timer(icount_rt_timer,
988 qemu_get_clock(rt_clock) + 1000);
989 icount_adjust();
992 static void icount_adjust_vm(void * opaque)
994 qemu_mod_timer(icount_vm_timer,
995 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
996 icount_adjust();
999 static void init_icount_adjust(void)
1001 /* Have both realtime and virtual time triggers for speed adjustment.
1002 The realtime trigger catches emulated time passing too slowly,
1003 the virtual time trigger catches emulated time passing too fast.
1004 Realtime triggers occur even when idle, so use them less frequently
1005 than VM triggers. */
1006 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1007 qemu_mod_timer(icount_rt_timer,
1008 qemu_get_clock(rt_clock) + 1000);
1009 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1010 qemu_mod_timer(icount_vm_timer,
1011 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1014 static struct qemu_alarm_timer alarm_timers[] = {
1015 #ifndef _WIN32
1016 #ifdef __linux__
1017 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1018 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1019 /* HPET - if available - is preferred */
1020 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1021 /* ...otherwise try RTC */
1022 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1023 #endif
1024 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1025 #else
1026 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1027 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1028 {"win32", 0, win32_start_timer,
1029 win32_stop_timer, NULL, &alarm_win32_data},
1030 #endif
1031 {NULL, }
1034 static void show_available_alarms(void)
1036 int i;
1038 printf("Available alarm timers, in order of precedence:\n");
1039 for (i = 0; alarm_timers[i].name; i++)
1040 printf("%s\n", alarm_timers[i].name);
1043 static void configure_alarms(char const *opt)
1045 int i;
1046 int cur = 0;
1047 int count = ARRAY_SIZE(alarm_timers) - 1;
1048 char *arg;
1049 char *name;
1050 struct qemu_alarm_timer tmp;
1052 if (!strcmp(opt, "?")) {
1053 show_available_alarms();
1054 exit(0);
1057 arg = strdup(opt);
1059 /* Reorder the array */
1060 name = strtok(arg, ",");
1061 while (name) {
1062 for (i = 0; i < count && alarm_timers[i].name; i++) {
1063 if (!strcmp(alarm_timers[i].name, name))
1064 break;
1067 if (i == count) {
1068 fprintf(stderr, "Unknown clock %s\n", name);
1069 goto next;
1072 if (i < cur)
1073 /* Ignore */
1074 goto next;
1076 /* Swap */
1077 tmp = alarm_timers[i];
1078 alarm_timers[i] = alarm_timers[cur];
1079 alarm_timers[cur] = tmp;
1081 cur++;
1082 next:
1083 name = strtok(NULL, ",");
1086 free(arg);
1088 if (cur) {
1089 /* Disable remaining timers */
1090 for (i = cur; i < count; i++)
1091 alarm_timers[i].name = NULL;
1092 } else {
1093 show_available_alarms();
1094 exit(1);
1098 QEMUClock *rt_clock;
1099 QEMUClock *vm_clock;
1101 static QEMUTimer *active_timers[2];
1103 static QEMUClock *qemu_new_clock(int type)
1105 QEMUClock *clock;
1106 clock = qemu_mallocz(sizeof(QEMUClock));
1107 clock->type = type;
1108 return clock;
1111 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1113 QEMUTimer *ts;
1115 ts = qemu_mallocz(sizeof(QEMUTimer));
1116 ts->clock = clock;
1117 ts->cb = cb;
1118 ts->opaque = opaque;
1119 return ts;
1122 void qemu_free_timer(QEMUTimer *ts)
1124 qemu_free(ts);
1127 /* stop a timer, but do not dealloc it */
1128 void qemu_del_timer(QEMUTimer *ts)
1130 QEMUTimer **pt, *t;
1132 /* NOTE: this code must be signal safe because
1133 qemu_timer_expired() can be called from a signal. */
1134 pt = &active_timers[ts->clock->type];
1135 for(;;) {
1136 t = *pt;
1137 if (!t)
1138 break;
1139 if (t == ts) {
1140 *pt = t->next;
1141 break;
1143 pt = &t->next;
1147 /* modify the current timer so that it will be fired when current_time
1148 >= expire_time. The corresponding callback will be called. */
1149 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1151 QEMUTimer **pt, *t;
1153 qemu_del_timer(ts);
1155 /* add the timer in the sorted list */
1156 /* NOTE: this code must be signal safe because
1157 qemu_timer_expired() can be called from a signal. */
1158 pt = &active_timers[ts->clock->type];
1159 for(;;) {
1160 t = *pt;
1161 if (!t)
1162 break;
1163 if (t->expire_time > expire_time)
1164 break;
1165 pt = &t->next;
1167 ts->expire_time = expire_time;
1168 ts->next = *pt;
1169 *pt = ts;
1171 /* Rearm if necessary */
1172 if (pt == &active_timers[ts->clock->type]) {
1173 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1174 qemu_rearm_alarm_timer(alarm_timer);
1176 /* Interrupt execution to force deadline recalculation. */
1177 if (use_icount && cpu_single_env) {
1178 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1183 int qemu_timer_pending(QEMUTimer *ts)
1185 QEMUTimer *t;
1186 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1187 if (t == ts)
1188 return 1;
1190 return 0;
1193 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1195 if (!timer_head)
1196 return 0;
1197 return (timer_head->expire_time <= current_time);
1200 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1202 QEMUTimer *ts;
1204 for(;;) {
1205 ts = *ptimer_head;
1206 if (!ts || ts->expire_time > current_time)
1207 break;
1208 /* remove timer from the list before calling the callback */
1209 *ptimer_head = ts->next;
1210 ts->next = NULL;
1212 /* run the callback (the timer list can be modified) */
1213 ts->cb(ts->opaque);
1217 int64_t qemu_get_clock(QEMUClock *clock)
1219 switch(clock->type) {
1220 case QEMU_TIMER_REALTIME:
1221 return get_clock() / 1000000;
1222 default:
1223 case QEMU_TIMER_VIRTUAL:
1224 if (use_icount) {
1225 return cpu_get_icount();
1226 } else {
1227 return cpu_get_clock();
1232 static void init_timers(void)
1234 init_get_clock();
1235 ticks_per_sec = QEMU_TIMER_BASE;
1236 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1237 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1240 /* save a timer */
1241 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1243 uint64_t expire_time;
1245 if (qemu_timer_pending(ts)) {
1246 expire_time = ts->expire_time;
1247 } else {
1248 expire_time = -1;
1250 qemu_put_be64(f, expire_time);
1253 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1255 uint64_t expire_time;
1257 expire_time = qemu_get_be64(f);
1258 if (expire_time != -1) {
1259 qemu_mod_timer(ts, expire_time);
1260 } else {
1261 qemu_del_timer(ts);
1265 static void timer_save(QEMUFile *f, void *opaque)
1267 if (cpu_ticks_enabled) {
1268 hw_error("cannot save state if virtual timers are running");
1270 qemu_put_be64(f, cpu_ticks_offset);
1271 qemu_put_be64(f, ticks_per_sec);
1272 qemu_put_be64(f, cpu_clock_offset);
1275 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1277 if (version_id != 1 && version_id != 2)
1278 return -EINVAL;
1279 if (cpu_ticks_enabled) {
1280 return -EINVAL;
1282 cpu_ticks_offset=qemu_get_be64(f);
1283 ticks_per_sec=qemu_get_be64(f);
1284 if (version_id == 2) {
1285 cpu_clock_offset=qemu_get_be64(f);
1287 return 0;
1290 #ifdef _WIN32
1291 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1292 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1293 #else
1294 static void host_alarm_handler(int host_signum)
1295 #endif
1297 #if 0
1298 #define DISP_FREQ 1000
1300 static int64_t delta_min = INT64_MAX;
1301 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1302 static int count;
1303 ti = qemu_get_clock(vm_clock);
1304 if (last_clock != 0) {
1305 delta = ti - last_clock;
1306 if (delta < delta_min)
1307 delta_min = delta;
1308 if (delta > delta_max)
1309 delta_max = delta;
1310 delta_cum += delta;
1311 if (++count == DISP_FREQ) {
1312 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1313 muldiv64(delta_min, 1000000, ticks_per_sec),
1314 muldiv64(delta_max, 1000000, ticks_per_sec),
1315 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1316 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1317 count = 0;
1318 delta_min = INT64_MAX;
1319 delta_max = 0;
1320 delta_cum = 0;
1323 last_clock = ti;
1325 #endif
1326 if (alarm_has_dynticks(alarm_timer) ||
1327 (!use_icount &&
1328 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1329 qemu_get_clock(vm_clock))) ||
1330 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1331 qemu_get_clock(rt_clock))) {
1332 CPUState *env = next_cpu;
1334 #ifdef _WIN32
1335 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1336 SetEvent(data->host_alarm);
1337 #else
1338 static const char byte = 0;
1339 write(alarm_timer_wfd, &byte, sizeof(byte));
1340 #endif
1341 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1343 if (env) {
1344 /* stop the currently executing cpu because a timer occured */
1345 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1346 #ifdef USE_KQEMU
1347 if (env->kqemu_enabled) {
1348 kqemu_cpu_interrupt(env);
1350 #endif
1352 event_pending = 1;
1356 static int64_t qemu_next_deadline(void)
1358 int64_t delta;
1360 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1361 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1362 qemu_get_clock(vm_clock);
1363 } else {
1364 /* To avoid problems with overflow limit this to 2^32. */
1365 delta = INT32_MAX;
1368 if (delta < 0)
1369 delta = 0;
1371 return delta;
1374 #if defined(__linux__) || defined(_WIN32)
1375 static uint64_t qemu_next_deadline_dyntick(void)
1377 int64_t delta;
1378 int64_t rtdelta;
1380 if (use_icount)
1381 delta = INT32_MAX;
1382 else
1383 delta = (qemu_next_deadline() + 999) / 1000;
1385 if (active_timers[QEMU_TIMER_REALTIME]) {
1386 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1387 qemu_get_clock(rt_clock))*1000;
1388 if (rtdelta < delta)
1389 delta = rtdelta;
1392 if (delta < MIN_TIMER_REARM_US)
1393 delta = MIN_TIMER_REARM_US;
1395 return delta;
1397 #endif
1399 #ifndef _WIN32
1401 /* Sets a specific flag */
1402 static int fcntl_setfl(int fd, int flag)
1404 int flags;
1406 flags = fcntl(fd, F_GETFL);
1407 if (flags == -1)
1408 return -errno;
1410 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1411 return -errno;
1413 return 0;
1416 #if defined(__linux__)
1418 #define RTC_FREQ 1024
1420 static void enable_sigio_timer(int fd)
1422 struct sigaction act;
1424 /* timer signal */
1425 sigfillset(&act.sa_mask);
1426 act.sa_flags = 0;
1427 act.sa_handler = host_alarm_handler;
1429 sigaction(SIGIO, &act, NULL);
1430 fcntl_setfl(fd, O_ASYNC);
1431 fcntl(fd, F_SETOWN, getpid());
1434 static int hpet_start_timer(struct qemu_alarm_timer *t)
1436 struct hpet_info info;
1437 int r, fd;
1439 fd = open("/dev/hpet", O_RDONLY);
1440 if (fd < 0)
1441 return -1;
1443 /* Set frequency */
1444 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1445 if (r < 0) {
1446 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1447 "error, but for better emulation accuracy type:\n"
1448 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1449 goto fail;
1452 /* Check capabilities */
1453 r = ioctl(fd, HPET_INFO, &info);
1454 if (r < 0)
1455 goto fail;
1457 /* Enable periodic mode */
1458 r = ioctl(fd, HPET_EPI, 0);
1459 if (info.hi_flags && (r < 0))
1460 goto fail;
1462 /* Enable interrupt */
1463 r = ioctl(fd, HPET_IE_ON, 0);
1464 if (r < 0)
1465 goto fail;
1467 enable_sigio_timer(fd);
1468 t->priv = (void *)(long)fd;
1470 return 0;
1471 fail:
1472 close(fd);
1473 return -1;
1476 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1478 int fd = (long)t->priv;
1480 close(fd);
1483 static int rtc_start_timer(struct qemu_alarm_timer *t)
1485 int rtc_fd;
1486 unsigned long current_rtc_freq = 0;
1488 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1489 if (rtc_fd < 0)
1490 return -1;
1491 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1492 if (current_rtc_freq != RTC_FREQ &&
1493 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1494 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1495 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1496 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1497 goto fail;
1499 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1500 fail:
1501 close(rtc_fd);
1502 return -1;
1505 enable_sigio_timer(rtc_fd);
1507 t->priv = (void *)(long)rtc_fd;
1509 return 0;
1512 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1514 int rtc_fd = (long)t->priv;
1516 close(rtc_fd);
1519 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1521 struct sigevent ev;
1522 timer_t host_timer;
1523 struct sigaction act;
1525 sigfillset(&act.sa_mask);
1526 act.sa_flags = 0;
1527 act.sa_handler = host_alarm_handler;
1529 sigaction(SIGALRM, &act, NULL);
1531 ev.sigev_value.sival_int = 0;
1532 ev.sigev_notify = SIGEV_SIGNAL;
1533 ev.sigev_signo = SIGALRM;
1535 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1536 perror("timer_create");
1538 /* disable dynticks */
1539 fprintf(stderr, "Dynamic Ticks disabled\n");
1541 return -1;
1544 t->priv = (void *)(long)host_timer;
1546 return 0;
1549 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1551 timer_t host_timer = (timer_t)(long)t->priv;
1553 timer_delete(host_timer);
1556 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1558 timer_t host_timer = (timer_t)(long)t->priv;
1559 struct itimerspec timeout;
1560 int64_t nearest_delta_us = INT64_MAX;
1561 int64_t current_us;
1563 if (!active_timers[QEMU_TIMER_REALTIME] &&
1564 !active_timers[QEMU_TIMER_VIRTUAL])
1565 return;
1567 nearest_delta_us = qemu_next_deadline_dyntick();
1569 /* check whether a timer is already running */
1570 if (timer_gettime(host_timer, &timeout)) {
1571 perror("gettime");
1572 fprintf(stderr, "Internal timer error: aborting\n");
1573 exit(1);
1575 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1576 if (current_us && current_us <= nearest_delta_us)
1577 return;
1579 timeout.it_interval.tv_sec = 0;
1580 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1581 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1582 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1583 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1584 perror("settime");
1585 fprintf(stderr, "Internal timer error: aborting\n");
1586 exit(1);
1590 #endif /* defined(__linux__) */
1592 static int unix_start_timer(struct qemu_alarm_timer *t)
1594 struct sigaction act;
1595 struct itimerval itv;
1596 int err;
1598 /* timer signal */
1599 sigfillset(&act.sa_mask);
1600 act.sa_flags = 0;
1601 act.sa_handler = host_alarm_handler;
1603 sigaction(SIGALRM, &act, NULL);
1605 itv.it_interval.tv_sec = 0;
1606 /* for i386 kernel 2.6 to get 1 ms */
1607 itv.it_interval.tv_usec = 999;
1608 itv.it_value.tv_sec = 0;
1609 itv.it_value.tv_usec = 10 * 1000;
1611 err = setitimer(ITIMER_REAL, &itv, NULL);
1612 if (err)
1613 return -1;
1615 return 0;
1618 static void unix_stop_timer(struct qemu_alarm_timer *t)
1620 struct itimerval itv;
1622 memset(&itv, 0, sizeof(itv));
1623 setitimer(ITIMER_REAL, &itv, NULL);
1626 #endif /* !defined(_WIN32) */
1628 static void try_to_rearm_timer(void *opaque)
1630 struct qemu_alarm_timer *t = opaque;
1631 #ifndef _WIN32
1632 ssize_t len;
1634 /* Drain the notify pipe */
1635 do {
1636 char buffer[512];
1637 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1638 } while ((len == -1 && errno == EINTR) || len > 0);
1639 #endif
1641 if (t->flags & ALARM_FLAG_EXPIRED) {
1642 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1643 qemu_rearm_alarm_timer(alarm_timer);
1647 #ifdef _WIN32
1649 static int win32_start_timer(struct qemu_alarm_timer *t)
1651 TIMECAPS tc;
1652 struct qemu_alarm_win32 *data = t->priv;
1653 UINT flags;
1655 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1656 if (!data->host_alarm) {
1657 perror("Failed CreateEvent");
1658 return -1;
1661 memset(&tc, 0, sizeof(tc));
1662 timeGetDevCaps(&tc, sizeof(tc));
1664 if (data->period < tc.wPeriodMin)
1665 data->period = tc.wPeriodMin;
1667 timeBeginPeriod(data->period);
1669 flags = TIME_CALLBACK_FUNCTION;
1670 if (alarm_has_dynticks(t))
1671 flags |= TIME_ONESHOT;
1672 else
1673 flags |= TIME_PERIODIC;
1675 data->timerId = timeSetEvent(1, // interval (ms)
1676 data->period, // resolution
1677 host_alarm_handler, // function
1678 (DWORD)t, // parameter
1679 flags);
1681 if (!data->timerId) {
1682 perror("Failed to initialize win32 alarm timer");
1684 timeEndPeriod(data->period);
1685 CloseHandle(data->host_alarm);
1686 return -1;
1689 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1691 return 0;
1694 static void win32_stop_timer(struct qemu_alarm_timer *t)
1696 struct qemu_alarm_win32 *data = t->priv;
1698 timeKillEvent(data->timerId);
1699 timeEndPeriod(data->period);
1701 CloseHandle(data->host_alarm);
1704 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1706 struct qemu_alarm_win32 *data = t->priv;
1707 uint64_t nearest_delta_us;
1709 if (!active_timers[QEMU_TIMER_REALTIME] &&
1710 !active_timers[QEMU_TIMER_VIRTUAL])
1711 return;
1713 nearest_delta_us = qemu_next_deadline_dyntick();
1714 nearest_delta_us /= 1000;
1716 timeKillEvent(data->timerId);
1718 data->timerId = timeSetEvent(1,
1719 data->period,
1720 host_alarm_handler,
1721 (DWORD)t,
1722 TIME_ONESHOT | TIME_PERIODIC);
1724 if (!data->timerId) {
1725 perror("Failed to re-arm win32 alarm timer");
1727 timeEndPeriod(data->period);
1728 CloseHandle(data->host_alarm);
1729 exit(1);
1733 #endif /* _WIN32 */
1735 static int init_timer_alarm(void)
1737 struct qemu_alarm_timer *t = NULL;
1738 int i, err = -1;
1740 #ifndef _WIN32
1741 int fds[2];
1743 err = pipe(fds);
1744 if (err == -1)
1745 return -errno;
1747 err = fcntl_setfl(fds[0], O_NONBLOCK);
1748 if (err < 0)
1749 goto fail;
1751 err = fcntl_setfl(fds[1], O_NONBLOCK);
1752 if (err < 0)
1753 goto fail;
1755 alarm_timer_rfd = fds[0];
1756 alarm_timer_wfd = fds[1];
1757 #endif
1759 for (i = 0; alarm_timers[i].name; i++) {
1760 t = &alarm_timers[i];
1762 err = t->start(t);
1763 if (!err)
1764 break;
1767 if (err) {
1768 err = -ENOENT;
1769 goto fail;
1772 #ifndef _WIN32
1773 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1774 try_to_rearm_timer, NULL, t);
1775 #endif
1777 alarm_timer = t;
1779 return 0;
1781 fail:
1782 #ifndef _WIN32
1783 close(fds[0]);
1784 close(fds[1]);
1785 #endif
1786 return err;
1789 static void quit_timers(void)
1791 alarm_timer->stop(alarm_timer);
1792 alarm_timer = NULL;
1795 /***********************************************************/
1796 /* host time/date access */
1797 void qemu_get_timedate(struct tm *tm, int offset)
1799 time_t ti;
1800 struct tm *ret;
1802 time(&ti);
1803 ti += offset;
1804 if (rtc_date_offset == -1) {
1805 if (rtc_utc)
1806 ret = gmtime(&ti);
1807 else
1808 ret = localtime(&ti);
1809 } else {
1810 ti -= rtc_date_offset;
1811 ret = gmtime(&ti);
1814 memcpy(tm, ret, sizeof(struct tm));
1817 int qemu_timedate_diff(struct tm *tm)
1819 time_t seconds;
1821 if (rtc_date_offset == -1)
1822 if (rtc_utc)
1823 seconds = mktimegm(tm);
1824 else
1825 seconds = mktime(tm);
1826 else
1827 seconds = mktimegm(tm) + rtc_date_offset;
1829 return seconds - time(NULL);
1832 #ifdef _WIN32
1833 static void socket_cleanup(void)
1835 WSACleanup();
1838 static int socket_init(void)
1840 WSADATA Data;
1841 int ret, err;
1843 ret = WSAStartup(MAKEWORD(2,2), &Data);
1844 if (ret != 0) {
1845 err = WSAGetLastError();
1846 fprintf(stderr, "WSAStartup: %d\n", err);
1847 return -1;
1849 atexit(socket_cleanup);
1850 return 0;
1852 #endif
1854 const char *get_opt_name(char *buf, int buf_size, const char *p)
1856 char *q;
1858 q = buf;
1859 while (*p != '\0' && *p != '=') {
1860 if (q && (q - buf) < buf_size - 1)
1861 *q++ = *p;
1862 p++;
1864 if (q)
1865 *q = '\0';
1867 return p;
1870 const char *get_opt_value(char *buf, int buf_size, const char *p)
1872 char *q;
1874 q = buf;
1875 while (*p != '\0') {
1876 if (*p == ',') {
1877 if (*(p + 1) != ',')
1878 break;
1879 p++;
1881 if (q && (q - buf) < buf_size - 1)
1882 *q++ = *p;
1883 p++;
1885 if (q)
1886 *q = '\0';
1888 return p;
1891 int get_param_value(char *buf, int buf_size,
1892 const char *tag, const char *str)
1894 const char *p;
1895 char option[128];
1897 p = str;
1898 for(;;) {
1899 p = get_opt_name(option, sizeof(option), p);
1900 if (*p != '=')
1901 break;
1902 p++;
1903 if (!strcmp(tag, option)) {
1904 (void)get_opt_value(buf, buf_size, p);
1905 return strlen(buf);
1906 } else {
1907 p = get_opt_value(NULL, 0, p);
1909 if (*p != ',')
1910 break;
1911 p++;
1913 return 0;
1916 int check_params(char *buf, int buf_size,
1917 const char * const *params, const char *str)
1919 const char *p;
1920 int i;
1922 p = str;
1923 for(;;) {
1924 p = get_opt_name(buf, buf_size, p);
1925 if (*p != '=')
1926 return -1;
1927 p++;
1928 for(i = 0; params[i] != NULL; i++)
1929 if (!strcmp(params[i], buf))
1930 break;
1931 if (params[i] == NULL)
1932 return -1;
1933 p = get_opt_value(NULL, 0, p);
1934 if (*p != ',')
1935 break;
1936 p++;
1938 return 0;
1941 /***********************************************************/
1942 /* Bluetooth support */
1943 static int nb_hcis;
1944 static int cur_hci;
1945 static struct HCIInfo *hci_table[MAX_NICS];
1947 static struct bt_vlan_s {
1948 struct bt_scatternet_s net;
1949 int id;
1950 struct bt_vlan_s *next;
1951 } *first_bt_vlan;
1953 /* find or alloc a new bluetooth "VLAN" */
1954 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1956 struct bt_vlan_s **pvlan, *vlan;
1957 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1958 if (vlan->id == id)
1959 return &vlan->net;
1961 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1962 vlan->id = id;
1963 pvlan = &first_bt_vlan;
1964 while (*pvlan != NULL)
1965 pvlan = &(*pvlan)->next;
1966 *pvlan = vlan;
1967 return &vlan->net;
1970 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1974 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1976 return -ENOTSUP;
1979 static struct HCIInfo null_hci = {
1980 .cmd_send = null_hci_send,
1981 .sco_send = null_hci_send,
1982 .acl_send = null_hci_send,
1983 .bdaddr_set = null_hci_addr_set,
1986 struct HCIInfo *qemu_next_hci(void)
1988 if (cur_hci == nb_hcis)
1989 return &null_hci;
1991 return hci_table[cur_hci++];
1994 static struct HCIInfo *hci_init(const char *str)
1996 char *endp;
1997 struct bt_scatternet_s *vlan = 0;
1999 if (!strcmp(str, "null"))
2000 /* null */
2001 return &null_hci;
2002 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2003 /* host[:hciN] */
2004 return bt_host_hci(str[4] ? str + 5 : "hci0");
2005 else if (!strncmp(str, "hci", 3)) {
2006 /* hci[,vlan=n] */
2007 if (str[3]) {
2008 if (!strncmp(str + 3, ",vlan=", 6)) {
2009 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2010 if (*endp)
2011 vlan = 0;
2013 } else
2014 vlan = qemu_find_bt_vlan(0);
2015 if (vlan)
2016 return bt_new_hci(vlan);
2019 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2021 return 0;
2024 static int bt_hci_parse(const char *str)
2026 struct HCIInfo *hci;
2027 bdaddr_t bdaddr;
2029 if (nb_hcis >= MAX_NICS) {
2030 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2031 return -1;
2034 hci = hci_init(str);
2035 if (!hci)
2036 return -1;
2038 bdaddr.b[0] = 0x52;
2039 bdaddr.b[1] = 0x54;
2040 bdaddr.b[2] = 0x00;
2041 bdaddr.b[3] = 0x12;
2042 bdaddr.b[4] = 0x34;
2043 bdaddr.b[5] = 0x56 + nb_hcis;
2044 hci->bdaddr_set(hci, bdaddr.b);
2046 hci_table[nb_hcis++] = hci;
2048 return 0;
2051 static void bt_vhci_add(int vlan_id)
2053 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2055 if (!vlan->slave)
2056 fprintf(stderr, "qemu: warning: adding a VHCI to "
2057 "an empty scatternet %i\n", vlan_id);
2059 bt_vhci_init(bt_new_hci(vlan));
2062 static struct bt_device_s *bt_device_add(const char *opt)
2064 struct bt_scatternet_s *vlan;
2065 int vlan_id = 0;
2066 char *endp = strstr(opt, ",vlan=");
2067 int len = (endp ? endp - opt : strlen(opt)) + 1;
2068 char devname[10];
2070 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2072 if (endp) {
2073 vlan_id = strtol(endp + 6, &endp, 0);
2074 if (*endp) {
2075 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2076 return 0;
2080 vlan = qemu_find_bt_vlan(vlan_id);
2082 if (!vlan->slave)
2083 fprintf(stderr, "qemu: warning: adding a slave device to "
2084 "an empty scatternet %i\n", vlan_id);
2086 if (!strcmp(devname, "keyboard"))
2087 return bt_keyboard_init(vlan);
2089 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2090 return 0;
2093 static int bt_parse(const char *opt)
2095 const char *endp, *p;
2096 int vlan;
2098 if (strstart(opt, "hci", &endp)) {
2099 if (!*endp || *endp == ',') {
2100 if (*endp)
2101 if (!strstart(endp, ",vlan=", 0))
2102 opt = endp + 1;
2104 return bt_hci_parse(opt);
2106 } else if (strstart(opt, "vhci", &endp)) {
2107 if (!*endp || *endp == ',') {
2108 if (*endp) {
2109 if (strstart(endp, ",vlan=", &p)) {
2110 vlan = strtol(p, (char **) &endp, 0);
2111 if (*endp) {
2112 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2113 return 1;
2115 } else {
2116 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2117 return 1;
2119 } else
2120 vlan = 0;
2122 bt_vhci_add(vlan);
2123 return 0;
2125 } else if (strstart(opt, "device:", &endp))
2126 return !bt_device_add(endp);
2128 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2129 return 1;
2132 /***********************************************************/
2133 /* QEMU Block devices */
2135 #define HD_ALIAS "index=%d,media=disk"
2136 #ifdef TARGET_PPC
2137 #define CDROM_ALIAS "index=1,media=cdrom"
2138 #else
2139 #define CDROM_ALIAS "index=2,media=cdrom"
2140 #endif
2141 #define FD_ALIAS "index=%d,if=floppy"
2142 #define PFLASH_ALIAS "if=pflash"
2143 #define MTD_ALIAS "if=mtd"
2144 #define SD_ALIAS "index=0,if=sd"
2146 static int drive_opt_get_free_idx(void)
2148 int index;
2150 for (index = 0; index < MAX_DRIVES; index++)
2151 if (!drives_opt[index].used) {
2152 drives_opt[index].used = 1;
2153 return index;
2156 return -1;
2159 static int drive_get_free_idx(void)
2161 int index;
2163 for (index = 0; index < MAX_DRIVES; index++)
2164 if (!drives_table[index].used) {
2165 drives_table[index].used = 1;
2166 return index;
2169 return -1;
2172 int drive_add(const char *file, const char *fmt, ...)
2174 va_list ap;
2175 int index = drive_opt_get_free_idx();
2177 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2178 fprintf(stderr, "qemu: too many drives\n");
2179 return -1;
2182 drives_opt[index].file = file;
2183 va_start(ap, fmt);
2184 vsnprintf(drives_opt[index].opt,
2185 sizeof(drives_opt[0].opt), fmt, ap);
2186 va_end(ap);
2188 nb_drives_opt++;
2189 return index;
2192 void drive_remove(int index)
2194 drives_opt[index].used = 0;
2195 nb_drives_opt--;
2198 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2200 int index;
2202 /* seek interface, bus and unit */
2204 for (index = 0; index < MAX_DRIVES; index++)
2205 if (drives_table[index].type == type &&
2206 drives_table[index].bus == bus &&
2207 drives_table[index].unit == unit &&
2208 drives_table[index].used)
2209 return index;
2211 return -1;
2214 int drive_get_max_bus(BlockInterfaceType type)
2216 int max_bus;
2217 int index;
2219 max_bus = -1;
2220 for (index = 0; index < nb_drives; index++) {
2221 if(drives_table[index].type == type &&
2222 drives_table[index].bus > max_bus)
2223 max_bus = drives_table[index].bus;
2225 return max_bus;
2228 const char *drive_get_serial(BlockDriverState *bdrv)
2230 int index;
2232 for (index = 0; index < nb_drives; index++)
2233 if (drives_table[index].bdrv == bdrv)
2234 return drives_table[index].serial;
2236 return "\0";
2239 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2241 int index;
2243 for (index = 0; index < nb_drives; index++)
2244 if (drives_table[index].bdrv == bdrv)
2245 return drives_table[index].onerror;
2247 return BLOCK_ERR_STOP_ENOSPC;
2250 static void bdrv_format_print(void *opaque, const char *name)
2252 fprintf(stderr, " %s", name);
2255 void drive_uninit(BlockDriverState *bdrv)
2257 int i;
2259 for (i = 0; i < MAX_DRIVES; i++)
2260 if (drives_table[i].bdrv == bdrv) {
2261 drives_table[i].bdrv = NULL;
2262 drives_table[i].used = 0;
2263 drive_remove(drives_table[i].drive_opt_idx);
2264 nb_drives--;
2265 break;
2269 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2271 char buf[128];
2272 char file[1024];
2273 char devname[128];
2274 char serial[21];
2275 const char *mediastr = "";
2276 BlockInterfaceType type;
2277 enum { MEDIA_DISK, MEDIA_CDROM } media;
2278 int bus_id, unit_id;
2279 int cyls, heads, secs, translation;
2280 BlockDriverState *bdrv;
2281 BlockDriver *drv = NULL;
2282 QEMUMachine *machine = opaque;
2283 int max_devs;
2284 int index;
2285 int cache;
2286 int bdrv_flags, onerror;
2287 int drives_table_idx;
2288 char *str = arg->opt;
2289 static const char * const params[] = { "bus", "unit", "if", "index",
2290 "cyls", "heads", "secs", "trans",
2291 "media", "snapshot", "file",
2292 "cache", "format", "serial", "werror",
2293 NULL };
2295 if (check_params(buf, sizeof(buf), params, str) < 0) {
2296 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2297 buf, str);
2298 return -1;
2301 file[0] = 0;
2302 cyls = heads = secs = 0;
2303 bus_id = 0;
2304 unit_id = -1;
2305 translation = BIOS_ATA_TRANSLATION_AUTO;
2306 index = -1;
2307 cache = 3;
2309 if (machine->use_scsi) {
2310 type = IF_SCSI;
2311 max_devs = MAX_SCSI_DEVS;
2312 pstrcpy(devname, sizeof(devname), "scsi");
2313 } else {
2314 type = IF_IDE;
2315 max_devs = MAX_IDE_DEVS;
2316 pstrcpy(devname, sizeof(devname), "ide");
2318 media = MEDIA_DISK;
2320 /* extract parameters */
2322 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2323 bus_id = strtol(buf, NULL, 0);
2324 if (bus_id < 0) {
2325 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2326 return -1;
2330 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2331 unit_id = strtol(buf, NULL, 0);
2332 if (unit_id < 0) {
2333 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2334 return -1;
2338 if (get_param_value(buf, sizeof(buf), "if", str)) {
2339 pstrcpy(devname, sizeof(devname), buf);
2340 if (!strcmp(buf, "ide")) {
2341 type = IF_IDE;
2342 max_devs = MAX_IDE_DEVS;
2343 } else if (!strcmp(buf, "scsi")) {
2344 type = IF_SCSI;
2345 max_devs = MAX_SCSI_DEVS;
2346 } else if (!strcmp(buf, "floppy")) {
2347 type = IF_FLOPPY;
2348 max_devs = 0;
2349 } else if (!strcmp(buf, "pflash")) {
2350 type = IF_PFLASH;
2351 max_devs = 0;
2352 } else if (!strcmp(buf, "mtd")) {
2353 type = IF_MTD;
2354 max_devs = 0;
2355 } else if (!strcmp(buf, "sd")) {
2356 type = IF_SD;
2357 max_devs = 0;
2358 } else if (!strcmp(buf, "virtio")) {
2359 type = IF_VIRTIO;
2360 max_devs = 0;
2361 } else {
2362 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2363 return -1;
2367 if (get_param_value(buf, sizeof(buf), "index", str)) {
2368 index = strtol(buf, NULL, 0);
2369 if (index < 0) {
2370 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2371 return -1;
2375 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2376 cyls = strtol(buf, NULL, 0);
2379 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2380 heads = strtol(buf, NULL, 0);
2383 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2384 secs = strtol(buf, NULL, 0);
2387 if (cyls || heads || secs) {
2388 if (cyls < 1 || cyls > 16383) {
2389 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2390 return -1;
2392 if (heads < 1 || heads > 16) {
2393 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2394 return -1;
2396 if (secs < 1 || secs > 63) {
2397 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2398 return -1;
2402 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2403 if (!cyls) {
2404 fprintf(stderr,
2405 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2406 str);
2407 return -1;
2409 if (!strcmp(buf, "none"))
2410 translation = BIOS_ATA_TRANSLATION_NONE;
2411 else if (!strcmp(buf, "lba"))
2412 translation = BIOS_ATA_TRANSLATION_LBA;
2413 else if (!strcmp(buf, "auto"))
2414 translation = BIOS_ATA_TRANSLATION_AUTO;
2415 else {
2416 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2417 return -1;
2421 if (get_param_value(buf, sizeof(buf), "media", str)) {
2422 if (!strcmp(buf, "disk")) {
2423 media = MEDIA_DISK;
2424 } else if (!strcmp(buf, "cdrom")) {
2425 if (cyls || secs || heads) {
2426 fprintf(stderr,
2427 "qemu: '%s' invalid physical CHS format\n", str);
2428 return -1;
2430 media = MEDIA_CDROM;
2431 } else {
2432 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2433 return -1;
2437 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2438 if (!strcmp(buf, "on"))
2439 snapshot = 1;
2440 else if (!strcmp(buf, "off"))
2441 snapshot = 0;
2442 else {
2443 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2444 return -1;
2448 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2449 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2450 cache = 0;
2451 else if (!strcmp(buf, "writethrough"))
2452 cache = 1;
2453 else if (!strcmp(buf, "writeback"))
2454 cache = 2;
2455 else {
2456 fprintf(stderr, "qemu: invalid cache option\n");
2457 return -1;
2461 if (get_param_value(buf, sizeof(buf), "format", str)) {
2462 if (strcmp(buf, "?") == 0) {
2463 fprintf(stderr, "qemu: Supported formats:");
2464 bdrv_iterate_format(bdrv_format_print, NULL);
2465 fprintf(stderr, "\n");
2466 return -1;
2468 drv = bdrv_find_format(buf);
2469 if (!drv) {
2470 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2471 return -1;
2475 if (arg->file == NULL)
2476 get_param_value(file, sizeof(file), "file", str);
2477 else
2478 pstrcpy(file, sizeof(file), arg->file);
2480 if (!get_param_value(serial, sizeof(serial), "serial", str))
2481 memset(serial, 0, sizeof(serial));
2483 onerror = BLOCK_ERR_STOP_ENOSPC;
2484 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2485 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2486 fprintf(stderr, "werror is no supported by this format\n");
2487 return -1;
2489 if (!strcmp(buf, "ignore"))
2490 onerror = BLOCK_ERR_IGNORE;
2491 else if (!strcmp(buf, "enospc"))
2492 onerror = BLOCK_ERR_STOP_ENOSPC;
2493 else if (!strcmp(buf, "stop"))
2494 onerror = BLOCK_ERR_STOP_ANY;
2495 else if (!strcmp(buf, "report"))
2496 onerror = BLOCK_ERR_REPORT;
2497 else {
2498 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2499 return -1;
2503 /* compute bus and unit according index */
2505 if (index != -1) {
2506 if (bus_id != 0 || unit_id != -1) {
2507 fprintf(stderr,
2508 "qemu: '%s' index cannot be used with bus and unit\n", str);
2509 return -1;
2511 if (max_devs == 0)
2513 unit_id = index;
2514 bus_id = 0;
2515 } else {
2516 unit_id = index % max_devs;
2517 bus_id = index / max_devs;
2521 /* if user doesn't specify a unit_id,
2522 * try to find the first free
2525 if (unit_id == -1) {
2526 unit_id = 0;
2527 while (drive_get_index(type, bus_id, unit_id) != -1) {
2528 unit_id++;
2529 if (max_devs && unit_id >= max_devs) {
2530 unit_id -= max_devs;
2531 bus_id++;
2536 /* check unit id */
2538 if (max_devs && unit_id >= max_devs) {
2539 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2540 str, unit_id, max_devs - 1);
2541 return -1;
2545 * ignore multiple definitions
2548 if (drive_get_index(type, bus_id, unit_id) != -1)
2549 return -2;
2551 /* init */
2553 if (type == IF_IDE || type == IF_SCSI)
2554 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2555 if (max_devs)
2556 snprintf(buf, sizeof(buf), "%s%i%s%i",
2557 devname, bus_id, mediastr, unit_id);
2558 else
2559 snprintf(buf, sizeof(buf), "%s%s%i",
2560 devname, mediastr, unit_id);
2561 bdrv = bdrv_new(buf);
2562 drives_table_idx = drive_get_free_idx();
2563 drives_table[drives_table_idx].bdrv = bdrv;
2564 drives_table[drives_table_idx].type = type;
2565 drives_table[drives_table_idx].bus = bus_id;
2566 drives_table[drives_table_idx].unit = unit_id;
2567 drives_table[drives_table_idx].onerror = onerror;
2568 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2569 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2570 nb_drives++;
2572 switch(type) {
2573 case IF_IDE:
2574 case IF_SCSI:
2575 switch(media) {
2576 case MEDIA_DISK:
2577 if (cyls != 0) {
2578 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2579 bdrv_set_translation_hint(bdrv, translation);
2581 break;
2582 case MEDIA_CDROM:
2583 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2584 break;
2586 break;
2587 case IF_SD:
2588 /* FIXME: This isn't really a floppy, but it's a reasonable
2589 approximation. */
2590 case IF_FLOPPY:
2591 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2592 break;
2593 case IF_PFLASH:
2594 case IF_MTD:
2595 case IF_VIRTIO:
2596 break;
2598 if (!file[0])
2599 return -2;
2600 bdrv_flags = 0;
2601 if (snapshot) {
2602 bdrv_flags |= BDRV_O_SNAPSHOT;
2603 cache = 2; /* always use write-back with snapshot */
2605 if (cache == 0) /* no caching */
2606 bdrv_flags |= BDRV_O_NOCACHE;
2607 else if (cache == 2) /* write-back */
2608 bdrv_flags |= BDRV_O_CACHE_WB;
2609 else if (cache == 3) /* not specified */
2610 bdrv_flags |= BDRV_O_CACHE_DEF;
2611 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2612 fprintf(stderr, "qemu: could not open disk image %s\n",
2613 file);
2614 return -1;
2616 if (bdrv_key_required(bdrv))
2617 autostart = 0;
2618 return drives_table_idx;
2621 /***********************************************************/
2622 /* USB devices */
2624 static USBPort *used_usb_ports;
2625 static USBPort *free_usb_ports;
2627 /* ??? Maybe change this to register a hub to keep track of the topology. */
2628 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2629 usb_attachfn attach)
2631 port->opaque = opaque;
2632 port->index = index;
2633 port->attach = attach;
2634 port->next = free_usb_ports;
2635 free_usb_ports = port;
2638 int usb_device_add_dev(USBDevice *dev)
2640 USBPort *port;
2642 /* Find a USB port to add the device to. */
2643 port = free_usb_ports;
2644 if (!port->next) {
2645 USBDevice *hub;
2647 /* Create a new hub and chain it on. */
2648 free_usb_ports = NULL;
2649 port->next = used_usb_ports;
2650 used_usb_ports = port;
2652 hub = usb_hub_init(VM_USB_HUB_SIZE);
2653 usb_attach(port, hub);
2654 port = free_usb_ports;
2657 free_usb_ports = port->next;
2658 port->next = used_usb_ports;
2659 used_usb_ports = port;
2660 usb_attach(port, dev);
2661 return 0;
2664 static int usb_device_add(const char *devname, int is_hotplug)
2666 const char *p;
2667 USBDevice *dev;
2669 if (!free_usb_ports)
2670 return -1;
2672 if (strstart(devname, "host:", &p)) {
2673 dev = usb_host_device_open(p);
2674 } else if (!strcmp(devname, "mouse")) {
2675 dev = usb_mouse_init();
2676 } else if (!strcmp(devname, "tablet")) {
2677 dev = usb_tablet_init();
2678 } else if (!strcmp(devname, "keyboard")) {
2679 dev = usb_keyboard_init();
2680 } else if (strstart(devname, "disk:", &p)) {
2681 BlockDriverState *bs;
2683 dev = usb_msd_init(p, &bs);
2684 if (!dev)
2685 return -1;
2686 if (bdrv_key_required(bs)) {
2687 autostart = 0;
2688 if (is_hotplug && monitor_read_bdrv_key(bs) < 0) {
2689 dev->handle_destroy(dev);
2690 return -1;
2693 } else if (!strcmp(devname, "wacom-tablet")) {
2694 dev = usb_wacom_init();
2695 } else if (strstart(devname, "serial:", &p)) {
2696 dev = usb_serial_init(p);
2697 #ifdef CONFIG_BRLAPI
2698 } else if (!strcmp(devname, "braille")) {
2699 dev = usb_baum_init();
2700 #endif
2701 } else if (strstart(devname, "net:", &p)) {
2702 int nic = nb_nics;
2704 if (net_client_init("nic", p) < 0)
2705 return -1;
2706 nd_table[nic].model = "usb";
2707 dev = usb_net_init(&nd_table[nic]);
2708 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2709 dev = usb_bt_init(devname[2] ? hci_init(p) :
2710 bt_new_hci(qemu_find_bt_vlan(0)));
2711 } else {
2712 return -1;
2714 if (!dev)
2715 return -1;
2717 return usb_device_add_dev(dev);
2720 int usb_device_del_addr(int bus_num, int addr)
2722 USBPort *port;
2723 USBPort **lastp;
2724 USBDevice *dev;
2726 if (!used_usb_ports)
2727 return -1;
2729 if (bus_num != 0)
2730 return -1;
2732 lastp = &used_usb_ports;
2733 port = used_usb_ports;
2734 while (port && port->dev->addr != addr) {
2735 lastp = &port->next;
2736 port = port->next;
2739 if (!port)
2740 return -1;
2742 dev = port->dev;
2743 *lastp = port->next;
2744 usb_attach(port, NULL);
2745 dev->handle_destroy(dev);
2746 port->next = free_usb_ports;
2747 free_usb_ports = port;
2748 return 0;
2751 static int usb_device_del(const char *devname)
2753 int bus_num, addr;
2754 const char *p;
2756 if (strstart(devname, "host:", &p))
2757 return usb_host_device_close(p);
2759 if (!used_usb_ports)
2760 return -1;
2762 p = strchr(devname, '.');
2763 if (!p)
2764 return -1;
2765 bus_num = strtoul(devname, NULL, 0);
2766 addr = strtoul(p + 1, NULL, 0);
2768 return usb_device_del_addr(bus_num, addr);
2771 void do_usb_add(const char *devname)
2773 usb_device_add(devname, 1);
2776 void do_usb_del(const char *devname)
2778 usb_device_del(devname);
2781 void usb_info(void)
2783 USBDevice *dev;
2784 USBPort *port;
2785 const char *speed_str;
2787 if (!usb_enabled) {
2788 term_printf("USB support not enabled\n");
2789 return;
2792 for (port = used_usb_ports; port; port = port->next) {
2793 dev = port->dev;
2794 if (!dev)
2795 continue;
2796 switch(dev->speed) {
2797 case USB_SPEED_LOW:
2798 speed_str = "1.5";
2799 break;
2800 case USB_SPEED_FULL:
2801 speed_str = "12";
2802 break;
2803 case USB_SPEED_HIGH:
2804 speed_str = "480";
2805 break;
2806 default:
2807 speed_str = "?";
2808 break;
2810 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2811 0, dev->addr, speed_str, dev->devname);
2815 /***********************************************************/
2816 /* PCMCIA/Cardbus */
2818 static struct pcmcia_socket_entry_s {
2819 struct pcmcia_socket_s *socket;
2820 struct pcmcia_socket_entry_s *next;
2821 } *pcmcia_sockets = 0;
2823 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2825 struct pcmcia_socket_entry_s *entry;
2827 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2828 entry->socket = socket;
2829 entry->next = pcmcia_sockets;
2830 pcmcia_sockets = entry;
2833 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2835 struct pcmcia_socket_entry_s *entry, **ptr;
2837 ptr = &pcmcia_sockets;
2838 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2839 if (entry->socket == socket) {
2840 *ptr = entry->next;
2841 qemu_free(entry);
2845 void pcmcia_info(void)
2847 struct pcmcia_socket_entry_s *iter;
2848 if (!pcmcia_sockets)
2849 term_printf("No PCMCIA sockets\n");
2851 for (iter = pcmcia_sockets; iter; iter = iter->next)
2852 term_printf("%s: %s\n", iter->socket->slot_string,
2853 iter->socket->attached ? iter->socket->card_string :
2854 "Empty");
2857 /***********************************************************/
2858 /* register display */
2860 void register_displaystate(DisplayState *ds)
2862 DisplayState **s;
2863 s = &display_state;
2864 while (*s != NULL)
2865 s = &(*s)->next;
2866 ds->next = NULL;
2867 *s = ds;
2870 DisplayState *get_displaystate(void)
2872 return display_state;
2875 /* dumb display */
2877 static void dumb_display_init(void)
2879 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2880 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2881 register_displaystate(ds);
2884 /***********************************************************/
2885 /* I/O handling */
2887 #define MAX_IO_HANDLERS 64
2889 typedef struct IOHandlerRecord {
2890 int fd;
2891 IOCanRWHandler *fd_read_poll;
2892 IOHandler *fd_read;
2893 IOHandler *fd_write;
2894 int deleted;
2895 void *opaque;
2896 /* temporary data */
2897 struct pollfd *ufd;
2898 struct IOHandlerRecord *next;
2899 } IOHandlerRecord;
2901 static IOHandlerRecord *first_io_handler;
2903 /* XXX: fd_read_poll should be suppressed, but an API change is
2904 necessary in the character devices to suppress fd_can_read(). */
2905 int qemu_set_fd_handler2(int fd,
2906 IOCanRWHandler *fd_read_poll,
2907 IOHandler *fd_read,
2908 IOHandler *fd_write,
2909 void *opaque)
2911 IOHandlerRecord **pioh, *ioh;
2913 if (!fd_read && !fd_write) {
2914 pioh = &first_io_handler;
2915 for(;;) {
2916 ioh = *pioh;
2917 if (ioh == NULL)
2918 break;
2919 if (ioh->fd == fd) {
2920 ioh->deleted = 1;
2921 break;
2923 pioh = &ioh->next;
2925 } else {
2926 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2927 if (ioh->fd == fd)
2928 goto found;
2930 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2931 ioh->next = first_io_handler;
2932 first_io_handler = ioh;
2933 found:
2934 ioh->fd = fd;
2935 ioh->fd_read_poll = fd_read_poll;
2936 ioh->fd_read = fd_read;
2937 ioh->fd_write = fd_write;
2938 ioh->opaque = opaque;
2939 ioh->deleted = 0;
2941 return 0;
2944 int qemu_set_fd_handler(int fd,
2945 IOHandler *fd_read,
2946 IOHandler *fd_write,
2947 void *opaque)
2949 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2952 #ifdef _WIN32
2953 /***********************************************************/
2954 /* Polling handling */
2956 typedef struct PollingEntry {
2957 PollingFunc *func;
2958 void *opaque;
2959 struct PollingEntry *next;
2960 } PollingEntry;
2962 static PollingEntry *first_polling_entry;
2964 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2966 PollingEntry **ppe, *pe;
2967 pe = qemu_mallocz(sizeof(PollingEntry));
2968 pe->func = func;
2969 pe->opaque = opaque;
2970 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2971 *ppe = pe;
2972 return 0;
2975 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2977 PollingEntry **ppe, *pe;
2978 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2979 pe = *ppe;
2980 if (pe->func == func && pe->opaque == opaque) {
2981 *ppe = pe->next;
2982 qemu_free(pe);
2983 break;
2988 /***********************************************************/
2989 /* Wait objects support */
2990 typedef struct WaitObjects {
2991 int num;
2992 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2993 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2994 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2995 } WaitObjects;
2997 static WaitObjects wait_objects = {0};
2999 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3001 WaitObjects *w = &wait_objects;
3003 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3004 return -1;
3005 w->events[w->num] = handle;
3006 w->func[w->num] = func;
3007 w->opaque[w->num] = opaque;
3008 w->num++;
3009 return 0;
3012 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3014 int i, found;
3015 WaitObjects *w = &wait_objects;
3017 found = 0;
3018 for (i = 0; i < w->num; i++) {
3019 if (w->events[i] == handle)
3020 found = 1;
3021 if (found) {
3022 w->events[i] = w->events[i + 1];
3023 w->func[i] = w->func[i + 1];
3024 w->opaque[i] = w->opaque[i + 1];
3027 if (found)
3028 w->num--;
3030 #endif
3032 /***********************************************************/
3033 /* ram save/restore */
3035 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3037 int v;
3039 v = qemu_get_byte(f);
3040 switch(v) {
3041 case 0:
3042 if (qemu_get_buffer(f, buf, len) != len)
3043 return -EIO;
3044 break;
3045 case 1:
3046 v = qemu_get_byte(f);
3047 memset(buf, v, len);
3048 break;
3049 default:
3050 return -EINVAL;
3053 if (qemu_file_has_error(f))
3054 return -EIO;
3056 return 0;
3059 static int ram_load_v1(QEMUFile *f, void *opaque)
3061 int ret;
3062 ram_addr_t i;
3064 if (qemu_get_be32(f) != phys_ram_size)
3065 return -EINVAL;
3066 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3067 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3068 if (ret)
3069 return ret;
3071 return 0;
3074 #define BDRV_HASH_BLOCK_SIZE 1024
3075 #define IOBUF_SIZE 4096
3076 #define RAM_CBLOCK_MAGIC 0xfabe
3078 typedef struct RamDecompressState {
3079 z_stream zstream;
3080 QEMUFile *f;
3081 uint8_t buf[IOBUF_SIZE];
3082 } RamDecompressState;
3084 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3086 int ret;
3087 memset(s, 0, sizeof(*s));
3088 s->f = f;
3089 ret = inflateInit(&s->zstream);
3090 if (ret != Z_OK)
3091 return -1;
3092 return 0;
3095 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3097 int ret, clen;
3099 s->zstream.avail_out = len;
3100 s->zstream.next_out = buf;
3101 while (s->zstream.avail_out > 0) {
3102 if (s->zstream.avail_in == 0) {
3103 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3104 return -1;
3105 clen = qemu_get_be16(s->f);
3106 if (clen > IOBUF_SIZE)
3107 return -1;
3108 qemu_get_buffer(s->f, s->buf, clen);
3109 s->zstream.avail_in = clen;
3110 s->zstream.next_in = s->buf;
3112 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3113 if (ret != Z_OK && ret != Z_STREAM_END) {
3114 return -1;
3117 return 0;
3120 static void ram_decompress_close(RamDecompressState *s)
3122 inflateEnd(&s->zstream);
3125 #define RAM_SAVE_FLAG_FULL 0x01
3126 #define RAM_SAVE_FLAG_COMPRESS 0x02
3127 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3128 #define RAM_SAVE_FLAG_PAGE 0x08
3129 #define RAM_SAVE_FLAG_EOS 0x10
3131 static int is_dup_page(uint8_t *page, uint8_t ch)
3133 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3134 uint32_t *array = (uint32_t *)page;
3135 int i;
3137 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3138 if (array[i] != val)
3139 return 0;
3142 return 1;
3145 static int ram_save_block(QEMUFile *f)
3147 static ram_addr_t current_addr = 0;
3148 ram_addr_t saved_addr = current_addr;
3149 ram_addr_t addr = 0;
3150 int found = 0;
3152 while (addr < phys_ram_size) {
3153 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3154 uint8_t ch;
3156 cpu_physical_memory_reset_dirty(current_addr,
3157 current_addr + TARGET_PAGE_SIZE,
3158 MIGRATION_DIRTY_FLAG);
3160 ch = *(phys_ram_base + current_addr);
3162 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3163 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3164 qemu_put_byte(f, ch);
3165 } else {
3166 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3167 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3170 found = 1;
3171 break;
3173 addr += TARGET_PAGE_SIZE;
3174 current_addr = (saved_addr + addr) % phys_ram_size;
3177 return found;
3180 static ram_addr_t ram_save_threshold = 10;
3182 static ram_addr_t ram_save_remaining(void)
3184 ram_addr_t addr;
3185 ram_addr_t count = 0;
3187 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3188 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3189 count++;
3192 return count;
3195 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3197 ram_addr_t addr;
3199 if (stage == 1) {
3200 /* Make sure all dirty bits are set */
3201 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3202 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3203 cpu_physical_memory_set_dirty(addr);
3206 /* Enable dirty memory tracking */
3207 cpu_physical_memory_set_dirty_tracking(1);
3209 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3212 while (!qemu_file_rate_limit(f)) {
3213 int ret;
3215 ret = ram_save_block(f);
3216 if (ret == 0) /* no more blocks */
3217 break;
3220 /* try transferring iterative blocks of memory */
3222 if (stage == 3) {
3223 cpu_physical_memory_set_dirty_tracking(0);
3225 /* flush all remaining blocks regardless of rate limiting */
3226 while (ram_save_block(f) != 0);
3229 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3231 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3234 static int ram_load_dead(QEMUFile *f, void *opaque)
3236 RamDecompressState s1, *s = &s1;
3237 uint8_t buf[10];
3238 ram_addr_t i;
3240 if (ram_decompress_open(s, f) < 0)
3241 return -EINVAL;
3242 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3243 if (ram_decompress_buf(s, buf, 1) < 0) {
3244 fprintf(stderr, "Error while reading ram block header\n");
3245 goto error;
3247 if (buf[0] == 0) {
3248 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3249 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3250 goto error;
3252 } else {
3253 error:
3254 printf("Error block header\n");
3255 return -EINVAL;
3258 ram_decompress_close(s);
3260 return 0;
3263 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3265 ram_addr_t addr;
3266 int flags;
3268 if (version_id == 1)
3269 return ram_load_v1(f, opaque);
3271 if (version_id == 2) {
3272 if (qemu_get_be32(f) != phys_ram_size)
3273 return -EINVAL;
3274 return ram_load_dead(f, opaque);
3277 if (version_id != 3)
3278 return -EINVAL;
3280 do {
3281 addr = qemu_get_be64(f);
3283 flags = addr & ~TARGET_PAGE_MASK;
3284 addr &= TARGET_PAGE_MASK;
3286 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3287 if (addr != phys_ram_size)
3288 return -EINVAL;
3291 if (flags & RAM_SAVE_FLAG_FULL) {
3292 if (ram_load_dead(f, opaque) < 0)
3293 return -EINVAL;
3296 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3297 uint8_t ch = qemu_get_byte(f);
3298 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3299 } else if (flags & RAM_SAVE_FLAG_PAGE)
3300 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3301 } while (!(flags & RAM_SAVE_FLAG_EOS));
3303 return 0;
3306 void qemu_service_io(void)
3308 CPUState *env = cpu_single_env;
3309 if (env) {
3310 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3311 #ifdef USE_KQEMU
3312 if (env->kqemu_enabled) {
3313 kqemu_cpu_interrupt(env);
3315 #endif
3319 /***********************************************************/
3320 /* bottom halves (can be seen as timers which expire ASAP) */
3322 struct QEMUBH {
3323 QEMUBHFunc *cb;
3324 void *opaque;
3325 int scheduled;
3326 int idle;
3327 int deleted;
3328 QEMUBH *next;
3331 static QEMUBH *first_bh = NULL;
3333 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3335 QEMUBH *bh;
3336 bh = qemu_mallocz(sizeof(QEMUBH));
3337 bh->cb = cb;
3338 bh->opaque = opaque;
3339 bh->next = first_bh;
3340 first_bh = bh;
3341 return bh;
3344 int qemu_bh_poll(void)
3346 QEMUBH *bh, **bhp;
3347 int ret;
3349 ret = 0;
3350 for (bh = first_bh; bh; bh = bh->next) {
3351 if (!bh->deleted && bh->scheduled) {
3352 bh->scheduled = 0;
3353 if (!bh->idle)
3354 ret = 1;
3355 bh->idle = 0;
3356 bh->cb(bh->opaque);
3360 /* remove deleted bhs */
3361 bhp = &first_bh;
3362 while (*bhp) {
3363 bh = *bhp;
3364 if (bh->deleted) {
3365 *bhp = bh->next;
3366 qemu_free(bh);
3367 } else
3368 bhp = &bh->next;
3371 return ret;
3374 void qemu_bh_schedule_idle(QEMUBH *bh)
3376 if (bh->scheduled)
3377 return;
3378 bh->scheduled = 1;
3379 bh->idle = 1;
3382 void qemu_bh_schedule(QEMUBH *bh)
3384 CPUState *env = cpu_single_env;
3385 if (bh->scheduled)
3386 return;
3387 bh->scheduled = 1;
3388 bh->idle = 0;
3389 /* stop the currently executing CPU to execute the BH ASAP */
3390 if (env) {
3391 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3395 void qemu_bh_cancel(QEMUBH *bh)
3397 bh->scheduled = 0;
3400 void qemu_bh_delete(QEMUBH *bh)
3402 bh->scheduled = 0;
3403 bh->deleted = 1;
3406 static void qemu_bh_update_timeout(int *timeout)
3408 QEMUBH *bh;
3410 for (bh = first_bh; bh; bh = bh->next) {
3411 if (!bh->deleted && bh->scheduled) {
3412 if (bh->idle) {
3413 /* idle bottom halves will be polled at least
3414 * every 10ms */
3415 *timeout = MIN(10, *timeout);
3416 } else {
3417 /* non-idle bottom halves will be executed
3418 * immediately */
3419 *timeout = 0;
3420 break;
3426 /***********************************************************/
3427 /* machine registration */
3429 static QEMUMachine *first_machine = NULL;
3430 QEMUMachine *current_machine = NULL;
3432 int qemu_register_machine(QEMUMachine *m)
3434 QEMUMachine **pm;
3435 pm = &first_machine;
3436 while (*pm != NULL)
3437 pm = &(*pm)->next;
3438 m->next = NULL;
3439 *pm = m;
3440 return 0;
3443 static QEMUMachine *find_machine(const char *name)
3445 QEMUMachine *m;
3447 for(m = first_machine; m != NULL; m = m->next) {
3448 if (!strcmp(m->name, name))
3449 return m;
3451 return NULL;
3454 /***********************************************************/
3455 /* main execution loop */
3457 static void gui_update(void *opaque)
3459 uint64_t interval = GUI_REFRESH_INTERVAL;
3460 DisplayState *ds = opaque;
3461 DisplayChangeListener *dcl = ds->listeners;
3463 dpy_refresh(ds);
3465 while (dcl != NULL) {
3466 if (dcl->gui_timer_interval &&
3467 dcl->gui_timer_interval < interval)
3468 interval = dcl->gui_timer_interval;
3469 dcl = dcl->next;
3471 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3474 static void nographic_update(void *opaque)
3476 uint64_t interval = GUI_REFRESH_INTERVAL;
3478 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3481 struct vm_change_state_entry {
3482 VMChangeStateHandler *cb;
3483 void *opaque;
3484 LIST_ENTRY (vm_change_state_entry) entries;
3487 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3489 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3490 void *opaque)
3492 VMChangeStateEntry *e;
3494 e = qemu_mallocz(sizeof (*e));
3496 e->cb = cb;
3497 e->opaque = opaque;
3498 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3499 return e;
3502 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3504 LIST_REMOVE (e, entries);
3505 qemu_free (e);
3508 static void vm_state_notify(int running, int reason)
3510 VMChangeStateEntry *e;
3512 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3513 e->cb(e->opaque, running, reason);
3517 void vm_start(void)
3519 if (!vm_running) {
3520 cpu_enable_ticks();
3521 vm_running = 1;
3522 vm_state_notify(1, 0);
3523 qemu_rearm_alarm_timer(alarm_timer);
3527 void vm_stop(int reason)
3529 if (vm_running) {
3530 cpu_disable_ticks();
3531 vm_running = 0;
3532 vm_state_notify(0, reason);
3536 /* reset/shutdown handler */
3538 typedef struct QEMUResetEntry {
3539 QEMUResetHandler *func;
3540 void *opaque;
3541 struct QEMUResetEntry *next;
3542 } QEMUResetEntry;
3544 static QEMUResetEntry *first_reset_entry;
3545 static int reset_requested;
3546 static int shutdown_requested;
3547 static int powerdown_requested;
3549 int qemu_shutdown_requested(void)
3551 int r = shutdown_requested;
3552 shutdown_requested = 0;
3553 return r;
3556 int qemu_reset_requested(void)
3558 int r = reset_requested;
3559 reset_requested = 0;
3560 return r;
3563 int qemu_powerdown_requested(void)
3565 int r = powerdown_requested;
3566 powerdown_requested = 0;
3567 return r;
3570 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3572 QEMUResetEntry **pre, *re;
3574 pre = &first_reset_entry;
3575 while (*pre != NULL)
3576 pre = &(*pre)->next;
3577 re = qemu_mallocz(sizeof(QEMUResetEntry));
3578 re->func = func;
3579 re->opaque = opaque;
3580 re->next = NULL;
3581 *pre = re;
3584 void qemu_system_reset(void)
3586 QEMUResetEntry *re;
3588 /* reset all devices */
3589 for(re = first_reset_entry; re != NULL; re = re->next) {
3590 re->func(re->opaque);
3594 void qemu_system_reset_request(void)
3596 if (no_reboot) {
3597 shutdown_requested = 1;
3598 } else {
3599 reset_requested = 1;
3601 if (cpu_single_env)
3602 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3605 void qemu_system_shutdown_request(void)
3607 shutdown_requested = 1;
3608 if (cpu_single_env)
3609 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3612 void qemu_system_powerdown_request(void)
3614 powerdown_requested = 1;
3615 if (cpu_single_env)
3616 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3619 #ifdef _WIN32
3620 static void host_main_loop_wait(int *timeout)
3622 int ret, ret2, i;
3623 PollingEntry *pe;
3626 /* XXX: need to suppress polling by better using win32 events */
3627 ret = 0;
3628 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3629 ret |= pe->func(pe->opaque);
3631 if (ret == 0) {
3632 int err;
3633 WaitObjects *w = &wait_objects;
3635 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3636 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3637 if (w->func[ret - WAIT_OBJECT_0])
3638 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3640 /* Check for additional signaled events */
3641 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3643 /* Check if event is signaled */
3644 ret2 = WaitForSingleObject(w->events[i], 0);
3645 if(ret2 == WAIT_OBJECT_0) {
3646 if (w->func[i])
3647 w->func[i](w->opaque[i]);
3648 } else if (ret2 == WAIT_TIMEOUT) {
3649 } else {
3650 err = GetLastError();
3651 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3654 } else if (ret == WAIT_TIMEOUT) {
3655 } else {
3656 err = GetLastError();
3657 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3661 *timeout = 0;
3663 #else
3664 static void host_main_loop_wait(int *timeout)
3667 #endif
3669 void main_loop_wait(int timeout)
3671 IOHandlerRecord *ioh;
3672 fd_set rfds, wfds, xfds;
3673 int ret, nfds;
3674 struct timeval tv;
3676 qemu_bh_update_timeout(&timeout);
3678 host_main_loop_wait(&timeout);
3680 /* poll any events */
3681 /* XXX: separate device handlers from system ones */
3682 nfds = -1;
3683 FD_ZERO(&rfds);
3684 FD_ZERO(&wfds);
3685 FD_ZERO(&xfds);
3686 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3687 if (ioh->deleted)
3688 continue;
3689 if (ioh->fd_read &&
3690 (!ioh->fd_read_poll ||
3691 ioh->fd_read_poll(ioh->opaque) != 0)) {
3692 FD_SET(ioh->fd, &rfds);
3693 if (ioh->fd > nfds)
3694 nfds = ioh->fd;
3696 if (ioh->fd_write) {
3697 FD_SET(ioh->fd, &wfds);
3698 if (ioh->fd > nfds)
3699 nfds = ioh->fd;
3703 tv.tv_sec = timeout / 1000;
3704 tv.tv_usec = (timeout % 1000) * 1000;
3706 #if defined(CONFIG_SLIRP)
3707 if (slirp_is_inited()) {
3708 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3710 #endif
3711 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3712 if (ret > 0) {
3713 IOHandlerRecord **pioh;
3715 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3716 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3717 ioh->fd_read(ioh->opaque);
3719 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3720 ioh->fd_write(ioh->opaque);
3724 /* remove deleted IO handlers */
3725 pioh = &first_io_handler;
3726 while (*pioh) {
3727 ioh = *pioh;
3728 if (ioh->deleted) {
3729 *pioh = ioh->next;
3730 qemu_free(ioh);
3731 } else
3732 pioh = &ioh->next;
3735 #if defined(CONFIG_SLIRP)
3736 if (slirp_is_inited()) {
3737 if (ret < 0) {
3738 FD_ZERO(&rfds);
3739 FD_ZERO(&wfds);
3740 FD_ZERO(&xfds);
3742 slirp_select_poll(&rfds, &wfds, &xfds);
3744 #endif
3746 /* vm time timers */
3747 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3748 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3749 qemu_get_clock(vm_clock));
3751 /* real time timers */
3752 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3753 qemu_get_clock(rt_clock));
3755 /* Check bottom-halves last in case any of the earlier events triggered
3756 them. */
3757 qemu_bh_poll();
3761 static int main_loop(void)
3763 int ret, timeout;
3764 #ifdef CONFIG_PROFILER
3765 int64_t ti;
3766 #endif
3767 CPUState *env;
3769 cur_cpu = first_cpu;
3770 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3771 for(;;) {
3772 if (vm_running) {
3774 for(;;) {
3775 /* get next cpu */
3776 env = next_cpu;
3777 #ifdef CONFIG_PROFILER
3778 ti = profile_getclock();
3779 #endif
3780 if (use_icount) {
3781 int64_t count;
3782 int decr;
3783 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3784 env->icount_decr.u16.low = 0;
3785 env->icount_extra = 0;
3786 count = qemu_next_deadline();
3787 count = (count + (1 << icount_time_shift) - 1)
3788 >> icount_time_shift;
3789 qemu_icount += count;
3790 decr = (count > 0xffff) ? 0xffff : count;
3791 count -= decr;
3792 env->icount_decr.u16.low = decr;
3793 env->icount_extra = count;
3795 ret = cpu_exec(env);
3796 #ifdef CONFIG_PROFILER
3797 qemu_time += profile_getclock() - ti;
3798 #endif
3799 if (use_icount) {
3800 /* Fold pending instructions back into the
3801 instruction counter, and clear the interrupt flag. */
3802 qemu_icount -= (env->icount_decr.u16.low
3803 + env->icount_extra);
3804 env->icount_decr.u32 = 0;
3805 env->icount_extra = 0;
3807 next_cpu = env->next_cpu ?: first_cpu;
3808 if (event_pending && likely(ret != EXCP_DEBUG)) {
3809 ret = EXCP_INTERRUPT;
3810 event_pending = 0;
3811 break;
3813 if (ret == EXCP_HLT) {
3814 /* Give the next CPU a chance to run. */
3815 cur_cpu = env;
3816 continue;
3818 if (ret != EXCP_HALTED)
3819 break;
3820 /* all CPUs are halted ? */
3821 if (env == cur_cpu)
3822 break;
3824 cur_cpu = env;
3826 if (shutdown_requested) {
3827 ret = EXCP_INTERRUPT;
3828 if (no_shutdown) {
3829 vm_stop(0);
3830 no_shutdown = 0;
3832 else
3833 break;
3835 if (reset_requested) {
3836 reset_requested = 0;
3837 qemu_system_reset();
3838 ret = EXCP_INTERRUPT;
3840 if (powerdown_requested) {
3841 powerdown_requested = 0;
3842 qemu_system_powerdown();
3843 ret = EXCP_INTERRUPT;
3845 if (unlikely(ret == EXCP_DEBUG)) {
3846 gdb_set_stop_cpu(cur_cpu);
3847 vm_stop(EXCP_DEBUG);
3849 /* If all cpus are halted then wait until the next IRQ */
3850 /* XXX: use timeout computed from timers */
3851 if (ret == EXCP_HALTED) {
3852 if (use_icount) {
3853 int64_t add;
3854 int64_t delta;
3855 /* Advance virtual time to the next event. */
3856 if (use_icount == 1) {
3857 /* When not using an adaptive execution frequency
3858 we tend to get badly out of sync with real time,
3859 so just delay for a reasonable amount of time. */
3860 delta = 0;
3861 } else {
3862 delta = cpu_get_icount() - cpu_get_clock();
3864 if (delta > 0) {
3865 /* If virtual time is ahead of real time then just
3866 wait for IO. */
3867 timeout = (delta / 1000000) + 1;
3868 } else {
3869 /* Wait for either IO to occur or the next
3870 timer event. */
3871 add = qemu_next_deadline();
3872 /* We advance the timer before checking for IO.
3873 Limit the amount we advance so that early IO
3874 activity won't get the guest too far ahead. */
3875 if (add > 10000000)
3876 add = 10000000;
3877 delta += add;
3878 add = (add + (1 << icount_time_shift) - 1)
3879 >> icount_time_shift;
3880 qemu_icount += add;
3881 timeout = delta / 1000000;
3882 if (timeout < 0)
3883 timeout = 0;
3885 } else {
3886 timeout = 5000;
3888 } else {
3889 timeout = 0;
3891 } else {
3892 if (shutdown_requested) {
3893 ret = EXCP_INTERRUPT;
3894 break;
3896 timeout = 5000;
3898 #ifdef CONFIG_PROFILER
3899 ti = profile_getclock();
3900 #endif
3901 main_loop_wait(timeout);
3902 #ifdef CONFIG_PROFILER
3903 dev_time += profile_getclock() - ti;
3904 #endif
3906 cpu_disable_ticks();
3907 return ret;
3910 static void help(int exitcode)
3912 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3913 and qemu-doc.texi */
3914 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3915 "usage: %s [options] [disk_image]\n"
3916 "\n"
3917 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3918 "\n"
3919 "Standard options:\n"
3920 "-h or -help display this help and exit\n"
3921 "-M machine select emulated machine (-M ? for list)\n"
3922 "-cpu cpu select CPU (-cpu ? for list)\n"
3923 "-smp n set the number of CPUs to 'n' [default=1]\n"
3924 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3925 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3926 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3927 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3928 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3929 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3930 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3931 " use 'file' as a drive image\n"
3932 "-mtdblock file use 'file' as on-board Flash memory image\n"
3933 "-sd file use 'file' as SecureDigital card image\n"
3934 "-pflash file use 'file' as a parallel flash image\n"
3935 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3936 "-snapshot write to temporary files instead of disk image files\n"
3937 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3938 #ifndef _WIN32
3939 "-k language use keyboard layout (for example \"fr\" for French)\n"
3940 #endif
3941 #ifdef HAS_AUDIO
3942 "-audio-help print list of audio drivers and their options\n"
3943 "-soundhw c1,... enable audio support\n"
3944 " and only specified sound cards (comma separated list)\n"
3945 " use -soundhw ? to get the list of supported cards\n"
3946 " use -soundhw all to enable all of them\n"
3947 #endif
3948 "-usb enable the USB driver (will be the default soon)\n"
3949 "-usbdevice name add the host or guest USB device 'name'\n"
3950 "-name string set the name of the guest\n"
3951 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
3952 " specify machine UUID\n"
3953 "\n"
3954 "Display options:\n"
3955 "-nographic disable graphical output and redirect serial I/Os to console\n"
3956 #ifdef CONFIG_CURSES
3957 "-curses use a curses/ncurses interface instead of SDL\n"
3958 #endif
3959 #ifdef CONFIG_SDL
3960 "-no-frame open SDL window without a frame and window decorations\n"
3961 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3962 "-no-quit disable SDL window close capability\n"
3963 "-sdl enable SDL\n"
3964 #endif
3965 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3966 "-vga [std|cirrus|vmware|none]\n"
3967 " select video card type\n"
3968 "-full-screen start in full screen\n"
3969 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3970 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3971 #endif
3972 "-vnc display start a VNC server on display\n"
3973 "\n"
3974 "Network options:\n"
3975 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3976 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3977 #ifdef CONFIG_SLIRP
3978 "-net user[,vlan=n][,name=str][,hostname=host]\n"
3979 " connect the user mode network stack to VLAN 'n' and send\n"
3980 " hostname 'host' to DHCP clients\n"
3981 #endif
3982 #ifdef _WIN32
3983 "-net tap[,vlan=n][,name=str],ifname=name\n"
3984 " connect the host TAP network interface to VLAN 'n'\n"
3985 #else
3986 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
3987 " connect the host TAP network interface to VLAN 'n' and use the\n"
3988 " network scripts 'file' (default=%s)\n"
3989 " and 'dfile' (default=%s);\n"
3990 " use '[down]script=no' to disable script execution;\n"
3991 " use 'fd=h' to connect to an already opened TAP interface\n"
3992 #endif
3993 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3994 " connect the vlan 'n' to another VLAN using a socket connection\n"
3995 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
3996 " connect the vlan 'n' to multicast maddr and port\n"
3997 #ifdef CONFIG_VDE
3998 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
3999 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4000 " on host and listening for incoming connections on 'socketpath'.\n"
4001 " Use group 'groupname' and mode 'octalmode' to change default\n"
4002 " ownership and permissions for communication port.\n"
4003 #endif
4004 "-net none use it alone to have zero network devices; if no -net option\n"
4005 " is provided, the default is '-net nic -net user'\n"
4006 #ifdef CONFIG_SLIRP
4007 "-tftp dir allow tftp access to files in dir [-net user]\n"
4008 "-bootp file advertise file in BOOTP replies\n"
4009 #ifndef _WIN32
4010 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4011 #endif
4012 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4013 " redirect TCP or UDP connections from host to guest [-net user]\n"
4014 #endif
4015 "\n"
4016 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
4017 "-bt hci,host[:id]\n"
4018 " use host's HCI with the given name\n"
4019 "-bt hci[,vlan=n]\n"
4020 " emulate a standard HCI in virtual scatternet 'n'\n"
4021 "-bt vhci[,vlan=n]\n"
4022 " add host computer to virtual scatternet 'n' using VHCI\n"
4023 "-bt device:dev[,vlan=n]\n"
4024 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4025 "\n"
4026 #ifdef TARGET_I386
4027 "\n"
4028 "i386 target only:\n"
4029 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4030 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4031 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4032 "-no-acpi disable ACPI\n"
4033 "-no-hpet disable HPET\n"
4034 "-acpitable [sig=str][,rev=n][,oem_id=str][,oem_table_id=str][,oem_rev=n][,asl_compiler_id=str][,asl_compiler_rev=n][,data=file1[:file2]...]\n"
4035 " ACPI table description\n"
4036 #endif
4037 "Linux boot specific:\n"
4038 "-kernel bzImage use 'bzImage' as kernel image\n"
4039 "-append cmdline use 'cmdline' as kernel command line\n"
4040 "-initrd file use 'file' as initial ram disk\n"
4041 "\n"
4042 "Debug/Expert options:\n"
4043 "-serial dev redirect the serial port to char device 'dev'\n"
4044 "-parallel dev redirect the parallel port to char device 'dev'\n"
4045 "-monitor dev redirect the monitor to char device 'dev'\n"
4046 "-pidfile file write PID to 'file'\n"
4047 "-S freeze CPU at startup (use 'c' to start execution)\n"
4048 "-s wait gdb connection to port\n"
4049 "-p port set gdb connection port [default=%s]\n"
4050 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4051 "-hdachs c,h,s[,t]\n"
4052 " force hard disk 0 physical geometry and the optional BIOS\n"
4053 " translation (t=none or lba) (usually qemu can guess them)\n"
4054 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4055 "-bios file set the filename for the BIOS\n"
4056 #ifdef USE_KQEMU
4057 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4058 "-no-kqemu disable KQEMU kernel module usage\n"
4059 #endif
4060 #ifdef CONFIG_KVM
4061 "-enable-kvm enable KVM full virtualization support\n"
4062 #endif
4063 "-no-reboot exit instead of rebooting\n"
4064 "-no-shutdown stop before shutdown\n"
4065 "-loadvm [tag|id]\n"
4066 " start right away with a saved state (loadvm in monitor)\n"
4067 #ifndef _WIN32
4068 "-daemonize daemonize QEMU after initializing\n"
4069 #endif
4070 "-option-rom rom load a file, rom, into the option ROM space\n"
4071 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4072 "-prom-env variable=value\n"
4073 " set OpenBIOS nvram variables\n"
4074 #endif
4075 "-clock force the use of the given methods for timer alarm.\n"
4076 " To see what timers are available use -clock ?\n"
4077 "-localtime set the real time clock to local time [default=utc]\n"
4078 "-startdate select initial date of the clock\n"
4079 "-icount [N|auto]\n"
4080 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4081 "-echr chr set terminal escape character instead of ctrl-a\n"
4082 "-virtioconsole c\n"
4083 " set virtio console\n"
4084 "-show-cursor show cursor\n"
4085 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4086 "-semihosting semihosting mode\n"
4087 #endif
4088 #if defined(TARGET_ARM)
4089 "-old-param old param mode\n"
4090 #endif
4091 "-tb-size n set TB size\n"
4092 "-incoming p prepare for incoming migration, listen on port p\n"
4093 #ifndef _WIN32
4094 "-chroot dir Chroot to dir just before starting the VM.\n"
4095 "-runas user Change to user id user just before starting the VM.\n"
4096 #endif
4097 "\n"
4098 "During emulation, the following keys are useful:\n"
4099 "ctrl-alt-f toggle full screen\n"
4100 "ctrl-alt-n switch to virtual console 'n'\n"
4101 "ctrl-alt toggle mouse and keyboard grab\n"
4102 "\n"
4103 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4105 "qemu",
4106 DEFAULT_RAM_SIZE,
4107 #ifndef _WIN32
4108 DEFAULT_NETWORK_SCRIPT,
4109 DEFAULT_NETWORK_DOWN_SCRIPT,
4110 #endif
4111 DEFAULT_GDBSTUB_PORT,
4112 "/tmp/qemu.log");
4113 exit(exitcode);
4116 #define HAS_ARG 0x0001
4118 enum {
4119 /* Please keep in synch with help, qemu_options[] and
4120 qemu-doc.texi */
4121 /* Standard options: */
4122 QEMU_OPTION_h,
4123 QEMU_OPTION_M,
4124 QEMU_OPTION_cpu,
4125 QEMU_OPTION_smp,
4126 QEMU_OPTION_fda,
4127 QEMU_OPTION_fdb,
4128 QEMU_OPTION_hda,
4129 QEMU_OPTION_hdb,
4130 QEMU_OPTION_hdc,
4131 QEMU_OPTION_hdd,
4132 QEMU_OPTION_cdrom,
4133 QEMU_OPTION_drive,
4134 QEMU_OPTION_mtdblock,
4135 QEMU_OPTION_sd,
4136 QEMU_OPTION_pflash,
4137 QEMU_OPTION_boot,
4138 QEMU_OPTION_snapshot,
4139 QEMU_OPTION_m,
4140 QEMU_OPTION_k,
4141 QEMU_OPTION_audio_help,
4142 QEMU_OPTION_soundhw,
4143 QEMU_OPTION_usb,
4144 QEMU_OPTION_usbdevice,
4145 QEMU_OPTION_name,
4146 QEMU_OPTION_uuid,
4148 /* Display options: */
4149 QEMU_OPTION_nographic,
4150 QEMU_OPTION_curses,
4151 QEMU_OPTION_no_frame,
4152 QEMU_OPTION_alt_grab,
4153 QEMU_OPTION_no_quit,
4154 QEMU_OPTION_sdl,
4155 QEMU_OPTION_portrait,
4156 QEMU_OPTION_vga,
4157 QEMU_OPTION_full_screen,
4158 QEMU_OPTION_g,
4159 QEMU_OPTION_vnc,
4161 /* Network options: */
4162 QEMU_OPTION_net,
4163 QEMU_OPTION_tftp,
4164 QEMU_OPTION_bootp,
4165 QEMU_OPTION_smb,
4166 QEMU_OPTION_redir,
4167 QEMU_OPTION_bt,
4169 /* i386 target only: */
4170 QEMU_OPTION_win2k_hack,
4171 QEMU_OPTION_rtc_td_hack,
4172 QEMU_OPTION_no_fd_bootchk,
4173 QEMU_OPTION_no_acpi,
4174 QEMU_OPTION_no_hpet,
4175 QEMU_OPTION_acpitable,
4177 /* Linux boot specific: */
4178 QEMU_OPTION_kernel,
4179 QEMU_OPTION_append,
4180 QEMU_OPTION_initrd,
4182 /* Debug/Expert options: */
4183 QEMU_OPTION_serial,
4184 QEMU_OPTION_parallel,
4185 QEMU_OPTION_monitor,
4186 QEMU_OPTION_pidfile,
4187 QEMU_OPTION_S,
4188 QEMU_OPTION_s,
4189 QEMU_OPTION_p,
4190 QEMU_OPTION_d,
4191 QEMU_OPTION_hdachs,
4192 QEMU_OPTION_L,
4193 QEMU_OPTION_bios,
4194 QEMU_OPTION_kernel_kqemu,
4195 QEMU_OPTION_no_kqemu,
4196 QEMU_OPTION_enable_kvm,
4197 QEMU_OPTION_no_reboot,
4198 QEMU_OPTION_no_shutdown,
4199 QEMU_OPTION_loadvm,
4200 QEMU_OPTION_daemonize,
4201 QEMU_OPTION_option_rom,
4202 QEMU_OPTION_prom_env,
4203 QEMU_OPTION_clock,
4204 QEMU_OPTION_localtime,
4205 QEMU_OPTION_startdate,
4206 QEMU_OPTION_icount,
4207 QEMU_OPTION_echr,
4208 QEMU_OPTION_virtiocon,
4209 QEMU_OPTION_show_cursor,
4210 QEMU_OPTION_semihosting,
4211 QEMU_OPTION_old_param,
4212 QEMU_OPTION_tb_size,
4213 QEMU_OPTION_incoming,
4214 QEMU_OPTION_chroot,
4215 QEMU_OPTION_runas,
4218 typedef struct QEMUOption {
4219 const char *name;
4220 int flags;
4221 int index;
4222 } QEMUOption;
4224 static const QEMUOption qemu_options[] = {
4225 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4226 qemu-doc.texi */
4227 /* Standard options: */
4228 { "h", 0, QEMU_OPTION_h },
4229 { "help", 0, QEMU_OPTION_h },
4230 { "M", HAS_ARG, QEMU_OPTION_M },
4231 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4232 { "smp", HAS_ARG, QEMU_OPTION_smp },
4233 { "fda", HAS_ARG, QEMU_OPTION_fda },
4234 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4235 { "hda", HAS_ARG, QEMU_OPTION_hda },
4236 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4237 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4238 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4239 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4240 { "drive", HAS_ARG, QEMU_OPTION_drive },
4241 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4242 { "sd", HAS_ARG, QEMU_OPTION_sd },
4243 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4244 { "boot", HAS_ARG, QEMU_OPTION_boot },
4245 { "snapshot", 0, QEMU_OPTION_snapshot },
4246 { "m", HAS_ARG, QEMU_OPTION_m },
4247 #ifndef _WIN32
4248 { "k", HAS_ARG, QEMU_OPTION_k },
4249 #endif
4250 #ifdef HAS_AUDIO
4251 { "audio-help", 0, QEMU_OPTION_audio_help },
4252 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4253 #endif
4254 { "usb", 0, QEMU_OPTION_usb },
4255 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4256 { "name", HAS_ARG, QEMU_OPTION_name },
4257 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4259 /* Display options: */
4260 { "nographic", 0, QEMU_OPTION_nographic },
4261 #ifdef CONFIG_CURSES
4262 { "curses", 0, QEMU_OPTION_curses },
4263 #endif
4264 #ifdef CONFIG_SDL
4265 { "no-frame", 0, QEMU_OPTION_no_frame },
4266 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4267 { "no-quit", 0, QEMU_OPTION_no_quit },
4268 { "sdl", 0, QEMU_OPTION_sdl },
4269 #endif
4270 { "portrait", 0, QEMU_OPTION_portrait },
4271 { "vga", HAS_ARG, QEMU_OPTION_vga },
4272 { "full-screen", 0, QEMU_OPTION_full_screen },
4273 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4274 { "g", 1, QEMU_OPTION_g },
4275 #endif
4276 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4278 /* Network options: */
4279 { "net", HAS_ARG, QEMU_OPTION_net},
4280 #ifdef CONFIG_SLIRP
4281 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4282 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4283 #ifndef _WIN32
4284 { "smb", HAS_ARG, QEMU_OPTION_smb },
4285 #endif
4286 { "redir", HAS_ARG, QEMU_OPTION_redir },
4287 #endif
4288 { "bt", HAS_ARG, QEMU_OPTION_bt },
4289 #ifdef TARGET_I386
4290 /* i386 target only: */
4291 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4292 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4293 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4294 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4295 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4296 { "acpitable", HAS_ARG, QEMU_OPTION_acpitable },
4297 #endif
4299 /* Linux boot specific: */
4300 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4301 { "append", HAS_ARG, QEMU_OPTION_append },
4302 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4304 /* Debug/Expert options: */
4305 { "serial", HAS_ARG, QEMU_OPTION_serial },
4306 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4307 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4308 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4309 { "S", 0, QEMU_OPTION_S },
4310 { "s", 0, QEMU_OPTION_s },
4311 { "p", HAS_ARG, QEMU_OPTION_p },
4312 { "d", HAS_ARG, QEMU_OPTION_d },
4313 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4314 { "L", HAS_ARG, QEMU_OPTION_L },
4315 { "bios", HAS_ARG, QEMU_OPTION_bios },
4316 #ifdef USE_KQEMU
4317 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4318 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4319 #endif
4320 #ifdef CONFIG_KVM
4321 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4322 #endif
4323 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4324 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4325 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4326 { "daemonize", 0, QEMU_OPTION_daemonize },
4327 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4328 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4329 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4330 #endif
4331 { "clock", HAS_ARG, QEMU_OPTION_clock },
4332 { "localtime", 0, QEMU_OPTION_localtime },
4333 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4334 { "icount", HAS_ARG, QEMU_OPTION_icount },
4335 { "echr", HAS_ARG, QEMU_OPTION_echr },
4336 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4337 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4338 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4339 { "semihosting", 0, QEMU_OPTION_semihosting },
4340 #endif
4341 #if defined(TARGET_ARM)
4342 { "old-param", 0, QEMU_OPTION_old_param },
4343 #endif
4344 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4345 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4346 { "chroot", HAS_ARG, QEMU_OPTION_chroot },
4347 { "runas", HAS_ARG, QEMU_OPTION_runas },
4348 { NULL },
4351 #ifdef HAS_AUDIO
4352 struct soundhw soundhw[] = {
4353 #ifdef HAS_AUDIO_CHOICE
4354 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4356 "pcspk",
4357 "PC speaker",
4360 { .init_isa = pcspk_audio_init }
4362 #endif
4364 #ifdef CONFIG_SB16
4366 "sb16",
4367 "Creative Sound Blaster 16",
4370 { .init_isa = SB16_init }
4372 #endif
4374 #ifdef CONFIG_CS4231A
4376 "cs4231a",
4377 "CS4231A",
4380 { .init_isa = cs4231a_init }
4382 #endif
4384 #ifdef CONFIG_ADLIB
4386 "adlib",
4387 #ifdef HAS_YMF262
4388 "Yamaha YMF262 (OPL3)",
4389 #else
4390 "Yamaha YM3812 (OPL2)",
4391 #endif
4394 { .init_isa = Adlib_init }
4396 #endif
4398 #ifdef CONFIG_GUS
4400 "gus",
4401 "Gravis Ultrasound GF1",
4404 { .init_isa = GUS_init }
4406 #endif
4408 #ifdef CONFIG_AC97
4410 "ac97",
4411 "Intel 82801AA AC97 Audio",
4414 { .init_pci = ac97_init }
4416 #endif
4418 #ifdef CONFIG_ES1370
4420 "es1370",
4421 "ENSONIQ AudioPCI ES1370",
4424 { .init_pci = es1370_init }
4426 #endif
4428 #endif /* HAS_AUDIO_CHOICE */
4430 { NULL, NULL, 0, 0, { NULL } }
4433 static void select_soundhw (const char *optarg)
4435 struct soundhw *c;
4437 if (*optarg == '?') {
4438 show_valid_cards:
4440 printf ("Valid sound card names (comma separated):\n");
4441 for (c = soundhw; c->name; ++c) {
4442 printf ("%-11s %s\n", c->name, c->descr);
4444 printf ("\n-soundhw all will enable all of the above\n");
4445 exit (*optarg != '?');
4447 else {
4448 size_t l;
4449 const char *p;
4450 char *e;
4451 int bad_card = 0;
4453 if (!strcmp (optarg, "all")) {
4454 for (c = soundhw; c->name; ++c) {
4455 c->enabled = 1;
4457 return;
4460 p = optarg;
4461 while (*p) {
4462 e = strchr (p, ',');
4463 l = !e ? strlen (p) : (size_t) (e - p);
4465 for (c = soundhw; c->name; ++c) {
4466 if (!strncmp (c->name, p, l)) {
4467 c->enabled = 1;
4468 break;
4472 if (!c->name) {
4473 if (l > 80) {
4474 fprintf (stderr,
4475 "Unknown sound card name (too big to show)\n");
4477 else {
4478 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4479 (int) l, p);
4481 bad_card = 1;
4483 p += l + (e != NULL);
4486 if (bad_card)
4487 goto show_valid_cards;
4490 #endif
4492 static void select_vgahw (const char *p)
4494 const char *opts;
4496 if (strstart(p, "std", &opts)) {
4497 std_vga_enabled = 1;
4498 cirrus_vga_enabled = 0;
4499 vmsvga_enabled = 0;
4500 } else if (strstart(p, "cirrus", &opts)) {
4501 cirrus_vga_enabled = 1;
4502 std_vga_enabled = 0;
4503 vmsvga_enabled = 0;
4504 } else if (strstart(p, "vmware", &opts)) {
4505 cirrus_vga_enabled = 0;
4506 std_vga_enabled = 0;
4507 vmsvga_enabled = 1;
4508 } else if (strstart(p, "none", &opts)) {
4509 cirrus_vga_enabled = 0;
4510 std_vga_enabled = 0;
4511 vmsvga_enabled = 0;
4512 } else {
4513 invalid_vga:
4514 fprintf(stderr, "Unknown vga type: %s\n", p);
4515 exit(1);
4517 while (*opts) {
4518 const char *nextopt;
4520 if (strstart(opts, ",retrace=", &nextopt)) {
4521 opts = nextopt;
4522 if (strstart(opts, "dumb", &nextopt))
4523 vga_retrace_method = VGA_RETRACE_DUMB;
4524 else if (strstart(opts, "precise", &nextopt))
4525 vga_retrace_method = VGA_RETRACE_PRECISE;
4526 else goto invalid_vga;
4527 } else goto invalid_vga;
4528 opts = nextopt;
4532 #ifdef _WIN32
4533 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4535 exit(STATUS_CONTROL_C_EXIT);
4536 return TRUE;
4538 #endif
4540 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4542 int ret;
4544 if(strlen(str) != 36)
4545 return -1;
4547 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4548 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4549 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4551 if(ret != 16)
4552 return -1;
4554 return 0;
4557 #define MAX_NET_CLIENTS 32
4559 #ifndef _WIN32
4561 static void termsig_handler(int signal)
4563 qemu_system_shutdown_request();
4566 static void termsig_setup(void)
4568 struct sigaction act;
4570 memset(&act, 0, sizeof(act));
4571 act.sa_handler = termsig_handler;
4572 sigaction(SIGINT, &act, NULL);
4573 sigaction(SIGHUP, &act, NULL);
4574 sigaction(SIGTERM, &act, NULL);
4577 #endif
4579 int main(int argc, char **argv, char **envp)
4581 #ifdef CONFIG_GDBSTUB
4582 int use_gdbstub;
4583 const char *gdbstub_port;
4584 #endif
4585 uint32_t boot_devices_bitmap = 0;
4586 int i;
4587 int snapshot, linux_boot, net_boot;
4588 const char *initrd_filename;
4589 const char *kernel_filename, *kernel_cmdline;
4590 const char *boot_devices = "";
4591 DisplayState *ds;
4592 DisplayChangeListener *dcl;
4593 int cyls, heads, secs, translation;
4594 const char *net_clients[MAX_NET_CLIENTS];
4595 int nb_net_clients;
4596 const char *bt_opts[MAX_BT_CMDLINE];
4597 int nb_bt_opts;
4598 int hda_index;
4599 int optind;
4600 const char *r, *optarg;
4601 CharDriverState *monitor_hd = NULL;
4602 const char *monitor_device;
4603 const char *serial_devices[MAX_SERIAL_PORTS];
4604 int serial_device_index;
4605 const char *parallel_devices[MAX_PARALLEL_PORTS];
4606 int parallel_device_index;
4607 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4608 int virtio_console_index;
4609 const char *loadvm = NULL;
4610 QEMUMachine *machine;
4611 const char *cpu_model;
4612 const char *usb_devices[MAX_USB_CMDLINE];
4613 int usb_devices_index;
4614 int fds[2];
4615 int tb_size;
4616 const char *pid_file = NULL;
4617 const char *incoming = NULL;
4618 int fd = 0;
4619 struct passwd *pwd = NULL;
4620 const char *chroot_dir = NULL;
4621 const char *run_as = NULL;
4623 qemu_cache_utils_init(envp);
4625 LIST_INIT (&vm_change_state_head);
4626 #ifndef _WIN32
4628 struct sigaction act;
4629 sigfillset(&act.sa_mask);
4630 act.sa_flags = 0;
4631 act.sa_handler = SIG_IGN;
4632 sigaction(SIGPIPE, &act, NULL);
4634 #else
4635 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4636 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4637 QEMU to run on a single CPU */
4639 HANDLE h;
4640 DWORD mask, smask;
4641 int i;
4642 h = GetCurrentProcess();
4643 if (GetProcessAffinityMask(h, &mask, &smask)) {
4644 for(i = 0; i < 32; i++) {
4645 if (mask & (1 << i))
4646 break;
4648 if (i != 32) {
4649 mask = 1 << i;
4650 SetProcessAffinityMask(h, mask);
4654 #endif
4656 register_machines();
4657 machine = first_machine;
4658 cpu_model = NULL;
4659 initrd_filename = NULL;
4660 ram_size = 0;
4661 vga_ram_size = VGA_RAM_SIZE;
4662 #ifdef CONFIG_GDBSTUB
4663 use_gdbstub = 0;
4664 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4665 #endif
4666 snapshot = 0;
4667 nographic = 0;
4668 curses = 0;
4669 kernel_filename = NULL;
4670 kernel_cmdline = "";
4671 cyls = heads = secs = 0;
4672 translation = BIOS_ATA_TRANSLATION_AUTO;
4673 monitor_device = "vc:80Cx24C";
4675 serial_devices[0] = "vc:80Cx24C";
4676 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4677 serial_devices[i] = NULL;
4678 serial_device_index = 0;
4680 parallel_devices[0] = "vc:80Cx24C";
4681 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4682 parallel_devices[i] = NULL;
4683 parallel_device_index = 0;
4685 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4686 virtio_consoles[i] = NULL;
4687 virtio_console_index = 0;
4689 usb_devices_index = 0;
4691 nb_net_clients = 0;
4692 nb_bt_opts = 0;
4693 nb_drives = 0;
4694 nb_drives_opt = 0;
4695 hda_index = -1;
4697 nb_nics = 0;
4699 tb_size = 0;
4700 autostart= 1;
4702 optind = 1;
4703 for(;;) {
4704 if (optind >= argc)
4705 break;
4706 r = argv[optind];
4707 if (r[0] != '-') {
4708 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4709 } else {
4710 const QEMUOption *popt;
4712 optind++;
4713 /* Treat --foo the same as -foo. */
4714 if (r[1] == '-')
4715 r++;
4716 popt = qemu_options;
4717 for(;;) {
4718 if (!popt->name) {
4719 fprintf(stderr, "%s: invalid option -- '%s'\n",
4720 argv[0], r);
4721 exit(1);
4723 if (!strcmp(popt->name, r + 1))
4724 break;
4725 popt++;
4727 if (popt->flags & HAS_ARG) {
4728 if (optind >= argc) {
4729 fprintf(stderr, "%s: option '%s' requires an argument\n",
4730 argv[0], r);
4731 exit(1);
4733 optarg = argv[optind++];
4734 } else {
4735 optarg = NULL;
4738 switch(popt->index) {
4739 case QEMU_OPTION_M:
4740 machine = find_machine(optarg);
4741 if (!machine) {
4742 QEMUMachine *m;
4743 printf("Supported machines are:\n");
4744 for(m = first_machine; m != NULL; m = m->next) {
4745 printf("%-10s %s%s\n",
4746 m->name, m->desc,
4747 m == first_machine ? " (default)" : "");
4749 exit(*optarg != '?');
4751 break;
4752 case QEMU_OPTION_cpu:
4753 /* hw initialization will check this */
4754 if (*optarg == '?') {
4755 /* XXX: implement xxx_cpu_list for targets that still miss it */
4756 #if defined(cpu_list)
4757 cpu_list(stdout, &fprintf);
4758 #endif
4759 exit(0);
4760 } else {
4761 cpu_model = optarg;
4763 break;
4764 case QEMU_OPTION_initrd:
4765 initrd_filename = optarg;
4766 break;
4767 case QEMU_OPTION_hda:
4768 if (cyls == 0)
4769 hda_index = drive_add(optarg, HD_ALIAS, 0);
4770 else
4771 hda_index = drive_add(optarg, HD_ALIAS
4772 ",cyls=%d,heads=%d,secs=%d%s",
4773 0, cyls, heads, secs,
4774 translation == BIOS_ATA_TRANSLATION_LBA ?
4775 ",trans=lba" :
4776 translation == BIOS_ATA_TRANSLATION_NONE ?
4777 ",trans=none" : "");
4778 break;
4779 case QEMU_OPTION_hdb:
4780 case QEMU_OPTION_hdc:
4781 case QEMU_OPTION_hdd:
4782 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4783 break;
4784 case QEMU_OPTION_drive:
4785 drive_add(NULL, "%s", optarg);
4786 break;
4787 case QEMU_OPTION_mtdblock:
4788 drive_add(optarg, MTD_ALIAS);
4789 break;
4790 case QEMU_OPTION_sd:
4791 drive_add(optarg, SD_ALIAS);
4792 break;
4793 case QEMU_OPTION_pflash:
4794 drive_add(optarg, PFLASH_ALIAS);
4795 break;
4796 case QEMU_OPTION_snapshot:
4797 snapshot = 1;
4798 break;
4799 case QEMU_OPTION_hdachs:
4801 const char *p;
4802 p = optarg;
4803 cyls = strtol(p, (char **)&p, 0);
4804 if (cyls < 1 || cyls > 16383)
4805 goto chs_fail;
4806 if (*p != ',')
4807 goto chs_fail;
4808 p++;
4809 heads = strtol(p, (char **)&p, 0);
4810 if (heads < 1 || heads > 16)
4811 goto chs_fail;
4812 if (*p != ',')
4813 goto chs_fail;
4814 p++;
4815 secs = strtol(p, (char **)&p, 0);
4816 if (secs < 1 || secs > 63)
4817 goto chs_fail;
4818 if (*p == ',') {
4819 p++;
4820 if (!strcmp(p, "none"))
4821 translation = BIOS_ATA_TRANSLATION_NONE;
4822 else if (!strcmp(p, "lba"))
4823 translation = BIOS_ATA_TRANSLATION_LBA;
4824 else if (!strcmp(p, "auto"))
4825 translation = BIOS_ATA_TRANSLATION_AUTO;
4826 else
4827 goto chs_fail;
4828 } else if (*p != '\0') {
4829 chs_fail:
4830 fprintf(stderr, "qemu: invalid physical CHS format\n");
4831 exit(1);
4833 if (hda_index != -1)
4834 snprintf(drives_opt[hda_index].opt,
4835 sizeof(drives_opt[hda_index].opt),
4836 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4837 0, cyls, heads, secs,
4838 translation == BIOS_ATA_TRANSLATION_LBA ?
4839 ",trans=lba" :
4840 translation == BIOS_ATA_TRANSLATION_NONE ?
4841 ",trans=none" : "");
4843 break;
4844 case QEMU_OPTION_nographic:
4845 nographic = 1;
4846 break;
4847 #ifdef CONFIG_CURSES
4848 case QEMU_OPTION_curses:
4849 curses = 1;
4850 break;
4851 #endif
4852 case QEMU_OPTION_portrait:
4853 graphic_rotate = 1;
4854 break;
4855 case QEMU_OPTION_kernel:
4856 kernel_filename = optarg;
4857 break;
4858 case QEMU_OPTION_append:
4859 kernel_cmdline = optarg;
4860 break;
4861 case QEMU_OPTION_cdrom:
4862 drive_add(optarg, CDROM_ALIAS);
4863 break;
4864 case QEMU_OPTION_boot:
4865 boot_devices = optarg;
4866 /* We just do some generic consistency checks */
4868 /* Could easily be extended to 64 devices if needed */
4869 const char *p;
4871 boot_devices_bitmap = 0;
4872 for (p = boot_devices; *p != '\0'; p++) {
4873 /* Allowed boot devices are:
4874 * a b : floppy disk drives
4875 * c ... f : IDE disk drives
4876 * g ... m : machine implementation dependant drives
4877 * n ... p : network devices
4878 * It's up to each machine implementation to check
4879 * if the given boot devices match the actual hardware
4880 * implementation and firmware features.
4882 if (*p < 'a' || *p > 'q') {
4883 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4884 exit(1);
4886 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4887 fprintf(stderr,
4888 "Boot device '%c' was given twice\n",*p);
4889 exit(1);
4891 boot_devices_bitmap |= 1 << (*p - 'a');
4894 break;
4895 case QEMU_OPTION_fda:
4896 case QEMU_OPTION_fdb:
4897 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4898 break;
4899 #ifdef TARGET_I386
4900 case QEMU_OPTION_no_fd_bootchk:
4901 fd_bootchk = 0;
4902 break;
4903 #endif
4904 case QEMU_OPTION_net:
4905 if (nb_net_clients >= MAX_NET_CLIENTS) {
4906 fprintf(stderr, "qemu: too many network clients\n");
4907 exit(1);
4909 net_clients[nb_net_clients] = optarg;
4910 nb_net_clients++;
4911 break;
4912 #ifdef CONFIG_SLIRP
4913 case QEMU_OPTION_tftp:
4914 tftp_prefix = optarg;
4915 break;
4916 case QEMU_OPTION_bootp:
4917 bootp_filename = optarg;
4918 break;
4919 #ifndef _WIN32
4920 case QEMU_OPTION_smb:
4921 net_slirp_smb(optarg);
4922 break;
4923 #endif
4924 case QEMU_OPTION_redir:
4925 net_slirp_redir(optarg);
4926 break;
4927 #endif
4928 case QEMU_OPTION_bt:
4929 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4930 fprintf(stderr, "qemu: too many bluetooth options\n");
4931 exit(1);
4933 bt_opts[nb_bt_opts++] = optarg;
4934 break;
4935 #ifdef HAS_AUDIO
4936 case QEMU_OPTION_audio_help:
4937 AUD_help ();
4938 exit (0);
4939 break;
4940 case QEMU_OPTION_soundhw:
4941 select_soundhw (optarg);
4942 break;
4943 #endif
4944 case QEMU_OPTION_h:
4945 help(0);
4946 break;
4947 case QEMU_OPTION_m: {
4948 uint64_t value;
4949 char *ptr;
4951 value = strtoul(optarg, &ptr, 10);
4952 switch (*ptr) {
4953 case 0: case 'M': case 'm':
4954 value <<= 20;
4955 break;
4956 case 'G': case 'g':
4957 value <<= 30;
4958 break;
4959 default:
4960 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4961 exit(1);
4964 /* On 32-bit hosts, QEMU is limited by virtual address space */
4965 if (value > (2047 << 20)
4966 #ifndef USE_KQEMU
4967 && HOST_LONG_BITS == 32
4968 #endif
4970 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4971 exit(1);
4973 if (value != (uint64_t)(ram_addr_t)value) {
4974 fprintf(stderr, "qemu: ram size too large\n");
4975 exit(1);
4977 ram_size = value;
4978 break;
4980 case QEMU_OPTION_d:
4982 int mask;
4983 const CPULogItem *item;
4985 mask = cpu_str_to_log_mask(optarg);
4986 if (!mask) {
4987 printf("Log items (comma separated):\n");
4988 for(item = cpu_log_items; item->mask != 0; item++) {
4989 printf("%-10s %s\n", item->name, item->help);
4991 exit(1);
4993 cpu_set_log(mask);
4995 break;
4996 #ifdef CONFIG_GDBSTUB
4997 case QEMU_OPTION_s:
4998 use_gdbstub = 1;
4999 break;
5000 case QEMU_OPTION_p:
5001 gdbstub_port = optarg;
5002 break;
5003 #endif
5004 case QEMU_OPTION_L:
5005 bios_dir = optarg;
5006 break;
5007 case QEMU_OPTION_bios:
5008 bios_name = optarg;
5009 break;
5010 case QEMU_OPTION_S:
5011 autostart = 0;
5012 break;
5013 case QEMU_OPTION_k:
5014 keyboard_layout = optarg;
5015 break;
5016 case QEMU_OPTION_localtime:
5017 rtc_utc = 0;
5018 break;
5019 case QEMU_OPTION_vga:
5020 select_vgahw (optarg);
5021 break;
5022 case QEMU_OPTION_g:
5024 const char *p;
5025 int w, h, depth;
5026 p = optarg;
5027 w = strtol(p, (char **)&p, 10);
5028 if (w <= 0) {
5029 graphic_error:
5030 fprintf(stderr, "qemu: invalid resolution or depth\n");
5031 exit(1);
5033 if (*p != 'x')
5034 goto graphic_error;
5035 p++;
5036 h = strtol(p, (char **)&p, 10);
5037 if (h <= 0)
5038 goto graphic_error;
5039 if (*p == 'x') {
5040 p++;
5041 depth = strtol(p, (char **)&p, 10);
5042 if (depth != 8 && depth != 15 && depth != 16 &&
5043 depth != 24 && depth != 32)
5044 goto graphic_error;
5045 } else if (*p == '\0') {
5046 depth = graphic_depth;
5047 } else {
5048 goto graphic_error;
5051 graphic_width = w;
5052 graphic_height = h;
5053 graphic_depth = depth;
5055 break;
5056 case QEMU_OPTION_echr:
5058 char *r;
5059 term_escape_char = strtol(optarg, &r, 0);
5060 if (r == optarg)
5061 printf("Bad argument to echr\n");
5062 break;
5064 case QEMU_OPTION_monitor:
5065 monitor_device = optarg;
5066 break;
5067 case QEMU_OPTION_serial:
5068 if (serial_device_index >= MAX_SERIAL_PORTS) {
5069 fprintf(stderr, "qemu: too many serial ports\n");
5070 exit(1);
5072 serial_devices[serial_device_index] = optarg;
5073 serial_device_index++;
5074 break;
5075 case QEMU_OPTION_virtiocon:
5076 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5077 fprintf(stderr, "qemu: too many virtio consoles\n");
5078 exit(1);
5080 virtio_consoles[virtio_console_index] = optarg;
5081 virtio_console_index++;
5082 break;
5083 case QEMU_OPTION_parallel:
5084 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5085 fprintf(stderr, "qemu: too many parallel ports\n");
5086 exit(1);
5088 parallel_devices[parallel_device_index] = optarg;
5089 parallel_device_index++;
5090 break;
5091 case QEMU_OPTION_loadvm:
5092 loadvm = optarg;
5093 break;
5094 case QEMU_OPTION_full_screen:
5095 full_screen = 1;
5096 break;
5097 #ifdef CONFIG_SDL
5098 case QEMU_OPTION_no_frame:
5099 no_frame = 1;
5100 break;
5101 case QEMU_OPTION_alt_grab:
5102 alt_grab = 1;
5103 break;
5104 case QEMU_OPTION_no_quit:
5105 no_quit = 1;
5106 break;
5107 case QEMU_OPTION_sdl:
5108 sdl = 1;
5109 break;
5110 #endif
5111 case QEMU_OPTION_pidfile:
5112 pid_file = optarg;
5113 break;
5114 #ifdef TARGET_I386
5115 case QEMU_OPTION_win2k_hack:
5116 win2k_install_hack = 1;
5117 break;
5118 case QEMU_OPTION_rtc_td_hack:
5119 rtc_td_hack = 1;
5120 break;
5121 case QEMU_OPTION_acpitable:
5122 if(acpi_table_add(optarg) < 0) {
5123 fprintf(stderr, "Wrong acpi table provided\n");
5124 exit(1);
5126 break;
5127 #endif
5128 #ifdef USE_KQEMU
5129 case QEMU_OPTION_no_kqemu:
5130 kqemu_allowed = 0;
5131 break;
5132 case QEMU_OPTION_kernel_kqemu:
5133 kqemu_allowed = 2;
5134 break;
5135 #endif
5136 #ifdef CONFIG_KVM
5137 case QEMU_OPTION_enable_kvm:
5138 kvm_allowed = 1;
5139 #ifdef USE_KQEMU
5140 kqemu_allowed = 0;
5141 #endif
5142 break;
5143 #endif
5144 case QEMU_OPTION_usb:
5145 usb_enabled = 1;
5146 break;
5147 case QEMU_OPTION_usbdevice:
5148 usb_enabled = 1;
5149 if (usb_devices_index >= MAX_USB_CMDLINE) {
5150 fprintf(stderr, "Too many USB devices\n");
5151 exit(1);
5153 usb_devices[usb_devices_index] = optarg;
5154 usb_devices_index++;
5155 break;
5156 case QEMU_OPTION_smp:
5157 smp_cpus = atoi(optarg);
5158 if (smp_cpus < 1) {
5159 fprintf(stderr, "Invalid number of CPUs\n");
5160 exit(1);
5162 break;
5163 case QEMU_OPTION_vnc:
5164 vnc_display = optarg;
5165 break;
5166 case QEMU_OPTION_no_acpi:
5167 acpi_enabled = 0;
5168 break;
5169 case QEMU_OPTION_no_hpet:
5170 no_hpet = 1;
5171 break;
5172 case QEMU_OPTION_no_reboot:
5173 no_reboot = 1;
5174 break;
5175 case QEMU_OPTION_no_shutdown:
5176 no_shutdown = 1;
5177 break;
5178 case QEMU_OPTION_show_cursor:
5179 cursor_hide = 0;
5180 break;
5181 case QEMU_OPTION_uuid:
5182 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5183 fprintf(stderr, "Fail to parse UUID string."
5184 " Wrong format.\n");
5185 exit(1);
5187 break;
5188 case QEMU_OPTION_daemonize:
5189 daemonize = 1;
5190 break;
5191 case QEMU_OPTION_option_rom:
5192 if (nb_option_roms >= MAX_OPTION_ROMS) {
5193 fprintf(stderr, "Too many option ROMs\n");
5194 exit(1);
5196 option_rom[nb_option_roms] = optarg;
5197 nb_option_roms++;
5198 break;
5199 case QEMU_OPTION_semihosting:
5200 semihosting_enabled = 1;
5201 break;
5202 case QEMU_OPTION_name:
5203 qemu_name = optarg;
5204 break;
5205 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5206 case QEMU_OPTION_prom_env:
5207 if (nb_prom_envs >= MAX_PROM_ENVS) {
5208 fprintf(stderr, "Too many prom variables\n");
5209 exit(1);
5211 prom_envs[nb_prom_envs] = optarg;
5212 nb_prom_envs++;
5213 break;
5214 #endif
5215 #ifdef TARGET_ARM
5216 case QEMU_OPTION_old_param:
5217 old_param = 1;
5218 break;
5219 #endif
5220 case QEMU_OPTION_clock:
5221 configure_alarms(optarg);
5222 break;
5223 case QEMU_OPTION_startdate:
5225 struct tm tm;
5226 time_t rtc_start_date;
5227 if (!strcmp(optarg, "now")) {
5228 rtc_date_offset = -1;
5229 } else {
5230 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5231 &tm.tm_year,
5232 &tm.tm_mon,
5233 &tm.tm_mday,
5234 &tm.tm_hour,
5235 &tm.tm_min,
5236 &tm.tm_sec) == 6) {
5237 /* OK */
5238 } else if (sscanf(optarg, "%d-%d-%d",
5239 &tm.tm_year,
5240 &tm.tm_mon,
5241 &tm.tm_mday) == 3) {
5242 tm.tm_hour = 0;
5243 tm.tm_min = 0;
5244 tm.tm_sec = 0;
5245 } else {
5246 goto date_fail;
5248 tm.tm_year -= 1900;
5249 tm.tm_mon--;
5250 rtc_start_date = mktimegm(&tm);
5251 if (rtc_start_date == -1) {
5252 date_fail:
5253 fprintf(stderr, "Invalid date format. Valid format are:\n"
5254 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5255 exit(1);
5257 rtc_date_offset = time(NULL) - rtc_start_date;
5260 break;
5261 case QEMU_OPTION_tb_size:
5262 tb_size = strtol(optarg, NULL, 0);
5263 if (tb_size < 0)
5264 tb_size = 0;
5265 break;
5266 case QEMU_OPTION_icount:
5267 use_icount = 1;
5268 if (strcmp(optarg, "auto") == 0) {
5269 icount_time_shift = -1;
5270 } else {
5271 icount_time_shift = strtol(optarg, NULL, 0);
5273 break;
5274 case QEMU_OPTION_incoming:
5275 incoming = optarg;
5276 break;
5277 case QEMU_OPTION_chroot:
5278 chroot_dir = optarg;
5279 break;
5280 case QEMU_OPTION_runas:
5281 run_as = optarg;
5282 break;
5287 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5288 if (kvm_allowed && kqemu_allowed) {
5289 fprintf(stderr,
5290 "You can not enable both KVM and kqemu at the same time\n");
5291 exit(1);
5293 #endif
5295 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5296 if (smp_cpus > machine->max_cpus) {
5297 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5298 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5299 machine->max_cpus);
5300 exit(1);
5303 if (nographic) {
5304 if (serial_device_index == 0)
5305 serial_devices[0] = "stdio";
5306 if (parallel_device_index == 0)
5307 parallel_devices[0] = "null";
5308 if (strncmp(monitor_device, "vc", 2) == 0)
5309 monitor_device = "stdio";
5312 #ifndef _WIN32
5313 if (daemonize) {
5314 pid_t pid;
5316 if (pipe(fds) == -1)
5317 exit(1);
5319 pid = fork();
5320 if (pid > 0) {
5321 uint8_t status;
5322 ssize_t len;
5324 close(fds[1]);
5326 again:
5327 len = read(fds[0], &status, 1);
5328 if (len == -1 && (errno == EINTR))
5329 goto again;
5331 if (len != 1)
5332 exit(1);
5333 else if (status == 1) {
5334 fprintf(stderr, "Could not acquire pidfile\n");
5335 exit(1);
5336 } else
5337 exit(0);
5338 } else if (pid < 0)
5339 exit(1);
5341 setsid();
5343 pid = fork();
5344 if (pid > 0)
5345 exit(0);
5346 else if (pid < 0)
5347 exit(1);
5349 umask(027);
5351 signal(SIGTSTP, SIG_IGN);
5352 signal(SIGTTOU, SIG_IGN);
5353 signal(SIGTTIN, SIG_IGN);
5355 #endif
5357 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5358 if (daemonize) {
5359 uint8_t status = 1;
5360 write(fds[1], &status, 1);
5361 } else
5362 fprintf(stderr, "Could not acquire pid file\n");
5363 exit(1);
5366 #ifdef USE_KQEMU
5367 if (smp_cpus > 1)
5368 kqemu_allowed = 0;
5369 #endif
5370 linux_boot = (kernel_filename != NULL);
5371 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5373 if (!linux_boot && net_boot == 0 &&
5374 !machine->nodisk_ok && nb_drives_opt == 0)
5375 help(1);
5377 if (!linux_boot && *kernel_cmdline != '\0') {
5378 fprintf(stderr, "-append only allowed with -kernel option\n");
5379 exit(1);
5382 if (!linux_boot && initrd_filename != NULL) {
5383 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5384 exit(1);
5387 /* boot to floppy or the default cd if no hard disk defined yet */
5388 if (!boot_devices[0]) {
5389 boot_devices = "cad";
5391 setvbuf(stdout, NULL, _IOLBF, 0);
5393 init_timers();
5394 if (init_timer_alarm() < 0) {
5395 fprintf(stderr, "could not initialize alarm timer\n");
5396 exit(1);
5398 if (use_icount && icount_time_shift < 0) {
5399 use_icount = 2;
5400 /* 125MIPS seems a reasonable initial guess at the guest speed.
5401 It will be corrected fairly quickly anyway. */
5402 icount_time_shift = 3;
5403 init_icount_adjust();
5406 #ifdef _WIN32
5407 socket_init();
5408 #endif
5410 /* init network clients */
5411 if (nb_net_clients == 0) {
5412 /* if no clients, we use a default config */
5413 net_clients[nb_net_clients++] = "nic";
5414 #ifdef CONFIG_SLIRP
5415 net_clients[nb_net_clients++] = "user";
5416 #endif
5419 for(i = 0;i < nb_net_clients; i++) {
5420 if (net_client_parse(net_clients[i]) < 0)
5421 exit(1);
5423 net_client_check();
5425 #ifdef TARGET_I386
5426 /* XXX: this should be moved in the PC machine instantiation code */
5427 if (net_boot != 0) {
5428 int netroms = 0;
5429 for (i = 0; i < nb_nics && i < 4; i++) {
5430 const char *model = nd_table[i].model;
5431 char buf[1024];
5432 if (net_boot & (1 << i)) {
5433 if (model == NULL)
5434 model = "ne2k_pci";
5435 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5436 if (get_image_size(buf) > 0) {
5437 if (nb_option_roms >= MAX_OPTION_ROMS) {
5438 fprintf(stderr, "Too many option ROMs\n");
5439 exit(1);
5441 option_rom[nb_option_roms] = strdup(buf);
5442 nb_option_roms++;
5443 netroms++;
5447 if (netroms == 0) {
5448 fprintf(stderr, "No valid PXE rom found for network device\n");
5449 exit(1);
5452 #endif
5454 /* init the bluetooth world */
5455 for (i = 0; i < nb_bt_opts; i++)
5456 if (bt_parse(bt_opts[i]))
5457 exit(1);
5459 /* init the memory */
5460 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5462 if (machine->ram_require & RAMSIZE_FIXED) {
5463 if (ram_size > 0) {
5464 if (ram_size < phys_ram_size) {
5465 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5466 machine->name, (unsigned long long) phys_ram_size);
5467 exit(-1);
5470 phys_ram_size = ram_size;
5471 } else
5472 ram_size = phys_ram_size;
5473 } else {
5474 if (ram_size == 0)
5475 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5477 phys_ram_size += ram_size;
5480 phys_ram_base = qemu_vmalloc(phys_ram_size);
5481 if (!phys_ram_base) {
5482 fprintf(stderr, "Could not allocate physical memory\n");
5483 exit(1);
5486 /* init the dynamic translator */
5487 cpu_exec_init_all(tb_size * 1024 * 1024);
5489 bdrv_init();
5491 /* we always create the cdrom drive, even if no disk is there */
5493 if (nb_drives_opt < MAX_DRIVES)
5494 drive_add(NULL, CDROM_ALIAS);
5496 /* we always create at least one floppy */
5498 if (nb_drives_opt < MAX_DRIVES)
5499 drive_add(NULL, FD_ALIAS, 0);
5501 /* we always create one sd slot, even if no card is in it */
5503 if (nb_drives_opt < MAX_DRIVES)
5504 drive_add(NULL, SD_ALIAS);
5506 /* open the virtual block devices */
5508 for(i = 0; i < nb_drives_opt; i++)
5509 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5510 exit(1);
5512 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5513 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5515 #ifndef _WIN32
5516 /* must be after terminal init, SDL library changes signal handlers */
5517 termsig_setup();
5518 #endif
5520 /* Maintain compatibility with multiple stdio monitors */
5521 if (!strcmp(monitor_device,"stdio")) {
5522 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5523 const char *devname = serial_devices[i];
5524 if (devname && !strcmp(devname,"mon:stdio")) {
5525 monitor_device = NULL;
5526 break;
5527 } else if (devname && !strcmp(devname,"stdio")) {
5528 monitor_device = NULL;
5529 serial_devices[i] = "mon:stdio";
5530 break;
5535 if (kvm_enabled()) {
5536 int ret;
5538 ret = kvm_init(smp_cpus);
5539 if (ret < 0) {
5540 fprintf(stderr, "failed to initialize KVM\n");
5541 exit(1);
5545 if (monitor_device) {
5546 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5547 if (!monitor_hd) {
5548 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5549 exit(1);
5553 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5554 const char *devname = serial_devices[i];
5555 if (devname && strcmp(devname, "none")) {
5556 char label[32];
5557 snprintf(label, sizeof(label), "serial%d", i);
5558 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5559 if (!serial_hds[i]) {
5560 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5561 devname);
5562 exit(1);
5567 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5568 const char *devname = parallel_devices[i];
5569 if (devname && strcmp(devname, "none")) {
5570 char label[32];
5571 snprintf(label, sizeof(label), "parallel%d", i);
5572 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5573 if (!parallel_hds[i]) {
5574 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5575 devname);
5576 exit(1);
5581 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5582 const char *devname = virtio_consoles[i];
5583 if (devname && strcmp(devname, "none")) {
5584 char label[32];
5585 snprintf(label, sizeof(label), "virtcon%d", i);
5586 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5587 if (!virtcon_hds[i]) {
5588 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5589 devname);
5590 exit(1);
5595 machine->init(ram_size, vga_ram_size, boot_devices,
5596 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5598 current_machine = machine;
5600 /* Set KVM's vcpu state to qemu's initial CPUState. */
5601 if (kvm_enabled()) {
5602 int ret;
5604 ret = kvm_sync_vcpus();
5605 if (ret < 0) {
5606 fprintf(stderr, "failed to initialize vcpus\n");
5607 exit(1);
5611 /* init USB devices */
5612 if (usb_enabled) {
5613 for(i = 0; i < usb_devices_index; i++) {
5614 if (usb_device_add(usb_devices[i], 0) < 0) {
5615 fprintf(stderr, "Warning: could not add USB device %s\n",
5616 usb_devices[i]);
5621 if (!display_state)
5622 dumb_display_init();
5623 /* just use the first displaystate for the moment */
5624 ds = display_state;
5625 /* terminal init */
5626 if (nographic) {
5627 if (curses) {
5628 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5629 exit(1);
5631 } else {
5632 #if defined(CONFIG_CURSES)
5633 if (curses) {
5634 /* At the moment curses cannot be used with other displays */
5635 curses_display_init(ds, full_screen);
5636 } else
5637 #endif
5639 if (vnc_display != NULL) {
5640 vnc_display_init(ds);
5641 if (vnc_display_open(ds, vnc_display) < 0)
5642 exit(1);
5644 #if defined(CONFIG_SDL)
5645 if (sdl || !vnc_display)
5646 sdl_display_init(ds, full_screen, no_frame);
5647 #elif defined(CONFIG_COCOA)
5648 if (sdl || !vnc_display)
5649 cocoa_display_init(ds, full_screen);
5650 #endif
5653 dpy_resize(ds);
5655 dcl = ds->listeners;
5656 while (dcl != NULL) {
5657 if (dcl->dpy_refresh != NULL) {
5658 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5659 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5661 dcl = dcl->next;
5664 if (nographic || (vnc_display && !sdl)) {
5665 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5666 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5669 text_consoles_set_display(display_state);
5670 qemu_chr_initial_reset();
5672 if (monitor_device && monitor_hd)
5673 monitor_init(monitor_hd, !nographic);
5675 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5676 const char *devname = serial_devices[i];
5677 if (devname && strcmp(devname, "none")) {
5678 char label[32];
5679 snprintf(label, sizeof(label), "serial%d", i);
5680 if (strstart(devname, "vc", 0))
5681 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5685 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5686 const char *devname = parallel_devices[i];
5687 if (devname && strcmp(devname, "none")) {
5688 char label[32];
5689 snprintf(label, sizeof(label), "parallel%d", i);
5690 if (strstart(devname, "vc", 0))
5691 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5695 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5696 const char *devname = virtio_consoles[i];
5697 if (virtcon_hds[i] && devname) {
5698 char label[32];
5699 snprintf(label, sizeof(label), "virtcon%d", i);
5700 if (strstart(devname, "vc", 0))
5701 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5705 #ifdef CONFIG_GDBSTUB
5706 if (use_gdbstub) {
5707 /* XXX: use standard host:port notation and modify options
5708 accordingly. */
5709 if (gdbserver_start(gdbstub_port) < 0) {
5710 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5711 gdbstub_port);
5712 exit(1);
5715 #endif
5717 if (loadvm)
5718 do_loadvm(loadvm);
5720 if (incoming) {
5721 autostart = 0; /* fixme how to deal with -daemonize */
5722 qemu_start_incoming_migration(incoming);
5725 if (autostart)
5726 vm_start();
5728 if (daemonize) {
5729 uint8_t status = 0;
5730 ssize_t len;
5732 again1:
5733 len = write(fds[1], &status, 1);
5734 if (len == -1 && (errno == EINTR))
5735 goto again1;
5737 if (len != 1)
5738 exit(1);
5740 chdir("/");
5741 TFR(fd = open("/dev/null", O_RDWR));
5742 if (fd == -1)
5743 exit(1);
5746 #ifndef _WIN32
5747 if (run_as) {
5748 pwd = getpwnam(run_as);
5749 if (!pwd) {
5750 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5751 exit(1);
5755 if (chroot_dir) {
5756 if (chroot(chroot_dir) < 0) {
5757 fprintf(stderr, "chroot failed\n");
5758 exit(1);
5760 chdir("/");
5763 if (run_as) {
5764 if (setgid(pwd->pw_gid) < 0) {
5765 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5766 exit(1);
5768 if (setuid(pwd->pw_uid) < 0) {
5769 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5770 exit(1);
5772 if (setuid(0) != -1) {
5773 fprintf(stderr, "Dropping privileges failed\n");
5774 exit(1);
5777 #endif
5779 if (daemonize) {
5780 dup2(fd, 0);
5781 dup2(fd, 1);
5782 dup2(fd, 2);
5784 close(fd);
5787 main_loop();
5788 quit_timers();
5789 net_cleanup();
5791 return 0;