Make x86 cpuid feature names available in file scope
[qemu-kvm/fedora.git] / vl.c
blob56623fb576ae9637d320cfb97c3c21872b1494d9
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 && (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 if (alarm_timer) 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);
1532 * Initialize ev struct to 0 to avoid valgrind complaining
1533 * about uninitialized data in timer_create call
1535 memset(&ev, 0, sizeof(ev));
1536 ev.sigev_value.sival_int = 0;
1537 ev.sigev_notify = SIGEV_SIGNAL;
1538 ev.sigev_signo = SIGALRM;
1540 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1541 perror("timer_create");
1543 /* disable dynticks */
1544 fprintf(stderr, "Dynamic Ticks disabled\n");
1546 return -1;
1549 t->priv = (void *)(long)host_timer;
1551 return 0;
1554 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1556 timer_t host_timer = (timer_t)(long)t->priv;
1558 timer_delete(host_timer);
1561 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1563 timer_t host_timer = (timer_t)(long)t->priv;
1564 struct itimerspec timeout;
1565 int64_t nearest_delta_us = INT64_MAX;
1566 int64_t current_us;
1568 if (!active_timers[QEMU_TIMER_REALTIME] &&
1569 !active_timers[QEMU_TIMER_VIRTUAL])
1570 return;
1572 nearest_delta_us = qemu_next_deadline_dyntick();
1574 /* check whether a timer is already running */
1575 if (timer_gettime(host_timer, &timeout)) {
1576 perror("gettime");
1577 fprintf(stderr, "Internal timer error: aborting\n");
1578 exit(1);
1580 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1581 if (current_us && current_us <= nearest_delta_us)
1582 return;
1584 timeout.it_interval.tv_sec = 0;
1585 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1586 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1587 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1588 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1589 perror("settime");
1590 fprintf(stderr, "Internal timer error: aborting\n");
1591 exit(1);
1595 #endif /* defined(__linux__) */
1597 static int unix_start_timer(struct qemu_alarm_timer *t)
1599 struct sigaction act;
1600 struct itimerval itv;
1601 int err;
1603 /* timer signal */
1604 sigfillset(&act.sa_mask);
1605 act.sa_flags = 0;
1606 act.sa_handler = host_alarm_handler;
1608 sigaction(SIGALRM, &act, NULL);
1610 itv.it_interval.tv_sec = 0;
1611 /* for i386 kernel 2.6 to get 1 ms */
1612 itv.it_interval.tv_usec = 999;
1613 itv.it_value.tv_sec = 0;
1614 itv.it_value.tv_usec = 10 * 1000;
1616 err = setitimer(ITIMER_REAL, &itv, NULL);
1617 if (err)
1618 return -1;
1620 return 0;
1623 static void unix_stop_timer(struct qemu_alarm_timer *t)
1625 struct itimerval itv;
1627 memset(&itv, 0, sizeof(itv));
1628 setitimer(ITIMER_REAL, &itv, NULL);
1631 #endif /* !defined(_WIN32) */
1633 static void try_to_rearm_timer(void *opaque)
1635 struct qemu_alarm_timer *t = opaque;
1636 #ifndef _WIN32
1637 ssize_t len;
1639 /* Drain the notify pipe */
1640 do {
1641 char buffer[512];
1642 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1643 } while ((len == -1 && errno == EINTR) || len > 0);
1644 #endif
1646 if (t->flags & ALARM_FLAG_EXPIRED) {
1647 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1648 qemu_rearm_alarm_timer(alarm_timer);
1652 #ifdef _WIN32
1654 static int win32_start_timer(struct qemu_alarm_timer *t)
1656 TIMECAPS tc;
1657 struct qemu_alarm_win32 *data = t->priv;
1658 UINT flags;
1660 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1661 if (!data->host_alarm) {
1662 perror("Failed CreateEvent");
1663 return -1;
1666 memset(&tc, 0, sizeof(tc));
1667 timeGetDevCaps(&tc, sizeof(tc));
1669 if (data->period < tc.wPeriodMin)
1670 data->period = tc.wPeriodMin;
1672 timeBeginPeriod(data->period);
1674 flags = TIME_CALLBACK_FUNCTION;
1675 if (alarm_has_dynticks(t))
1676 flags |= TIME_ONESHOT;
1677 else
1678 flags |= TIME_PERIODIC;
1680 data->timerId = timeSetEvent(1, // interval (ms)
1681 data->period, // resolution
1682 host_alarm_handler, // function
1683 (DWORD)t, // parameter
1684 flags);
1686 if (!data->timerId) {
1687 perror("Failed to initialize win32 alarm timer");
1689 timeEndPeriod(data->period);
1690 CloseHandle(data->host_alarm);
1691 return -1;
1694 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1696 return 0;
1699 static void win32_stop_timer(struct qemu_alarm_timer *t)
1701 struct qemu_alarm_win32 *data = t->priv;
1703 timeKillEvent(data->timerId);
1704 timeEndPeriod(data->period);
1706 CloseHandle(data->host_alarm);
1709 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1711 struct qemu_alarm_win32 *data = t->priv;
1712 uint64_t nearest_delta_us;
1714 if (!active_timers[QEMU_TIMER_REALTIME] &&
1715 !active_timers[QEMU_TIMER_VIRTUAL])
1716 return;
1718 nearest_delta_us = qemu_next_deadline_dyntick();
1719 nearest_delta_us /= 1000;
1721 timeKillEvent(data->timerId);
1723 data->timerId = timeSetEvent(1,
1724 data->period,
1725 host_alarm_handler,
1726 (DWORD)t,
1727 TIME_ONESHOT | TIME_PERIODIC);
1729 if (!data->timerId) {
1730 perror("Failed to re-arm win32 alarm timer");
1732 timeEndPeriod(data->period);
1733 CloseHandle(data->host_alarm);
1734 exit(1);
1738 #endif /* _WIN32 */
1740 static int init_timer_alarm(void)
1742 struct qemu_alarm_timer *t = NULL;
1743 int i, err = -1;
1745 #ifndef _WIN32
1746 int fds[2];
1748 err = pipe(fds);
1749 if (err == -1)
1750 return -errno;
1752 err = fcntl_setfl(fds[0], O_NONBLOCK);
1753 if (err < 0)
1754 goto fail;
1756 err = fcntl_setfl(fds[1], O_NONBLOCK);
1757 if (err < 0)
1758 goto fail;
1760 alarm_timer_rfd = fds[0];
1761 alarm_timer_wfd = fds[1];
1762 #endif
1764 for (i = 0; alarm_timers[i].name; i++) {
1765 t = &alarm_timers[i];
1767 err = t->start(t);
1768 if (!err)
1769 break;
1772 if (err) {
1773 err = -ENOENT;
1774 goto fail;
1777 #ifndef _WIN32
1778 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1779 try_to_rearm_timer, NULL, t);
1780 #endif
1782 alarm_timer = t;
1784 return 0;
1786 fail:
1787 #ifndef _WIN32
1788 close(fds[0]);
1789 close(fds[1]);
1790 #endif
1791 return err;
1794 static void quit_timers(void)
1796 alarm_timer->stop(alarm_timer);
1797 alarm_timer = NULL;
1800 /***********************************************************/
1801 /* host time/date access */
1802 void qemu_get_timedate(struct tm *tm, int offset)
1804 time_t ti;
1805 struct tm *ret;
1807 time(&ti);
1808 ti += offset;
1809 if (rtc_date_offset == -1) {
1810 if (rtc_utc)
1811 ret = gmtime(&ti);
1812 else
1813 ret = localtime(&ti);
1814 } else {
1815 ti -= rtc_date_offset;
1816 ret = gmtime(&ti);
1819 memcpy(tm, ret, sizeof(struct tm));
1822 int qemu_timedate_diff(struct tm *tm)
1824 time_t seconds;
1826 if (rtc_date_offset == -1)
1827 if (rtc_utc)
1828 seconds = mktimegm(tm);
1829 else
1830 seconds = mktime(tm);
1831 else
1832 seconds = mktimegm(tm) + rtc_date_offset;
1834 return seconds - time(NULL);
1837 #ifdef _WIN32
1838 static void socket_cleanup(void)
1840 WSACleanup();
1843 static int socket_init(void)
1845 WSADATA Data;
1846 int ret, err;
1848 ret = WSAStartup(MAKEWORD(2,2), &Data);
1849 if (ret != 0) {
1850 err = WSAGetLastError();
1851 fprintf(stderr, "WSAStartup: %d\n", err);
1852 return -1;
1854 atexit(socket_cleanup);
1855 return 0;
1857 #endif
1859 const char *get_opt_name(char *buf, int buf_size, const char *p)
1861 char *q;
1863 q = buf;
1864 while (*p != '\0' && *p != '=') {
1865 if (q && (q - buf) < buf_size - 1)
1866 *q++ = *p;
1867 p++;
1869 if (q)
1870 *q = '\0';
1872 return p;
1875 const char *get_opt_value(char *buf, int buf_size, const char *p)
1877 char *q;
1879 q = buf;
1880 while (*p != '\0') {
1881 if (*p == ',') {
1882 if (*(p + 1) != ',')
1883 break;
1884 p++;
1886 if (q && (q - buf) < buf_size - 1)
1887 *q++ = *p;
1888 p++;
1890 if (q)
1891 *q = '\0';
1893 return p;
1896 int get_param_value(char *buf, int buf_size,
1897 const char *tag, const char *str)
1899 const char *p;
1900 char option[128];
1902 p = str;
1903 for(;;) {
1904 p = get_opt_name(option, sizeof(option), p);
1905 if (*p != '=')
1906 break;
1907 p++;
1908 if (!strcmp(tag, option)) {
1909 (void)get_opt_value(buf, buf_size, p);
1910 return strlen(buf);
1911 } else {
1912 p = get_opt_value(NULL, 0, p);
1914 if (*p != ',')
1915 break;
1916 p++;
1918 return 0;
1921 int check_params(char *buf, int buf_size,
1922 const char * const *params, const char *str)
1924 const char *p;
1925 int i;
1927 p = str;
1928 for(;;) {
1929 p = get_opt_name(buf, buf_size, p);
1930 if (*p != '=')
1931 return -1;
1932 p++;
1933 for(i = 0; params[i] != NULL; i++)
1934 if (!strcmp(params[i], buf))
1935 break;
1936 if (params[i] == NULL)
1937 return -1;
1938 p = get_opt_value(NULL, 0, p);
1939 if (*p != ',')
1940 break;
1941 p++;
1943 return 0;
1946 /***********************************************************/
1947 /* Bluetooth support */
1948 static int nb_hcis;
1949 static int cur_hci;
1950 static struct HCIInfo *hci_table[MAX_NICS];
1952 static struct bt_vlan_s {
1953 struct bt_scatternet_s net;
1954 int id;
1955 struct bt_vlan_s *next;
1956 } *first_bt_vlan;
1958 /* find or alloc a new bluetooth "VLAN" */
1959 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1961 struct bt_vlan_s **pvlan, *vlan;
1962 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1963 if (vlan->id == id)
1964 return &vlan->net;
1966 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1967 vlan->id = id;
1968 pvlan = &first_bt_vlan;
1969 while (*pvlan != NULL)
1970 pvlan = &(*pvlan)->next;
1971 *pvlan = vlan;
1972 return &vlan->net;
1975 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1979 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1981 return -ENOTSUP;
1984 static struct HCIInfo null_hci = {
1985 .cmd_send = null_hci_send,
1986 .sco_send = null_hci_send,
1987 .acl_send = null_hci_send,
1988 .bdaddr_set = null_hci_addr_set,
1991 struct HCIInfo *qemu_next_hci(void)
1993 if (cur_hci == nb_hcis)
1994 return &null_hci;
1996 return hci_table[cur_hci++];
1999 static struct HCIInfo *hci_init(const char *str)
2001 char *endp;
2002 struct bt_scatternet_s *vlan = 0;
2004 if (!strcmp(str, "null"))
2005 /* null */
2006 return &null_hci;
2007 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2008 /* host[:hciN] */
2009 return bt_host_hci(str[4] ? str + 5 : "hci0");
2010 else if (!strncmp(str, "hci", 3)) {
2011 /* hci[,vlan=n] */
2012 if (str[3]) {
2013 if (!strncmp(str + 3, ",vlan=", 6)) {
2014 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2015 if (*endp)
2016 vlan = 0;
2018 } else
2019 vlan = qemu_find_bt_vlan(0);
2020 if (vlan)
2021 return bt_new_hci(vlan);
2024 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2026 return 0;
2029 static int bt_hci_parse(const char *str)
2031 struct HCIInfo *hci;
2032 bdaddr_t bdaddr;
2034 if (nb_hcis >= MAX_NICS) {
2035 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2036 return -1;
2039 hci = hci_init(str);
2040 if (!hci)
2041 return -1;
2043 bdaddr.b[0] = 0x52;
2044 bdaddr.b[1] = 0x54;
2045 bdaddr.b[2] = 0x00;
2046 bdaddr.b[3] = 0x12;
2047 bdaddr.b[4] = 0x34;
2048 bdaddr.b[5] = 0x56 + nb_hcis;
2049 hci->bdaddr_set(hci, bdaddr.b);
2051 hci_table[nb_hcis++] = hci;
2053 return 0;
2056 static void bt_vhci_add(int vlan_id)
2058 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2060 if (!vlan->slave)
2061 fprintf(stderr, "qemu: warning: adding a VHCI to "
2062 "an empty scatternet %i\n", vlan_id);
2064 bt_vhci_init(bt_new_hci(vlan));
2067 static struct bt_device_s *bt_device_add(const char *opt)
2069 struct bt_scatternet_s *vlan;
2070 int vlan_id = 0;
2071 char *endp = strstr(opt, ",vlan=");
2072 int len = (endp ? endp - opt : strlen(opt)) + 1;
2073 char devname[10];
2075 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2077 if (endp) {
2078 vlan_id = strtol(endp + 6, &endp, 0);
2079 if (*endp) {
2080 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2081 return 0;
2085 vlan = qemu_find_bt_vlan(vlan_id);
2087 if (!vlan->slave)
2088 fprintf(stderr, "qemu: warning: adding a slave device to "
2089 "an empty scatternet %i\n", vlan_id);
2091 if (!strcmp(devname, "keyboard"))
2092 return bt_keyboard_init(vlan);
2094 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2095 return 0;
2098 static int bt_parse(const char *opt)
2100 const char *endp, *p;
2101 int vlan;
2103 if (strstart(opt, "hci", &endp)) {
2104 if (!*endp || *endp == ',') {
2105 if (*endp)
2106 if (!strstart(endp, ",vlan=", 0))
2107 opt = endp + 1;
2109 return bt_hci_parse(opt);
2111 } else if (strstart(opt, "vhci", &endp)) {
2112 if (!*endp || *endp == ',') {
2113 if (*endp) {
2114 if (strstart(endp, ",vlan=", &p)) {
2115 vlan = strtol(p, (char **) &endp, 0);
2116 if (*endp) {
2117 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2118 return 1;
2120 } else {
2121 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2122 return 1;
2124 } else
2125 vlan = 0;
2127 bt_vhci_add(vlan);
2128 return 0;
2130 } else if (strstart(opt, "device:", &endp))
2131 return !bt_device_add(endp);
2133 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2134 return 1;
2137 /***********************************************************/
2138 /* QEMU Block devices */
2140 #define HD_ALIAS "index=%d,media=disk"
2141 #ifdef TARGET_PPC
2142 #define CDROM_ALIAS "index=1,media=cdrom"
2143 #else
2144 #define CDROM_ALIAS "index=2,media=cdrom"
2145 #endif
2146 #define FD_ALIAS "index=%d,if=floppy"
2147 #define PFLASH_ALIAS "if=pflash"
2148 #define MTD_ALIAS "if=mtd"
2149 #define SD_ALIAS "index=0,if=sd"
2151 static int drive_opt_get_free_idx(void)
2153 int index;
2155 for (index = 0; index < MAX_DRIVES; index++)
2156 if (!drives_opt[index].used) {
2157 drives_opt[index].used = 1;
2158 return index;
2161 return -1;
2164 static int drive_get_free_idx(void)
2166 int index;
2168 for (index = 0; index < MAX_DRIVES; index++)
2169 if (!drives_table[index].used) {
2170 drives_table[index].used = 1;
2171 return index;
2174 return -1;
2177 int drive_add(const char *file, const char *fmt, ...)
2179 va_list ap;
2180 int index = drive_opt_get_free_idx();
2182 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2183 fprintf(stderr, "qemu: too many drives\n");
2184 return -1;
2187 drives_opt[index].file = file;
2188 va_start(ap, fmt);
2189 vsnprintf(drives_opt[index].opt,
2190 sizeof(drives_opt[0].opt), fmt, ap);
2191 va_end(ap);
2193 nb_drives_opt++;
2194 return index;
2197 void drive_remove(int index)
2199 drives_opt[index].used = 0;
2200 nb_drives_opt--;
2203 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2205 int index;
2207 /* seek interface, bus and unit */
2209 for (index = 0; index < MAX_DRIVES; index++)
2210 if (drives_table[index].type == type &&
2211 drives_table[index].bus == bus &&
2212 drives_table[index].unit == unit &&
2213 drives_table[index].used)
2214 return index;
2216 return -1;
2219 int drive_get_max_bus(BlockInterfaceType type)
2221 int max_bus;
2222 int index;
2224 max_bus = -1;
2225 for (index = 0; index < nb_drives; index++) {
2226 if(drives_table[index].type == type &&
2227 drives_table[index].bus > max_bus)
2228 max_bus = drives_table[index].bus;
2230 return max_bus;
2233 const char *drive_get_serial(BlockDriverState *bdrv)
2235 int index;
2237 for (index = 0; index < nb_drives; index++)
2238 if (drives_table[index].bdrv == bdrv)
2239 return drives_table[index].serial;
2241 return "\0";
2244 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2246 int index;
2248 for (index = 0; index < nb_drives; index++)
2249 if (drives_table[index].bdrv == bdrv)
2250 return drives_table[index].onerror;
2252 return BLOCK_ERR_STOP_ENOSPC;
2255 static void bdrv_format_print(void *opaque, const char *name)
2257 fprintf(stderr, " %s", name);
2260 void drive_uninit(BlockDriverState *bdrv)
2262 int i;
2264 for (i = 0; i < MAX_DRIVES; i++)
2265 if (drives_table[i].bdrv == bdrv) {
2266 drives_table[i].bdrv = NULL;
2267 drives_table[i].used = 0;
2268 drive_remove(drives_table[i].drive_opt_idx);
2269 nb_drives--;
2270 break;
2274 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2276 char buf[128];
2277 char file[1024];
2278 char devname[128];
2279 char serial[21];
2280 const char *mediastr = "";
2281 BlockInterfaceType type;
2282 enum { MEDIA_DISK, MEDIA_CDROM } media;
2283 int bus_id, unit_id;
2284 int cyls, heads, secs, translation;
2285 BlockDriverState *bdrv;
2286 BlockDriver *drv = NULL;
2287 QEMUMachine *machine = opaque;
2288 int max_devs;
2289 int index;
2290 int cache;
2291 int bdrv_flags, onerror;
2292 int drives_table_idx;
2293 char *str = arg->opt;
2294 static const char * const params[] = { "bus", "unit", "if", "index",
2295 "cyls", "heads", "secs", "trans",
2296 "media", "snapshot", "file",
2297 "cache", "format", "serial", "werror",
2298 NULL };
2300 if (check_params(buf, sizeof(buf), params, str) < 0) {
2301 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2302 buf, str);
2303 return -1;
2306 file[0] = 0;
2307 cyls = heads = secs = 0;
2308 bus_id = 0;
2309 unit_id = -1;
2310 translation = BIOS_ATA_TRANSLATION_AUTO;
2311 index = -1;
2312 cache = 3;
2314 if (machine->use_scsi) {
2315 type = IF_SCSI;
2316 max_devs = MAX_SCSI_DEVS;
2317 pstrcpy(devname, sizeof(devname), "scsi");
2318 } else {
2319 type = IF_IDE;
2320 max_devs = MAX_IDE_DEVS;
2321 pstrcpy(devname, sizeof(devname), "ide");
2323 media = MEDIA_DISK;
2325 /* extract parameters */
2327 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2328 bus_id = strtol(buf, NULL, 0);
2329 if (bus_id < 0) {
2330 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2331 return -1;
2335 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2336 unit_id = strtol(buf, NULL, 0);
2337 if (unit_id < 0) {
2338 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2339 return -1;
2343 if (get_param_value(buf, sizeof(buf), "if", str)) {
2344 pstrcpy(devname, sizeof(devname), buf);
2345 if (!strcmp(buf, "ide")) {
2346 type = IF_IDE;
2347 max_devs = MAX_IDE_DEVS;
2348 } else if (!strcmp(buf, "scsi")) {
2349 type = IF_SCSI;
2350 max_devs = MAX_SCSI_DEVS;
2351 } else if (!strcmp(buf, "floppy")) {
2352 type = IF_FLOPPY;
2353 max_devs = 0;
2354 } else if (!strcmp(buf, "pflash")) {
2355 type = IF_PFLASH;
2356 max_devs = 0;
2357 } else if (!strcmp(buf, "mtd")) {
2358 type = IF_MTD;
2359 max_devs = 0;
2360 } else if (!strcmp(buf, "sd")) {
2361 type = IF_SD;
2362 max_devs = 0;
2363 } else if (!strcmp(buf, "virtio")) {
2364 type = IF_VIRTIO;
2365 max_devs = 0;
2366 } else {
2367 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2368 return -1;
2372 if (get_param_value(buf, sizeof(buf), "index", str)) {
2373 index = strtol(buf, NULL, 0);
2374 if (index < 0) {
2375 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2376 return -1;
2380 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2381 cyls = strtol(buf, NULL, 0);
2384 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2385 heads = strtol(buf, NULL, 0);
2388 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2389 secs = strtol(buf, NULL, 0);
2392 if (cyls || heads || secs) {
2393 if (cyls < 1 || cyls > 16383) {
2394 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2395 return -1;
2397 if (heads < 1 || heads > 16) {
2398 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2399 return -1;
2401 if (secs < 1 || secs > 63) {
2402 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2403 return -1;
2407 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2408 if (!cyls) {
2409 fprintf(stderr,
2410 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2411 str);
2412 return -1;
2414 if (!strcmp(buf, "none"))
2415 translation = BIOS_ATA_TRANSLATION_NONE;
2416 else if (!strcmp(buf, "lba"))
2417 translation = BIOS_ATA_TRANSLATION_LBA;
2418 else if (!strcmp(buf, "auto"))
2419 translation = BIOS_ATA_TRANSLATION_AUTO;
2420 else {
2421 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2422 return -1;
2426 if (get_param_value(buf, sizeof(buf), "media", str)) {
2427 if (!strcmp(buf, "disk")) {
2428 media = MEDIA_DISK;
2429 } else if (!strcmp(buf, "cdrom")) {
2430 if (cyls || secs || heads) {
2431 fprintf(stderr,
2432 "qemu: '%s' invalid physical CHS format\n", str);
2433 return -1;
2435 media = MEDIA_CDROM;
2436 } else {
2437 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2438 return -1;
2442 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2443 if (!strcmp(buf, "on"))
2444 snapshot = 1;
2445 else if (!strcmp(buf, "off"))
2446 snapshot = 0;
2447 else {
2448 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2449 return -1;
2453 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2454 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2455 cache = 0;
2456 else if (!strcmp(buf, "writethrough"))
2457 cache = 1;
2458 else if (!strcmp(buf, "writeback"))
2459 cache = 2;
2460 else {
2461 fprintf(stderr, "qemu: invalid cache option\n");
2462 return -1;
2466 if (get_param_value(buf, sizeof(buf), "format", str)) {
2467 if (strcmp(buf, "?") == 0) {
2468 fprintf(stderr, "qemu: Supported formats:");
2469 bdrv_iterate_format(bdrv_format_print, NULL);
2470 fprintf(stderr, "\n");
2471 return -1;
2473 drv = bdrv_find_format(buf);
2474 if (!drv) {
2475 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2476 return -1;
2480 if (arg->file == NULL)
2481 get_param_value(file, sizeof(file), "file", str);
2482 else
2483 pstrcpy(file, sizeof(file), arg->file);
2485 if (!get_param_value(serial, sizeof(serial), "serial", str))
2486 memset(serial, 0, sizeof(serial));
2488 onerror = BLOCK_ERR_STOP_ENOSPC;
2489 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2490 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2491 fprintf(stderr, "werror is no supported by this format\n");
2492 return -1;
2494 if (!strcmp(buf, "ignore"))
2495 onerror = BLOCK_ERR_IGNORE;
2496 else if (!strcmp(buf, "enospc"))
2497 onerror = BLOCK_ERR_STOP_ENOSPC;
2498 else if (!strcmp(buf, "stop"))
2499 onerror = BLOCK_ERR_STOP_ANY;
2500 else if (!strcmp(buf, "report"))
2501 onerror = BLOCK_ERR_REPORT;
2502 else {
2503 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2504 return -1;
2508 /* compute bus and unit according index */
2510 if (index != -1) {
2511 if (bus_id != 0 || unit_id != -1) {
2512 fprintf(stderr,
2513 "qemu: '%s' index cannot be used with bus and unit\n", str);
2514 return -1;
2516 if (max_devs == 0)
2518 unit_id = index;
2519 bus_id = 0;
2520 } else {
2521 unit_id = index % max_devs;
2522 bus_id = index / max_devs;
2526 /* if user doesn't specify a unit_id,
2527 * try to find the first free
2530 if (unit_id == -1) {
2531 unit_id = 0;
2532 while (drive_get_index(type, bus_id, unit_id) != -1) {
2533 unit_id++;
2534 if (max_devs && unit_id >= max_devs) {
2535 unit_id -= max_devs;
2536 bus_id++;
2541 /* check unit id */
2543 if (max_devs && unit_id >= max_devs) {
2544 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2545 str, unit_id, max_devs - 1);
2546 return -1;
2550 * ignore multiple definitions
2553 if (drive_get_index(type, bus_id, unit_id) != -1)
2554 return -2;
2556 /* init */
2558 if (type == IF_IDE || type == IF_SCSI)
2559 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2560 if (max_devs)
2561 snprintf(buf, sizeof(buf), "%s%i%s%i",
2562 devname, bus_id, mediastr, unit_id);
2563 else
2564 snprintf(buf, sizeof(buf), "%s%s%i",
2565 devname, mediastr, unit_id);
2566 bdrv = bdrv_new(buf);
2567 drives_table_idx = drive_get_free_idx();
2568 drives_table[drives_table_idx].bdrv = bdrv;
2569 drives_table[drives_table_idx].type = type;
2570 drives_table[drives_table_idx].bus = bus_id;
2571 drives_table[drives_table_idx].unit = unit_id;
2572 drives_table[drives_table_idx].onerror = onerror;
2573 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2574 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2575 nb_drives++;
2577 switch(type) {
2578 case IF_IDE:
2579 case IF_SCSI:
2580 switch(media) {
2581 case MEDIA_DISK:
2582 if (cyls != 0) {
2583 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2584 bdrv_set_translation_hint(bdrv, translation);
2586 break;
2587 case MEDIA_CDROM:
2588 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2589 break;
2591 break;
2592 case IF_SD:
2593 /* FIXME: This isn't really a floppy, but it's a reasonable
2594 approximation. */
2595 case IF_FLOPPY:
2596 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2597 break;
2598 case IF_PFLASH:
2599 case IF_MTD:
2600 case IF_VIRTIO:
2601 break;
2603 if (!file[0])
2604 return -2;
2605 bdrv_flags = 0;
2606 if (snapshot) {
2607 bdrv_flags |= BDRV_O_SNAPSHOT;
2608 cache = 2; /* always use write-back with snapshot */
2610 if (cache == 0) /* no caching */
2611 bdrv_flags |= BDRV_O_NOCACHE;
2612 else if (cache == 2) /* write-back */
2613 bdrv_flags |= BDRV_O_CACHE_WB;
2614 else if (cache == 3) /* not specified */
2615 bdrv_flags |= BDRV_O_CACHE_DEF;
2616 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2617 fprintf(stderr, "qemu: could not open disk image %s\n",
2618 file);
2619 return -1;
2621 if (bdrv_key_required(bdrv))
2622 autostart = 0;
2623 return drives_table_idx;
2626 /***********************************************************/
2627 /* USB devices */
2629 static USBPort *used_usb_ports;
2630 static USBPort *free_usb_ports;
2632 /* ??? Maybe change this to register a hub to keep track of the topology. */
2633 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2634 usb_attachfn attach)
2636 port->opaque = opaque;
2637 port->index = index;
2638 port->attach = attach;
2639 port->next = free_usb_ports;
2640 free_usb_ports = port;
2643 int usb_device_add_dev(USBDevice *dev)
2645 USBPort *port;
2647 /* Find a USB port to add the device to. */
2648 port = free_usb_ports;
2649 if (!port->next) {
2650 USBDevice *hub;
2652 /* Create a new hub and chain it on. */
2653 free_usb_ports = NULL;
2654 port->next = used_usb_ports;
2655 used_usb_ports = port;
2657 hub = usb_hub_init(VM_USB_HUB_SIZE);
2658 usb_attach(port, hub);
2659 port = free_usb_ports;
2662 free_usb_ports = port->next;
2663 port->next = used_usb_ports;
2664 used_usb_ports = port;
2665 usb_attach(port, dev);
2666 return 0;
2669 static int usb_device_add(const char *devname, int is_hotplug)
2671 const char *p;
2672 USBDevice *dev;
2674 if (!free_usb_ports)
2675 return -1;
2677 if (strstart(devname, "host:", &p)) {
2678 dev = usb_host_device_open(p);
2679 } else if (!strcmp(devname, "mouse")) {
2680 dev = usb_mouse_init();
2681 } else if (!strcmp(devname, "tablet")) {
2682 dev = usb_tablet_init();
2683 } else if (!strcmp(devname, "keyboard")) {
2684 dev = usb_keyboard_init();
2685 } else if (strstart(devname, "disk:", &p)) {
2686 BlockDriverState *bs;
2688 dev = usb_msd_init(p, &bs);
2689 if (!dev)
2690 return -1;
2691 if (bdrv_key_required(bs)) {
2692 autostart = 0;
2693 if (is_hotplug && monitor_read_bdrv_key(bs) < 0) {
2694 dev->handle_destroy(dev);
2695 return -1;
2698 } else if (!strcmp(devname, "wacom-tablet")) {
2699 dev = usb_wacom_init();
2700 } else if (strstart(devname, "serial:", &p)) {
2701 dev = usb_serial_init(p);
2702 #ifdef CONFIG_BRLAPI
2703 } else if (!strcmp(devname, "braille")) {
2704 dev = usb_baum_init();
2705 #endif
2706 } else if (strstart(devname, "net:", &p)) {
2707 int nic = nb_nics;
2709 if (net_client_init("nic", p) < 0)
2710 return -1;
2711 nd_table[nic].model = "usb";
2712 dev = usb_net_init(&nd_table[nic]);
2713 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2714 dev = usb_bt_init(devname[2] ? hci_init(p) :
2715 bt_new_hci(qemu_find_bt_vlan(0)));
2716 } else {
2717 return -1;
2719 if (!dev)
2720 return -1;
2722 return usb_device_add_dev(dev);
2725 int usb_device_del_addr(int bus_num, int addr)
2727 USBPort *port;
2728 USBPort **lastp;
2729 USBDevice *dev;
2731 if (!used_usb_ports)
2732 return -1;
2734 if (bus_num != 0)
2735 return -1;
2737 lastp = &used_usb_ports;
2738 port = used_usb_ports;
2739 while (port && port->dev->addr != addr) {
2740 lastp = &port->next;
2741 port = port->next;
2744 if (!port)
2745 return -1;
2747 dev = port->dev;
2748 *lastp = port->next;
2749 usb_attach(port, NULL);
2750 dev->handle_destroy(dev);
2751 port->next = free_usb_ports;
2752 free_usb_ports = port;
2753 return 0;
2756 static int usb_device_del(const char *devname)
2758 int bus_num, addr;
2759 const char *p;
2761 if (strstart(devname, "host:", &p))
2762 return usb_host_device_close(p);
2764 if (!used_usb_ports)
2765 return -1;
2767 p = strchr(devname, '.');
2768 if (!p)
2769 return -1;
2770 bus_num = strtoul(devname, NULL, 0);
2771 addr = strtoul(p + 1, NULL, 0);
2773 return usb_device_del_addr(bus_num, addr);
2776 void do_usb_add(const char *devname)
2778 usb_device_add(devname, 1);
2781 void do_usb_del(const char *devname)
2783 usb_device_del(devname);
2786 void usb_info(void)
2788 USBDevice *dev;
2789 USBPort *port;
2790 const char *speed_str;
2792 if (!usb_enabled) {
2793 term_printf("USB support not enabled\n");
2794 return;
2797 for (port = used_usb_ports; port; port = port->next) {
2798 dev = port->dev;
2799 if (!dev)
2800 continue;
2801 switch(dev->speed) {
2802 case USB_SPEED_LOW:
2803 speed_str = "1.5";
2804 break;
2805 case USB_SPEED_FULL:
2806 speed_str = "12";
2807 break;
2808 case USB_SPEED_HIGH:
2809 speed_str = "480";
2810 break;
2811 default:
2812 speed_str = "?";
2813 break;
2815 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2816 0, dev->addr, speed_str, dev->devname);
2820 /***********************************************************/
2821 /* PCMCIA/Cardbus */
2823 static struct pcmcia_socket_entry_s {
2824 struct pcmcia_socket_s *socket;
2825 struct pcmcia_socket_entry_s *next;
2826 } *pcmcia_sockets = 0;
2828 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2830 struct pcmcia_socket_entry_s *entry;
2832 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2833 entry->socket = socket;
2834 entry->next = pcmcia_sockets;
2835 pcmcia_sockets = entry;
2838 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2840 struct pcmcia_socket_entry_s *entry, **ptr;
2842 ptr = &pcmcia_sockets;
2843 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2844 if (entry->socket == socket) {
2845 *ptr = entry->next;
2846 qemu_free(entry);
2850 void pcmcia_info(void)
2852 struct pcmcia_socket_entry_s *iter;
2853 if (!pcmcia_sockets)
2854 term_printf("No PCMCIA sockets\n");
2856 for (iter = pcmcia_sockets; iter; iter = iter->next)
2857 term_printf("%s: %s\n", iter->socket->slot_string,
2858 iter->socket->attached ? iter->socket->card_string :
2859 "Empty");
2862 /***********************************************************/
2863 /* register display */
2865 void register_displaystate(DisplayState *ds)
2867 DisplayState **s;
2868 s = &display_state;
2869 while (*s != NULL)
2870 s = &(*s)->next;
2871 ds->next = NULL;
2872 *s = ds;
2875 DisplayState *get_displaystate(void)
2877 return display_state;
2880 /* dumb display */
2882 static void dumb_display_init(void)
2884 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2885 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2886 register_displaystate(ds);
2889 /***********************************************************/
2890 /* I/O handling */
2892 #define MAX_IO_HANDLERS 64
2894 typedef struct IOHandlerRecord {
2895 int fd;
2896 IOCanRWHandler *fd_read_poll;
2897 IOHandler *fd_read;
2898 IOHandler *fd_write;
2899 int deleted;
2900 void *opaque;
2901 /* temporary data */
2902 struct pollfd *ufd;
2903 struct IOHandlerRecord *next;
2904 } IOHandlerRecord;
2906 static IOHandlerRecord *first_io_handler;
2908 /* XXX: fd_read_poll should be suppressed, but an API change is
2909 necessary in the character devices to suppress fd_can_read(). */
2910 int qemu_set_fd_handler2(int fd,
2911 IOCanRWHandler *fd_read_poll,
2912 IOHandler *fd_read,
2913 IOHandler *fd_write,
2914 void *opaque)
2916 IOHandlerRecord **pioh, *ioh;
2918 if (!fd_read && !fd_write) {
2919 pioh = &first_io_handler;
2920 for(;;) {
2921 ioh = *pioh;
2922 if (ioh == NULL)
2923 break;
2924 if (ioh->fd == fd) {
2925 ioh->deleted = 1;
2926 break;
2928 pioh = &ioh->next;
2930 } else {
2931 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2932 if (ioh->fd == fd)
2933 goto found;
2935 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2936 ioh->next = first_io_handler;
2937 first_io_handler = ioh;
2938 found:
2939 ioh->fd = fd;
2940 ioh->fd_read_poll = fd_read_poll;
2941 ioh->fd_read = fd_read;
2942 ioh->fd_write = fd_write;
2943 ioh->opaque = opaque;
2944 ioh->deleted = 0;
2946 return 0;
2949 int qemu_set_fd_handler(int fd,
2950 IOHandler *fd_read,
2951 IOHandler *fd_write,
2952 void *opaque)
2954 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2957 #ifdef _WIN32
2958 /***********************************************************/
2959 /* Polling handling */
2961 typedef struct PollingEntry {
2962 PollingFunc *func;
2963 void *opaque;
2964 struct PollingEntry *next;
2965 } PollingEntry;
2967 static PollingEntry *first_polling_entry;
2969 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2971 PollingEntry **ppe, *pe;
2972 pe = qemu_mallocz(sizeof(PollingEntry));
2973 pe->func = func;
2974 pe->opaque = opaque;
2975 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2976 *ppe = pe;
2977 return 0;
2980 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2982 PollingEntry **ppe, *pe;
2983 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2984 pe = *ppe;
2985 if (pe->func == func && pe->opaque == opaque) {
2986 *ppe = pe->next;
2987 qemu_free(pe);
2988 break;
2993 /***********************************************************/
2994 /* Wait objects support */
2995 typedef struct WaitObjects {
2996 int num;
2997 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2998 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2999 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3000 } WaitObjects;
3002 static WaitObjects wait_objects = {0};
3004 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3006 WaitObjects *w = &wait_objects;
3008 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3009 return -1;
3010 w->events[w->num] = handle;
3011 w->func[w->num] = func;
3012 w->opaque[w->num] = opaque;
3013 w->num++;
3014 return 0;
3017 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3019 int i, found;
3020 WaitObjects *w = &wait_objects;
3022 found = 0;
3023 for (i = 0; i < w->num; i++) {
3024 if (w->events[i] == handle)
3025 found = 1;
3026 if (found) {
3027 w->events[i] = w->events[i + 1];
3028 w->func[i] = w->func[i + 1];
3029 w->opaque[i] = w->opaque[i + 1];
3032 if (found)
3033 w->num--;
3035 #endif
3037 /***********************************************************/
3038 /* ram save/restore */
3040 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3042 int v;
3044 v = qemu_get_byte(f);
3045 switch(v) {
3046 case 0:
3047 if (qemu_get_buffer(f, buf, len) != len)
3048 return -EIO;
3049 break;
3050 case 1:
3051 v = qemu_get_byte(f);
3052 memset(buf, v, len);
3053 break;
3054 default:
3055 return -EINVAL;
3058 if (qemu_file_has_error(f))
3059 return -EIO;
3061 return 0;
3064 static int ram_load_v1(QEMUFile *f, void *opaque)
3066 int ret;
3067 ram_addr_t i;
3069 if (qemu_get_be32(f) != phys_ram_size)
3070 return -EINVAL;
3071 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3072 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3073 if (ret)
3074 return ret;
3076 return 0;
3079 #define BDRV_HASH_BLOCK_SIZE 1024
3080 #define IOBUF_SIZE 4096
3081 #define RAM_CBLOCK_MAGIC 0xfabe
3083 typedef struct RamDecompressState {
3084 z_stream zstream;
3085 QEMUFile *f;
3086 uint8_t buf[IOBUF_SIZE];
3087 } RamDecompressState;
3089 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3091 int ret;
3092 memset(s, 0, sizeof(*s));
3093 s->f = f;
3094 ret = inflateInit(&s->zstream);
3095 if (ret != Z_OK)
3096 return -1;
3097 return 0;
3100 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3102 int ret, clen;
3104 s->zstream.avail_out = len;
3105 s->zstream.next_out = buf;
3106 while (s->zstream.avail_out > 0) {
3107 if (s->zstream.avail_in == 0) {
3108 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3109 return -1;
3110 clen = qemu_get_be16(s->f);
3111 if (clen > IOBUF_SIZE)
3112 return -1;
3113 qemu_get_buffer(s->f, s->buf, clen);
3114 s->zstream.avail_in = clen;
3115 s->zstream.next_in = s->buf;
3117 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3118 if (ret != Z_OK && ret != Z_STREAM_END) {
3119 return -1;
3122 return 0;
3125 static void ram_decompress_close(RamDecompressState *s)
3127 inflateEnd(&s->zstream);
3130 #define RAM_SAVE_FLAG_FULL 0x01
3131 #define RAM_SAVE_FLAG_COMPRESS 0x02
3132 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3133 #define RAM_SAVE_FLAG_PAGE 0x08
3134 #define RAM_SAVE_FLAG_EOS 0x10
3136 static int is_dup_page(uint8_t *page, uint8_t ch)
3138 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3139 uint32_t *array = (uint32_t *)page;
3140 int i;
3142 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3143 if (array[i] != val)
3144 return 0;
3147 return 1;
3150 static int ram_save_block(QEMUFile *f)
3152 static ram_addr_t current_addr = 0;
3153 ram_addr_t saved_addr = current_addr;
3154 ram_addr_t addr = 0;
3155 int found = 0;
3157 while (addr < phys_ram_size) {
3158 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3159 uint8_t ch;
3161 cpu_physical_memory_reset_dirty(current_addr,
3162 current_addr + TARGET_PAGE_SIZE,
3163 MIGRATION_DIRTY_FLAG);
3165 ch = *(phys_ram_base + current_addr);
3167 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3168 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3169 qemu_put_byte(f, ch);
3170 } else {
3171 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3172 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3175 found = 1;
3176 break;
3178 addr += TARGET_PAGE_SIZE;
3179 current_addr = (saved_addr + addr) % phys_ram_size;
3182 return found;
3185 static ram_addr_t ram_save_threshold = 10;
3187 static ram_addr_t ram_save_remaining(void)
3189 ram_addr_t addr;
3190 ram_addr_t count = 0;
3192 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3193 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3194 count++;
3197 return count;
3200 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3202 ram_addr_t addr;
3204 if (stage == 1) {
3205 /* Make sure all dirty bits are set */
3206 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3207 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3208 cpu_physical_memory_set_dirty(addr);
3211 /* Enable dirty memory tracking */
3212 cpu_physical_memory_set_dirty_tracking(1);
3214 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3217 while (!qemu_file_rate_limit(f)) {
3218 int ret;
3220 ret = ram_save_block(f);
3221 if (ret == 0) /* no more blocks */
3222 break;
3225 /* try transferring iterative blocks of memory */
3227 if (stage == 3) {
3229 /* flush all remaining blocks regardless of rate limiting */
3230 while (ram_save_block(f) != 0);
3231 cpu_physical_memory_set_dirty_tracking(0);
3234 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3236 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3239 static int ram_load_dead(QEMUFile *f, void *opaque)
3241 RamDecompressState s1, *s = &s1;
3242 uint8_t buf[10];
3243 ram_addr_t i;
3245 if (ram_decompress_open(s, f) < 0)
3246 return -EINVAL;
3247 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3248 if (ram_decompress_buf(s, buf, 1) < 0) {
3249 fprintf(stderr, "Error while reading ram block header\n");
3250 goto error;
3252 if (buf[0] == 0) {
3253 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3254 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3255 goto error;
3257 } else {
3258 error:
3259 printf("Error block header\n");
3260 return -EINVAL;
3263 ram_decompress_close(s);
3265 return 0;
3268 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3270 ram_addr_t addr;
3271 int flags;
3273 if (version_id == 1)
3274 return ram_load_v1(f, opaque);
3276 if (version_id == 2) {
3277 if (qemu_get_be32(f) != phys_ram_size)
3278 return -EINVAL;
3279 return ram_load_dead(f, opaque);
3282 if (version_id != 3)
3283 return -EINVAL;
3285 do {
3286 addr = qemu_get_be64(f);
3288 flags = addr & ~TARGET_PAGE_MASK;
3289 addr &= TARGET_PAGE_MASK;
3291 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3292 if (addr != phys_ram_size)
3293 return -EINVAL;
3296 if (flags & RAM_SAVE_FLAG_FULL) {
3297 if (ram_load_dead(f, opaque) < 0)
3298 return -EINVAL;
3301 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3302 uint8_t ch = qemu_get_byte(f);
3303 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3304 } else if (flags & RAM_SAVE_FLAG_PAGE)
3305 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3306 } while (!(flags & RAM_SAVE_FLAG_EOS));
3308 return 0;
3311 void qemu_service_io(void)
3313 CPUState *env = cpu_single_env;
3314 if (env) {
3315 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3316 #ifdef USE_KQEMU
3317 if (env->kqemu_enabled) {
3318 kqemu_cpu_interrupt(env);
3320 #endif
3324 /***********************************************************/
3325 /* bottom halves (can be seen as timers which expire ASAP) */
3327 struct QEMUBH {
3328 QEMUBHFunc *cb;
3329 void *opaque;
3330 int scheduled;
3331 int idle;
3332 int deleted;
3333 QEMUBH *next;
3336 static QEMUBH *first_bh = NULL;
3338 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3340 QEMUBH *bh;
3341 bh = qemu_mallocz(sizeof(QEMUBH));
3342 bh->cb = cb;
3343 bh->opaque = opaque;
3344 bh->next = first_bh;
3345 first_bh = bh;
3346 return bh;
3349 int qemu_bh_poll(void)
3351 QEMUBH *bh, **bhp;
3352 int ret;
3354 ret = 0;
3355 for (bh = first_bh; bh; bh = bh->next) {
3356 if (!bh->deleted && bh->scheduled) {
3357 bh->scheduled = 0;
3358 if (!bh->idle)
3359 ret = 1;
3360 bh->idle = 0;
3361 bh->cb(bh->opaque);
3365 /* remove deleted bhs */
3366 bhp = &first_bh;
3367 while (*bhp) {
3368 bh = *bhp;
3369 if (bh->deleted) {
3370 *bhp = bh->next;
3371 qemu_free(bh);
3372 } else
3373 bhp = &bh->next;
3376 return ret;
3379 void qemu_bh_schedule_idle(QEMUBH *bh)
3381 if (bh->scheduled)
3382 return;
3383 bh->scheduled = 1;
3384 bh->idle = 1;
3387 void qemu_bh_schedule(QEMUBH *bh)
3389 CPUState *env = cpu_single_env;
3390 if (bh->scheduled)
3391 return;
3392 bh->scheduled = 1;
3393 bh->idle = 0;
3394 /* stop the currently executing CPU to execute the BH ASAP */
3395 if (env) {
3396 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3400 void qemu_bh_cancel(QEMUBH *bh)
3402 bh->scheduled = 0;
3405 void qemu_bh_delete(QEMUBH *bh)
3407 bh->scheduled = 0;
3408 bh->deleted = 1;
3411 static void qemu_bh_update_timeout(int *timeout)
3413 QEMUBH *bh;
3415 for (bh = first_bh; bh; bh = bh->next) {
3416 if (!bh->deleted && bh->scheduled) {
3417 if (bh->idle) {
3418 /* idle bottom halves will be polled at least
3419 * every 10ms */
3420 *timeout = MIN(10, *timeout);
3421 } else {
3422 /* non-idle bottom halves will be executed
3423 * immediately */
3424 *timeout = 0;
3425 break;
3431 /***********************************************************/
3432 /* machine registration */
3434 static QEMUMachine *first_machine = NULL;
3435 QEMUMachine *current_machine = NULL;
3437 int qemu_register_machine(QEMUMachine *m)
3439 QEMUMachine **pm;
3440 pm = &first_machine;
3441 while (*pm != NULL)
3442 pm = &(*pm)->next;
3443 m->next = NULL;
3444 *pm = m;
3445 return 0;
3448 static QEMUMachine *find_machine(const char *name)
3450 QEMUMachine *m;
3452 for(m = first_machine; m != NULL; m = m->next) {
3453 if (!strcmp(m->name, name))
3454 return m;
3456 return NULL;
3459 /***********************************************************/
3460 /* main execution loop */
3462 static void gui_update(void *opaque)
3464 uint64_t interval = GUI_REFRESH_INTERVAL;
3465 DisplayState *ds = opaque;
3466 DisplayChangeListener *dcl = ds->listeners;
3468 dpy_refresh(ds);
3470 while (dcl != NULL) {
3471 if (dcl->gui_timer_interval &&
3472 dcl->gui_timer_interval < interval)
3473 interval = dcl->gui_timer_interval;
3474 dcl = dcl->next;
3476 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3479 static void nographic_update(void *opaque)
3481 uint64_t interval = GUI_REFRESH_INTERVAL;
3483 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3486 struct vm_change_state_entry {
3487 VMChangeStateHandler *cb;
3488 void *opaque;
3489 LIST_ENTRY (vm_change_state_entry) entries;
3492 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3494 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3495 void *opaque)
3497 VMChangeStateEntry *e;
3499 e = qemu_mallocz(sizeof (*e));
3501 e->cb = cb;
3502 e->opaque = opaque;
3503 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3504 return e;
3507 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3509 LIST_REMOVE (e, entries);
3510 qemu_free (e);
3513 static void vm_state_notify(int running, int reason)
3515 VMChangeStateEntry *e;
3517 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3518 e->cb(e->opaque, running, reason);
3522 void vm_start(void)
3524 if (!vm_running) {
3525 cpu_enable_ticks();
3526 vm_running = 1;
3527 vm_state_notify(1, 0);
3528 qemu_rearm_alarm_timer(alarm_timer);
3532 void vm_stop(int reason)
3534 if (vm_running) {
3535 cpu_disable_ticks();
3536 vm_running = 0;
3537 vm_state_notify(0, reason);
3541 /* reset/shutdown handler */
3543 typedef struct QEMUResetEntry {
3544 QEMUResetHandler *func;
3545 void *opaque;
3546 struct QEMUResetEntry *next;
3547 } QEMUResetEntry;
3549 static QEMUResetEntry *first_reset_entry;
3550 static int reset_requested;
3551 static int shutdown_requested;
3552 static int powerdown_requested;
3554 int qemu_shutdown_requested(void)
3556 int r = shutdown_requested;
3557 shutdown_requested = 0;
3558 return r;
3561 int qemu_reset_requested(void)
3563 int r = reset_requested;
3564 reset_requested = 0;
3565 return r;
3568 int qemu_powerdown_requested(void)
3570 int r = powerdown_requested;
3571 powerdown_requested = 0;
3572 return r;
3575 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3577 QEMUResetEntry **pre, *re;
3579 pre = &first_reset_entry;
3580 while (*pre != NULL)
3581 pre = &(*pre)->next;
3582 re = qemu_mallocz(sizeof(QEMUResetEntry));
3583 re->func = func;
3584 re->opaque = opaque;
3585 re->next = NULL;
3586 *pre = re;
3589 void qemu_system_reset(void)
3591 QEMUResetEntry *re;
3593 /* reset all devices */
3594 for(re = first_reset_entry; re != NULL; re = re->next) {
3595 re->func(re->opaque);
3599 void qemu_system_reset_request(void)
3601 if (no_reboot) {
3602 shutdown_requested = 1;
3603 } else {
3604 reset_requested = 1;
3606 if (cpu_single_env)
3607 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3610 void qemu_system_shutdown_request(void)
3612 shutdown_requested = 1;
3613 if (cpu_single_env)
3614 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3617 void qemu_system_powerdown_request(void)
3619 powerdown_requested = 1;
3620 if (cpu_single_env)
3621 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3624 #ifdef _WIN32
3625 static void host_main_loop_wait(int *timeout)
3627 int ret, ret2, i;
3628 PollingEntry *pe;
3631 /* XXX: need to suppress polling by better using win32 events */
3632 ret = 0;
3633 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3634 ret |= pe->func(pe->opaque);
3636 if (ret == 0) {
3637 int err;
3638 WaitObjects *w = &wait_objects;
3640 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3641 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3642 if (w->func[ret - WAIT_OBJECT_0])
3643 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3645 /* Check for additional signaled events */
3646 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3648 /* Check if event is signaled */
3649 ret2 = WaitForSingleObject(w->events[i], 0);
3650 if(ret2 == WAIT_OBJECT_0) {
3651 if (w->func[i])
3652 w->func[i](w->opaque[i]);
3653 } else if (ret2 == WAIT_TIMEOUT) {
3654 } else {
3655 err = GetLastError();
3656 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3659 } else if (ret == WAIT_TIMEOUT) {
3660 } else {
3661 err = GetLastError();
3662 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3666 *timeout = 0;
3668 #else
3669 static void host_main_loop_wait(int *timeout)
3672 #endif
3674 void main_loop_wait(int timeout)
3676 IOHandlerRecord *ioh;
3677 fd_set rfds, wfds, xfds;
3678 int ret, nfds;
3679 struct timeval tv;
3681 qemu_bh_update_timeout(&timeout);
3683 host_main_loop_wait(&timeout);
3685 /* poll any events */
3686 /* XXX: separate device handlers from system ones */
3687 nfds = -1;
3688 FD_ZERO(&rfds);
3689 FD_ZERO(&wfds);
3690 FD_ZERO(&xfds);
3691 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3692 if (ioh->deleted)
3693 continue;
3694 if (ioh->fd_read &&
3695 (!ioh->fd_read_poll ||
3696 ioh->fd_read_poll(ioh->opaque) != 0)) {
3697 FD_SET(ioh->fd, &rfds);
3698 if (ioh->fd > nfds)
3699 nfds = ioh->fd;
3701 if (ioh->fd_write) {
3702 FD_SET(ioh->fd, &wfds);
3703 if (ioh->fd > nfds)
3704 nfds = ioh->fd;
3708 tv.tv_sec = timeout / 1000;
3709 tv.tv_usec = (timeout % 1000) * 1000;
3711 #if defined(CONFIG_SLIRP)
3712 if (slirp_is_inited()) {
3713 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3715 #endif
3716 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3717 if (ret > 0) {
3718 IOHandlerRecord **pioh;
3720 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3721 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3722 ioh->fd_read(ioh->opaque);
3724 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3725 ioh->fd_write(ioh->opaque);
3729 /* remove deleted IO handlers */
3730 pioh = &first_io_handler;
3731 while (*pioh) {
3732 ioh = *pioh;
3733 if (ioh->deleted) {
3734 *pioh = ioh->next;
3735 qemu_free(ioh);
3736 } else
3737 pioh = &ioh->next;
3740 #if defined(CONFIG_SLIRP)
3741 if (slirp_is_inited()) {
3742 if (ret < 0) {
3743 FD_ZERO(&rfds);
3744 FD_ZERO(&wfds);
3745 FD_ZERO(&xfds);
3747 slirp_select_poll(&rfds, &wfds, &xfds);
3749 #endif
3751 /* vm time timers */
3752 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3753 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3754 qemu_get_clock(vm_clock));
3756 /* real time timers */
3757 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3758 qemu_get_clock(rt_clock));
3760 /* Check bottom-halves last in case any of the earlier events triggered
3761 them. */
3762 qemu_bh_poll();
3766 static int main_loop(void)
3768 int ret, timeout;
3769 #ifdef CONFIG_PROFILER
3770 int64_t ti;
3771 #endif
3772 CPUState *env;
3774 cur_cpu = first_cpu;
3775 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3776 for(;;) {
3777 if (vm_running) {
3779 for(;;) {
3780 /* get next cpu */
3781 env = next_cpu;
3782 #ifdef CONFIG_PROFILER
3783 ti = profile_getclock();
3784 #endif
3785 if (use_icount) {
3786 int64_t count;
3787 int decr;
3788 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3789 env->icount_decr.u16.low = 0;
3790 env->icount_extra = 0;
3791 count = qemu_next_deadline();
3792 count = (count + (1 << icount_time_shift) - 1)
3793 >> icount_time_shift;
3794 qemu_icount += count;
3795 decr = (count > 0xffff) ? 0xffff : count;
3796 count -= decr;
3797 env->icount_decr.u16.low = decr;
3798 env->icount_extra = count;
3800 ret = cpu_exec(env);
3801 #ifdef CONFIG_PROFILER
3802 qemu_time += profile_getclock() - ti;
3803 #endif
3804 if (use_icount) {
3805 /* Fold pending instructions back into the
3806 instruction counter, and clear the interrupt flag. */
3807 qemu_icount -= (env->icount_decr.u16.low
3808 + env->icount_extra);
3809 env->icount_decr.u32 = 0;
3810 env->icount_extra = 0;
3812 next_cpu = env->next_cpu ?: first_cpu;
3813 if (event_pending && likely(ret != EXCP_DEBUG)) {
3814 ret = EXCP_INTERRUPT;
3815 event_pending = 0;
3816 break;
3818 if (ret == EXCP_HLT) {
3819 /* Give the next CPU a chance to run. */
3820 cur_cpu = env;
3821 continue;
3823 if (ret != EXCP_HALTED)
3824 break;
3825 /* all CPUs are halted ? */
3826 if (env == cur_cpu)
3827 break;
3829 cur_cpu = env;
3831 if (shutdown_requested) {
3832 ret = EXCP_INTERRUPT;
3833 if (no_shutdown) {
3834 vm_stop(0);
3835 no_shutdown = 0;
3837 else
3838 break;
3840 if (reset_requested) {
3841 reset_requested = 0;
3842 qemu_system_reset();
3843 ret = EXCP_INTERRUPT;
3845 if (powerdown_requested) {
3846 powerdown_requested = 0;
3847 qemu_system_powerdown();
3848 ret = EXCP_INTERRUPT;
3850 if (unlikely(ret == EXCP_DEBUG)) {
3851 gdb_set_stop_cpu(cur_cpu);
3852 vm_stop(EXCP_DEBUG);
3854 /* If all cpus are halted then wait until the next IRQ */
3855 /* XXX: use timeout computed from timers */
3856 if (ret == EXCP_HALTED) {
3857 if (use_icount) {
3858 int64_t add;
3859 int64_t delta;
3860 /* Advance virtual time to the next event. */
3861 if (use_icount == 1) {
3862 /* When not using an adaptive execution frequency
3863 we tend to get badly out of sync with real time,
3864 so just delay for a reasonable amount of time. */
3865 delta = 0;
3866 } else {
3867 delta = cpu_get_icount() - cpu_get_clock();
3869 if (delta > 0) {
3870 /* If virtual time is ahead of real time then just
3871 wait for IO. */
3872 timeout = (delta / 1000000) + 1;
3873 } else {
3874 /* Wait for either IO to occur or the next
3875 timer event. */
3876 add = qemu_next_deadline();
3877 /* We advance the timer before checking for IO.
3878 Limit the amount we advance so that early IO
3879 activity won't get the guest too far ahead. */
3880 if (add > 10000000)
3881 add = 10000000;
3882 delta += add;
3883 add = (add + (1 << icount_time_shift) - 1)
3884 >> icount_time_shift;
3885 qemu_icount += add;
3886 timeout = delta / 1000000;
3887 if (timeout < 0)
3888 timeout = 0;
3890 } else {
3891 timeout = 5000;
3893 } else {
3894 timeout = 0;
3896 } else {
3897 if (shutdown_requested) {
3898 ret = EXCP_INTERRUPT;
3899 break;
3901 timeout = 5000;
3903 #ifdef CONFIG_PROFILER
3904 ti = profile_getclock();
3905 #endif
3906 main_loop_wait(timeout);
3907 #ifdef CONFIG_PROFILER
3908 dev_time += profile_getclock() - ti;
3909 #endif
3911 cpu_disable_ticks();
3912 return ret;
3915 static void help(int exitcode)
3917 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3918 and qemu-doc.texi */
3919 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3920 "usage: %s [options] [disk_image]\n"
3921 "\n"
3922 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3923 "\n"
3924 "Standard options:\n"
3925 "-h or -help display this help and exit\n"
3926 "-M machine select emulated machine (-M ? for list)\n"
3927 "-cpu cpu select CPU (-cpu ? for list)\n"
3928 "-smp n set the number of CPUs to 'n' [default=1]\n"
3929 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3930 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3931 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3932 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3933 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3934 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3935 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3936 " use 'file' as a drive image\n"
3937 "-mtdblock file use 'file' as on-board Flash memory image\n"
3938 "-sd file use 'file' as SecureDigital card image\n"
3939 "-pflash file use 'file' as a parallel flash image\n"
3940 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3941 "-snapshot write to temporary files instead of disk image files\n"
3942 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3943 #ifndef _WIN32
3944 "-k language use keyboard layout (for example \"fr\" for French)\n"
3945 #endif
3946 #ifdef HAS_AUDIO
3947 "-audio-help print list of audio drivers and their options\n"
3948 "-soundhw c1,... enable audio support\n"
3949 " and only specified sound cards (comma separated list)\n"
3950 " use -soundhw ? to get the list of supported cards\n"
3951 " use -soundhw all to enable all of them\n"
3952 #endif
3953 "-usb enable the USB driver (will be the default soon)\n"
3954 "-usbdevice name add the host or guest USB device 'name'\n"
3955 "-name string set the name of the guest\n"
3956 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
3957 " specify machine UUID\n"
3958 "\n"
3959 "Display options:\n"
3960 "-nographic disable graphical output and redirect serial I/Os to console\n"
3961 #ifdef CONFIG_CURSES
3962 "-curses use a curses/ncurses interface instead of SDL\n"
3963 #endif
3964 #ifdef CONFIG_SDL
3965 "-no-frame open SDL window without a frame and window decorations\n"
3966 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3967 "-no-quit disable SDL window close capability\n"
3968 "-sdl enable SDL\n"
3969 #endif
3970 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3971 "-vga [std|cirrus|vmware|none]\n"
3972 " select video card type\n"
3973 "-full-screen start in full screen\n"
3974 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3975 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3976 #endif
3977 "-vnc display start a VNC server on display\n"
3978 "\n"
3979 "Network options:\n"
3980 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3981 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3982 #ifdef CONFIG_SLIRP
3983 "-net user[,vlan=n][,name=str][,hostname=host]\n"
3984 " connect the user mode network stack to VLAN 'n' and send\n"
3985 " hostname 'host' to DHCP clients\n"
3986 #endif
3987 #ifdef _WIN32
3988 "-net tap[,vlan=n][,name=str],ifname=name\n"
3989 " connect the host TAP network interface to VLAN 'n'\n"
3990 #else
3991 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
3992 " connect the host TAP network interface to VLAN 'n' and use the\n"
3993 " network scripts 'file' (default=%s)\n"
3994 " and 'dfile' (default=%s);\n"
3995 " use '[down]script=no' to disable script execution;\n"
3996 " use 'fd=h' to connect to an already opened TAP interface\n"
3997 #endif
3998 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3999 " connect the vlan 'n' to another VLAN using a socket connection\n"
4000 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
4001 " connect the vlan 'n' to multicast maddr and port\n"
4002 #ifdef CONFIG_VDE
4003 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4004 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4005 " on host and listening for incoming connections on 'socketpath'.\n"
4006 " Use group 'groupname' and mode 'octalmode' to change default\n"
4007 " ownership and permissions for communication port.\n"
4008 #endif
4009 "-net none use it alone to have zero network devices; if no -net option\n"
4010 " is provided, the default is '-net nic -net user'\n"
4011 #ifdef CONFIG_SLIRP
4012 "-tftp dir allow tftp access to files in dir [-net user]\n"
4013 "-bootp file advertise file in BOOTP replies\n"
4014 #ifndef _WIN32
4015 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4016 #endif
4017 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4018 " redirect TCP or UDP connections from host to guest [-net user]\n"
4019 #endif
4020 "\n"
4021 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
4022 "-bt hci,host[:id]\n"
4023 " use host's HCI with the given name\n"
4024 "-bt hci[,vlan=n]\n"
4025 " emulate a standard HCI in virtual scatternet 'n'\n"
4026 "-bt vhci[,vlan=n]\n"
4027 " add host computer to virtual scatternet 'n' using VHCI\n"
4028 "-bt device:dev[,vlan=n]\n"
4029 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4030 "\n"
4031 #ifdef TARGET_I386
4032 "\n"
4033 "i386 target only:\n"
4034 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4035 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4036 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4037 "-no-acpi disable ACPI\n"
4038 "-no-hpet disable HPET\n"
4039 "-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"
4040 " ACPI table description\n"
4041 #endif
4042 "Linux boot specific:\n"
4043 "-kernel bzImage use 'bzImage' as kernel image\n"
4044 "-append cmdline use 'cmdline' as kernel command line\n"
4045 "-initrd file use 'file' as initial ram disk\n"
4046 "\n"
4047 "Debug/Expert options:\n"
4048 "-serial dev redirect the serial port to char device 'dev'\n"
4049 "-parallel dev redirect the parallel port to char device 'dev'\n"
4050 "-monitor dev redirect the monitor to char device 'dev'\n"
4051 "-pidfile file write PID to 'file'\n"
4052 "-S freeze CPU at startup (use 'c' to start execution)\n"
4053 "-s wait gdb connection to port\n"
4054 "-p port set gdb connection port [default=%s]\n"
4055 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4056 "-hdachs c,h,s[,t]\n"
4057 " force hard disk 0 physical geometry and the optional BIOS\n"
4058 " translation (t=none or lba) (usually qemu can guess them)\n"
4059 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4060 "-bios file set the filename for the BIOS\n"
4061 #ifdef USE_KQEMU
4062 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4063 "-no-kqemu disable KQEMU kernel module usage\n"
4064 #endif
4065 #ifdef CONFIG_KVM
4066 "-enable-kvm enable KVM full virtualization support\n"
4067 #endif
4068 "-no-reboot exit instead of rebooting\n"
4069 "-no-shutdown stop before shutdown\n"
4070 "-loadvm [tag|id]\n"
4071 " start right away with a saved state (loadvm in monitor)\n"
4072 #ifndef _WIN32
4073 "-daemonize daemonize QEMU after initializing\n"
4074 #endif
4075 "-option-rom rom load a file, rom, into the option ROM space\n"
4076 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4077 "-prom-env variable=value\n"
4078 " set OpenBIOS nvram variables\n"
4079 #endif
4080 "-clock force the use of the given methods for timer alarm.\n"
4081 " To see what timers are available use -clock ?\n"
4082 "-localtime set the real time clock to local time [default=utc]\n"
4083 "-startdate select initial date of the clock\n"
4084 "-icount [N|auto]\n"
4085 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4086 "-echr chr set terminal escape character instead of ctrl-a\n"
4087 "-virtioconsole c\n"
4088 " set virtio console\n"
4089 "-show-cursor show cursor\n"
4090 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4091 "-semihosting semihosting mode\n"
4092 #endif
4093 #if defined(TARGET_ARM)
4094 "-old-param old param mode\n"
4095 #endif
4096 "-tb-size n set TB size\n"
4097 "-incoming p prepare for incoming migration, listen on port p\n"
4098 #ifndef _WIN32
4099 "-chroot dir Chroot to dir just before starting the VM.\n"
4100 "-runas user Change to user id user just before starting the VM.\n"
4101 #endif
4102 "\n"
4103 "During emulation, the following keys are useful:\n"
4104 "ctrl-alt-f toggle full screen\n"
4105 "ctrl-alt-n switch to virtual console 'n'\n"
4106 "ctrl-alt toggle mouse and keyboard grab\n"
4107 "\n"
4108 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4110 "qemu",
4111 DEFAULT_RAM_SIZE,
4112 #ifndef _WIN32
4113 DEFAULT_NETWORK_SCRIPT,
4114 DEFAULT_NETWORK_DOWN_SCRIPT,
4115 #endif
4116 DEFAULT_GDBSTUB_PORT,
4117 "/tmp/qemu.log");
4118 exit(exitcode);
4121 #define HAS_ARG 0x0001
4123 enum {
4124 /* Please keep in synch with help, qemu_options[] and
4125 qemu-doc.texi */
4126 /* Standard options: */
4127 QEMU_OPTION_h,
4128 QEMU_OPTION_M,
4129 QEMU_OPTION_cpu,
4130 QEMU_OPTION_smp,
4131 QEMU_OPTION_fda,
4132 QEMU_OPTION_fdb,
4133 QEMU_OPTION_hda,
4134 QEMU_OPTION_hdb,
4135 QEMU_OPTION_hdc,
4136 QEMU_OPTION_hdd,
4137 QEMU_OPTION_cdrom,
4138 QEMU_OPTION_drive,
4139 QEMU_OPTION_mtdblock,
4140 QEMU_OPTION_sd,
4141 QEMU_OPTION_pflash,
4142 QEMU_OPTION_boot,
4143 QEMU_OPTION_snapshot,
4144 QEMU_OPTION_m,
4145 QEMU_OPTION_k,
4146 QEMU_OPTION_audio_help,
4147 QEMU_OPTION_soundhw,
4148 QEMU_OPTION_usb,
4149 QEMU_OPTION_usbdevice,
4150 QEMU_OPTION_name,
4151 QEMU_OPTION_uuid,
4153 /* Display options: */
4154 QEMU_OPTION_nographic,
4155 QEMU_OPTION_curses,
4156 QEMU_OPTION_no_frame,
4157 QEMU_OPTION_alt_grab,
4158 QEMU_OPTION_no_quit,
4159 QEMU_OPTION_sdl,
4160 QEMU_OPTION_portrait,
4161 QEMU_OPTION_vga,
4162 QEMU_OPTION_full_screen,
4163 QEMU_OPTION_g,
4164 QEMU_OPTION_vnc,
4166 /* Network options: */
4167 QEMU_OPTION_net,
4168 QEMU_OPTION_tftp,
4169 QEMU_OPTION_bootp,
4170 QEMU_OPTION_smb,
4171 QEMU_OPTION_redir,
4172 QEMU_OPTION_bt,
4174 /* i386 target only: */
4175 QEMU_OPTION_win2k_hack,
4176 QEMU_OPTION_rtc_td_hack,
4177 QEMU_OPTION_no_fd_bootchk,
4178 QEMU_OPTION_no_acpi,
4179 QEMU_OPTION_no_hpet,
4180 QEMU_OPTION_acpitable,
4182 /* Linux boot specific: */
4183 QEMU_OPTION_kernel,
4184 QEMU_OPTION_append,
4185 QEMU_OPTION_initrd,
4187 /* Debug/Expert options: */
4188 QEMU_OPTION_serial,
4189 QEMU_OPTION_parallel,
4190 QEMU_OPTION_monitor,
4191 QEMU_OPTION_pidfile,
4192 QEMU_OPTION_S,
4193 QEMU_OPTION_s,
4194 QEMU_OPTION_p,
4195 QEMU_OPTION_d,
4196 QEMU_OPTION_hdachs,
4197 QEMU_OPTION_L,
4198 QEMU_OPTION_bios,
4199 QEMU_OPTION_kernel_kqemu,
4200 QEMU_OPTION_no_kqemu,
4201 QEMU_OPTION_enable_kvm,
4202 QEMU_OPTION_no_reboot,
4203 QEMU_OPTION_no_shutdown,
4204 QEMU_OPTION_loadvm,
4205 QEMU_OPTION_daemonize,
4206 QEMU_OPTION_option_rom,
4207 QEMU_OPTION_prom_env,
4208 QEMU_OPTION_clock,
4209 QEMU_OPTION_localtime,
4210 QEMU_OPTION_startdate,
4211 QEMU_OPTION_icount,
4212 QEMU_OPTION_echr,
4213 QEMU_OPTION_virtiocon,
4214 QEMU_OPTION_show_cursor,
4215 QEMU_OPTION_semihosting,
4216 QEMU_OPTION_old_param,
4217 QEMU_OPTION_tb_size,
4218 QEMU_OPTION_incoming,
4219 QEMU_OPTION_chroot,
4220 QEMU_OPTION_runas,
4223 typedef struct QEMUOption {
4224 const char *name;
4225 int flags;
4226 int index;
4227 } QEMUOption;
4229 static const QEMUOption qemu_options[] = {
4230 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4231 qemu-doc.texi */
4232 /* Standard options: */
4233 { "h", 0, QEMU_OPTION_h },
4234 { "help", 0, QEMU_OPTION_h },
4235 { "M", HAS_ARG, QEMU_OPTION_M },
4236 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4237 { "smp", HAS_ARG, QEMU_OPTION_smp },
4238 { "fda", HAS_ARG, QEMU_OPTION_fda },
4239 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4240 { "hda", HAS_ARG, QEMU_OPTION_hda },
4241 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4242 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4243 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4244 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4245 { "drive", HAS_ARG, QEMU_OPTION_drive },
4246 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4247 { "sd", HAS_ARG, QEMU_OPTION_sd },
4248 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4249 { "boot", HAS_ARG, QEMU_OPTION_boot },
4250 { "snapshot", 0, QEMU_OPTION_snapshot },
4251 { "m", HAS_ARG, QEMU_OPTION_m },
4252 { "k", HAS_ARG, QEMU_OPTION_k },
4253 #ifdef HAS_AUDIO
4254 { "audio-help", 0, QEMU_OPTION_audio_help },
4255 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4256 #endif
4257 { "usb", 0, QEMU_OPTION_usb },
4258 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4259 { "name", HAS_ARG, QEMU_OPTION_name },
4260 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4262 /* Display options: */
4263 { "nographic", 0, QEMU_OPTION_nographic },
4264 #ifdef CONFIG_CURSES
4265 { "curses", 0, QEMU_OPTION_curses },
4266 #endif
4267 #ifdef CONFIG_SDL
4268 { "no-frame", 0, QEMU_OPTION_no_frame },
4269 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4270 { "no-quit", 0, QEMU_OPTION_no_quit },
4271 { "sdl", 0, QEMU_OPTION_sdl },
4272 #endif
4273 { "portrait", 0, QEMU_OPTION_portrait },
4274 { "vga", HAS_ARG, QEMU_OPTION_vga },
4275 { "full-screen", 0, QEMU_OPTION_full_screen },
4276 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4277 { "g", 1, QEMU_OPTION_g },
4278 #endif
4279 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4281 /* Network options: */
4282 { "net", HAS_ARG, QEMU_OPTION_net},
4283 #ifdef CONFIG_SLIRP
4284 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4285 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4286 #ifndef _WIN32
4287 { "smb", HAS_ARG, QEMU_OPTION_smb },
4288 #endif
4289 { "redir", HAS_ARG, QEMU_OPTION_redir },
4290 #endif
4291 { "bt", HAS_ARG, QEMU_OPTION_bt },
4292 #ifdef TARGET_I386
4293 /* i386 target only: */
4294 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4295 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4296 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4297 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4298 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4299 { "acpitable", HAS_ARG, QEMU_OPTION_acpitable },
4300 #endif
4302 /* Linux boot specific: */
4303 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4304 { "append", HAS_ARG, QEMU_OPTION_append },
4305 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4307 /* Debug/Expert options: */
4308 { "serial", HAS_ARG, QEMU_OPTION_serial },
4309 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4310 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4311 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4312 { "S", 0, QEMU_OPTION_S },
4313 { "s", 0, QEMU_OPTION_s },
4314 { "p", HAS_ARG, QEMU_OPTION_p },
4315 { "d", HAS_ARG, QEMU_OPTION_d },
4316 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4317 { "L", HAS_ARG, QEMU_OPTION_L },
4318 { "bios", HAS_ARG, QEMU_OPTION_bios },
4319 #ifdef USE_KQEMU
4320 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4321 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4322 #endif
4323 #ifdef CONFIG_KVM
4324 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4325 #endif
4326 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4327 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4328 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4329 { "daemonize", 0, QEMU_OPTION_daemonize },
4330 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4331 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4332 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4333 #endif
4334 { "clock", HAS_ARG, QEMU_OPTION_clock },
4335 { "localtime", 0, QEMU_OPTION_localtime },
4336 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4337 { "icount", HAS_ARG, QEMU_OPTION_icount },
4338 { "echr", HAS_ARG, QEMU_OPTION_echr },
4339 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4340 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4341 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4342 { "semihosting", 0, QEMU_OPTION_semihosting },
4343 #endif
4344 #if defined(TARGET_ARM)
4345 { "old-param", 0, QEMU_OPTION_old_param },
4346 #endif
4347 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4348 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4349 { "chroot", HAS_ARG, QEMU_OPTION_chroot },
4350 { "runas", HAS_ARG, QEMU_OPTION_runas },
4351 { NULL },
4354 #ifdef HAS_AUDIO
4355 struct soundhw soundhw[] = {
4356 #ifdef HAS_AUDIO_CHOICE
4357 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4359 "pcspk",
4360 "PC speaker",
4363 { .init_isa = pcspk_audio_init }
4365 #endif
4367 #ifdef CONFIG_SB16
4369 "sb16",
4370 "Creative Sound Blaster 16",
4373 { .init_isa = SB16_init }
4375 #endif
4377 #ifdef CONFIG_CS4231A
4379 "cs4231a",
4380 "CS4231A",
4383 { .init_isa = cs4231a_init }
4385 #endif
4387 #ifdef CONFIG_ADLIB
4389 "adlib",
4390 #ifdef HAS_YMF262
4391 "Yamaha YMF262 (OPL3)",
4392 #else
4393 "Yamaha YM3812 (OPL2)",
4394 #endif
4397 { .init_isa = Adlib_init }
4399 #endif
4401 #ifdef CONFIG_GUS
4403 "gus",
4404 "Gravis Ultrasound GF1",
4407 { .init_isa = GUS_init }
4409 #endif
4411 #ifdef CONFIG_AC97
4413 "ac97",
4414 "Intel 82801AA AC97 Audio",
4417 { .init_pci = ac97_init }
4419 #endif
4421 #ifdef CONFIG_ES1370
4423 "es1370",
4424 "ENSONIQ AudioPCI ES1370",
4427 { .init_pci = es1370_init }
4429 #endif
4431 #endif /* HAS_AUDIO_CHOICE */
4433 { NULL, NULL, 0, 0, { NULL } }
4436 static void select_soundhw (const char *optarg)
4438 struct soundhw *c;
4440 if (*optarg == '?') {
4441 show_valid_cards:
4443 printf ("Valid sound card names (comma separated):\n");
4444 for (c = soundhw; c->name; ++c) {
4445 printf ("%-11s %s\n", c->name, c->descr);
4447 printf ("\n-soundhw all will enable all of the above\n");
4448 exit (*optarg != '?');
4450 else {
4451 size_t l;
4452 const char *p;
4453 char *e;
4454 int bad_card = 0;
4456 if (!strcmp (optarg, "all")) {
4457 for (c = soundhw; c->name; ++c) {
4458 c->enabled = 1;
4460 return;
4463 p = optarg;
4464 while (*p) {
4465 e = strchr (p, ',');
4466 l = !e ? strlen (p) : (size_t) (e - p);
4468 for (c = soundhw; c->name; ++c) {
4469 if (!strncmp (c->name, p, l)) {
4470 c->enabled = 1;
4471 break;
4475 if (!c->name) {
4476 if (l > 80) {
4477 fprintf (stderr,
4478 "Unknown sound card name (too big to show)\n");
4480 else {
4481 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4482 (int) l, p);
4484 bad_card = 1;
4486 p += l + (e != NULL);
4489 if (bad_card)
4490 goto show_valid_cards;
4493 #endif
4495 static void select_vgahw (const char *p)
4497 const char *opts;
4499 if (strstart(p, "std", &opts)) {
4500 std_vga_enabled = 1;
4501 cirrus_vga_enabled = 0;
4502 vmsvga_enabled = 0;
4503 } else if (strstart(p, "cirrus", &opts)) {
4504 cirrus_vga_enabled = 1;
4505 std_vga_enabled = 0;
4506 vmsvga_enabled = 0;
4507 } else if (strstart(p, "vmware", &opts)) {
4508 cirrus_vga_enabled = 0;
4509 std_vga_enabled = 0;
4510 vmsvga_enabled = 1;
4511 } else if (strstart(p, "none", &opts)) {
4512 cirrus_vga_enabled = 0;
4513 std_vga_enabled = 0;
4514 vmsvga_enabled = 0;
4515 } else {
4516 invalid_vga:
4517 fprintf(stderr, "Unknown vga type: %s\n", p);
4518 exit(1);
4520 while (*opts) {
4521 const char *nextopt;
4523 if (strstart(opts, ",retrace=", &nextopt)) {
4524 opts = nextopt;
4525 if (strstart(opts, "dumb", &nextopt))
4526 vga_retrace_method = VGA_RETRACE_DUMB;
4527 else if (strstart(opts, "precise", &nextopt))
4528 vga_retrace_method = VGA_RETRACE_PRECISE;
4529 else goto invalid_vga;
4530 } else goto invalid_vga;
4531 opts = nextopt;
4535 #ifdef _WIN32
4536 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4538 exit(STATUS_CONTROL_C_EXIT);
4539 return TRUE;
4541 #endif
4543 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4545 int ret;
4547 if(strlen(str) != 36)
4548 return -1;
4550 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4551 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4552 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4554 if(ret != 16)
4555 return -1;
4557 return 0;
4560 #define MAX_NET_CLIENTS 32
4562 #ifndef _WIN32
4564 static void termsig_handler(int signal)
4566 qemu_system_shutdown_request();
4569 static void termsig_setup(void)
4571 struct sigaction act;
4573 memset(&act, 0, sizeof(act));
4574 act.sa_handler = termsig_handler;
4575 sigaction(SIGINT, &act, NULL);
4576 sigaction(SIGHUP, &act, NULL);
4577 sigaction(SIGTERM, &act, NULL);
4580 #endif
4582 int main(int argc, char **argv, char **envp)
4584 #ifdef CONFIG_GDBSTUB
4585 int use_gdbstub;
4586 const char *gdbstub_port;
4587 #endif
4588 uint32_t boot_devices_bitmap = 0;
4589 int i;
4590 int snapshot, linux_boot, net_boot;
4591 const char *initrd_filename;
4592 const char *kernel_filename, *kernel_cmdline;
4593 const char *boot_devices = "";
4594 DisplayState *ds;
4595 DisplayChangeListener *dcl;
4596 int cyls, heads, secs, translation;
4597 const char *net_clients[MAX_NET_CLIENTS];
4598 int nb_net_clients;
4599 const char *bt_opts[MAX_BT_CMDLINE];
4600 int nb_bt_opts;
4601 int hda_index;
4602 int optind;
4603 const char *r, *optarg;
4604 CharDriverState *monitor_hd = NULL;
4605 const char *monitor_device;
4606 const char *serial_devices[MAX_SERIAL_PORTS];
4607 int serial_device_index;
4608 const char *parallel_devices[MAX_PARALLEL_PORTS];
4609 int parallel_device_index;
4610 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4611 int virtio_console_index;
4612 const char *loadvm = NULL;
4613 QEMUMachine *machine;
4614 const char *cpu_model;
4615 const char *usb_devices[MAX_USB_CMDLINE];
4616 int usb_devices_index;
4617 int fds[2];
4618 int tb_size;
4619 const char *pid_file = NULL;
4620 const char *incoming = NULL;
4621 int fd = 0;
4622 struct passwd *pwd = NULL;
4623 const char *chroot_dir = NULL;
4624 const char *run_as = NULL;
4626 qemu_cache_utils_init(envp);
4628 LIST_INIT (&vm_change_state_head);
4629 #ifndef _WIN32
4631 struct sigaction act;
4632 sigfillset(&act.sa_mask);
4633 act.sa_flags = 0;
4634 act.sa_handler = SIG_IGN;
4635 sigaction(SIGPIPE, &act, NULL);
4637 #else
4638 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4639 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4640 QEMU to run on a single CPU */
4642 HANDLE h;
4643 DWORD mask, smask;
4644 int i;
4645 h = GetCurrentProcess();
4646 if (GetProcessAffinityMask(h, &mask, &smask)) {
4647 for(i = 0; i < 32; i++) {
4648 if (mask & (1 << i))
4649 break;
4651 if (i != 32) {
4652 mask = 1 << i;
4653 SetProcessAffinityMask(h, mask);
4657 #endif
4659 register_machines();
4660 machine = first_machine;
4661 cpu_model = NULL;
4662 initrd_filename = NULL;
4663 ram_size = 0;
4664 vga_ram_size = VGA_RAM_SIZE;
4665 #ifdef CONFIG_GDBSTUB
4666 use_gdbstub = 0;
4667 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4668 #endif
4669 snapshot = 0;
4670 nographic = 0;
4671 curses = 0;
4672 kernel_filename = NULL;
4673 kernel_cmdline = "";
4674 cyls = heads = secs = 0;
4675 translation = BIOS_ATA_TRANSLATION_AUTO;
4676 monitor_device = "vc:80Cx24C";
4678 serial_devices[0] = "vc:80Cx24C";
4679 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4680 serial_devices[i] = NULL;
4681 serial_device_index = 0;
4683 parallel_devices[0] = "vc:80Cx24C";
4684 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4685 parallel_devices[i] = NULL;
4686 parallel_device_index = 0;
4688 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4689 virtio_consoles[i] = NULL;
4690 virtio_console_index = 0;
4692 usb_devices_index = 0;
4694 nb_net_clients = 0;
4695 nb_bt_opts = 0;
4696 nb_drives = 0;
4697 nb_drives_opt = 0;
4698 hda_index = -1;
4700 nb_nics = 0;
4702 tb_size = 0;
4703 autostart= 1;
4705 optind = 1;
4706 for(;;) {
4707 if (optind >= argc)
4708 break;
4709 r = argv[optind];
4710 if (r[0] != '-') {
4711 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4712 } else {
4713 const QEMUOption *popt;
4715 optind++;
4716 /* Treat --foo the same as -foo. */
4717 if (r[1] == '-')
4718 r++;
4719 popt = qemu_options;
4720 for(;;) {
4721 if (!popt->name) {
4722 fprintf(stderr, "%s: invalid option -- '%s'\n",
4723 argv[0], r);
4724 exit(1);
4726 if (!strcmp(popt->name, r + 1))
4727 break;
4728 popt++;
4730 if (popt->flags & HAS_ARG) {
4731 if (optind >= argc) {
4732 fprintf(stderr, "%s: option '%s' requires an argument\n",
4733 argv[0], r);
4734 exit(1);
4736 optarg = argv[optind++];
4737 } else {
4738 optarg = NULL;
4741 switch(popt->index) {
4742 case QEMU_OPTION_M:
4743 machine = find_machine(optarg);
4744 if (!machine) {
4745 QEMUMachine *m;
4746 printf("Supported machines are:\n");
4747 for(m = first_machine; m != NULL; m = m->next) {
4748 printf("%-10s %s%s\n",
4749 m->name, m->desc,
4750 m == first_machine ? " (default)" : "");
4752 exit(*optarg != '?');
4754 break;
4755 case QEMU_OPTION_cpu:
4756 /* hw initialization will check this */
4757 if (*optarg == '?') {
4758 /* XXX: implement xxx_cpu_list for targets that still miss it */
4759 #if defined(cpu_list)
4760 cpu_list(stdout, &fprintf);
4761 #endif
4762 exit(0);
4763 } else {
4764 cpu_model = optarg;
4766 break;
4767 case QEMU_OPTION_initrd:
4768 initrd_filename = optarg;
4769 break;
4770 case QEMU_OPTION_hda:
4771 if (cyls == 0)
4772 hda_index = drive_add(optarg, HD_ALIAS, 0);
4773 else
4774 hda_index = drive_add(optarg, HD_ALIAS
4775 ",cyls=%d,heads=%d,secs=%d%s",
4776 0, cyls, heads, secs,
4777 translation == BIOS_ATA_TRANSLATION_LBA ?
4778 ",trans=lba" :
4779 translation == BIOS_ATA_TRANSLATION_NONE ?
4780 ",trans=none" : "");
4781 break;
4782 case QEMU_OPTION_hdb:
4783 case QEMU_OPTION_hdc:
4784 case QEMU_OPTION_hdd:
4785 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4786 break;
4787 case QEMU_OPTION_drive:
4788 drive_add(NULL, "%s", optarg);
4789 break;
4790 case QEMU_OPTION_mtdblock:
4791 drive_add(optarg, MTD_ALIAS);
4792 break;
4793 case QEMU_OPTION_sd:
4794 drive_add(optarg, SD_ALIAS);
4795 break;
4796 case QEMU_OPTION_pflash:
4797 drive_add(optarg, PFLASH_ALIAS);
4798 break;
4799 case QEMU_OPTION_snapshot:
4800 snapshot = 1;
4801 break;
4802 case QEMU_OPTION_hdachs:
4804 const char *p;
4805 p = optarg;
4806 cyls = strtol(p, (char **)&p, 0);
4807 if (cyls < 1 || cyls > 16383)
4808 goto chs_fail;
4809 if (*p != ',')
4810 goto chs_fail;
4811 p++;
4812 heads = strtol(p, (char **)&p, 0);
4813 if (heads < 1 || heads > 16)
4814 goto chs_fail;
4815 if (*p != ',')
4816 goto chs_fail;
4817 p++;
4818 secs = strtol(p, (char **)&p, 0);
4819 if (secs < 1 || secs > 63)
4820 goto chs_fail;
4821 if (*p == ',') {
4822 p++;
4823 if (!strcmp(p, "none"))
4824 translation = BIOS_ATA_TRANSLATION_NONE;
4825 else if (!strcmp(p, "lba"))
4826 translation = BIOS_ATA_TRANSLATION_LBA;
4827 else if (!strcmp(p, "auto"))
4828 translation = BIOS_ATA_TRANSLATION_AUTO;
4829 else
4830 goto chs_fail;
4831 } else if (*p != '\0') {
4832 chs_fail:
4833 fprintf(stderr, "qemu: invalid physical CHS format\n");
4834 exit(1);
4836 if (hda_index != -1)
4837 snprintf(drives_opt[hda_index].opt,
4838 sizeof(drives_opt[hda_index].opt),
4839 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4840 0, cyls, heads, secs,
4841 translation == BIOS_ATA_TRANSLATION_LBA ?
4842 ",trans=lba" :
4843 translation == BIOS_ATA_TRANSLATION_NONE ?
4844 ",trans=none" : "");
4846 break;
4847 case QEMU_OPTION_nographic:
4848 nographic = 1;
4849 break;
4850 #ifdef CONFIG_CURSES
4851 case QEMU_OPTION_curses:
4852 curses = 1;
4853 break;
4854 #endif
4855 case QEMU_OPTION_portrait:
4856 graphic_rotate = 1;
4857 break;
4858 case QEMU_OPTION_kernel:
4859 kernel_filename = optarg;
4860 break;
4861 case QEMU_OPTION_append:
4862 kernel_cmdline = optarg;
4863 break;
4864 case QEMU_OPTION_cdrom:
4865 drive_add(optarg, CDROM_ALIAS);
4866 break;
4867 case QEMU_OPTION_boot:
4868 boot_devices = optarg;
4869 /* We just do some generic consistency checks */
4871 /* Could easily be extended to 64 devices if needed */
4872 const char *p;
4874 boot_devices_bitmap = 0;
4875 for (p = boot_devices; *p != '\0'; p++) {
4876 /* Allowed boot devices are:
4877 * a b : floppy disk drives
4878 * c ... f : IDE disk drives
4879 * g ... m : machine implementation dependant drives
4880 * n ... p : network devices
4881 * It's up to each machine implementation to check
4882 * if the given boot devices match the actual hardware
4883 * implementation and firmware features.
4885 if (*p < 'a' || *p > 'q') {
4886 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4887 exit(1);
4889 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4890 fprintf(stderr,
4891 "Boot device '%c' was given twice\n",*p);
4892 exit(1);
4894 boot_devices_bitmap |= 1 << (*p - 'a');
4897 break;
4898 case QEMU_OPTION_fda:
4899 case QEMU_OPTION_fdb:
4900 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4901 break;
4902 #ifdef TARGET_I386
4903 case QEMU_OPTION_no_fd_bootchk:
4904 fd_bootchk = 0;
4905 break;
4906 #endif
4907 case QEMU_OPTION_net:
4908 if (nb_net_clients >= MAX_NET_CLIENTS) {
4909 fprintf(stderr, "qemu: too many network clients\n");
4910 exit(1);
4912 net_clients[nb_net_clients] = optarg;
4913 nb_net_clients++;
4914 break;
4915 #ifdef CONFIG_SLIRP
4916 case QEMU_OPTION_tftp:
4917 tftp_prefix = optarg;
4918 break;
4919 case QEMU_OPTION_bootp:
4920 bootp_filename = optarg;
4921 break;
4922 #ifndef _WIN32
4923 case QEMU_OPTION_smb:
4924 net_slirp_smb(optarg);
4925 break;
4926 #endif
4927 case QEMU_OPTION_redir:
4928 net_slirp_redir(optarg);
4929 break;
4930 #endif
4931 case QEMU_OPTION_bt:
4932 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4933 fprintf(stderr, "qemu: too many bluetooth options\n");
4934 exit(1);
4936 bt_opts[nb_bt_opts++] = optarg;
4937 break;
4938 #ifdef HAS_AUDIO
4939 case QEMU_OPTION_audio_help:
4940 AUD_help ();
4941 exit (0);
4942 break;
4943 case QEMU_OPTION_soundhw:
4944 select_soundhw (optarg);
4945 break;
4946 #endif
4947 case QEMU_OPTION_h:
4948 help(0);
4949 break;
4950 case QEMU_OPTION_m: {
4951 uint64_t value;
4952 char *ptr;
4954 value = strtoul(optarg, &ptr, 10);
4955 switch (*ptr) {
4956 case 0: case 'M': case 'm':
4957 value <<= 20;
4958 break;
4959 case 'G': case 'g':
4960 value <<= 30;
4961 break;
4962 default:
4963 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4964 exit(1);
4967 /* On 32-bit hosts, QEMU is limited by virtual address space */
4968 if (value > (2047 << 20)
4969 #ifndef USE_KQEMU
4970 && HOST_LONG_BITS == 32
4971 #endif
4973 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4974 exit(1);
4976 if (value != (uint64_t)(ram_addr_t)value) {
4977 fprintf(stderr, "qemu: ram size too large\n");
4978 exit(1);
4980 ram_size = value;
4981 break;
4983 case QEMU_OPTION_d:
4985 int mask;
4986 const CPULogItem *item;
4988 mask = cpu_str_to_log_mask(optarg);
4989 if (!mask) {
4990 printf("Log items (comma separated):\n");
4991 for(item = cpu_log_items; item->mask != 0; item++) {
4992 printf("%-10s %s\n", item->name, item->help);
4994 exit(1);
4996 cpu_set_log(mask);
4998 break;
4999 #ifdef CONFIG_GDBSTUB
5000 case QEMU_OPTION_s:
5001 use_gdbstub = 1;
5002 break;
5003 case QEMU_OPTION_p:
5004 gdbstub_port = optarg;
5005 break;
5006 #endif
5007 case QEMU_OPTION_L:
5008 bios_dir = optarg;
5009 break;
5010 case QEMU_OPTION_bios:
5011 bios_name = optarg;
5012 break;
5013 case QEMU_OPTION_S:
5014 autostart = 0;
5015 break;
5016 case QEMU_OPTION_k:
5017 keyboard_layout = optarg;
5018 break;
5019 case QEMU_OPTION_localtime:
5020 rtc_utc = 0;
5021 break;
5022 case QEMU_OPTION_vga:
5023 select_vgahw (optarg);
5024 break;
5025 case QEMU_OPTION_g:
5027 const char *p;
5028 int w, h, depth;
5029 p = optarg;
5030 w = strtol(p, (char **)&p, 10);
5031 if (w <= 0) {
5032 graphic_error:
5033 fprintf(stderr, "qemu: invalid resolution or depth\n");
5034 exit(1);
5036 if (*p != 'x')
5037 goto graphic_error;
5038 p++;
5039 h = strtol(p, (char **)&p, 10);
5040 if (h <= 0)
5041 goto graphic_error;
5042 if (*p == 'x') {
5043 p++;
5044 depth = strtol(p, (char **)&p, 10);
5045 if (depth != 8 && depth != 15 && depth != 16 &&
5046 depth != 24 && depth != 32)
5047 goto graphic_error;
5048 } else if (*p == '\0') {
5049 depth = graphic_depth;
5050 } else {
5051 goto graphic_error;
5054 graphic_width = w;
5055 graphic_height = h;
5056 graphic_depth = depth;
5058 break;
5059 case QEMU_OPTION_echr:
5061 char *r;
5062 term_escape_char = strtol(optarg, &r, 0);
5063 if (r == optarg)
5064 printf("Bad argument to echr\n");
5065 break;
5067 case QEMU_OPTION_monitor:
5068 monitor_device = optarg;
5069 break;
5070 case QEMU_OPTION_serial:
5071 if (serial_device_index >= MAX_SERIAL_PORTS) {
5072 fprintf(stderr, "qemu: too many serial ports\n");
5073 exit(1);
5075 serial_devices[serial_device_index] = optarg;
5076 serial_device_index++;
5077 break;
5078 case QEMU_OPTION_virtiocon:
5079 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5080 fprintf(stderr, "qemu: too many virtio consoles\n");
5081 exit(1);
5083 virtio_consoles[virtio_console_index] = optarg;
5084 virtio_console_index++;
5085 break;
5086 case QEMU_OPTION_parallel:
5087 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5088 fprintf(stderr, "qemu: too many parallel ports\n");
5089 exit(1);
5091 parallel_devices[parallel_device_index] = optarg;
5092 parallel_device_index++;
5093 break;
5094 case QEMU_OPTION_loadvm:
5095 loadvm = optarg;
5096 break;
5097 case QEMU_OPTION_full_screen:
5098 full_screen = 1;
5099 break;
5100 #ifdef CONFIG_SDL
5101 case QEMU_OPTION_no_frame:
5102 no_frame = 1;
5103 break;
5104 case QEMU_OPTION_alt_grab:
5105 alt_grab = 1;
5106 break;
5107 case QEMU_OPTION_no_quit:
5108 no_quit = 1;
5109 break;
5110 case QEMU_OPTION_sdl:
5111 sdl = 1;
5112 break;
5113 #endif
5114 case QEMU_OPTION_pidfile:
5115 pid_file = optarg;
5116 break;
5117 #ifdef TARGET_I386
5118 case QEMU_OPTION_win2k_hack:
5119 win2k_install_hack = 1;
5120 break;
5121 case QEMU_OPTION_rtc_td_hack:
5122 rtc_td_hack = 1;
5123 break;
5124 case QEMU_OPTION_acpitable:
5125 if(acpi_table_add(optarg) < 0) {
5126 fprintf(stderr, "Wrong acpi table provided\n");
5127 exit(1);
5129 break;
5130 #endif
5131 #ifdef USE_KQEMU
5132 case QEMU_OPTION_no_kqemu:
5133 kqemu_allowed = 0;
5134 break;
5135 case QEMU_OPTION_kernel_kqemu:
5136 kqemu_allowed = 2;
5137 break;
5138 #endif
5139 #ifdef CONFIG_KVM
5140 case QEMU_OPTION_enable_kvm:
5141 kvm_allowed = 1;
5142 #ifdef USE_KQEMU
5143 kqemu_allowed = 0;
5144 #endif
5145 break;
5146 #endif
5147 case QEMU_OPTION_usb:
5148 usb_enabled = 1;
5149 break;
5150 case QEMU_OPTION_usbdevice:
5151 usb_enabled = 1;
5152 if (usb_devices_index >= MAX_USB_CMDLINE) {
5153 fprintf(stderr, "Too many USB devices\n");
5154 exit(1);
5156 usb_devices[usb_devices_index] = optarg;
5157 usb_devices_index++;
5158 break;
5159 case QEMU_OPTION_smp:
5160 smp_cpus = atoi(optarg);
5161 if (smp_cpus < 1) {
5162 fprintf(stderr, "Invalid number of CPUs\n");
5163 exit(1);
5165 break;
5166 case QEMU_OPTION_vnc:
5167 vnc_display = optarg;
5168 break;
5169 case QEMU_OPTION_no_acpi:
5170 acpi_enabled = 0;
5171 break;
5172 case QEMU_OPTION_no_hpet:
5173 no_hpet = 1;
5174 break;
5175 case QEMU_OPTION_no_reboot:
5176 no_reboot = 1;
5177 break;
5178 case QEMU_OPTION_no_shutdown:
5179 no_shutdown = 1;
5180 break;
5181 case QEMU_OPTION_show_cursor:
5182 cursor_hide = 0;
5183 break;
5184 case QEMU_OPTION_uuid:
5185 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5186 fprintf(stderr, "Fail to parse UUID string."
5187 " Wrong format.\n");
5188 exit(1);
5190 break;
5191 case QEMU_OPTION_daemonize:
5192 daemonize = 1;
5193 break;
5194 case QEMU_OPTION_option_rom:
5195 if (nb_option_roms >= MAX_OPTION_ROMS) {
5196 fprintf(stderr, "Too many option ROMs\n");
5197 exit(1);
5199 option_rom[nb_option_roms] = optarg;
5200 nb_option_roms++;
5201 break;
5202 case QEMU_OPTION_semihosting:
5203 semihosting_enabled = 1;
5204 break;
5205 case QEMU_OPTION_name:
5206 qemu_name = optarg;
5207 break;
5208 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5209 case QEMU_OPTION_prom_env:
5210 if (nb_prom_envs >= MAX_PROM_ENVS) {
5211 fprintf(stderr, "Too many prom variables\n");
5212 exit(1);
5214 prom_envs[nb_prom_envs] = optarg;
5215 nb_prom_envs++;
5216 break;
5217 #endif
5218 #ifdef TARGET_ARM
5219 case QEMU_OPTION_old_param:
5220 old_param = 1;
5221 break;
5222 #endif
5223 case QEMU_OPTION_clock:
5224 configure_alarms(optarg);
5225 break;
5226 case QEMU_OPTION_startdate:
5228 struct tm tm;
5229 time_t rtc_start_date;
5230 if (!strcmp(optarg, "now")) {
5231 rtc_date_offset = -1;
5232 } else {
5233 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5234 &tm.tm_year,
5235 &tm.tm_mon,
5236 &tm.tm_mday,
5237 &tm.tm_hour,
5238 &tm.tm_min,
5239 &tm.tm_sec) == 6) {
5240 /* OK */
5241 } else if (sscanf(optarg, "%d-%d-%d",
5242 &tm.tm_year,
5243 &tm.tm_mon,
5244 &tm.tm_mday) == 3) {
5245 tm.tm_hour = 0;
5246 tm.tm_min = 0;
5247 tm.tm_sec = 0;
5248 } else {
5249 goto date_fail;
5251 tm.tm_year -= 1900;
5252 tm.tm_mon--;
5253 rtc_start_date = mktimegm(&tm);
5254 if (rtc_start_date == -1) {
5255 date_fail:
5256 fprintf(stderr, "Invalid date format. Valid format are:\n"
5257 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5258 exit(1);
5260 rtc_date_offset = time(NULL) - rtc_start_date;
5263 break;
5264 case QEMU_OPTION_tb_size:
5265 tb_size = strtol(optarg, NULL, 0);
5266 if (tb_size < 0)
5267 tb_size = 0;
5268 break;
5269 case QEMU_OPTION_icount:
5270 use_icount = 1;
5271 if (strcmp(optarg, "auto") == 0) {
5272 icount_time_shift = -1;
5273 } else {
5274 icount_time_shift = strtol(optarg, NULL, 0);
5276 break;
5277 case QEMU_OPTION_incoming:
5278 incoming = optarg;
5279 break;
5280 case QEMU_OPTION_chroot:
5281 chroot_dir = optarg;
5282 break;
5283 case QEMU_OPTION_runas:
5284 run_as = optarg;
5285 break;
5290 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5291 if (kvm_allowed && kqemu_allowed) {
5292 fprintf(stderr,
5293 "You can not enable both KVM and kqemu at the same time\n");
5294 exit(1);
5296 #endif
5298 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5299 if (smp_cpus > machine->max_cpus) {
5300 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5301 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5302 machine->max_cpus);
5303 exit(1);
5306 if (nographic) {
5307 if (serial_device_index == 0)
5308 serial_devices[0] = "stdio";
5309 if (parallel_device_index == 0)
5310 parallel_devices[0] = "null";
5311 if (strncmp(monitor_device, "vc", 2) == 0)
5312 monitor_device = "stdio";
5315 #ifndef _WIN32
5316 if (daemonize) {
5317 pid_t pid;
5319 if (pipe(fds) == -1)
5320 exit(1);
5322 pid = fork();
5323 if (pid > 0) {
5324 uint8_t status;
5325 ssize_t len;
5327 close(fds[1]);
5329 again:
5330 len = read(fds[0], &status, 1);
5331 if (len == -1 && (errno == EINTR))
5332 goto again;
5334 if (len != 1)
5335 exit(1);
5336 else if (status == 1) {
5337 fprintf(stderr, "Could not acquire pidfile\n");
5338 exit(1);
5339 } else
5340 exit(0);
5341 } else if (pid < 0)
5342 exit(1);
5344 setsid();
5346 pid = fork();
5347 if (pid > 0)
5348 exit(0);
5349 else if (pid < 0)
5350 exit(1);
5352 umask(027);
5354 signal(SIGTSTP, SIG_IGN);
5355 signal(SIGTTOU, SIG_IGN);
5356 signal(SIGTTIN, SIG_IGN);
5358 #endif
5360 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5361 if (daemonize) {
5362 uint8_t status = 1;
5363 write(fds[1], &status, 1);
5364 } else
5365 fprintf(stderr, "Could not acquire pid file\n");
5366 exit(1);
5369 #ifdef USE_KQEMU
5370 if (smp_cpus > 1)
5371 kqemu_allowed = 0;
5372 #endif
5373 linux_boot = (kernel_filename != NULL);
5374 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5376 if (!linux_boot && net_boot == 0 &&
5377 !machine->nodisk_ok && nb_drives_opt == 0)
5378 help(1);
5380 if (!linux_boot && *kernel_cmdline != '\0') {
5381 fprintf(stderr, "-append only allowed with -kernel option\n");
5382 exit(1);
5385 if (!linux_boot && initrd_filename != NULL) {
5386 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5387 exit(1);
5390 /* boot to floppy or the default cd if no hard disk defined yet */
5391 if (!boot_devices[0]) {
5392 boot_devices = "cad";
5394 setvbuf(stdout, NULL, _IOLBF, 0);
5396 init_timers();
5397 if (init_timer_alarm() < 0) {
5398 fprintf(stderr, "could not initialize alarm timer\n");
5399 exit(1);
5401 if (use_icount && icount_time_shift < 0) {
5402 use_icount = 2;
5403 /* 125MIPS seems a reasonable initial guess at the guest speed.
5404 It will be corrected fairly quickly anyway. */
5405 icount_time_shift = 3;
5406 init_icount_adjust();
5409 #ifdef _WIN32
5410 socket_init();
5411 #endif
5413 /* init network clients */
5414 if (nb_net_clients == 0) {
5415 /* if no clients, we use a default config */
5416 net_clients[nb_net_clients++] = "nic";
5417 #ifdef CONFIG_SLIRP
5418 net_clients[nb_net_clients++] = "user";
5419 #endif
5422 for(i = 0;i < nb_net_clients; i++) {
5423 if (net_client_parse(net_clients[i]) < 0)
5424 exit(1);
5426 net_client_check();
5428 #ifdef TARGET_I386
5429 /* XXX: this should be moved in the PC machine instantiation code */
5430 if (net_boot != 0) {
5431 int netroms = 0;
5432 for (i = 0; i < nb_nics && i < 4; i++) {
5433 const char *model = nd_table[i].model;
5434 char buf[1024];
5435 if (net_boot & (1 << i)) {
5436 if (model == NULL)
5437 model = "ne2k_pci";
5438 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5439 if (get_image_size(buf) > 0) {
5440 if (nb_option_roms >= MAX_OPTION_ROMS) {
5441 fprintf(stderr, "Too many option ROMs\n");
5442 exit(1);
5444 option_rom[nb_option_roms] = strdup(buf);
5445 nb_option_roms++;
5446 netroms++;
5450 if (netroms == 0) {
5451 fprintf(stderr, "No valid PXE rom found for network device\n");
5452 exit(1);
5455 #endif
5457 /* init the bluetooth world */
5458 for (i = 0; i < nb_bt_opts; i++)
5459 if (bt_parse(bt_opts[i]))
5460 exit(1);
5462 /* init the memory */
5463 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5465 if (machine->ram_require & RAMSIZE_FIXED) {
5466 if (ram_size > 0) {
5467 if (ram_size < phys_ram_size) {
5468 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5469 machine->name, (unsigned long long) phys_ram_size);
5470 exit(-1);
5473 phys_ram_size = ram_size;
5474 } else
5475 ram_size = phys_ram_size;
5476 } else {
5477 if (ram_size == 0)
5478 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5480 phys_ram_size += ram_size;
5483 phys_ram_base = qemu_vmalloc(phys_ram_size);
5484 if (!phys_ram_base) {
5485 fprintf(stderr, "Could not allocate physical memory\n");
5486 exit(1);
5489 /* init the dynamic translator */
5490 cpu_exec_init_all(tb_size * 1024 * 1024);
5492 bdrv_init();
5493 dma_helper_init();
5495 /* we always create the cdrom drive, even if no disk is there */
5497 if (nb_drives_opt < MAX_DRIVES)
5498 drive_add(NULL, CDROM_ALIAS);
5500 /* we always create at least one floppy */
5502 if (nb_drives_opt < MAX_DRIVES)
5503 drive_add(NULL, FD_ALIAS, 0);
5505 /* we always create one sd slot, even if no card is in it */
5507 if (nb_drives_opt < MAX_DRIVES)
5508 drive_add(NULL, SD_ALIAS);
5510 /* open the virtual block devices */
5512 for(i = 0; i < nb_drives_opt; i++)
5513 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5514 exit(1);
5516 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5517 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5519 #ifndef _WIN32
5520 /* must be after terminal init, SDL library changes signal handlers */
5521 termsig_setup();
5522 #endif
5524 /* Maintain compatibility with multiple stdio monitors */
5525 if (!strcmp(monitor_device,"stdio")) {
5526 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5527 const char *devname = serial_devices[i];
5528 if (devname && !strcmp(devname,"mon:stdio")) {
5529 monitor_device = NULL;
5530 break;
5531 } else if (devname && !strcmp(devname,"stdio")) {
5532 monitor_device = NULL;
5533 serial_devices[i] = "mon:stdio";
5534 break;
5539 if (kvm_enabled()) {
5540 int ret;
5542 ret = kvm_init(smp_cpus);
5543 if (ret < 0) {
5544 fprintf(stderr, "failed to initialize KVM\n");
5545 exit(1);
5549 if (monitor_device) {
5550 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5551 if (!monitor_hd) {
5552 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5553 exit(1);
5557 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5558 const char *devname = serial_devices[i];
5559 if (devname && strcmp(devname, "none")) {
5560 char label[32];
5561 snprintf(label, sizeof(label), "serial%d", i);
5562 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5563 if (!serial_hds[i]) {
5564 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5565 devname);
5566 exit(1);
5571 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5572 const char *devname = parallel_devices[i];
5573 if (devname && strcmp(devname, "none")) {
5574 char label[32];
5575 snprintf(label, sizeof(label), "parallel%d", i);
5576 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5577 if (!parallel_hds[i]) {
5578 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5579 devname);
5580 exit(1);
5585 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5586 const char *devname = virtio_consoles[i];
5587 if (devname && strcmp(devname, "none")) {
5588 char label[32];
5589 snprintf(label, sizeof(label), "virtcon%d", i);
5590 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5591 if (!virtcon_hds[i]) {
5592 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5593 devname);
5594 exit(1);
5599 machine->init(ram_size, vga_ram_size, boot_devices,
5600 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5602 current_machine = machine;
5604 /* Set KVM's vcpu state to qemu's initial CPUState. */
5605 if (kvm_enabled()) {
5606 int ret;
5608 ret = kvm_sync_vcpus();
5609 if (ret < 0) {
5610 fprintf(stderr, "failed to initialize vcpus\n");
5611 exit(1);
5615 /* init USB devices */
5616 if (usb_enabled) {
5617 for(i = 0; i < usb_devices_index; i++) {
5618 if (usb_device_add(usb_devices[i], 0) < 0) {
5619 fprintf(stderr, "Warning: could not add USB device %s\n",
5620 usb_devices[i]);
5625 if (!display_state)
5626 dumb_display_init();
5627 /* just use the first displaystate for the moment */
5628 ds = display_state;
5629 /* terminal init */
5630 if (nographic) {
5631 if (curses) {
5632 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5633 exit(1);
5635 } else {
5636 #if defined(CONFIG_CURSES)
5637 if (curses) {
5638 /* At the moment curses cannot be used with other displays */
5639 curses_display_init(ds, full_screen);
5640 } else
5641 #endif
5643 if (vnc_display != NULL) {
5644 vnc_display_init(ds);
5645 if (vnc_display_open(ds, vnc_display) < 0)
5646 exit(1);
5648 #if defined(CONFIG_SDL)
5649 if (sdl || !vnc_display)
5650 sdl_display_init(ds, full_screen, no_frame);
5651 #elif defined(CONFIG_COCOA)
5652 if (sdl || !vnc_display)
5653 cocoa_display_init(ds, full_screen);
5654 #endif
5657 dpy_resize(ds);
5659 dcl = ds->listeners;
5660 while (dcl != NULL) {
5661 if (dcl->dpy_refresh != NULL) {
5662 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5663 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5665 dcl = dcl->next;
5668 if (nographic || (vnc_display && !sdl)) {
5669 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5670 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5673 text_consoles_set_display(display_state);
5674 qemu_chr_initial_reset();
5676 if (monitor_device && monitor_hd)
5677 monitor_init(monitor_hd, !nographic);
5679 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5680 const char *devname = serial_devices[i];
5681 if (devname && strcmp(devname, "none")) {
5682 char label[32];
5683 snprintf(label, sizeof(label), "serial%d", i);
5684 if (strstart(devname, "vc", 0))
5685 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5689 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5690 const char *devname = parallel_devices[i];
5691 if (devname && strcmp(devname, "none")) {
5692 char label[32];
5693 snprintf(label, sizeof(label), "parallel%d", i);
5694 if (strstart(devname, "vc", 0))
5695 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5699 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5700 const char *devname = virtio_consoles[i];
5701 if (virtcon_hds[i] && devname) {
5702 char label[32];
5703 snprintf(label, sizeof(label), "virtcon%d", i);
5704 if (strstart(devname, "vc", 0))
5705 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5709 #ifdef CONFIG_GDBSTUB
5710 if (use_gdbstub) {
5711 /* XXX: use standard host:port notation and modify options
5712 accordingly. */
5713 if (gdbserver_start(gdbstub_port) < 0) {
5714 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5715 gdbstub_port);
5716 exit(1);
5719 #endif
5721 if (loadvm)
5722 do_loadvm(loadvm);
5724 if (incoming) {
5725 autostart = 0; /* fixme how to deal with -daemonize */
5726 qemu_start_incoming_migration(incoming);
5729 if (autostart)
5730 vm_start();
5732 if (daemonize) {
5733 uint8_t status = 0;
5734 ssize_t len;
5736 again1:
5737 len = write(fds[1], &status, 1);
5738 if (len == -1 && (errno == EINTR))
5739 goto again1;
5741 if (len != 1)
5742 exit(1);
5744 chdir("/");
5745 TFR(fd = open("/dev/null", O_RDWR));
5746 if (fd == -1)
5747 exit(1);
5750 #ifndef _WIN32
5751 if (run_as) {
5752 pwd = getpwnam(run_as);
5753 if (!pwd) {
5754 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5755 exit(1);
5759 if (chroot_dir) {
5760 if (chroot(chroot_dir) < 0) {
5761 fprintf(stderr, "chroot failed\n");
5762 exit(1);
5764 chdir("/");
5767 if (run_as) {
5768 if (setgid(pwd->pw_gid) < 0) {
5769 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5770 exit(1);
5772 if (setuid(pwd->pw_uid) < 0) {
5773 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5774 exit(1);
5776 if (setuid(0) != -1) {
5777 fprintf(stderr, "Dropping privileges failed\n");
5778 exit(1);
5781 #endif
5783 if (daemonize) {
5784 dup2(fd, 0);
5785 dup2(fd, 1);
5786 dup2(fd, 2);
5788 close(fd);
5791 main_loop();
5792 quit_timers();
5793 net_cleanup();
5795 return 0;