fixed refresh logic (initial patch by Igor Kovalenko)
[qemu/mini2440.git] / vl.c
blobb31b2398a9709f3db0a6f6e552ee1818e91826ed
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2005 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
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 "vl.h"
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <sys/time.h>
33 #ifndef _WIN32
34 #include <sys/times.h>
35 #include <sys/wait.h>
36 #include <termios.h>
37 #include <sys/poll.h>
38 #include <sys/mman.h>
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <dirent.h>
43 #include <netdb.h>
44 #ifdef _BSD
45 #include <sys/stat.h>
46 #ifndef __APPLE__
47 #include <libutil.h>
48 #endif
49 #else
50 #ifndef __sun__
51 #include <linux/if.h>
52 #include <linux/if_tun.h>
53 #include <pty.h>
54 #include <malloc.h>
55 #include <linux/rtc.h>
56 #include <linux/ppdev.h>
57 #endif
58 #endif
59 #endif
61 #if defined(CONFIG_SLIRP)
62 #include "libslirp.h"
63 #endif
65 #ifdef _WIN32
66 #include <malloc.h>
67 #include <sys/timeb.h>
68 #include <windows.h>
69 #define getopt_long_only getopt_long
70 #define memalign(align, size) malloc(size)
71 #endif
73 #include "qemu_socket.h"
75 #ifdef CONFIG_SDL
76 #ifdef __APPLE__
77 #include <SDL/SDL.h>
78 #endif
79 #endif /* CONFIG_SDL */
81 #ifdef CONFIG_COCOA
82 #undef main
83 #define main qemu_main
84 #endif /* CONFIG_COCOA */
86 #include "disas.h"
88 #include "exec-all.h"
90 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
92 //#define DEBUG_UNUSED_IOPORT
93 //#define DEBUG_IOPORT
95 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
97 #ifdef TARGET_PPC
98 #define DEFAULT_RAM_SIZE 144
99 #else
100 #define DEFAULT_RAM_SIZE 128
101 #endif
102 /* in ms */
103 #define GUI_REFRESH_INTERVAL 30
105 /* Max number of USB devices that can be specified on the commandline. */
106 #define MAX_USB_CMDLINE 8
108 /* XXX: use a two level table to limit memory usage */
109 #define MAX_IOPORTS 65536
111 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
112 char phys_ram_file[1024];
113 void *ioport_opaque[MAX_IOPORTS];
114 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
115 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
116 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
117 int vga_ram_size;
118 int bios_size;
119 static DisplayState display_state;
120 int nographic;
121 const char* keyboard_layout = NULL;
122 int64_t ticks_per_sec;
123 int boot_device = 'c';
124 int ram_size;
125 int pit_min_timer_count = 0;
126 int nb_nics;
127 NICInfo nd_table[MAX_NICS];
128 QEMUTimer *gui_timer;
129 int vm_running;
130 int rtc_utc = 1;
131 int cirrus_vga_enabled = 1;
132 #ifdef TARGET_SPARC
133 int graphic_width = 1024;
134 int graphic_height = 768;
135 #else
136 int graphic_width = 800;
137 int graphic_height = 600;
138 #endif
139 int graphic_depth = 15;
140 int full_screen = 0;
141 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
142 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
143 #ifdef TARGET_I386
144 int win2k_install_hack = 0;
145 #endif
146 int usb_enabled = 0;
147 static VLANState *first_vlan;
148 int smp_cpus = 1;
149 int vnc_display = -1;
150 #if defined(TARGET_SPARC)
151 #define MAX_CPUS 16
152 #elif defined(TARGET_I386)
153 #define MAX_CPUS 255
154 #else
155 #define MAX_CPUS 1
156 #endif
157 int acpi_enabled = 1;
158 int fd_bootchk = 1;
160 /***********************************************************/
161 /* x86 ISA bus support */
163 target_phys_addr_t isa_mem_base = 0;
164 PicState2 *isa_pic;
166 uint32_t default_ioport_readb(void *opaque, uint32_t address)
168 #ifdef DEBUG_UNUSED_IOPORT
169 fprintf(stderr, "inb: port=0x%04x\n", address);
170 #endif
171 return 0xff;
174 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
176 #ifdef DEBUG_UNUSED_IOPORT
177 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
178 #endif
181 /* default is to make two byte accesses */
182 uint32_t default_ioport_readw(void *opaque, uint32_t address)
184 uint32_t data;
185 data = ioport_read_table[0][address](ioport_opaque[address], address);
186 address = (address + 1) & (MAX_IOPORTS - 1);
187 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
188 return data;
191 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
193 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
194 address = (address + 1) & (MAX_IOPORTS - 1);
195 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
198 uint32_t default_ioport_readl(void *opaque, uint32_t address)
200 #ifdef DEBUG_UNUSED_IOPORT
201 fprintf(stderr, "inl: port=0x%04x\n", address);
202 #endif
203 return 0xffffffff;
206 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
208 #ifdef DEBUG_UNUSED_IOPORT
209 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
210 #endif
213 void init_ioports(void)
215 int i;
217 for(i = 0; i < MAX_IOPORTS; i++) {
218 ioport_read_table[0][i] = default_ioport_readb;
219 ioport_write_table[0][i] = default_ioport_writeb;
220 ioport_read_table[1][i] = default_ioport_readw;
221 ioport_write_table[1][i] = default_ioport_writew;
222 ioport_read_table[2][i] = default_ioport_readl;
223 ioport_write_table[2][i] = default_ioport_writel;
227 /* size is the word size in byte */
228 int register_ioport_read(int start, int length, int size,
229 IOPortReadFunc *func, void *opaque)
231 int i, bsize;
233 if (size == 1) {
234 bsize = 0;
235 } else if (size == 2) {
236 bsize = 1;
237 } else if (size == 4) {
238 bsize = 2;
239 } else {
240 hw_error("register_ioport_read: invalid size");
241 return -1;
243 for(i = start; i < start + length; i += size) {
244 ioport_read_table[bsize][i] = func;
245 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
246 hw_error("register_ioport_read: invalid opaque");
247 ioport_opaque[i] = opaque;
249 return 0;
252 /* size is the word size in byte */
253 int register_ioport_write(int start, int length, int size,
254 IOPortWriteFunc *func, void *opaque)
256 int i, bsize;
258 if (size == 1) {
259 bsize = 0;
260 } else if (size == 2) {
261 bsize = 1;
262 } else if (size == 4) {
263 bsize = 2;
264 } else {
265 hw_error("register_ioport_write: invalid size");
266 return -1;
268 for(i = start; i < start + length; i += size) {
269 ioport_write_table[bsize][i] = func;
270 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
271 hw_error("register_ioport_read: invalid opaque");
272 ioport_opaque[i] = opaque;
274 return 0;
277 void isa_unassign_ioport(int start, int length)
279 int i;
281 for(i = start; i < start + length; i++) {
282 ioport_read_table[0][i] = default_ioport_readb;
283 ioport_read_table[1][i] = default_ioport_readw;
284 ioport_read_table[2][i] = default_ioport_readl;
286 ioport_write_table[0][i] = default_ioport_writeb;
287 ioport_write_table[1][i] = default_ioport_writew;
288 ioport_write_table[2][i] = default_ioport_writel;
292 /***********************************************************/
294 void pstrcpy(char *buf, int buf_size, const char *str)
296 int c;
297 char *q = buf;
299 if (buf_size <= 0)
300 return;
302 for(;;) {
303 c = *str++;
304 if (c == 0 || q >= buf + buf_size - 1)
305 break;
306 *q++ = c;
308 *q = '\0';
311 /* strcat and truncate. */
312 char *pstrcat(char *buf, int buf_size, const char *s)
314 int len;
315 len = strlen(buf);
316 if (len < buf_size)
317 pstrcpy(buf + len, buf_size - len, s);
318 return buf;
321 int strstart(const char *str, const char *val, const char **ptr)
323 const char *p, *q;
324 p = str;
325 q = val;
326 while (*q != '\0') {
327 if (*p != *q)
328 return 0;
329 p++;
330 q++;
332 if (ptr)
333 *ptr = p;
334 return 1;
337 void cpu_outb(CPUState *env, int addr, int val)
339 #ifdef DEBUG_IOPORT
340 if (loglevel & CPU_LOG_IOPORT)
341 fprintf(logfile, "outb: %04x %02x\n", addr, val);
342 #endif
343 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
344 #ifdef USE_KQEMU
345 if (env)
346 env->last_io_time = cpu_get_time_fast();
347 #endif
350 void cpu_outw(CPUState *env, int addr, int val)
352 #ifdef DEBUG_IOPORT
353 if (loglevel & CPU_LOG_IOPORT)
354 fprintf(logfile, "outw: %04x %04x\n", addr, val);
355 #endif
356 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
357 #ifdef USE_KQEMU
358 if (env)
359 env->last_io_time = cpu_get_time_fast();
360 #endif
363 void cpu_outl(CPUState *env, int addr, int val)
365 #ifdef DEBUG_IOPORT
366 if (loglevel & CPU_LOG_IOPORT)
367 fprintf(logfile, "outl: %04x %08x\n", addr, val);
368 #endif
369 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
370 #ifdef USE_KQEMU
371 if (env)
372 env->last_io_time = cpu_get_time_fast();
373 #endif
376 int cpu_inb(CPUState *env, int addr)
378 int val;
379 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
380 #ifdef DEBUG_IOPORT
381 if (loglevel & CPU_LOG_IOPORT)
382 fprintf(logfile, "inb : %04x %02x\n", addr, val);
383 #endif
384 #ifdef USE_KQEMU
385 if (env)
386 env->last_io_time = cpu_get_time_fast();
387 #endif
388 return val;
391 int cpu_inw(CPUState *env, int addr)
393 int val;
394 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
395 #ifdef DEBUG_IOPORT
396 if (loglevel & CPU_LOG_IOPORT)
397 fprintf(logfile, "inw : %04x %04x\n", addr, val);
398 #endif
399 #ifdef USE_KQEMU
400 if (env)
401 env->last_io_time = cpu_get_time_fast();
402 #endif
403 return val;
406 int cpu_inl(CPUState *env, int addr)
408 int val;
409 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
410 #ifdef DEBUG_IOPORT
411 if (loglevel & CPU_LOG_IOPORT)
412 fprintf(logfile, "inl : %04x %08x\n", addr, val);
413 #endif
414 #ifdef USE_KQEMU
415 if (env)
416 env->last_io_time = cpu_get_time_fast();
417 #endif
418 return val;
421 /***********************************************************/
422 void hw_error(const char *fmt, ...)
424 va_list ap;
425 CPUState *env;
427 va_start(ap, fmt);
428 fprintf(stderr, "qemu: hardware error: ");
429 vfprintf(stderr, fmt, ap);
430 fprintf(stderr, "\n");
431 for(env = first_cpu; env != NULL; env = env->next_cpu) {
432 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
433 #ifdef TARGET_I386
434 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
435 #else
436 cpu_dump_state(env, stderr, fprintf, 0);
437 #endif
439 va_end(ap);
440 abort();
443 /***********************************************************/
444 /* keyboard/mouse */
446 static QEMUPutKBDEvent *qemu_put_kbd_event;
447 static void *qemu_put_kbd_event_opaque;
448 static QEMUPutMouseEvent *qemu_put_mouse_event;
449 static void *qemu_put_mouse_event_opaque;
450 static int qemu_put_mouse_event_absolute;
452 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
454 qemu_put_kbd_event_opaque = opaque;
455 qemu_put_kbd_event = func;
458 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
460 qemu_put_mouse_event_opaque = opaque;
461 qemu_put_mouse_event = func;
462 qemu_put_mouse_event_absolute = absolute;
465 void kbd_put_keycode(int keycode)
467 if (qemu_put_kbd_event) {
468 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
472 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
474 if (qemu_put_mouse_event) {
475 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
476 dx, dy, dz, buttons_state);
480 int kbd_mouse_is_absolute(void)
482 return qemu_put_mouse_event_absolute;
485 /* compute with 96 bit intermediate result: (a*b)/c */
486 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
488 union {
489 uint64_t ll;
490 struct {
491 #ifdef WORDS_BIGENDIAN
492 uint32_t high, low;
493 #else
494 uint32_t low, high;
495 #endif
496 } l;
497 } u, res;
498 uint64_t rl, rh;
500 u.ll = a;
501 rl = (uint64_t)u.l.low * (uint64_t)b;
502 rh = (uint64_t)u.l.high * (uint64_t)b;
503 rh += (rl >> 32);
504 res.l.high = rh / c;
505 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
506 return res.ll;
509 /***********************************************************/
510 /* real time host monotonic timer */
512 #define QEMU_TIMER_BASE 1000000000LL
514 #ifdef WIN32
516 static int64_t clock_freq;
518 static void init_get_clock(void)
520 LARGE_INTEGER freq;
521 int ret;
522 ret = QueryPerformanceFrequency(&freq);
523 if (ret == 0) {
524 fprintf(stderr, "Could not calibrate ticks\n");
525 exit(1);
527 clock_freq = freq.QuadPart;
530 static int64_t get_clock(void)
532 LARGE_INTEGER ti;
533 QueryPerformanceCounter(&ti);
534 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
537 #else
539 static int use_rt_clock;
541 static void init_get_clock(void)
543 use_rt_clock = 0;
544 #if defined(__linux__)
546 struct timespec ts;
547 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
548 use_rt_clock = 1;
551 #endif
554 static int64_t get_clock(void)
556 #if defined(__linux__)
557 if (use_rt_clock) {
558 struct timespec ts;
559 clock_gettime(CLOCK_MONOTONIC, &ts);
560 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
561 } else
562 #endif
564 /* XXX: using gettimeofday leads to problems if the date
565 changes, so it should be avoided. */
566 struct timeval tv;
567 gettimeofday(&tv, NULL);
568 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
572 #endif
574 /***********************************************************/
575 /* guest cycle counter */
577 static int64_t cpu_ticks_prev;
578 static int64_t cpu_ticks_offset;
579 static int64_t cpu_clock_offset;
580 static int cpu_ticks_enabled;
582 /* return the host CPU cycle counter and handle stop/restart */
583 int64_t cpu_get_ticks(void)
585 if (!cpu_ticks_enabled) {
586 return cpu_ticks_offset;
587 } else {
588 int64_t ticks;
589 ticks = cpu_get_real_ticks();
590 if (cpu_ticks_prev > ticks) {
591 /* Note: non increasing ticks may happen if the host uses
592 software suspend */
593 cpu_ticks_offset += cpu_ticks_prev - ticks;
595 cpu_ticks_prev = ticks;
596 return ticks + cpu_ticks_offset;
600 /* return the host CPU monotonic timer and handle stop/restart */
601 static int64_t cpu_get_clock(void)
603 int64_t ti;
604 if (!cpu_ticks_enabled) {
605 return cpu_clock_offset;
606 } else {
607 ti = get_clock();
608 return ti + cpu_clock_offset;
612 /* enable cpu_get_ticks() */
613 void cpu_enable_ticks(void)
615 if (!cpu_ticks_enabled) {
616 cpu_ticks_offset -= cpu_get_real_ticks();
617 cpu_clock_offset -= get_clock();
618 cpu_ticks_enabled = 1;
622 /* disable cpu_get_ticks() : the clock is stopped. You must not call
623 cpu_get_ticks() after that. */
624 void cpu_disable_ticks(void)
626 if (cpu_ticks_enabled) {
627 cpu_ticks_offset = cpu_get_ticks();
628 cpu_clock_offset = cpu_get_clock();
629 cpu_ticks_enabled = 0;
633 /***********************************************************/
634 /* timers */
636 #define QEMU_TIMER_REALTIME 0
637 #define QEMU_TIMER_VIRTUAL 1
639 struct QEMUClock {
640 int type;
641 /* XXX: add frequency */
644 struct QEMUTimer {
645 QEMUClock *clock;
646 int64_t expire_time;
647 QEMUTimerCB *cb;
648 void *opaque;
649 struct QEMUTimer *next;
652 QEMUClock *rt_clock;
653 QEMUClock *vm_clock;
655 static QEMUTimer *active_timers[2];
656 #ifdef _WIN32
657 static MMRESULT timerID;
658 static HANDLE host_alarm = NULL;
659 static unsigned int period = 1;
660 #else
661 /* frequency of the times() clock tick */
662 static int timer_freq;
663 #endif
665 QEMUClock *qemu_new_clock(int type)
667 QEMUClock *clock;
668 clock = qemu_mallocz(sizeof(QEMUClock));
669 if (!clock)
670 return NULL;
671 clock->type = type;
672 return clock;
675 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
677 QEMUTimer *ts;
679 ts = qemu_mallocz(sizeof(QEMUTimer));
680 ts->clock = clock;
681 ts->cb = cb;
682 ts->opaque = opaque;
683 return ts;
686 void qemu_free_timer(QEMUTimer *ts)
688 qemu_free(ts);
691 /* stop a timer, but do not dealloc it */
692 void qemu_del_timer(QEMUTimer *ts)
694 QEMUTimer **pt, *t;
696 /* NOTE: this code must be signal safe because
697 qemu_timer_expired() can be called from a signal. */
698 pt = &active_timers[ts->clock->type];
699 for(;;) {
700 t = *pt;
701 if (!t)
702 break;
703 if (t == ts) {
704 *pt = t->next;
705 break;
707 pt = &t->next;
711 /* modify the current timer so that it will be fired when current_time
712 >= expire_time. The corresponding callback will be called. */
713 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
715 QEMUTimer **pt, *t;
717 qemu_del_timer(ts);
719 /* add the timer in the sorted list */
720 /* NOTE: this code must be signal safe because
721 qemu_timer_expired() can be called from a signal. */
722 pt = &active_timers[ts->clock->type];
723 for(;;) {
724 t = *pt;
725 if (!t)
726 break;
727 if (t->expire_time > expire_time)
728 break;
729 pt = &t->next;
731 ts->expire_time = expire_time;
732 ts->next = *pt;
733 *pt = ts;
736 int qemu_timer_pending(QEMUTimer *ts)
738 QEMUTimer *t;
739 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
740 if (t == ts)
741 return 1;
743 return 0;
746 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
748 if (!timer_head)
749 return 0;
750 return (timer_head->expire_time <= current_time);
753 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
755 QEMUTimer *ts;
757 for(;;) {
758 ts = *ptimer_head;
759 if (!ts || ts->expire_time > current_time)
760 break;
761 /* remove timer from the list before calling the callback */
762 *ptimer_head = ts->next;
763 ts->next = NULL;
765 /* run the callback (the timer list can be modified) */
766 ts->cb(ts->opaque);
770 int64_t qemu_get_clock(QEMUClock *clock)
772 switch(clock->type) {
773 case QEMU_TIMER_REALTIME:
774 return get_clock() / 1000000;
775 default:
776 case QEMU_TIMER_VIRTUAL:
777 return cpu_get_clock();
781 static void init_timers(void)
783 init_get_clock();
784 ticks_per_sec = QEMU_TIMER_BASE;
785 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
786 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
789 /* save a timer */
790 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
792 uint64_t expire_time;
794 if (qemu_timer_pending(ts)) {
795 expire_time = ts->expire_time;
796 } else {
797 expire_time = -1;
799 qemu_put_be64(f, expire_time);
802 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
804 uint64_t expire_time;
806 expire_time = qemu_get_be64(f);
807 if (expire_time != -1) {
808 qemu_mod_timer(ts, expire_time);
809 } else {
810 qemu_del_timer(ts);
814 static void timer_save(QEMUFile *f, void *opaque)
816 if (cpu_ticks_enabled) {
817 hw_error("cannot save state if virtual timers are running");
819 qemu_put_be64s(f, &cpu_ticks_offset);
820 qemu_put_be64s(f, &ticks_per_sec);
823 static int timer_load(QEMUFile *f, void *opaque, int version_id)
825 if (version_id != 1)
826 return -EINVAL;
827 if (cpu_ticks_enabled) {
828 return -EINVAL;
830 qemu_get_be64s(f, &cpu_ticks_offset);
831 qemu_get_be64s(f, &ticks_per_sec);
832 return 0;
835 #ifdef _WIN32
836 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
837 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
838 #else
839 static void host_alarm_handler(int host_signum)
840 #endif
842 #if 0
843 #define DISP_FREQ 1000
845 static int64_t delta_min = INT64_MAX;
846 static int64_t delta_max, delta_cum, last_clock, delta, ti;
847 static int count;
848 ti = qemu_get_clock(vm_clock);
849 if (last_clock != 0) {
850 delta = ti - last_clock;
851 if (delta < delta_min)
852 delta_min = delta;
853 if (delta > delta_max)
854 delta_max = delta;
855 delta_cum += delta;
856 if (++count == DISP_FREQ) {
857 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
858 muldiv64(delta_min, 1000000, ticks_per_sec),
859 muldiv64(delta_max, 1000000, ticks_per_sec),
860 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
861 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
862 count = 0;
863 delta_min = INT64_MAX;
864 delta_max = 0;
865 delta_cum = 0;
868 last_clock = ti;
870 #endif
871 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
872 qemu_get_clock(vm_clock)) ||
873 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
874 qemu_get_clock(rt_clock))) {
875 #ifdef _WIN32
876 SetEvent(host_alarm);
877 #endif
878 CPUState *env = cpu_single_env;
879 if (env) {
880 /* stop the currently executing cpu because a timer occured */
881 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
882 #ifdef USE_KQEMU
883 if (env->kqemu_enabled) {
884 kqemu_cpu_interrupt(env);
886 #endif
891 #ifndef _WIN32
893 #if defined(__linux__)
895 #define RTC_FREQ 1024
897 static int rtc_fd;
899 static int start_rtc_timer(void)
901 rtc_fd = open("/dev/rtc", O_RDONLY);
902 if (rtc_fd < 0)
903 return -1;
904 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
905 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
906 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
907 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
908 goto fail;
910 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
911 fail:
912 close(rtc_fd);
913 return -1;
915 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
916 return 0;
919 #else
921 static int start_rtc_timer(void)
923 return -1;
926 #endif /* !defined(__linux__) */
928 #endif /* !defined(_WIN32) */
930 static void init_timer_alarm(void)
932 #ifdef _WIN32
934 int count=0;
935 TIMECAPS tc;
937 ZeroMemory(&tc, sizeof(TIMECAPS));
938 timeGetDevCaps(&tc, sizeof(TIMECAPS));
939 if (period < tc.wPeriodMin)
940 period = tc.wPeriodMin;
941 timeBeginPeriod(period);
942 timerID = timeSetEvent(1, // interval (ms)
943 period, // resolution
944 host_alarm_handler, // function
945 (DWORD)&count, // user parameter
946 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
947 if( !timerID ) {
948 perror("failed timer alarm");
949 exit(1);
951 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
952 if (!host_alarm) {
953 perror("failed CreateEvent");
954 exit(1);
956 qemu_add_wait_object(host_alarm, NULL, NULL);
958 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
959 #else
961 struct sigaction act;
962 struct itimerval itv;
964 /* get times() syscall frequency */
965 timer_freq = sysconf(_SC_CLK_TCK);
967 /* timer signal */
968 sigfillset(&act.sa_mask);
969 act.sa_flags = 0;
970 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
971 act.sa_flags |= SA_ONSTACK;
972 #endif
973 act.sa_handler = host_alarm_handler;
974 sigaction(SIGALRM, &act, NULL);
976 itv.it_interval.tv_sec = 0;
977 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
978 itv.it_value.tv_sec = 0;
979 itv.it_value.tv_usec = 10 * 1000;
980 setitimer(ITIMER_REAL, &itv, NULL);
981 /* we probe the tick duration of the kernel to inform the user if
982 the emulated kernel requested a too high timer frequency */
983 getitimer(ITIMER_REAL, &itv);
985 #if defined(__linux__)
986 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
987 have timers with 1 ms resolution. The correct solution will
988 be to use the POSIX real time timers available in recent
989 2.6 kernels */
990 if (itv.it_interval.tv_usec > 1000 || 1) {
991 /* try to use /dev/rtc to have a faster timer */
992 if (start_rtc_timer() < 0)
993 goto use_itimer;
994 /* disable itimer */
995 itv.it_interval.tv_sec = 0;
996 itv.it_interval.tv_usec = 0;
997 itv.it_value.tv_sec = 0;
998 itv.it_value.tv_usec = 0;
999 setitimer(ITIMER_REAL, &itv, NULL);
1001 /* use the RTC */
1002 sigaction(SIGIO, &act, NULL);
1003 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1004 fcntl(rtc_fd, F_SETOWN, getpid());
1005 } else
1006 #endif /* defined(__linux__) */
1008 use_itimer:
1009 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1010 PIT_FREQ) / 1000000;
1013 #endif
1016 void quit_timers(void)
1018 #ifdef _WIN32
1019 timeKillEvent(timerID);
1020 timeEndPeriod(period);
1021 if (host_alarm) {
1022 CloseHandle(host_alarm);
1023 host_alarm = NULL;
1025 #endif
1028 /***********************************************************/
1029 /* character device */
1031 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1033 return s->chr_write(s, buf, len);
1036 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1038 if (!s->chr_ioctl)
1039 return -ENOTSUP;
1040 return s->chr_ioctl(s, cmd, arg);
1043 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1045 char buf[4096];
1046 va_list ap;
1047 va_start(ap, fmt);
1048 vsnprintf(buf, sizeof(buf), fmt, ap);
1049 qemu_chr_write(s, buf, strlen(buf));
1050 va_end(ap);
1053 void qemu_chr_send_event(CharDriverState *s, int event)
1055 if (s->chr_send_event)
1056 s->chr_send_event(s, event);
1059 void qemu_chr_add_read_handler(CharDriverState *s,
1060 IOCanRWHandler *fd_can_read,
1061 IOReadHandler *fd_read, void *opaque)
1063 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1066 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1068 s->chr_event = chr_event;
1071 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1073 return len;
1076 static void null_chr_add_read_handler(CharDriverState *chr,
1077 IOCanRWHandler *fd_can_read,
1078 IOReadHandler *fd_read, void *opaque)
1082 CharDriverState *qemu_chr_open_null(void)
1084 CharDriverState *chr;
1086 chr = qemu_mallocz(sizeof(CharDriverState));
1087 if (!chr)
1088 return NULL;
1089 chr->chr_write = null_chr_write;
1090 chr->chr_add_read_handler = null_chr_add_read_handler;
1091 return chr;
1094 #ifdef _WIN32
1096 static void socket_cleanup(void)
1098 WSACleanup();
1101 static int socket_init(void)
1103 WSADATA Data;
1104 int ret, err;
1106 ret = WSAStartup(MAKEWORD(2,2), &Data);
1107 if (ret != 0) {
1108 err = WSAGetLastError();
1109 fprintf(stderr, "WSAStartup: %d\n", err);
1110 return -1;
1112 atexit(socket_cleanup);
1113 return 0;
1116 static int send_all(int fd, const uint8_t *buf, int len1)
1118 int ret, len;
1120 len = len1;
1121 while (len > 0) {
1122 ret = send(fd, buf, len, 0);
1123 if (ret < 0) {
1124 int errno;
1125 errno = WSAGetLastError();
1126 if (errno != WSAEWOULDBLOCK) {
1127 return -1;
1129 } else if (ret == 0) {
1130 break;
1131 } else {
1132 buf += ret;
1133 len -= ret;
1136 return len1 - len;
1139 void socket_set_nonblock(int fd)
1141 unsigned long opt = 1;
1142 ioctlsocket(fd, FIONBIO, &opt);
1145 #else
1147 static int unix_write(int fd, const uint8_t *buf, int len1)
1149 int ret, len;
1151 len = len1;
1152 while (len > 0) {
1153 ret = write(fd, buf, len);
1154 if (ret < 0) {
1155 if (errno != EINTR && errno != EAGAIN)
1156 return -1;
1157 } else if (ret == 0) {
1158 break;
1159 } else {
1160 buf += ret;
1161 len -= ret;
1164 return len1 - len;
1167 static inline int send_all(int fd, const uint8_t *buf, int len1)
1169 return unix_write(fd, buf, len1);
1172 void socket_set_nonblock(int fd)
1174 fcntl(fd, F_SETFL, O_NONBLOCK);
1176 #endif /* !_WIN32 */
1178 #ifndef _WIN32
1180 typedef struct {
1181 int fd_in, fd_out;
1182 IOCanRWHandler *fd_can_read;
1183 IOReadHandler *fd_read;
1184 void *fd_opaque;
1185 int max_size;
1186 } FDCharDriver;
1188 #define STDIO_MAX_CLIENTS 2
1190 static int stdio_nb_clients;
1191 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1193 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1195 FDCharDriver *s = chr->opaque;
1196 return unix_write(s->fd_out, buf, len);
1199 static int fd_chr_read_poll(void *opaque)
1201 CharDriverState *chr = opaque;
1202 FDCharDriver *s = chr->opaque;
1204 s->max_size = s->fd_can_read(s->fd_opaque);
1205 return s->max_size;
1208 static void fd_chr_read(void *opaque)
1210 CharDriverState *chr = opaque;
1211 FDCharDriver *s = chr->opaque;
1212 int size, len;
1213 uint8_t buf[1024];
1215 len = sizeof(buf);
1216 if (len > s->max_size)
1217 len = s->max_size;
1218 if (len == 0)
1219 return;
1220 size = read(s->fd_in, buf, len);
1221 if (size > 0) {
1222 s->fd_read(s->fd_opaque, buf, size);
1226 static void fd_chr_add_read_handler(CharDriverState *chr,
1227 IOCanRWHandler *fd_can_read,
1228 IOReadHandler *fd_read, void *opaque)
1230 FDCharDriver *s = chr->opaque;
1232 if (s->fd_in >= 0) {
1233 s->fd_can_read = fd_can_read;
1234 s->fd_read = fd_read;
1235 s->fd_opaque = opaque;
1236 if (nographic && s->fd_in == 0) {
1237 } else {
1238 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1239 fd_chr_read, NULL, chr);
1244 /* open a character device to a unix fd */
1245 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1247 CharDriverState *chr;
1248 FDCharDriver *s;
1250 chr = qemu_mallocz(sizeof(CharDriverState));
1251 if (!chr)
1252 return NULL;
1253 s = qemu_mallocz(sizeof(FDCharDriver));
1254 if (!s) {
1255 free(chr);
1256 return NULL;
1258 s->fd_in = fd_in;
1259 s->fd_out = fd_out;
1260 chr->opaque = s;
1261 chr->chr_write = fd_chr_write;
1262 chr->chr_add_read_handler = fd_chr_add_read_handler;
1263 return chr;
1266 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1268 int fd_out;
1270 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1271 if (fd_out < 0)
1272 return NULL;
1273 return qemu_chr_open_fd(-1, fd_out);
1276 CharDriverState *qemu_chr_open_pipe(const char *filename)
1278 int fd;
1280 fd = open(filename, O_RDWR | O_BINARY);
1281 if (fd < 0)
1282 return NULL;
1283 return qemu_chr_open_fd(fd, fd);
1287 /* for STDIO, we handle the case where several clients use it
1288 (nographic mode) */
1290 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1292 #define TERM_FIFO_MAX_SIZE 1
1294 static int term_got_escape, client_index;
1295 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1296 static int term_fifo_size;
1297 static int term_timestamps;
1298 static int64_t term_timestamps_start;
1300 void term_print_help(void)
1302 printf("\n"
1303 "C-a h print this help\n"
1304 "C-a x exit emulator\n"
1305 "C-a s save disk data back to file (if -snapshot)\n"
1306 "C-a b send break (magic sysrq)\n"
1307 "C-a t toggle console timestamps\n"
1308 "C-a c switch between console and monitor\n"
1309 "C-a C-a send C-a\n"
1313 /* called when a char is received */
1314 static void stdio_received_byte(int ch)
1316 if (term_got_escape) {
1317 term_got_escape = 0;
1318 switch(ch) {
1319 case 'h':
1320 term_print_help();
1321 break;
1322 case 'x':
1323 exit(0);
1324 break;
1325 case 's':
1327 int i;
1328 for (i = 0; i < MAX_DISKS; i++) {
1329 if (bs_table[i])
1330 bdrv_commit(bs_table[i]);
1333 break;
1334 case 'b':
1335 if (client_index < stdio_nb_clients) {
1336 CharDriverState *chr;
1337 FDCharDriver *s;
1339 chr = stdio_clients[client_index];
1340 s = chr->opaque;
1341 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1343 break;
1344 case 'c':
1345 client_index++;
1346 if (client_index >= stdio_nb_clients)
1347 client_index = 0;
1348 if (client_index == 0) {
1349 /* send a new line in the monitor to get the prompt */
1350 ch = '\r';
1351 goto send_char;
1353 break;
1354 case 't':
1355 term_timestamps = !term_timestamps;
1356 term_timestamps_start = -1;
1357 break;
1358 case TERM_ESCAPE:
1359 goto send_char;
1361 } else if (ch == TERM_ESCAPE) {
1362 term_got_escape = 1;
1363 } else {
1364 send_char:
1365 if (client_index < stdio_nb_clients) {
1366 uint8_t buf[1];
1367 CharDriverState *chr;
1368 FDCharDriver *s;
1370 chr = stdio_clients[client_index];
1371 s = chr->opaque;
1372 if (s->fd_can_read(s->fd_opaque) > 0) {
1373 buf[0] = ch;
1374 s->fd_read(s->fd_opaque, buf, 1);
1375 } else if (term_fifo_size == 0) {
1376 term_fifo[term_fifo_size++] = ch;
1382 static int stdio_read_poll(void *opaque)
1384 CharDriverState *chr;
1385 FDCharDriver *s;
1387 if (client_index < stdio_nb_clients) {
1388 chr = stdio_clients[client_index];
1389 s = chr->opaque;
1390 /* try to flush the queue if needed */
1391 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1392 s->fd_read(s->fd_opaque, term_fifo, 1);
1393 term_fifo_size = 0;
1395 /* see if we can absorb more chars */
1396 if (term_fifo_size == 0)
1397 return 1;
1398 else
1399 return 0;
1400 } else {
1401 return 1;
1405 static void stdio_read(void *opaque)
1407 int size;
1408 uint8_t buf[1];
1410 size = read(0, buf, 1);
1411 if (size > 0)
1412 stdio_received_byte(buf[0]);
1415 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1417 FDCharDriver *s = chr->opaque;
1418 if (!term_timestamps) {
1419 return unix_write(s->fd_out, buf, len);
1420 } else {
1421 int i;
1422 char buf1[64];
1424 for(i = 0; i < len; i++) {
1425 unix_write(s->fd_out, buf + i, 1);
1426 if (buf[i] == '\n') {
1427 int64_t ti;
1428 int secs;
1430 ti = get_clock();
1431 if (term_timestamps_start == -1)
1432 term_timestamps_start = ti;
1433 ti -= term_timestamps_start;
1434 secs = ti / 1000000000;
1435 snprintf(buf1, sizeof(buf1),
1436 "[%02d:%02d:%02d.%03d] ",
1437 secs / 3600,
1438 (secs / 60) % 60,
1439 secs % 60,
1440 (int)((ti / 1000000) % 1000));
1441 unix_write(s->fd_out, buf1, strlen(buf1));
1444 return len;
1448 /* init terminal so that we can grab keys */
1449 static struct termios oldtty;
1450 static int old_fd0_flags;
1452 static void term_exit(void)
1454 tcsetattr (0, TCSANOW, &oldtty);
1455 fcntl(0, F_SETFL, old_fd0_flags);
1458 static void term_init(void)
1460 struct termios tty;
1462 tcgetattr (0, &tty);
1463 oldtty = tty;
1464 old_fd0_flags = fcntl(0, F_GETFL);
1466 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1467 |INLCR|IGNCR|ICRNL|IXON);
1468 tty.c_oflag |= OPOST;
1469 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1470 /* if graphical mode, we allow Ctrl-C handling */
1471 if (nographic)
1472 tty.c_lflag &= ~ISIG;
1473 tty.c_cflag &= ~(CSIZE|PARENB);
1474 tty.c_cflag |= CS8;
1475 tty.c_cc[VMIN] = 1;
1476 tty.c_cc[VTIME] = 0;
1478 tcsetattr (0, TCSANOW, &tty);
1480 atexit(term_exit);
1482 fcntl(0, F_SETFL, O_NONBLOCK);
1485 CharDriverState *qemu_chr_open_stdio(void)
1487 CharDriverState *chr;
1489 if (nographic) {
1490 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1491 return NULL;
1492 chr = qemu_chr_open_fd(0, 1);
1493 chr->chr_write = stdio_write;
1494 if (stdio_nb_clients == 0)
1495 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1496 client_index = stdio_nb_clients;
1497 } else {
1498 if (stdio_nb_clients != 0)
1499 return NULL;
1500 chr = qemu_chr_open_fd(0, 1);
1502 stdio_clients[stdio_nb_clients++] = chr;
1503 if (stdio_nb_clients == 1) {
1504 /* set the terminal in raw mode */
1505 term_init();
1507 return chr;
1510 #if defined(__linux__)
1511 CharDriverState *qemu_chr_open_pty(void)
1513 struct termios tty;
1514 char slave_name[1024];
1515 int master_fd, slave_fd;
1517 /* Not satisfying */
1518 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1519 return NULL;
1522 /* Disabling local echo and line-buffered output */
1523 tcgetattr (master_fd, &tty);
1524 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1525 tty.c_cc[VMIN] = 1;
1526 tty.c_cc[VTIME] = 0;
1527 tcsetattr (master_fd, TCSAFLUSH, &tty);
1529 fprintf(stderr, "char device redirected to %s\n", slave_name);
1530 return qemu_chr_open_fd(master_fd, master_fd);
1533 static void tty_serial_init(int fd, int speed,
1534 int parity, int data_bits, int stop_bits)
1536 struct termios tty;
1537 speed_t spd;
1539 #if 0
1540 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1541 speed, parity, data_bits, stop_bits);
1542 #endif
1543 tcgetattr (fd, &tty);
1545 switch(speed) {
1546 case 50:
1547 spd = B50;
1548 break;
1549 case 75:
1550 spd = B75;
1551 break;
1552 case 300:
1553 spd = B300;
1554 break;
1555 case 600:
1556 spd = B600;
1557 break;
1558 case 1200:
1559 spd = B1200;
1560 break;
1561 case 2400:
1562 spd = B2400;
1563 break;
1564 case 4800:
1565 spd = B4800;
1566 break;
1567 case 9600:
1568 spd = B9600;
1569 break;
1570 case 19200:
1571 spd = B19200;
1572 break;
1573 case 38400:
1574 spd = B38400;
1575 break;
1576 case 57600:
1577 spd = B57600;
1578 break;
1579 default:
1580 case 115200:
1581 spd = B115200;
1582 break;
1585 cfsetispeed(&tty, spd);
1586 cfsetospeed(&tty, spd);
1588 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1589 |INLCR|IGNCR|ICRNL|IXON);
1590 tty.c_oflag |= OPOST;
1591 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1592 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1593 switch(data_bits) {
1594 default:
1595 case 8:
1596 tty.c_cflag |= CS8;
1597 break;
1598 case 7:
1599 tty.c_cflag |= CS7;
1600 break;
1601 case 6:
1602 tty.c_cflag |= CS6;
1603 break;
1604 case 5:
1605 tty.c_cflag |= CS5;
1606 break;
1608 switch(parity) {
1609 default:
1610 case 'N':
1611 break;
1612 case 'E':
1613 tty.c_cflag |= PARENB;
1614 break;
1615 case 'O':
1616 tty.c_cflag |= PARENB | PARODD;
1617 break;
1620 tcsetattr (fd, TCSANOW, &tty);
1623 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1625 FDCharDriver *s = chr->opaque;
1627 switch(cmd) {
1628 case CHR_IOCTL_SERIAL_SET_PARAMS:
1630 QEMUSerialSetParams *ssp = arg;
1631 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1632 ssp->data_bits, ssp->stop_bits);
1634 break;
1635 case CHR_IOCTL_SERIAL_SET_BREAK:
1637 int enable = *(int *)arg;
1638 if (enable)
1639 tcsendbreak(s->fd_in, 1);
1641 break;
1642 default:
1643 return -ENOTSUP;
1645 return 0;
1648 CharDriverState *qemu_chr_open_tty(const char *filename)
1650 CharDriverState *chr;
1651 int fd;
1653 fd = open(filename, O_RDWR | O_NONBLOCK);
1654 if (fd < 0)
1655 return NULL;
1656 fcntl(fd, F_SETFL, O_NONBLOCK);
1657 tty_serial_init(fd, 115200, 'N', 8, 1);
1658 chr = qemu_chr_open_fd(fd, fd);
1659 if (!chr)
1660 return NULL;
1661 chr->chr_ioctl = tty_serial_ioctl;
1662 return chr;
1665 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1667 int fd = (int)chr->opaque;
1668 uint8_t b;
1670 switch(cmd) {
1671 case CHR_IOCTL_PP_READ_DATA:
1672 if (ioctl(fd, PPRDATA, &b) < 0)
1673 return -ENOTSUP;
1674 *(uint8_t *)arg = b;
1675 break;
1676 case CHR_IOCTL_PP_WRITE_DATA:
1677 b = *(uint8_t *)arg;
1678 if (ioctl(fd, PPWDATA, &b) < 0)
1679 return -ENOTSUP;
1680 break;
1681 case CHR_IOCTL_PP_READ_CONTROL:
1682 if (ioctl(fd, PPRCONTROL, &b) < 0)
1683 return -ENOTSUP;
1684 *(uint8_t *)arg = b;
1685 break;
1686 case CHR_IOCTL_PP_WRITE_CONTROL:
1687 b = *(uint8_t *)arg;
1688 if (ioctl(fd, PPWCONTROL, &b) < 0)
1689 return -ENOTSUP;
1690 break;
1691 case CHR_IOCTL_PP_READ_STATUS:
1692 if (ioctl(fd, PPRSTATUS, &b) < 0)
1693 return -ENOTSUP;
1694 *(uint8_t *)arg = b;
1695 break;
1696 default:
1697 return -ENOTSUP;
1699 return 0;
1702 CharDriverState *qemu_chr_open_pp(const char *filename)
1704 CharDriverState *chr;
1705 int fd;
1707 fd = open(filename, O_RDWR);
1708 if (fd < 0)
1709 return NULL;
1711 if (ioctl(fd, PPCLAIM) < 0) {
1712 close(fd);
1713 return NULL;
1716 chr = qemu_mallocz(sizeof(CharDriverState));
1717 if (!chr) {
1718 close(fd);
1719 return NULL;
1721 chr->opaque = (void *)fd;
1722 chr->chr_write = null_chr_write;
1723 chr->chr_add_read_handler = null_chr_add_read_handler;
1724 chr->chr_ioctl = pp_ioctl;
1725 return chr;
1728 #else
1729 CharDriverState *qemu_chr_open_pty(void)
1731 return NULL;
1733 #endif
1735 #endif /* !defined(_WIN32) */
1737 #ifdef _WIN32
1738 typedef struct {
1739 IOCanRWHandler *fd_can_read;
1740 IOReadHandler *fd_read;
1741 void *win_opaque;
1742 int max_size;
1743 HANDLE hcom, hrecv, hsend;
1744 OVERLAPPED orecv, osend;
1745 BOOL fpipe;
1746 DWORD len;
1747 } WinCharState;
1749 #define NSENDBUF 2048
1750 #define NRECVBUF 2048
1751 #define MAXCONNECT 1
1752 #define NTIMEOUT 5000
1754 static int win_chr_poll(void *opaque);
1755 static int win_chr_pipe_poll(void *opaque);
1757 static void win_chr_close2(WinCharState *s)
1759 if (s->hsend) {
1760 CloseHandle(s->hsend);
1761 s->hsend = NULL;
1763 if (s->hrecv) {
1764 CloseHandle(s->hrecv);
1765 s->hrecv = NULL;
1767 if (s->hcom) {
1768 CloseHandle(s->hcom);
1769 s->hcom = NULL;
1771 if (s->fpipe)
1772 qemu_del_polling_cb(win_chr_pipe_poll, s);
1773 else
1774 qemu_del_polling_cb(win_chr_poll, s);
1777 static void win_chr_close(CharDriverState *chr)
1779 WinCharState *s = chr->opaque;
1780 win_chr_close2(s);
1783 static int win_chr_init(WinCharState *s, const char *filename)
1785 COMMCONFIG comcfg;
1786 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1787 COMSTAT comstat;
1788 DWORD size;
1789 DWORD err;
1791 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1792 if (!s->hsend) {
1793 fprintf(stderr, "Failed CreateEvent\n");
1794 goto fail;
1796 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1797 if (!s->hrecv) {
1798 fprintf(stderr, "Failed CreateEvent\n");
1799 goto fail;
1802 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1803 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1804 if (s->hcom == INVALID_HANDLE_VALUE) {
1805 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1806 s->hcom = NULL;
1807 goto fail;
1810 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1811 fprintf(stderr, "Failed SetupComm\n");
1812 goto fail;
1815 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1816 size = sizeof(COMMCONFIG);
1817 GetDefaultCommConfig(filename, &comcfg, &size);
1818 comcfg.dcb.DCBlength = sizeof(DCB);
1819 CommConfigDialog(filename, NULL, &comcfg);
1821 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1822 fprintf(stderr, "Failed SetCommState\n");
1823 goto fail;
1826 if (!SetCommMask(s->hcom, EV_ERR)) {
1827 fprintf(stderr, "Failed SetCommMask\n");
1828 goto fail;
1831 cto.ReadIntervalTimeout = MAXDWORD;
1832 if (!SetCommTimeouts(s->hcom, &cto)) {
1833 fprintf(stderr, "Failed SetCommTimeouts\n");
1834 goto fail;
1837 if (!ClearCommError(s->hcom, &err, &comstat)) {
1838 fprintf(stderr, "Failed ClearCommError\n");
1839 goto fail;
1841 qemu_add_polling_cb(win_chr_poll, s);
1842 return 0;
1844 fail:
1845 win_chr_close2(s);
1846 return -1;
1849 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1851 WinCharState *s = chr->opaque;
1852 DWORD len, ret, size, err;
1854 len = len1;
1855 ZeroMemory(&s->osend, sizeof(s->osend));
1856 s->osend.hEvent = s->hsend;
1857 while (len > 0) {
1858 if (s->hsend)
1859 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1860 else
1861 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1862 if (!ret) {
1863 err = GetLastError();
1864 if (err == ERROR_IO_PENDING) {
1865 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1866 if (ret) {
1867 buf += size;
1868 len -= size;
1869 } else {
1870 break;
1872 } else {
1873 break;
1875 } else {
1876 buf += size;
1877 len -= size;
1880 return len1 - len;
1883 static int win_chr_read_poll(WinCharState *s)
1885 s->max_size = s->fd_can_read(s->win_opaque);
1886 return s->max_size;
1889 static void win_chr_readfile(WinCharState *s)
1891 int ret, err;
1892 uint8_t buf[1024];
1893 DWORD size;
1895 ZeroMemory(&s->orecv, sizeof(s->orecv));
1896 s->orecv.hEvent = s->hrecv;
1897 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1898 if (!ret) {
1899 err = GetLastError();
1900 if (err == ERROR_IO_PENDING) {
1901 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1905 if (size > 0) {
1906 s->fd_read(s->win_opaque, buf, size);
1910 static void win_chr_read(WinCharState *s)
1912 if (s->len > s->max_size)
1913 s->len = s->max_size;
1914 if (s->len == 0)
1915 return;
1917 win_chr_readfile(s);
1920 static int win_chr_poll(void *opaque)
1922 WinCharState *s = opaque;
1923 COMSTAT status;
1924 DWORD comerr;
1926 ClearCommError(s->hcom, &comerr, &status);
1927 if (status.cbInQue > 0) {
1928 s->len = status.cbInQue;
1929 win_chr_read_poll(s);
1930 win_chr_read(s);
1931 return 1;
1933 return 0;
1936 static void win_chr_add_read_handler(CharDriverState *chr,
1937 IOCanRWHandler *fd_can_read,
1938 IOReadHandler *fd_read, void *opaque)
1940 WinCharState *s = chr->opaque;
1942 s->fd_can_read = fd_can_read;
1943 s->fd_read = fd_read;
1944 s->win_opaque = opaque;
1947 CharDriverState *qemu_chr_open_win(const char *filename)
1949 CharDriverState *chr;
1950 WinCharState *s;
1952 chr = qemu_mallocz(sizeof(CharDriverState));
1953 if (!chr)
1954 return NULL;
1955 s = qemu_mallocz(sizeof(WinCharState));
1956 if (!s) {
1957 free(chr);
1958 return NULL;
1960 chr->opaque = s;
1961 chr->chr_write = win_chr_write;
1962 chr->chr_add_read_handler = win_chr_add_read_handler;
1963 chr->chr_close = win_chr_close;
1965 if (win_chr_init(s, filename) < 0) {
1966 free(s);
1967 free(chr);
1968 return NULL;
1970 return chr;
1973 static int win_chr_pipe_poll(void *opaque)
1975 WinCharState *s = opaque;
1976 DWORD size;
1978 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1979 if (size > 0) {
1980 s->len = size;
1981 win_chr_read_poll(s);
1982 win_chr_read(s);
1983 return 1;
1985 return 0;
1988 static int win_chr_pipe_init(WinCharState *s, const char *filename)
1990 OVERLAPPED ov;
1991 int ret;
1992 DWORD size;
1993 char openname[256];
1995 s->fpipe = TRUE;
1997 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1998 if (!s->hsend) {
1999 fprintf(stderr, "Failed CreateEvent\n");
2000 goto fail;
2002 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2003 if (!s->hrecv) {
2004 fprintf(stderr, "Failed CreateEvent\n");
2005 goto fail;
2008 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2009 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2010 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2011 PIPE_WAIT,
2012 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2013 if (s->hcom == INVALID_HANDLE_VALUE) {
2014 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2015 s->hcom = NULL;
2016 goto fail;
2019 ZeroMemory(&ov, sizeof(ov));
2020 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2021 ret = ConnectNamedPipe(s->hcom, &ov);
2022 if (ret) {
2023 fprintf(stderr, "Failed ConnectNamedPipe\n");
2024 goto fail;
2027 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2028 if (!ret) {
2029 fprintf(stderr, "Failed GetOverlappedResult\n");
2030 if (ov.hEvent) {
2031 CloseHandle(ov.hEvent);
2032 ov.hEvent = NULL;
2034 goto fail;
2037 if (ov.hEvent) {
2038 CloseHandle(ov.hEvent);
2039 ov.hEvent = NULL;
2041 qemu_add_polling_cb(win_chr_pipe_poll, s);
2042 return 0;
2044 fail:
2045 win_chr_close2(s);
2046 return -1;
2050 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2052 CharDriverState *chr;
2053 WinCharState *s;
2055 chr = qemu_mallocz(sizeof(CharDriverState));
2056 if (!chr)
2057 return NULL;
2058 s = qemu_mallocz(sizeof(WinCharState));
2059 if (!s) {
2060 free(chr);
2061 return NULL;
2063 chr->opaque = s;
2064 chr->chr_write = win_chr_write;
2065 chr->chr_add_read_handler = win_chr_add_read_handler;
2066 chr->chr_close = win_chr_close;
2068 if (win_chr_pipe_init(s, filename) < 0) {
2069 free(s);
2070 free(chr);
2071 return NULL;
2073 return chr;
2076 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2078 CharDriverState *chr;
2079 WinCharState *s;
2081 chr = qemu_mallocz(sizeof(CharDriverState));
2082 if (!chr)
2083 return NULL;
2084 s = qemu_mallocz(sizeof(WinCharState));
2085 if (!s) {
2086 free(chr);
2087 return NULL;
2089 s->hcom = fd_out;
2090 chr->opaque = s;
2091 chr->chr_write = win_chr_write;
2092 chr->chr_add_read_handler = win_chr_add_read_handler;
2093 return chr;
2096 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2098 HANDLE fd_out;
2100 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2101 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2102 if (fd_out == INVALID_HANDLE_VALUE)
2103 return NULL;
2105 return qemu_chr_open_win_file(fd_out);
2107 #endif
2109 /***********************************************************/
2110 /* UDP Net console */
2112 typedef struct {
2113 IOCanRWHandler *fd_can_read;
2114 IOReadHandler *fd_read;
2115 void *fd_opaque;
2116 int fd;
2117 struct sockaddr_in daddr;
2118 char buf[1024];
2119 int bufcnt;
2120 int bufptr;
2121 int max_size;
2122 } NetCharDriver;
2124 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2126 NetCharDriver *s = chr->opaque;
2128 return sendto(s->fd, buf, len, 0,
2129 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2132 static int udp_chr_read_poll(void *opaque)
2134 CharDriverState *chr = opaque;
2135 NetCharDriver *s = chr->opaque;
2137 s->max_size = s->fd_can_read(s->fd_opaque);
2139 /* If there were any stray characters in the queue process them
2140 * first
2142 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2143 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2144 s->bufptr++;
2145 s->max_size = s->fd_can_read(s->fd_opaque);
2147 return s->max_size;
2150 static void udp_chr_read(void *opaque)
2152 CharDriverState *chr = opaque;
2153 NetCharDriver *s = chr->opaque;
2155 if (s->max_size == 0)
2156 return;
2157 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2158 s->bufptr = s->bufcnt;
2159 if (s->bufcnt <= 0)
2160 return;
2162 s->bufptr = 0;
2163 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2164 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2165 s->bufptr++;
2166 s->max_size = s->fd_can_read(s->fd_opaque);
2170 static void udp_chr_add_read_handler(CharDriverState *chr,
2171 IOCanRWHandler *fd_can_read,
2172 IOReadHandler *fd_read, void *opaque)
2174 NetCharDriver *s = chr->opaque;
2176 if (s->fd >= 0) {
2177 s->fd_can_read = fd_can_read;
2178 s->fd_read = fd_read;
2179 s->fd_opaque = opaque;
2180 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2181 udp_chr_read, NULL, chr);
2185 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2186 int parse_host_src_port(struct sockaddr_in *haddr,
2187 struct sockaddr_in *saddr,
2188 const char *str);
2190 CharDriverState *qemu_chr_open_udp(const char *def)
2192 CharDriverState *chr = NULL;
2193 NetCharDriver *s = NULL;
2194 int fd = -1;
2195 struct sockaddr_in saddr;
2197 chr = qemu_mallocz(sizeof(CharDriverState));
2198 if (!chr)
2199 goto return_err;
2200 s = qemu_mallocz(sizeof(NetCharDriver));
2201 if (!s)
2202 goto return_err;
2204 fd = socket(PF_INET, SOCK_DGRAM, 0);
2205 if (fd < 0) {
2206 perror("socket(PF_INET, SOCK_DGRAM)");
2207 goto return_err;
2210 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2211 printf("Could not parse: %s\n", def);
2212 goto return_err;
2215 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2217 perror("bind");
2218 goto return_err;
2221 s->fd = fd;
2222 s->bufcnt = 0;
2223 s->bufptr = 0;
2224 chr->opaque = s;
2225 chr->chr_write = udp_chr_write;
2226 chr->chr_add_read_handler = udp_chr_add_read_handler;
2227 return chr;
2229 return_err:
2230 if (chr)
2231 free(chr);
2232 if (s)
2233 free(s);
2234 if (fd >= 0)
2235 closesocket(fd);
2236 return NULL;
2239 /***********************************************************/
2240 /* TCP Net console */
2242 typedef struct {
2243 IOCanRWHandler *fd_can_read;
2244 IOReadHandler *fd_read;
2245 void *fd_opaque;
2246 int fd, listen_fd;
2247 int connected;
2248 int max_size;
2249 int do_telnetopt;
2250 } TCPCharDriver;
2252 static void tcp_chr_accept(void *opaque);
2254 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2256 TCPCharDriver *s = chr->opaque;
2257 if (s->connected) {
2258 return send_all(s->fd, buf, len);
2259 } else {
2260 /* XXX: indicate an error ? */
2261 return len;
2265 static int tcp_chr_read_poll(void *opaque)
2267 CharDriverState *chr = opaque;
2268 TCPCharDriver *s = chr->opaque;
2269 if (!s->connected)
2270 return 0;
2271 s->max_size = s->fd_can_read(s->fd_opaque);
2272 return s->max_size;
2275 #define IAC 255
2276 #define IAC_BREAK 243
2277 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2278 TCPCharDriver *s,
2279 char *buf, int *size)
2281 /* Handle any telnet client's basic IAC options to satisfy char by
2282 * char mode with no echo. All IAC options will be removed from
2283 * the buf and the do_telnetopt variable will be used to track the
2284 * state of the width of the IAC information.
2286 * IAC commands come in sets of 3 bytes with the exception of the
2287 * "IAC BREAK" command and the double IAC.
2290 int i;
2291 int j = 0;
2293 for (i = 0; i < *size; i++) {
2294 if (s->do_telnetopt > 1) {
2295 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2296 /* Double IAC means send an IAC */
2297 if (j != i)
2298 buf[j] = buf[i];
2299 j++;
2300 s->do_telnetopt = 1;
2301 } else {
2302 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2303 /* Handle IAC break commands by sending a serial break */
2304 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2305 s->do_telnetopt++;
2307 s->do_telnetopt++;
2309 if (s->do_telnetopt >= 4) {
2310 s->do_telnetopt = 1;
2312 } else {
2313 if ((unsigned char)buf[i] == IAC) {
2314 s->do_telnetopt = 2;
2315 } else {
2316 if (j != i)
2317 buf[j] = buf[i];
2318 j++;
2322 *size = j;
2325 static void tcp_chr_read(void *opaque)
2327 CharDriverState *chr = opaque;
2328 TCPCharDriver *s = chr->opaque;
2329 uint8_t buf[1024];
2330 int len, size;
2332 if (!s->connected || s->max_size <= 0)
2333 return;
2334 len = sizeof(buf);
2335 if (len > s->max_size)
2336 len = s->max_size;
2337 size = recv(s->fd, buf, len, 0);
2338 if (size == 0) {
2339 /* connection closed */
2340 s->connected = 0;
2341 if (s->listen_fd >= 0) {
2342 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2344 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2345 closesocket(s->fd);
2346 s->fd = -1;
2347 } else if (size > 0) {
2348 if (s->do_telnetopt)
2349 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2350 if (size > 0)
2351 s->fd_read(s->fd_opaque, buf, size);
2355 static void tcp_chr_add_read_handler(CharDriverState *chr,
2356 IOCanRWHandler *fd_can_read,
2357 IOReadHandler *fd_read, void *opaque)
2359 TCPCharDriver *s = chr->opaque;
2361 s->fd_can_read = fd_can_read;
2362 s->fd_read = fd_read;
2363 s->fd_opaque = opaque;
2366 static void tcp_chr_connect(void *opaque)
2368 CharDriverState *chr = opaque;
2369 TCPCharDriver *s = chr->opaque;
2371 s->connected = 1;
2372 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2373 tcp_chr_read, NULL, chr);
2376 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2377 static void tcp_chr_telnet_init(int fd)
2379 char buf[3];
2380 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2381 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2382 send(fd, (char *)buf, 3, 0);
2383 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2384 send(fd, (char *)buf, 3, 0);
2385 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2386 send(fd, (char *)buf, 3, 0);
2387 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2388 send(fd, (char *)buf, 3, 0);
2391 static void tcp_chr_accept(void *opaque)
2393 CharDriverState *chr = opaque;
2394 TCPCharDriver *s = chr->opaque;
2395 struct sockaddr_in saddr;
2396 socklen_t len;
2397 int fd;
2399 for(;;) {
2400 len = sizeof(saddr);
2401 fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2402 if (fd < 0 && errno != EINTR) {
2403 return;
2404 } else if (fd >= 0) {
2405 if (s->do_telnetopt)
2406 tcp_chr_telnet_init(fd);
2407 break;
2410 socket_set_nonblock(fd);
2411 s->fd = fd;
2412 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2413 tcp_chr_connect(chr);
2416 static void tcp_chr_close(CharDriverState *chr)
2418 TCPCharDriver *s = chr->opaque;
2419 if (s->fd >= 0)
2420 closesocket(s->fd);
2421 if (s->listen_fd >= 0)
2422 closesocket(s->listen_fd);
2423 qemu_free(s);
2426 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2427 int is_telnet)
2429 CharDriverState *chr = NULL;
2430 TCPCharDriver *s = NULL;
2431 int fd = -1, ret, err, val;
2432 int is_listen = 0;
2433 int is_waitconnect = 1;
2434 const char *ptr;
2435 struct sockaddr_in saddr;
2437 if (parse_host_port(&saddr, host_str) < 0)
2438 goto fail;
2440 ptr = host_str;
2441 while((ptr = strchr(ptr,','))) {
2442 ptr++;
2443 if (!strncmp(ptr,"server",6)) {
2444 is_listen = 1;
2445 } else if (!strncmp(ptr,"nowait",6)) {
2446 is_waitconnect = 0;
2447 } else {
2448 printf("Unknown option: %s\n", ptr);
2449 goto fail;
2452 if (!is_listen)
2453 is_waitconnect = 0;
2455 chr = qemu_mallocz(sizeof(CharDriverState));
2456 if (!chr)
2457 goto fail;
2458 s = qemu_mallocz(sizeof(TCPCharDriver));
2459 if (!s)
2460 goto fail;
2462 fd = socket(PF_INET, SOCK_STREAM, 0);
2463 if (fd < 0)
2464 goto fail;
2466 if (!is_waitconnect)
2467 socket_set_nonblock(fd);
2469 s->connected = 0;
2470 s->fd = -1;
2471 s->listen_fd = -1;
2472 if (is_listen) {
2473 /* allow fast reuse */
2474 val = 1;
2475 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2477 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2478 if (ret < 0)
2479 goto fail;
2480 ret = listen(fd, 0);
2481 if (ret < 0)
2482 goto fail;
2483 s->listen_fd = fd;
2484 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2485 if (is_telnet)
2486 s->do_telnetopt = 1;
2487 } else {
2488 for(;;) {
2489 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2490 if (ret < 0) {
2491 err = socket_error();
2492 if (err == EINTR || err == EWOULDBLOCK) {
2493 } else if (err == EINPROGRESS) {
2494 break;
2495 } else {
2496 goto fail;
2498 } else {
2499 s->connected = 1;
2500 break;
2503 s->fd = fd;
2504 if (s->connected)
2505 tcp_chr_connect(chr);
2506 else
2507 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2510 chr->opaque = s;
2511 chr->chr_write = tcp_chr_write;
2512 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2513 chr->chr_close = tcp_chr_close;
2514 if (is_listen && is_waitconnect) {
2515 printf("QEMU waiting for connection on: %s\n", host_str);
2516 tcp_chr_accept(chr);
2517 socket_set_nonblock(s->listen_fd);
2520 return chr;
2521 fail:
2522 if (fd >= 0)
2523 closesocket(fd);
2524 qemu_free(s);
2525 qemu_free(chr);
2526 return NULL;
2529 CharDriverState *qemu_chr_open(const char *filename)
2531 const char *p;
2533 if (!strcmp(filename, "vc")) {
2534 return text_console_init(&display_state);
2535 } else if (!strcmp(filename, "null")) {
2536 return qemu_chr_open_null();
2537 } else
2538 if (strstart(filename, "tcp:", &p)) {
2539 return qemu_chr_open_tcp(p, 0);
2540 } else
2541 if (strstart(filename, "telnet:", &p)) {
2542 return qemu_chr_open_tcp(p, 1);
2543 } else
2544 if (strstart(filename, "udp:", &p)) {
2545 return qemu_chr_open_udp(p);
2546 } else
2547 #ifndef _WIN32
2548 if (strstart(filename, "file:", &p)) {
2549 return qemu_chr_open_file_out(p);
2550 } else if (strstart(filename, "pipe:", &p)) {
2551 return qemu_chr_open_pipe(p);
2552 } else if (!strcmp(filename, "pty")) {
2553 return qemu_chr_open_pty();
2554 } else if (!strcmp(filename, "stdio")) {
2555 return qemu_chr_open_stdio();
2556 } else
2557 #endif
2558 #if defined(__linux__)
2559 if (strstart(filename, "/dev/parport", NULL)) {
2560 return qemu_chr_open_pp(filename);
2561 } else
2562 if (strstart(filename, "/dev/", NULL)) {
2563 return qemu_chr_open_tty(filename);
2564 } else
2565 #endif
2566 #ifdef _WIN32
2567 if (strstart(filename, "COM", NULL)) {
2568 return qemu_chr_open_win(filename);
2569 } else
2570 if (strstart(filename, "pipe:", &p)) {
2571 return qemu_chr_open_win_pipe(p);
2572 } else
2573 if (strstart(filename, "file:", &p)) {
2574 return qemu_chr_open_win_file_out(p);
2576 #endif
2578 return NULL;
2582 void qemu_chr_close(CharDriverState *chr)
2584 if (chr->chr_close)
2585 chr->chr_close(chr);
2588 /***********************************************************/
2589 /* network device redirectors */
2591 void hex_dump(FILE *f, const uint8_t *buf, int size)
2593 int len, i, j, c;
2595 for(i=0;i<size;i+=16) {
2596 len = size - i;
2597 if (len > 16)
2598 len = 16;
2599 fprintf(f, "%08x ", i);
2600 for(j=0;j<16;j++) {
2601 if (j < len)
2602 fprintf(f, " %02x", buf[i+j]);
2603 else
2604 fprintf(f, " ");
2606 fprintf(f, " ");
2607 for(j=0;j<len;j++) {
2608 c = buf[i+j];
2609 if (c < ' ' || c > '~')
2610 c = '.';
2611 fprintf(f, "%c", c);
2613 fprintf(f, "\n");
2617 static int parse_macaddr(uint8_t *macaddr, const char *p)
2619 int i;
2620 for(i = 0; i < 6; i++) {
2621 macaddr[i] = strtol(p, (char **)&p, 16);
2622 if (i == 5) {
2623 if (*p != '\0')
2624 return -1;
2625 } else {
2626 if (*p != ':')
2627 return -1;
2628 p++;
2631 return 0;
2634 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2636 const char *p, *p1;
2637 int len;
2638 p = *pp;
2639 p1 = strchr(p, sep);
2640 if (!p1)
2641 return -1;
2642 len = p1 - p;
2643 p1++;
2644 if (buf_size > 0) {
2645 if (len > buf_size - 1)
2646 len = buf_size - 1;
2647 memcpy(buf, p, len);
2648 buf[len] = '\0';
2650 *pp = p1;
2651 return 0;
2654 int parse_host_src_port(struct sockaddr_in *haddr,
2655 struct sockaddr_in *saddr,
2656 const char *input_str)
2658 char *str = strdup(input_str);
2659 char *host_str = str;
2660 char *src_str;
2661 char *ptr;
2664 * Chop off any extra arguments at the end of the string which
2665 * would start with a comma, then fill in the src port information
2666 * if it was provided else use the "any address" and "any port".
2668 if ((ptr = strchr(str,',')))
2669 *ptr = '\0';
2671 if ((src_str = strchr(input_str,'@'))) {
2672 *src_str = '\0';
2673 src_str++;
2676 if (parse_host_port(haddr, host_str) < 0)
2677 goto fail;
2679 if (!src_str || *src_str == '\0')
2680 src_str = ":0";
2682 if (parse_host_port(saddr, src_str) < 0)
2683 goto fail;
2685 free(str);
2686 return(0);
2688 fail:
2689 free(str);
2690 return -1;
2693 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2695 char buf[512];
2696 struct hostent *he;
2697 const char *p, *r;
2698 int port;
2700 p = str;
2701 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2702 return -1;
2703 saddr->sin_family = AF_INET;
2704 if (buf[0] == '\0') {
2705 saddr->sin_addr.s_addr = 0;
2706 } else {
2707 if (isdigit(buf[0])) {
2708 if (!inet_aton(buf, &saddr->sin_addr))
2709 return -1;
2710 } else {
2711 if ((he = gethostbyname(buf)) == NULL)
2712 return - 1;
2713 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2716 port = strtol(p, (char **)&r, 0);
2717 if (r == p)
2718 return -1;
2719 saddr->sin_port = htons(port);
2720 return 0;
2723 /* find or alloc a new VLAN */
2724 VLANState *qemu_find_vlan(int id)
2726 VLANState **pvlan, *vlan;
2727 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2728 if (vlan->id == id)
2729 return vlan;
2731 vlan = qemu_mallocz(sizeof(VLANState));
2732 if (!vlan)
2733 return NULL;
2734 vlan->id = id;
2735 vlan->next = NULL;
2736 pvlan = &first_vlan;
2737 while (*pvlan != NULL)
2738 pvlan = &(*pvlan)->next;
2739 *pvlan = vlan;
2740 return vlan;
2743 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2744 IOReadHandler *fd_read,
2745 IOCanRWHandler *fd_can_read,
2746 void *opaque)
2748 VLANClientState *vc, **pvc;
2749 vc = qemu_mallocz(sizeof(VLANClientState));
2750 if (!vc)
2751 return NULL;
2752 vc->fd_read = fd_read;
2753 vc->fd_can_read = fd_can_read;
2754 vc->opaque = opaque;
2755 vc->vlan = vlan;
2757 vc->next = NULL;
2758 pvc = &vlan->first_client;
2759 while (*pvc != NULL)
2760 pvc = &(*pvc)->next;
2761 *pvc = vc;
2762 return vc;
2765 int qemu_can_send_packet(VLANClientState *vc1)
2767 VLANState *vlan = vc1->vlan;
2768 VLANClientState *vc;
2770 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2771 if (vc != vc1) {
2772 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2773 return 0;
2776 return 1;
2779 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2781 VLANState *vlan = vc1->vlan;
2782 VLANClientState *vc;
2784 #if 0
2785 printf("vlan %d send:\n", vlan->id);
2786 hex_dump(stdout, buf, size);
2787 #endif
2788 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2789 if (vc != vc1) {
2790 vc->fd_read(vc->opaque, buf, size);
2795 #if defined(CONFIG_SLIRP)
2797 /* slirp network adapter */
2799 static int slirp_inited;
2800 static VLANClientState *slirp_vc;
2802 int slirp_can_output(void)
2804 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2807 void slirp_output(const uint8_t *pkt, int pkt_len)
2809 #if 0
2810 printf("slirp output:\n");
2811 hex_dump(stdout, pkt, pkt_len);
2812 #endif
2813 if (!slirp_vc)
2814 return;
2815 qemu_send_packet(slirp_vc, pkt, pkt_len);
2818 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2820 #if 0
2821 printf("slirp input:\n");
2822 hex_dump(stdout, buf, size);
2823 #endif
2824 slirp_input(buf, size);
2827 static int net_slirp_init(VLANState *vlan)
2829 if (!slirp_inited) {
2830 slirp_inited = 1;
2831 slirp_init();
2833 slirp_vc = qemu_new_vlan_client(vlan,
2834 slirp_receive, NULL, NULL);
2835 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2836 return 0;
2839 static void net_slirp_redir(const char *redir_str)
2841 int is_udp;
2842 char buf[256], *r;
2843 const char *p;
2844 struct in_addr guest_addr;
2845 int host_port, guest_port;
2847 if (!slirp_inited) {
2848 slirp_inited = 1;
2849 slirp_init();
2852 p = redir_str;
2853 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2854 goto fail;
2855 if (!strcmp(buf, "tcp")) {
2856 is_udp = 0;
2857 } else if (!strcmp(buf, "udp")) {
2858 is_udp = 1;
2859 } else {
2860 goto fail;
2863 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2864 goto fail;
2865 host_port = strtol(buf, &r, 0);
2866 if (r == buf)
2867 goto fail;
2869 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2870 goto fail;
2871 if (buf[0] == '\0') {
2872 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2874 if (!inet_aton(buf, &guest_addr))
2875 goto fail;
2877 guest_port = strtol(p, &r, 0);
2878 if (r == p)
2879 goto fail;
2881 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2882 fprintf(stderr, "qemu: could not set up redirection\n");
2883 exit(1);
2885 return;
2886 fail:
2887 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2888 exit(1);
2891 #ifndef _WIN32
2893 char smb_dir[1024];
2895 static void smb_exit(void)
2897 DIR *d;
2898 struct dirent *de;
2899 char filename[1024];
2901 /* erase all the files in the directory */
2902 d = opendir(smb_dir);
2903 for(;;) {
2904 de = readdir(d);
2905 if (!de)
2906 break;
2907 if (strcmp(de->d_name, ".") != 0 &&
2908 strcmp(de->d_name, "..") != 0) {
2909 snprintf(filename, sizeof(filename), "%s/%s",
2910 smb_dir, de->d_name);
2911 unlink(filename);
2914 closedir(d);
2915 rmdir(smb_dir);
2918 /* automatic user mode samba server configuration */
2919 void net_slirp_smb(const char *exported_dir)
2921 char smb_conf[1024];
2922 char smb_cmdline[1024];
2923 FILE *f;
2925 if (!slirp_inited) {
2926 slirp_inited = 1;
2927 slirp_init();
2930 /* XXX: better tmp dir construction */
2931 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2932 if (mkdir(smb_dir, 0700) < 0) {
2933 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2934 exit(1);
2936 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2938 f = fopen(smb_conf, "w");
2939 if (!f) {
2940 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2941 exit(1);
2943 fprintf(f,
2944 "[global]\n"
2945 "private dir=%s\n"
2946 "smb ports=0\n"
2947 "socket address=127.0.0.1\n"
2948 "pid directory=%s\n"
2949 "lock directory=%s\n"
2950 "log file=%s/log.smbd\n"
2951 "smb passwd file=%s/smbpasswd\n"
2952 "security = share\n"
2953 "[qemu]\n"
2954 "path=%s\n"
2955 "read only=no\n"
2956 "guest ok=yes\n",
2957 smb_dir,
2958 smb_dir,
2959 smb_dir,
2960 smb_dir,
2961 smb_dir,
2962 exported_dir
2964 fclose(f);
2965 atexit(smb_exit);
2967 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2968 smb_conf);
2970 slirp_add_exec(0, smb_cmdline, 4, 139);
2973 #endif /* !defined(_WIN32) */
2975 #endif /* CONFIG_SLIRP */
2977 #if !defined(_WIN32)
2979 typedef struct TAPState {
2980 VLANClientState *vc;
2981 int fd;
2982 } TAPState;
2984 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2986 TAPState *s = opaque;
2987 int ret;
2988 for(;;) {
2989 ret = write(s->fd, buf, size);
2990 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2991 } else {
2992 break;
2997 static void tap_send(void *opaque)
2999 TAPState *s = opaque;
3000 uint8_t buf[4096];
3001 int size;
3003 size = read(s->fd, buf, sizeof(buf));
3004 if (size > 0) {
3005 qemu_send_packet(s->vc, buf, size);
3009 /* fd support */
3011 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3013 TAPState *s;
3015 s = qemu_mallocz(sizeof(TAPState));
3016 if (!s)
3017 return NULL;
3018 s->fd = fd;
3019 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3020 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3021 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3022 return s;
3025 #ifdef _BSD
3026 static int tap_open(char *ifname, int ifname_size)
3028 int fd;
3029 char *dev;
3030 struct stat s;
3032 fd = open("/dev/tap", O_RDWR);
3033 if (fd < 0) {
3034 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3035 return -1;
3038 fstat(fd, &s);
3039 dev = devname(s.st_rdev, S_IFCHR);
3040 pstrcpy(ifname, ifname_size, dev);
3042 fcntl(fd, F_SETFL, O_NONBLOCK);
3043 return fd;
3045 #elif defined(__sun__)
3046 static int tap_open(char *ifname, int ifname_size)
3048 fprintf(stderr, "warning: tap_open not yet implemented\n");
3049 return -1;
3051 #else
3052 static int tap_open(char *ifname, int ifname_size)
3054 struct ifreq ifr;
3055 int fd, ret;
3057 fd = open("/dev/net/tun", O_RDWR);
3058 if (fd < 0) {
3059 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3060 return -1;
3062 memset(&ifr, 0, sizeof(ifr));
3063 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3064 if (ifname[0] != '\0')
3065 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3066 else
3067 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3068 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3069 if (ret != 0) {
3070 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3071 close(fd);
3072 return -1;
3074 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3075 fcntl(fd, F_SETFL, O_NONBLOCK);
3076 return fd;
3078 #endif
3080 static int net_tap_init(VLANState *vlan, const char *ifname1,
3081 const char *setup_script)
3083 TAPState *s;
3084 int pid, status, fd;
3085 char *args[3];
3086 char **parg;
3087 char ifname[128];
3089 if (ifname1 != NULL)
3090 pstrcpy(ifname, sizeof(ifname), ifname1);
3091 else
3092 ifname[0] = '\0';
3093 fd = tap_open(ifname, sizeof(ifname));
3094 if (fd < 0)
3095 return -1;
3097 if (!setup_script)
3098 setup_script = "";
3099 if (setup_script[0] != '\0') {
3100 /* try to launch network init script */
3101 pid = fork();
3102 if (pid >= 0) {
3103 if (pid == 0) {
3104 parg = args;
3105 *parg++ = (char *)setup_script;
3106 *parg++ = ifname;
3107 *parg++ = NULL;
3108 execv(setup_script, args);
3109 _exit(1);
3111 while (waitpid(pid, &status, 0) != pid);
3112 if (!WIFEXITED(status) ||
3113 WEXITSTATUS(status) != 0) {
3114 fprintf(stderr, "%s: could not launch network script\n",
3115 setup_script);
3116 return -1;
3120 s = net_tap_fd_init(vlan, fd);
3121 if (!s)
3122 return -1;
3123 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3124 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3125 return 0;
3128 #endif /* !_WIN32 */
3130 /* network connection */
3131 typedef struct NetSocketState {
3132 VLANClientState *vc;
3133 int fd;
3134 int state; /* 0 = getting length, 1 = getting data */
3135 int index;
3136 int packet_len;
3137 uint8_t buf[4096];
3138 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3139 } NetSocketState;
3141 typedef struct NetSocketListenState {
3142 VLANState *vlan;
3143 int fd;
3144 } NetSocketListenState;
3146 /* XXX: we consider we can send the whole packet without blocking */
3147 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3149 NetSocketState *s = opaque;
3150 uint32_t len;
3151 len = htonl(size);
3153 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3154 send_all(s->fd, buf, size);
3157 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3159 NetSocketState *s = opaque;
3160 sendto(s->fd, buf, size, 0,
3161 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3164 static void net_socket_send(void *opaque)
3166 NetSocketState *s = opaque;
3167 int l, size, err;
3168 uint8_t buf1[4096];
3169 const uint8_t *buf;
3171 size = recv(s->fd, buf1, sizeof(buf1), 0);
3172 if (size < 0) {
3173 err = socket_error();
3174 if (err != EWOULDBLOCK)
3175 goto eoc;
3176 } else if (size == 0) {
3177 /* end of connection */
3178 eoc:
3179 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3180 closesocket(s->fd);
3181 return;
3183 buf = buf1;
3184 while (size > 0) {
3185 /* reassemble a packet from the network */
3186 switch(s->state) {
3187 case 0:
3188 l = 4 - s->index;
3189 if (l > size)
3190 l = size;
3191 memcpy(s->buf + s->index, buf, l);
3192 buf += l;
3193 size -= l;
3194 s->index += l;
3195 if (s->index == 4) {
3196 /* got length */
3197 s->packet_len = ntohl(*(uint32_t *)s->buf);
3198 s->index = 0;
3199 s->state = 1;
3201 break;
3202 case 1:
3203 l = s->packet_len - s->index;
3204 if (l > size)
3205 l = size;
3206 memcpy(s->buf + s->index, buf, l);
3207 s->index += l;
3208 buf += l;
3209 size -= l;
3210 if (s->index >= s->packet_len) {
3211 qemu_send_packet(s->vc, s->buf, s->packet_len);
3212 s->index = 0;
3213 s->state = 0;
3215 break;
3220 static void net_socket_send_dgram(void *opaque)
3222 NetSocketState *s = opaque;
3223 int size;
3225 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3226 if (size < 0)
3227 return;
3228 if (size == 0) {
3229 /* end of connection */
3230 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3231 return;
3233 qemu_send_packet(s->vc, s->buf, size);
3236 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3238 struct ip_mreq imr;
3239 int fd;
3240 int val, ret;
3241 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3242 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3243 inet_ntoa(mcastaddr->sin_addr),
3244 (int)ntohl(mcastaddr->sin_addr.s_addr));
3245 return -1;
3248 fd = socket(PF_INET, SOCK_DGRAM, 0);
3249 if (fd < 0) {
3250 perror("socket(PF_INET, SOCK_DGRAM)");
3251 return -1;
3254 val = 1;
3255 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3256 (const char *)&val, sizeof(val));
3257 if (ret < 0) {
3258 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3259 goto fail;
3262 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3263 if (ret < 0) {
3264 perror("bind");
3265 goto fail;
3268 /* Add host to multicast group */
3269 imr.imr_multiaddr = mcastaddr->sin_addr;
3270 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3272 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3273 (const char *)&imr, sizeof(struct ip_mreq));
3274 if (ret < 0) {
3275 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3276 goto fail;
3279 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3280 val = 1;
3281 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3282 (const char *)&val, sizeof(val));
3283 if (ret < 0) {
3284 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3285 goto fail;
3288 socket_set_nonblock(fd);
3289 return fd;
3290 fail:
3291 if (fd >= 0)
3292 closesocket(fd);
3293 return -1;
3296 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3297 int is_connected)
3299 struct sockaddr_in saddr;
3300 int newfd;
3301 socklen_t saddr_len;
3302 NetSocketState *s;
3304 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3305 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3306 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3309 if (is_connected) {
3310 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3311 /* must be bound */
3312 if (saddr.sin_addr.s_addr==0) {
3313 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3314 fd);
3315 return NULL;
3317 /* clone dgram socket */
3318 newfd = net_socket_mcast_create(&saddr);
3319 if (newfd < 0) {
3320 /* error already reported by net_socket_mcast_create() */
3321 close(fd);
3322 return NULL;
3324 /* clone newfd to fd, close newfd */
3325 dup2(newfd, fd);
3326 close(newfd);
3328 } else {
3329 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3330 fd, strerror(errno));
3331 return NULL;
3335 s = qemu_mallocz(sizeof(NetSocketState));
3336 if (!s)
3337 return NULL;
3338 s->fd = fd;
3340 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3341 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3343 /* mcast: save bound address as dst */
3344 if (is_connected) s->dgram_dst=saddr;
3346 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3347 "socket: fd=%d (%s mcast=%s:%d)",
3348 fd, is_connected? "cloned" : "",
3349 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3350 return s;
3353 static void net_socket_connect(void *opaque)
3355 NetSocketState *s = opaque;
3356 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3359 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3360 int is_connected)
3362 NetSocketState *s;
3363 s = qemu_mallocz(sizeof(NetSocketState));
3364 if (!s)
3365 return NULL;
3366 s->fd = fd;
3367 s->vc = qemu_new_vlan_client(vlan,
3368 net_socket_receive, NULL, s);
3369 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3370 "socket: fd=%d", fd);
3371 if (is_connected) {
3372 net_socket_connect(s);
3373 } else {
3374 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3376 return s;
3379 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3380 int is_connected)
3382 int so_type=-1, optlen=sizeof(so_type);
3384 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3385 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3386 return NULL;
3388 switch(so_type) {
3389 case SOCK_DGRAM:
3390 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3391 case SOCK_STREAM:
3392 return net_socket_fd_init_stream(vlan, fd, is_connected);
3393 default:
3394 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3395 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3396 return net_socket_fd_init_stream(vlan, fd, is_connected);
3398 return NULL;
3401 static void net_socket_accept(void *opaque)
3403 NetSocketListenState *s = opaque;
3404 NetSocketState *s1;
3405 struct sockaddr_in saddr;
3406 socklen_t len;
3407 int fd;
3409 for(;;) {
3410 len = sizeof(saddr);
3411 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3412 if (fd < 0 && errno != EINTR) {
3413 return;
3414 } else if (fd >= 0) {
3415 break;
3418 s1 = net_socket_fd_init(s->vlan, fd, 1);
3419 if (!s1) {
3420 closesocket(fd);
3421 } else {
3422 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3423 "socket: connection from %s:%d",
3424 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3428 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3430 NetSocketListenState *s;
3431 int fd, val, ret;
3432 struct sockaddr_in saddr;
3434 if (parse_host_port(&saddr, host_str) < 0)
3435 return -1;
3437 s = qemu_mallocz(sizeof(NetSocketListenState));
3438 if (!s)
3439 return -1;
3441 fd = socket(PF_INET, SOCK_STREAM, 0);
3442 if (fd < 0) {
3443 perror("socket");
3444 return -1;
3446 socket_set_nonblock(fd);
3448 /* allow fast reuse */
3449 val = 1;
3450 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3452 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3453 if (ret < 0) {
3454 perror("bind");
3455 return -1;
3457 ret = listen(fd, 0);
3458 if (ret < 0) {
3459 perror("listen");
3460 return -1;
3462 s->vlan = vlan;
3463 s->fd = fd;
3464 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3465 return 0;
3468 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3470 NetSocketState *s;
3471 int fd, connected, ret, err;
3472 struct sockaddr_in saddr;
3474 if (parse_host_port(&saddr, host_str) < 0)
3475 return -1;
3477 fd = socket(PF_INET, SOCK_STREAM, 0);
3478 if (fd < 0) {
3479 perror("socket");
3480 return -1;
3482 socket_set_nonblock(fd);
3484 connected = 0;
3485 for(;;) {
3486 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3487 if (ret < 0) {
3488 err = socket_error();
3489 if (err == EINTR || err == EWOULDBLOCK) {
3490 } else if (err == EINPROGRESS) {
3491 break;
3492 } else {
3493 perror("connect");
3494 closesocket(fd);
3495 return -1;
3497 } else {
3498 connected = 1;
3499 break;
3502 s = net_socket_fd_init(vlan, fd, connected);
3503 if (!s)
3504 return -1;
3505 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3506 "socket: connect to %s:%d",
3507 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3508 return 0;
3511 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3513 NetSocketState *s;
3514 int fd;
3515 struct sockaddr_in saddr;
3517 if (parse_host_port(&saddr, host_str) < 0)
3518 return -1;
3521 fd = net_socket_mcast_create(&saddr);
3522 if (fd < 0)
3523 return -1;
3525 s = net_socket_fd_init(vlan, fd, 0);
3526 if (!s)
3527 return -1;
3529 s->dgram_dst = saddr;
3531 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3532 "socket: mcast=%s:%d",
3533 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3534 return 0;
3538 static int get_param_value(char *buf, int buf_size,
3539 const char *tag, const char *str)
3541 const char *p;
3542 char *q;
3543 char option[128];
3545 p = str;
3546 for(;;) {
3547 q = option;
3548 while (*p != '\0' && *p != '=') {
3549 if ((q - option) < sizeof(option) - 1)
3550 *q++ = *p;
3551 p++;
3553 *q = '\0';
3554 if (*p != '=')
3555 break;
3556 p++;
3557 if (!strcmp(tag, option)) {
3558 q = buf;
3559 while (*p != '\0' && *p != ',') {
3560 if ((q - buf) < buf_size - 1)
3561 *q++ = *p;
3562 p++;
3564 *q = '\0';
3565 return q - buf;
3566 } else {
3567 while (*p != '\0' && *p != ',') {
3568 p++;
3571 if (*p != ',')
3572 break;
3573 p++;
3575 return 0;
3578 int net_client_init(const char *str)
3580 const char *p;
3581 char *q;
3582 char device[64];
3583 char buf[1024];
3584 int vlan_id, ret;
3585 VLANState *vlan;
3587 p = str;
3588 q = device;
3589 while (*p != '\0' && *p != ',') {
3590 if ((q - device) < sizeof(device) - 1)
3591 *q++ = *p;
3592 p++;
3594 *q = '\0';
3595 if (*p == ',')
3596 p++;
3597 vlan_id = 0;
3598 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3599 vlan_id = strtol(buf, NULL, 0);
3601 vlan = qemu_find_vlan(vlan_id);
3602 if (!vlan) {
3603 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3604 return -1;
3606 if (!strcmp(device, "nic")) {
3607 NICInfo *nd;
3608 uint8_t *macaddr;
3610 if (nb_nics >= MAX_NICS) {
3611 fprintf(stderr, "Too Many NICs\n");
3612 return -1;
3614 nd = &nd_table[nb_nics];
3615 macaddr = nd->macaddr;
3616 macaddr[0] = 0x52;
3617 macaddr[1] = 0x54;
3618 macaddr[2] = 0x00;
3619 macaddr[3] = 0x12;
3620 macaddr[4] = 0x34;
3621 macaddr[5] = 0x56 + nb_nics;
3623 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3624 if (parse_macaddr(macaddr, buf) < 0) {
3625 fprintf(stderr, "invalid syntax for ethernet address\n");
3626 return -1;
3629 if (get_param_value(buf, sizeof(buf), "model", p)) {
3630 nd->model = strdup(buf);
3632 nd->vlan = vlan;
3633 nb_nics++;
3634 ret = 0;
3635 } else
3636 if (!strcmp(device, "none")) {
3637 /* does nothing. It is needed to signal that no network cards
3638 are wanted */
3639 ret = 0;
3640 } else
3641 #ifdef CONFIG_SLIRP
3642 if (!strcmp(device, "user")) {
3643 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3644 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3646 ret = net_slirp_init(vlan);
3647 } else
3648 #endif
3649 #ifdef _WIN32
3650 if (!strcmp(device, "tap")) {
3651 char ifname[64];
3652 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3653 fprintf(stderr, "tap: no interface name\n");
3654 return -1;
3656 ret = tap_win32_init(vlan, ifname);
3657 } else
3658 #else
3659 if (!strcmp(device, "tap")) {
3660 char ifname[64];
3661 char setup_script[1024];
3662 int fd;
3663 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3664 fd = strtol(buf, NULL, 0);
3665 ret = -1;
3666 if (net_tap_fd_init(vlan, fd))
3667 ret = 0;
3668 } else {
3669 get_param_value(ifname, sizeof(ifname), "ifname", p);
3670 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3671 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3673 ret = net_tap_init(vlan, ifname, setup_script);
3675 } else
3676 #endif
3677 if (!strcmp(device, "socket")) {
3678 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3679 int fd;
3680 fd = strtol(buf, NULL, 0);
3681 ret = -1;
3682 if (net_socket_fd_init(vlan, fd, 1))
3683 ret = 0;
3684 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3685 ret = net_socket_listen_init(vlan, buf);
3686 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3687 ret = net_socket_connect_init(vlan, buf);
3688 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3689 ret = net_socket_mcast_init(vlan, buf);
3690 } else {
3691 fprintf(stderr, "Unknown socket options: %s\n", p);
3692 return -1;
3694 } else
3696 fprintf(stderr, "Unknown network device: %s\n", device);
3697 return -1;
3699 if (ret < 0) {
3700 fprintf(stderr, "Could not initialize device '%s'\n", device);
3703 return ret;
3706 void do_info_network(void)
3708 VLANState *vlan;
3709 VLANClientState *vc;
3711 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3712 term_printf("VLAN %d devices:\n", vlan->id);
3713 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3714 term_printf(" %s\n", vc->info_str);
3718 /***********************************************************/
3719 /* USB devices */
3721 static USBPort *used_usb_ports;
3722 static USBPort *free_usb_ports;
3724 /* ??? Maybe change this to register a hub to keep track of the topology. */
3725 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3726 usb_attachfn attach)
3728 port->opaque = opaque;
3729 port->index = index;
3730 port->attach = attach;
3731 port->next = free_usb_ports;
3732 free_usb_ports = port;
3735 static int usb_device_add(const char *devname)
3737 const char *p;
3738 USBDevice *dev;
3739 USBPort *port;
3741 if (!free_usb_ports)
3742 return -1;
3744 if (strstart(devname, "host:", &p)) {
3745 dev = usb_host_device_open(p);
3746 } else if (!strcmp(devname, "mouse")) {
3747 dev = usb_mouse_init();
3748 } else if (!strcmp(devname, "tablet")) {
3749 dev = usb_tablet_init();
3750 } else if (strstart(devname, "disk:", &p)) {
3751 dev = usb_msd_init(p);
3752 } else {
3753 return -1;
3755 if (!dev)
3756 return -1;
3758 /* Find a USB port to add the device to. */
3759 port = free_usb_ports;
3760 if (!port->next) {
3761 USBDevice *hub;
3763 /* Create a new hub and chain it on. */
3764 free_usb_ports = NULL;
3765 port->next = used_usb_ports;
3766 used_usb_ports = port;
3768 hub = usb_hub_init(VM_USB_HUB_SIZE);
3769 usb_attach(port, hub);
3770 port = free_usb_ports;
3773 free_usb_ports = port->next;
3774 port->next = used_usb_ports;
3775 used_usb_ports = port;
3776 usb_attach(port, dev);
3777 return 0;
3780 static int usb_device_del(const char *devname)
3782 USBPort *port;
3783 USBPort **lastp;
3784 USBDevice *dev;
3785 int bus_num, addr;
3786 const char *p;
3788 if (!used_usb_ports)
3789 return -1;
3791 p = strchr(devname, '.');
3792 if (!p)
3793 return -1;
3794 bus_num = strtoul(devname, NULL, 0);
3795 addr = strtoul(p + 1, NULL, 0);
3796 if (bus_num != 0)
3797 return -1;
3799 lastp = &used_usb_ports;
3800 port = used_usb_ports;
3801 while (port && port->dev->addr != addr) {
3802 lastp = &port->next;
3803 port = port->next;
3806 if (!port)
3807 return -1;
3809 dev = port->dev;
3810 *lastp = port->next;
3811 usb_attach(port, NULL);
3812 dev->handle_destroy(dev);
3813 port->next = free_usb_ports;
3814 free_usb_ports = port;
3815 return 0;
3818 void do_usb_add(const char *devname)
3820 int ret;
3821 ret = usb_device_add(devname);
3822 if (ret < 0)
3823 term_printf("Could not add USB device '%s'\n", devname);
3826 void do_usb_del(const char *devname)
3828 int ret;
3829 ret = usb_device_del(devname);
3830 if (ret < 0)
3831 term_printf("Could not remove USB device '%s'\n", devname);
3834 void usb_info(void)
3836 USBDevice *dev;
3837 USBPort *port;
3838 const char *speed_str;
3840 if (!usb_enabled) {
3841 term_printf("USB support not enabled\n");
3842 return;
3845 for (port = used_usb_ports; port; port = port->next) {
3846 dev = port->dev;
3847 if (!dev)
3848 continue;
3849 switch(dev->speed) {
3850 case USB_SPEED_LOW:
3851 speed_str = "1.5";
3852 break;
3853 case USB_SPEED_FULL:
3854 speed_str = "12";
3855 break;
3856 case USB_SPEED_HIGH:
3857 speed_str = "480";
3858 break;
3859 default:
3860 speed_str = "?";
3861 break;
3863 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
3864 0, dev->addr, speed_str, dev->devname);
3868 /***********************************************************/
3869 /* pid file */
3871 static char *pid_filename;
3873 /* Remove PID file. Called on normal exit */
3875 static void remove_pidfile(void)
3877 unlink (pid_filename);
3880 static void create_pidfile(const char *filename)
3882 struct stat pidstat;
3883 FILE *f;
3885 /* Try to write our PID to the named file */
3886 if (stat(filename, &pidstat) < 0) {
3887 if (errno == ENOENT) {
3888 if ((f = fopen (filename, "w")) == NULL) {
3889 perror("Opening pidfile");
3890 exit(1);
3892 fprintf(f, "%d\n", getpid());
3893 fclose(f);
3894 pid_filename = qemu_strdup(filename);
3895 if (!pid_filename) {
3896 fprintf(stderr, "Could not save PID filename");
3897 exit(1);
3899 atexit(remove_pidfile);
3901 } else {
3902 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3903 filename);
3904 exit(1);
3908 /***********************************************************/
3909 /* dumb display */
3911 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3915 static void dumb_resize(DisplayState *ds, int w, int h)
3919 static void dumb_refresh(DisplayState *ds)
3921 vga_hw_update();
3924 void dumb_display_init(DisplayState *ds)
3926 ds->data = NULL;
3927 ds->linesize = 0;
3928 ds->depth = 0;
3929 ds->dpy_update = dumb_update;
3930 ds->dpy_resize = dumb_resize;
3931 ds->dpy_refresh = dumb_refresh;
3934 /***********************************************************/
3935 /* I/O handling */
3937 #define MAX_IO_HANDLERS 64
3939 typedef struct IOHandlerRecord {
3940 int fd;
3941 IOCanRWHandler *fd_read_poll;
3942 IOHandler *fd_read;
3943 IOHandler *fd_write;
3944 void *opaque;
3945 /* temporary data */
3946 struct pollfd *ufd;
3947 struct IOHandlerRecord *next;
3948 } IOHandlerRecord;
3950 static IOHandlerRecord *first_io_handler;
3952 /* XXX: fd_read_poll should be suppressed, but an API change is
3953 necessary in the character devices to suppress fd_can_read(). */
3954 int qemu_set_fd_handler2(int fd,
3955 IOCanRWHandler *fd_read_poll,
3956 IOHandler *fd_read,
3957 IOHandler *fd_write,
3958 void *opaque)
3960 IOHandlerRecord **pioh, *ioh;
3962 if (!fd_read && !fd_write) {
3963 pioh = &first_io_handler;
3964 for(;;) {
3965 ioh = *pioh;
3966 if (ioh == NULL)
3967 break;
3968 if (ioh->fd == fd) {
3969 *pioh = ioh->next;
3970 qemu_free(ioh);
3971 break;
3973 pioh = &ioh->next;
3975 } else {
3976 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3977 if (ioh->fd == fd)
3978 goto found;
3980 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3981 if (!ioh)
3982 return -1;
3983 ioh->next = first_io_handler;
3984 first_io_handler = ioh;
3985 found:
3986 ioh->fd = fd;
3987 ioh->fd_read_poll = fd_read_poll;
3988 ioh->fd_read = fd_read;
3989 ioh->fd_write = fd_write;
3990 ioh->opaque = opaque;
3992 return 0;
3995 int qemu_set_fd_handler(int fd,
3996 IOHandler *fd_read,
3997 IOHandler *fd_write,
3998 void *opaque)
4000 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4003 /***********************************************************/
4004 /* Polling handling */
4006 typedef struct PollingEntry {
4007 PollingFunc *func;
4008 void *opaque;
4009 struct PollingEntry *next;
4010 } PollingEntry;
4012 static PollingEntry *first_polling_entry;
4014 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4016 PollingEntry **ppe, *pe;
4017 pe = qemu_mallocz(sizeof(PollingEntry));
4018 if (!pe)
4019 return -1;
4020 pe->func = func;
4021 pe->opaque = opaque;
4022 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4023 *ppe = pe;
4024 return 0;
4027 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4029 PollingEntry **ppe, *pe;
4030 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4031 pe = *ppe;
4032 if (pe->func == func && pe->opaque == opaque) {
4033 *ppe = pe->next;
4034 qemu_free(pe);
4035 break;
4040 #ifdef _WIN32
4041 /***********************************************************/
4042 /* Wait objects support */
4043 typedef struct WaitObjects {
4044 int num;
4045 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4046 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4047 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4048 } WaitObjects;
4050 static WaitObjects wait_objects = {0};
4052 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4054 WaitObjects *w = &wait_objects;
4056 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4057 return -1;
4058 w->events[w->num] = handle;
4059 w->func[w->num] = func;
4060 w->opaque[w->num] = opaque;
4061 w->num++;
4062 return 0;
4065 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4067 int i, found;
4068 WaitObjects *w = &wait_objects;
4070 found = 0;
4071 for (i = 0; i < w->num; i++) {
4072 if (w->events[i] == handle)
4073 found = 1;
4074 if (found) {
4075 w->events[i] = w->events[i + 1];
4076 w->func[i] = w->func[i + 1];
4077 w->opaque[i] = w->opaque[i + 1];
4080 if (found)
4081 w->num--;
4083 #endif
4085 /***********************************************************/
4086 /* savevm/loadvm support */
4088 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4090 fwrite(buf, 1, size, f);
4093 void qemu_put_byte(QEMUFile *f, int v)
4095 fputc(v, f);
4098 void qemu_put_be16(QEMUFile *f, unsigned int v)
4100 qemu_put_byte(f, v >> 8);
4101 qemu_put_byte(f, v);
4104 void qemu_put_be32(QEMUFile *f, unsigned int v)
4106 qemu_put_byte(f, v >> 24);
4107 qemu_put_byte(f, v >> 16);
4108 qemu_put_byte(f, v >> 8);
4109 qemu_put_byte(f, v);
4112 void qemu_put_be64(QEMUFile *f, uint64_t v)
4114 qemu_put_be32(f, v >> 32);
4115 qemu_put_be32(f, v);
4118 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4120 return fread(buf, 1, size, f);
4123 int qemu_get_byte(QEMUFile *f)
4125 int v;
4126 v = fgetc(f);
4127 if (v == EOF)
4128 return 0;
4129 else
4130 return v;
4133 unsigned int qemu_get_be16(QEMUFile *f)
4135 unsigned int v;
4136 v = qemu_get_byte(f) << 8;
4137 v |= qemu_get_byte(f);
4138 return v;
4141 unsigned int qemu_get_be32(QEMUFile *f)
4143 unsigned int v;
4144 v = qemu_get_byte(f) << 24;
4145 v |= qemu_get_byte(f) << 16;
4146 v |= qemu_get_byte(f) << 8;
4147 v |= qemu_get_byte(f);
4148 return v;
4151 uint64_t qemu_get_be64(QEMUFile *f)
4153 uint64_t v;
4154 v = (uint64_t)qemu_get_be32(f) << 32;
4155 v |= qemu_get_be32(f);
4156 return v;
4159 int64_t qemu_ftell(QEMUFile *f)
4161 return ftell(f);
4164 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4166 if (fseek(f, pos, whence) < 0)
4167 return -1;
4168 return ftell(f);
4171 typedef struct SaveStateEntry {
4172 char idstr[256];
4173 int instance_id;
4174 int version_id;
4175 SaveStateHandler *save_state;
4176 LoadStateHandler *load_state;
4177 void *opaque;
4178 struct SaveStateEntry *next;
4179 } SaveStateEntry;
4181 static SaveStateEntry *first_se;
4183 int register_savevm(const char *idstr,
4184 int instance_id,
4185 int version_id,
4186 SaveStateHandler *save_state,
4187 LoadStateHandler *load_state,
4188 void *opaque)
4190 SaveStateEntry *se, **pse;
4192 se = qemu_malloc(sizeof(SaveStateEntry));
4193 if (!se)
4194 return -1;
4195 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4196 se->instance_id = instance_id;
4197 se->version_id = version_id;
4198 se->save_state = save_state;
4199 se->load_state = load_state;
4200 se->opaque = opaque;
4201 se->next = NULL;
4203 /* add at the end of list */
4204 pse = &first_se;
4205 while (*pse != NULL)
4206 pse = &(*pse)->next;
4207 *pse = se;
4208 return 0;
4211 #define QEMU_VM_FILE_MAGIC 0x5145564d
4212 #define QEMU_VM_FILE_VERSION 0x00000001
4214 int qemu_savevm(const char *filename)
4216 SaveStateEntry *se;
4217 QEMUFile *f;
4218 int len, len_pos, cur_pos, saved_vm_running, ret;
4220 saved_vm_running = vm_running;
4221 vm_stop(0);
4223 f = fopen(filename, "wb");
4224 if (!f) {
4225 ret = -1;
4226 goto the_end;
4229 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4230 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4232 for(se = first_se; se != NULL; se = se->next) {
4233 /* ID string */
4234 len = strlen(se->idstr);
4235 qemu_put_byte(f, len);
4236 qemu_put_buffer(f, se->idstr, len);
4238 qemu_put_be32(f, se->instance_id);
4239 qemu_put_be32(f, se->version_id);
4241 /* record size: filled later */
4242 len_pos = ftell(f);
4243 qemu_put_be32(f, 0);
4245 se->save_state(f, se->opaque);
4247 /* fill record size */
4248 cur_pos = ftell(f);
4249 len = ftell(f) - len_pos - 4;
4250 fseek(f, len_pos, SEEK_SET);
4251 qemu_put_be32(f, len);
4252 fseek(f, cur_pos, SEEK_SET);
4255 fclose(f);
4256 ret = 0;
4257 the_end:
4258 if (saved_vm_running)
4259 vm_start();
4260 return ret;
4263 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4265 SaveStateEntry *se;
4267 for(se = first_se; se != NULL; se = se->next) {
4268 if (!strcmp(se->idstr, idstr) &&
4269 instance_id == se->instance_id)
4270 return se;
4272 return NULL;
4275 int qemu_loadvm(const char *filename)
4277 SaveStateEntry *se;
4278 QEMUFile *f;
4279 int len, cur_pos, ret, instance_id, record_len, version_id;
4280 int saved_vm_running;
4281 unsigned int v;
4282 char idstr[256];
4284 saved_vm_running = vm_running;
4285 vm_stop(0);
4287 f = fopen(filename, "rb");
4288 if (!f) {
4289 ret = -1;
4290 goto the_end;
4293 v = qemu_get_be32(f);
4294 if (v != QEMU_VM_FILE_MAGIC)
4295 goto fail;
4296 v = qemu_get_be32(f);
4297 if (v != QEMU_VM_FILE_VERSION) {
4298 fail:
4299 fclose(f);
4300 ret = -1;
4301 goto the_end;
4303 for(;;) {
4304 len = qemu_get_byte(f);
4305 if (feof(f))
4306 break;
4307 qemu_get_buffer(f, idstr, len);
4308 idstr[len] = '\0';
4309 instance_id = qemu_get_be32(f);
4310 version_id = qemu_get_be32(f);
4311 record_len = qemu_get_be32(f);
4312 #if 0
4313 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4314 idstr, instance_id, version_id, record_len);
4315 #endif
4316 cur_pos = ftell(f);
4317 se = find_se(idstr, instance_id);
4318 if (!se) {
4319 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4320 instance_id, idstr);
4321 } else {
4322 ret = se->load_state(f, se->opaque, version_id);
4323 if (ret < 0) {
4324 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4325 instance_id, idstr);
4328 /* always seek to exact end of record */
4329 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4331 fclose(f);
4332 ret = 0;
4333 the_end:
4334 if (saved_vm_running)
4335 vm_start();
4336 return ret;
4339 /***********************************************************/
4340 /* cpu save/restore */
4342 #if defined(TARGET_I386)
4344 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4346 qemu_put_be32(f, dt->selector);
4347 qemu_put_betl(f, dt->base);
4348 qemu_put_be32(f, dt->limit);
4349 qemu_put_be32(f, dt->flags);
4352 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4354 dt->selector = qemu_get_be32(f);
4355 dt->base = qemu_get_betl(f);
4356 dt->limit = qemu_get_be32(f);
4357 dt->flags = qemu_get_be32(f);
4360 void cpu_save(QEMUFile *f, void *opaque)
4362 CPUState *env = opaque;
4363 uint16_t fptag, fpus, fpuc, fpregs_format;
4364 uint32_t hflags;
4365 int i;
4367 for(i = 0; i < CPU_NB_REGS; i++)
4368 qemu_put_betls(f, &env->regs[i]);
4369 qemu_put_betls(f, &env->eip);
4370 qemu_put_betls(f, &env->eflags);
4371 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4372 qemu_put_be32s(f, &hflags);
4374 /* FPU */
4375 fpuc = env->fpuc;
4376 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4377 fptag = 0;
4378 for(i = 0; i < 8; i++) {
4379 fptag |= ((!env->fptags[i]) << i);
4382 qemu_put_be16s(f, &fpuc);
4383 qemu_put_be16s(f, &fpus);
4384 qemu_put_be16s(f, &fptag);
4386 #ifdef USE_X86LDOUBLE
4387 fpregs_format = 0;
4388 #else
4389 fpregs_format = 1;
4390 #endif
4391 qemu_put_be16s(f, &fpregs_format);
4393 for(i = 0; i < 8; i++) {
4394 #ifdef USE_X86LDOUBLE
4396 uint64_t mant;
4397 uint16_t exp;
4398 /* we save the real CPU data (in case of MMX usage only 'mant'
4399 contains the MMX register */
4400 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4401 qemu_put_be64(f, mant);
4402 qemu_put_be16(f, exp);
4404 #else
4405 /* if we use doubles for float emulation, we save the doubles to
4406 avoid losing information in case of MMX usage. It can give
4407 problems if the image is restored on a CPU where long
4408 doubles are used instead. */
4409 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4410 #endif
4413 for(i = 0; i < 6; i++)
4414 cpu_put_seg(f, &env->segs[i]);
4415 cpu_put_seg(f, &env->ldt);
4416 cpu_put_seg(f, &env->tr);
4417 cpu_put_seg(f, &env->gdt);
4418 cpu_put_seg(f, &env->idt);
4420 qemu_put_be32s(f, &env->sysenter_cs);
4421 qemu_put_be32s(f, &env->sysenter_esp);
4422 qemu_put_be32s(f, &env->sysenter_eip);
4424 qemu_put_betls(f, &env->cr[0]);
4425 qemu_put_betls(f, &env->cr[2]);
4426 qemu_put_betls(f, &env->cr[3]);
4427 qemu_put_betls(f, &env->cr[4]);
4429 for(i = 0; i < 8; i++)
4430 qemu_put_betls(f, &env->dr[i]);
4432 /* MMU */
4433 qemu_put_be32s(f, &env->a20_mask);
4435 /* XMM */
4436 qemu_put_be32s(f, &env->mxcsr);
4437 for(i = 0; i < CPU_NB_REGS; i++) {
4438 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4439 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4442 #ifdef TARGET_X86_64
4443 qemu_put_be64s(f, &env->efer);
4444 qemu_put_be64s(f, &env->star);
4445 qemu_put_be64s(f, &env->lstar);
4446 qemu_put_be64s(f, &env->cstar);
4447 qemu_put_be64s(f, &env->fmask);
4448 qemu_put_be64s(f, &env->kernelgsbase);
4449 #endif
4452 #ifdef USE_X86LDOUBLE
4453 /* XXX: add that in a FPU generic layer */
4454 union x86_longdouble {
4455 uint64_t mant;
4456 uint16_t exp;
4459 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4460 #define EXPBIAS1 1023
4461 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4462 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4464 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4466 int e;
4467 /* mantissa */
4468 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4469 /* exponent + sign */
4470 e = EXPD1(temp) - EXPBIAS1 + 16383;
4471 e |= SIGND1(temp) >> 16;
4472 p->exp = e;
4474 #endif
4476 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4478 CPUState *env = opaque;
4479 int i, guess_mmx;
4480 uint32_t hflags;
4481 uint16_t fpus, fpuc, fptag, fpregs_format;
4483 if (version_id != 3)
4484 return -EINVAL;
4485 for(i = 0; i < CPU_NB_REGS; i++)
4486 qemu_get_betls(f, &env->regs[i]);
4487 qemu_get_betls(f, &env->eip);
4488 qemu_get_betls(f, &env->eflags);
4489 qemu_get_be32s(f, &hflags);
4491 qemu_get_be16s(f, &fpuc);
4492 qemu_get_be16s(f, &fpus);
4493 qemu_get_be16s(f, &fptag);
4494 qemu_get_be16s(f, &fpregs_format);
4496 /* NOTE: we cannot always restore the FPU state if the image come
4497 from a host with a different 'USE_X86LDOUBLE' define. We guess
4498 if we are in an MMX state to restore correctly in that case. */
4499 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4500 for(i = 0; i < 8; i++) {
4501 uint64_t mant;
4502 uint16_t exp;
4504 switch(fpregs_format) {
4505 case 0:
4506 mant = qemu_get_be64(f);
4507 exp = qemu_get_be16(f);
4508 #ifdef USE_X86LDOUBLE
4509 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4510 #else
4511 /* difficult case */
4512 if (guess_mmx)
4513 env->fpregs[i].mmx.MMX_Q(0) = mant;
4514 else
4515 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4516 #endif
4517 break;
4518 case 1:
4519 mant = qemu_get_be64(f);
4520 #ifdef USE_X86LDOUBLE
4522 union x86_longdouble *p;
4523 /* difficult case */
4524 p = (void *)&env->fpregs[i];
4525 if (guess_mmx) {
4526 p->mant = mant;
4527 p->exp = 0xffff;
4528 } else {
4529 fp64_to_fp80(p, mant);
4532 #else
4533 env->fpregs[i].mmx.MMX_Q(0) = mant;
4534 #endif
4535 break;
4536 default:
4537 return -EINVAL;
4541 env->fpuc = fpuc;
4542 /* XXX: restore FPU round state */
4543 env->fpstt = (fpus >> 11) & 7;
4544 env->fpus = fpus & ~0x3800;
4545 fptag ^= 0xff;
4546 for(i = 0; i < 8; i++) {
4547 env->fptags[i] = (fptag >> i) & 1;
4550 for(i = 0; i < 6; i++)
4551 cpu_get_seg(f, &env->segs[i]);
4552 cpu_get_seg(f, &env->ldt);
4553 cpu_get_seg(f, &env->tr);
4554 cpu_get_seg(f, &env->gdt);
4555 cpu_get_seg(f, &env->idt);
4557 qemu_get_be32s(f, &env->sysenter_cs);
4558 qemu_get_be32s(f, &env->sysenter_esp);
4559 qemu_get_be32s(f, &env->sysenter_eip);
4561 qemu_get_betls(f, &env->cr[0]);
4562 qemu_get_betls(f, &env->cr[2]);
4563 qemu_get_betls(f, &env->cr[3]);
4564 qemu_get_betls(f, &env->cr[4]);
4566 for(i = 0; i < 8; i++)
4567 qemu_get_betls(f, &env->dr[i]);
4569 /* MMU */
4570 qemu_get_be32s(f, &env->a20_mask);
4572 qemu_get_be32s(f, &env->mxcsr);
4573 for(i = 0; i < CPU_NB_REGS; i++) {
4574 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4575 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4578 #ifdef TARGET_X86_64
4579 qemu_get_be64s(f, &env->efer);
4580 qemu_get_be64s(f, &env->star);
4581 qemu_get_be64s(f, &env->lstar);
4582 qemu_get_be64s(f, &env->cstar);
4583 qemu_get_be64s(f, &env->fmask);
4584 qemu_get_be64s(f, &env->kernelgsbase);
4585 #endif
4587 /* XXX: compute hflags from scratch, except for CPL and IIF */
4588 env->hflags = hflags;
4589 tlb_flush(env, 1);
4590 return 0;
4593 #elif defined(TARGET_PPC)
4594 void cpu_save(QEMUFile *f, void *opaque)
4598 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4600 return 0;
4603 #elif defined(TARGET_MIPS)
4604 void cpu_save(QEMUFile *f, void *opaque)
4608 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4610 return 0;
4613 #elif defined(TARGET_SPARC)
4614 void cpu_save(QEMUFile *f, void *opaque)
4616 CPUState *env = opaque;
4617 int i;
4618 uint32_t tmp;
4620 for(i = 0; i < 8; i++)
4621 qemu_put_betls(f, &env->gregs[i]);
4622 for(i = 0; i < NWINDOWS * 16; i++)
4623 qemu_put_betls(f, &env->regbase[i]);
4625 /* FPU */
4626 for(i = 0; i < TARGET_FPREGS; i++) {
4627 union {
4628 float32 f;
4629 uint32_t i;
4630 } u;
4631 u.f = env->fpr[i];
4632 qemu_put_be32(f, u.i);
4635 qemu_put_betls(f, &env->pc);
4636 qemu_put_betls(f, &env->npc);
4637 qemu_put_betls(f, &env->y);
4638 tmp = GET_PSR(env);
4639 qemu_put_be32(f, tmp);
4640 qemu_put_betls(f, &env->fsr);
4641 qemu_put_betls(f, &env->tbr);
4642 #ifndef TARGET_SPARC64
4643 qemu_put_be32s(f, &env->wim);
4644 /* MMU */
4645 for(i = 0; i < 16; i++)
4646 qemu_put_be32s(f, &env->mmuregs[i]);
4647 #endif
4650 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4652 CPUState *env = opaque;
4653 int i;
4654 uint32_t tmp;
4656 for(i = 0; i < 8; i++)
4657 qemu_get_betls(f, &env->gregs[i]);
4658 for(i = 0; i < NWINDOWS * 16; i++)
4659 qemu_get_betls(f, &env->regbase[i]);
4661 /* FPU */
4662 for(i = 0; i < TARGET_FPREGS; i++) {
4663 union {
4664 float32 f;
4665 uint32_t i;
4666 } u;
4667 u.i = qemu_get_be32(f);
4668 env->fpr[i] = u.f;
4671 qemu_get_betls(f, &env->pc);
4672 qemu_get_betls(f, &env->npc);
4673 qemu_get_betls(f, &env->y);
4674 tmp = qemu_get_be32(f);
4675 env->cwp = 0; /* needed to ensure that the wrapping registers are
4676 correctly updated */
4677 PUT_PSR(env, tmp);
4678 qemu_get_betls(f, &env->fsr);
4679 qemu_get_betls(f, &env->tbr);
4680 #ifndef TARGET_SPARC64
4681 qemu_get_be32s(f, &env->wim);
4682 /* MMU */
4683 for(i = 0; i < 16; i++)
4684 qemu_get_be32s(f, &env->mmuregs[i]);
4685 #endif
4686 tlb_flush(env, 1);
4687 return 0;
4690 #elif defined(TARGET_ARM)
4692 /* ??? Need to implement these. */
4693 void cpu_save(QEMUFile *f, void *opaque)
4697 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4699 return 0;
4702 #else
4704 #warning No CPU save/restore functions
4706 #endif
4708 /***********************************************************/
4709 /* ram save/restore */
4711 /* we just avoid storing empty pages */
4712 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4714 int i, v;
4716 v = buf[0];
4717 for(i = 1; i < len; i++) {
4718 if (buf[i] != v)
4719 goto normal_save;
4721 qemu_put_byte(f, 1);
4722 qemu_put_byte(f, v);
4723 return;
4724 normal_save:
4725 qemu_put_byte(f, 0);
4726 qemu_put_buffer(f, buf, len);
4729 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4731 int v;
4733 v = qemu_get_byte(f);
4734 switch(v) {
4735 case 0:
4736 if (qemu_get_buffer(f, buf, len) != len)
4737 return -EIO;
4738 break;
4739 case 1:
4740 v = qemu_get_byte(f);
4741 memset(buf, v, len);
4742 break;
4743 default:
4744 return -EINVAL;
4746 return 0;
4749 static void ram_save(QEMUFile *f, void *opaque)
4751 int i;
4752 qemu_put_be32(f, phys_ram_size);
4753 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4754 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4758 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4760 int i, ret;
4762 if (version_id != 1)
4763 return -EINVAL;
4764 if (qemu_get_be32(f) != phys_ram_size)
4765 return -EINVAL;
4766 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4767 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4768 if (ret)
4769 return ret;
4771 return 0;
4774 /***********************************************************/
4775 /* bottom halves (can be seen as timers which expire ASAP) */
4777 struct QEMUBH {
4778 QEMUBHFunc *cb;
4779 void *opaque;
4780 int scheduled;
4781 QEMUBH *next;
4784 static QEMUBH *first_bh = NULL;
4786 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
4788 QEMUBH *bh;
4789 bh = qemu_mallocz(sizeof(QEMUBH));
4790 if (!bh)
4791 return NULL;
4792 bh->cb = cb;
4793 bh->opaque = opaque;
4794 return bh;
4797 void qemu_bh_poll(void)
4799 QEMUBH *bh, **pbh;
4801 for(;;) {
4802 pbh = &first_bh;
4803 bh = *pbh;
4804 if (!bh)
4805 break;
4806 *pbh = bh->next;
4807 bh->scheduled = 0;
4808 bh->cb(bh->opaque);
4812 void qemu_bh_schedule(QEMUBH *bh)
4814 CPUState *env = cpu_single_env;
4815 if (bh->scheduled)
4816 return;
4817 bh->scheduled = 1;
4818 bh->next = first_bh;
4819 first_bh = bh;
4821 /* stop the currently executing CPU to execute the BH ASAP */
4822 if (env) {
4823 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4827 void qemu_bh_cancel(QEMUBH *bh)
4829 QEMUBH **pbh;
4830 if (bh->scheduled) {
4831 pbh = &first_bh;
4832 while (*pbh != bh)
4833 pbh = &(*pbh)->next;
4834 *pbh = bh->next;
4835 bh->scheduled = 0;
4839 void qemu_bh_delete(QEMUBH *bh)
4841 qemu_bh_cancel(bh);
4842 qemu_free(bh);
4845 /***********************************************************/
4846 /* machine registration */
4848 QEMUMachine *first_machine = NULL;
4850 int qemu_register_machine(QEMUMachine *m)
4852 QEMUMachine **pm;
4853 pm = &first_machine;
4854 while (*pm != NULL)
4855 pm = &(*pm)->next;
4856 m->next = NULL;
4857 *pm = m;
4858 return 0;
4861 QEMUMachine *find_machine(const char *name)
4863 QEMUMachine *m;
4865 for(m = first_machine; m != NULL; m = m->next) {
4866 if (!strcmp(m->name, name))
4867 return m;
4869 return NULL;
4872 /***********************************************************/
4873 /* main execution loop */
4875 void gui_update(void *opaque)
4877 display_state.dpy_refresh(&display_state);
4878 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4881 struct vm_change_state_entry {
4882 VMChangeStateHandler *cb;
4883 void *opaque;
4884 LIST_ENTRY (vm_change_state_entry) entries;
4887 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4889 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4890 void *opaque)
4892 VMChangeStateEntry *e;
4894 e = qemu_mallocz(sizeof (*e));
4895 if (!e)
4896 return NULL;
4898 e->cb = cb;
4899 e->opaque = opaque;
4900 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4901 return e;
4904 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4906 LIST_REMOVE (e, entries);
4907 qemu_free (e);
4910 static void vm_state_notify(int running)
4912 VMChangeStateEntry *e;
4914 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4915 e->cb(e->opaque, running);
4919 /* XXX: support several handlers */
4920 static VMStopHandler *vm_stop_cb;
4921 static void *vm_stop_opaque;
4923 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4925 vm_stop_cb = cb;
4926 vm_stop_opaque = opaque;
4927 return 0;
4930 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4932 vm_stop_cb = NULL;
4935 void vm_start(void)
4937 if (!vm_running) {
4938 cpu_enable_ticks();
4939 vm_running = 1;
4940 vm_state_notify(1);
4944 void vm_stop(int reason)
4946 if (vm_running) {
4947 cpu_disable_ticks();
4948 vm_running = 0;
4949 if (reason != 0) {
4950 if (vm_stop_cb) {
4951 vm_stop_cb(vm_stop_opaque, reason);
4954 vm_state_notify(0);
4958 /* reset/shutdown handler */
4960 typedef struct QEMUResetEntry {
4961 QEMUResetHandler *func;
4962 void *opaque;
4963 struct QEMUResetEntry *next;
4964 } QEMUResetEntry;
4966 static QEMUResetEntry *first_reset_entry;
4967 static int reset_requested;
4968 static int shutdown_requested;
4969 static int powerdown_requested;
4971 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4973 QEMUResetEntry **pre, *re;
4975 pre = &first_reset_entry;
4976 while (*pre != NULL)
4977 pre = &(*pre)->next;
4978 re = qemu_mallocz(sizeof(QEMUResetEntry));
4979 re->func = func;
4980 re->opaque = opaque;
4981 re->next = NULL;
4982 *pre = re;
4985 void qemu_system_reset(void)
4987 QEMUResetEntry *re;
4989 /* reset all devices */
4990 for(re = first_reset_entry; re != NULL; re = re->next) {
4991 re->func(re->opaque);
4995 void qemu_system_reset_request(void)
4997 reset_requested = 1;
4998 if (cpu_single_env)
4999 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5002 void qemu_system_shutdown_request(void)
5004 shutdown_requested = 1;
5005 if (cpu_single_env)
5006 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5009 void qemu_system_powerdown_request(void)
5011 powerdown_requested = 1;
5012 if (cpu_single_env)
5013 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5016 void main_loop_wait(int timeout)
5018 IOHandlerRecord *ioh, *ioh_next;
5019 fd_set rfds, wfds, xfds;
5020 int ret, nfds;
5021 struct timeval tv;
5022 PollingEntry *pe;
5025 /* XXX: need to suppress polling by better using win32 events */
5026 ret = 0;
5027 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5028 ret |= pe->func(pe->opaque);
5030 #ifdef _WIN32
5031 if (ret == 0 && timeout > 0) {
5032 int err;
5033 WaitObjects *w = &wait_objects;
5035 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5036 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5037 if (w->func[ret - WAIT_OBJECT_0])
5038 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5039 } else if (ret == WAIT_TIMEOUT) {
5040 } else {
5041 err = GetLastError();
5042 fprintf(stderr, "Wait error %d %d\n", ret, err);
5045 #endif
5046 /* poll any events */
5047 /* XXX: separate device handlers from system ones */
5048 nfds = -1;
5049 FD_ZERO(&rfds);
5050 FD_ZERO(&wfds);
5051 FD_ZERO(&xfds);
5052 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5053 if (ioh->fd_read &&
5054 (!ioh->fd_read_poll ||
5055 ioh->fd_read_poll(ioh->opaque) != 0)) {
5056 FD_SET(ioh->fd, &rfds);
5057 if (ioh->fd > nfds)
5058 nfds = ioh->fd;
5060 if (ioh->fd_write) {
5061 FD_SET(ioh->fd, &wfds);
5062 if (ioh->fd > nfds)
5063 nfds = ioh->fd;
5067 tv.tv_sec = 0;
5068 #ifdef _WIN32
5069 tv.tv_usec = 0;
5070 #else
5071 tv.tv_usec = timeout * 1000;
5072 #endif
5073 #if defined(CONFIG_SLIRP)
5074 if (slirp_inited) {
5075 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5077 #endif
5078 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5079 if (ret > 0) {
5080 /* XXX: better handling of removal */
5081 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5082 ioh_next = ioh->next;
5083 if (FD_ISSET(ioh->fd, &rfds)) {
5084 ioh->fd_read(ioh->opaque);
5086 if (FD_ISSET(ioh->fd, &wfds)) {
5087 ioh->fd_write(ioh->opaque);
5091 #if defined(CONFIG_SLIRP)
5092 if (slirp_inited) {
5093 if (ret < 0) {
5094 FD_ZERO(&rfds);
5095 FD_ZERO(&wfds);
5096 FD_ZERO(&xfds);
5098 slirp_select_poll(&rfds, &wfds, &xfds);
5100 #endif
5101 #ifdef _WIN32
5102 tap_win32_poll();
5103 #endif
5104 qemu_aio_poll();
5105 qemu_bh_poll();
5107 if (vm_running) {
5108 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5109 qemu_get_clock(vm_clock));
5110 /* run dma transfers, if any */
5111 DMA_run();
5114 /* real time timers */
5115 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5116 qemu_get_clock(rt_clock));
5119 static CPUState *cur_cpu;
5121 int main_loop(void)
5123 int ret, timeout;
5124 #ifdef CONFIG_PROFILER
5125 int64_t ti;
5126 #endif
5127 CPUState *env;
5129 cur_cpu = first_cpu;
5130 for(;;) {
5131 if (vm_running) {
5133 env = cur_cpu;
5134 for(;;) {
5135 /* get next cpu */
5136 env = env->next_cpu;
5137 if (!env)
5138 env = first_cpu;
5139 #ifdef CONFIG_PROFILER
5140 ti = profile_getclock();
5141 #endif
5142 ret = cpu_exec(env);
5143 #ifdef CONFIG_PROFILER
5144 qemu_time += profile_getclock() - ti;
5145 #endif
5146 if (ret != EXCP_HALTED)
5147 break;
5148 /* all CPUs are halted ? */
5149 if (env == cur_cpu) {
5150 ret = EXCP_HLT;
5151 break;
5154 cur_cpu = env;
5156 if (shutdown_requested) {
5157 ret = EXCP_INTERRUPT;
5158 break;
5160 if (reset_requested) {
5161 reset_requested = 0;
5162 qemu_system_reset();
5163 ret = EXCP_INTERRUPT;
5165 if (powerdown_requested) {
5166 powerdown_requested = 0;
5167 qemu_system_powerdown();
5168 ret = EXCP_INTERRUPT;
5170 if (ret == EXCP_DEBUG) {
5171 vm_stop(EXCP_DEBUG);
5173 /* if hlt instruction, we wait until the next IRQ */
5174 /* XXX: use timeout computed from timers */
5175 if (ret == EXCP_HLT)
5176 timeout = 10;
5177 else
5178 timeout = 0;
5179 } else {
5180 timeout = 10;
5182 #ifdef CONFIG_PROFILER
5183 ti = profile_getclock();
5184 #endif
5185 main_loop_wait(timeout);
5186 #ifdef CONFIG_PROFILER
5187 dev_time += profile_getclock() - ti;
5188 #endif
5190 cpu_disable_ticks();
5191 return ret;
5194 void help(void)
5196 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
5197 "usage: %s [options] [disk_image]\n"
5198 "\n"
5199 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5200 "\n"
5201 "Standard options:\n"
5202 "-M machine select emulated machine (-M ? for list)\n"
5203 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5204 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5205 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5206 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5207 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5208 "-snapshot write to temporary files instead of disk image files\n"
5209 #ifdef TARGET_I386
5210 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5211 #endif
5212 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5213 "-smp n set the number of CPUs to 'n' [default=1]\n"
5214 "-nographic disable graphical output and redirect serial I/Os to console\n"
5215 #ifndef _WIN32
5216 "-k language use keyboard layout (for example \"fr\" for French)\n"
5217 #endif
5218 #ifdef HAS_AUDIO
5219 "-audio-help print list of audio drivers and their options\n"
5220 "-soundhw c1,... enable audio support\n"
5221 " and only specified sound cards (comma separated list)\n"
5222 " use -soundhw ? to get the list of supported cards\n"
5223 " use -soundhw all to enable all of them\n"
5224 #endif
5225 "-localtime set the real time clock to local time [default=utc]\n"
5226 "-full-screen start in full screen\n"
5227 #ifdef TARGET_I386
5228 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5229 #endif
5230 "-usb enable the USB driver (will be the default soon)\n"
5231 "-usbdevice name add the host or guest USB device 'name'\n"
5232 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5233 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5234 #endif
5235 "\n"
5236 "Network options:\n"
5237 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5238 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5239 #ifdef CONFIG_SLIRP
5240 "-net user[,vlan=n][,hostname=host]\n"
5241 " connect the user mode network stack to VLAN 'n' and send\n"
5242 " hostname 'host' to DHCP clients\n"
5243 #endif
5244 #ifdef _WIN32
5245 "-net tap[,vlan=n],ifname=name\n"
5246 " connect the host TAP network interface to VLAN 'n'\n"
5247 #else
5248 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
5249 " connect the host TAP network interface to VLAN 'n' and use\n"
5250 " the network script 'file' (default=%s);\n"
5251 " use 'fd=h' to connect to an already opened TAP interface\n"
5252 #endif
5253 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5254 " connect the vlan 'n' to another VLAN using a socket connection\n"
5255 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5256 " connect the vlan 'n' to multicast maddr and port\n"
5257 "-net none use it alone to have zero network devices; if no -net option\n"
5258 " is provided, the default is '-net nic -net user'\n"
5259 "\n"
5260 #ifdef CONFIG_SLIRP
5261 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5262 #ifndef _WIN32
5263 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5264 #endif
5265 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5266 " redirect TCP or UDP connections from host to guest [-net user]\n"
5267 #endif
5268 "\n"
5269 "Linux boot specific:\n"
5270 "-kernel bzImage use 'bzImage' as kernel image\n"
5271 "-append cmdline use 'cmdline' as kernel command line\n"
5272 "-initrd file use 'file' as initial ram disk\n"
5273 "\n"
5274 "Debug/Expert options:\n"
5275 "-monitor dev redirect the monitor to char device 'dev'\n"
5276 "-serial dev redirect the serial port to char device 'dev'\n"
5277 "-parallel dev redirect the parallel port to char device 'dev'\n"
5278 "-pidfile file Write PID to 'file'\n"
5279 "-S freeze CPU at startup (use 'c' to start execution)\n"
5280 "-s wait gdb connection to port %d\n"
5281 "-p port change gdb connection port\n"
5282 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
5283 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5284 " translation (t=none or lba) (usually qemu can guess them)\n"
5285 "-L path set the directory for the BIOS and VGA BIOS\n"
5286 #ifdef USE_KQEMU
5287 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5288 "-no-kqemu disable KQEMU kernel module usage\n"
5289 #endif
5290 #ifdef USE_CODE_COPY
5291 "-no-code-copy disable code copy acceleration\n"
5292 #endif
5293 #ifdef TARGET_I386
5294 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5295 " (default is CL-GD5446 PCI VGA)\n"
5296 "-no-acpi disable ACPI\n"
5297 #endif
5298 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5299 "-vnc display start a VNC server on display\n"
5300 "\n"
5301 "During emulation, the following keys are useful:\n"
5302 "ctrl-alt-f toggle full screen\n"
5303 "ctrl-alt-n switch to virtual console 'n'\n"
5304 "ctrl-alt toggle mouse and keyboard grab\n"
5305 "\n"
5306 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5308 "qemu",
5309 DEFAULT_RAM_SIZE,
5310 #ifndef _WIN32
5311 DEFAULT_NETWORK_SCRIPT,
5312 #endif
5313 DEFAULT_GDBSTUB_PORT,
5314 "/tmp/qemu.log");
5315 exit(1);
5318 #define HAS_ARG 0x0001
5320 enum {
5321 QEMU_OPTION_h,
5323 QEMU_OPTION_M,
5324 QEMU_OPTION_fda,
5325 QEMU_OPTION_fdb,
5326 QEMU_OPTION_hda,
5327 QEMU_OPTION_hdb,
5328 QEMU_OPTION_hdc,
5329 QEMU_OPTION_hdd,
5330 QEMU_OPTION_cdrom,
5331 QEMU_OPTION_boot,
5332 QEMU_OPTION_snapshot,
5333 #ifdef TARGET_I386
5334 QEMU_OPTION_no_fd_bootchk,
5335 #endif
5336 QEMU_OPTION_m,
5337 QEMU_OPTION_nographic,
5338 #ifdef HAS_AUDIO
5339 QEMU_OPTION_audio_help,
5340 QEMU_OPTION_soundhw,
5341 #endif
5343 QEMU_OPTION_net,
5344 QEMU_OPTION_tftp,
5345 QEMU_OPTION_smb,
5346 QEMU_OPTION_redir,
5348 QEMU_OPTION_kernel,
5349 QEMU_OPTION_append,
5350 QEMU_OPTION_initrd,
5352 QEMU_OPTION_S,
5353 QEMU_OPTION_s,
5354 QEMU_OPTION_p,
5355 QEMU_OPTION_d,
5356 QEMU_OPTION_hdachs,
5357 QEMU_OPTION_L,
5358 QEMU_OPTION_no_code_copy,
5359 QEMU_OPTION_k,
5360 QEMU_OPTION_localtime,
5361 QEMU_OPTION_cirrusvga,
5362 QEMU_OPTION_g,
5363 QEMU_OPTION_std_vga,
5364 QEMU_OPTION_monitor,
5365 QEMU_OPTION_serial,
5366 QEMU_OPTION_parallel,
5367 QEMU_OPTION_loadvm,
5368 QEMU_OPTION_full_screen,
5369 QEMU_OPTION_pidfile,
5370 QEMU_OPTION_no_kqemu,
5371 QEMU_OPTION_kernel_kqemu,
5372 QEMU_OPTION_win2k_hack,
5373 QEMU_OPTION_usb,
5374 QEMU_OPTION_usbdevice,
5375 QEMU_OPTION_smp,
5376 QEMU_OPTION_vnc,
5377 QEMU_OPTION_no_acpi,
5380 typedef struct QEMUOption {
5381 const char *name;
5382 int flags;
5383 int index;
5384 } QEMUOption;
5386 const QEMUOption qemu_options[] = {
5387 { "h", 0, QEMU_OPTION_h },
5389 { "M", HAS_ARG, QEMU_OPTION_M },
5390 { "fda", HAS_ARG, QEMU_OPTION_fda },
5391 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5392 { "hda", HAS_ARG, QEMU_OPTION_hda },
5393 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5394 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5395 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5396 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5397 { "boot", HAS_ARG, QEMU_OPTION_boot },
5398 { "snapshot", 0, QEMU_OPTION_snapshot },
5399 #ifdef TARGET_I386
5400 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5401 #endif
5402 { "m", HAS_ARG, QEMU_OPTION_m },
5403 { "nographic", 0, QEMU_OPTION_nographic },
5404 { "k", HAS_ARG, QEMU_OPTION_k },
5405 #ifdef HAS_AUDIO
5406 { "audio-help", 0, QEMU_OPTION_audio_help },
5407 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5408 #endif
5410 { "net", HAS_ARG, QEMU_OPTION_net},
5411 #ifdef CONFIG_SLIRP
5412 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5413 #ifndef _WIN32
5414 { "smb", HAS_ARG, QEMU_OPTION_smb },
5415 #endif
5416 { "redir", HAS_ARG, QEMU_OPTION_redir },
5417 #endif
5419 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5420 { "append", HAS_ARG, QEMU_OPTION_append },
5421 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5423 { "S", 0, QEMU_OPTION_S },
5424 { "s", 0, QEMU_OPTION_s },
5425 { "p", HAS_ARG, QEMU_OPTION_p },
5426 { "d", HAS_ARG, QEMU_OPTION_d },
5427 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5428 { "L", HAS_ARG, QEMU_OPTION_L },
5429 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
5430 #ifdef USE_KQEMU
5431 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5432 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5433 #endif
5434 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5435 { "g", 1, QEMU_OPTION_g },
5436 #endif
5437 { "localtime", 0, QEMU_OPTION_localtime },
5438 { "std-vga", 0, QEMU_OPTION_std_vga },
5439 { "monitor", 1, QEMU_OPTION_monitor },
5440 { "serial", 1, QEMU_OPTION_serial },
5441 { "parallel", 1, QEMU_OPTION_parallel },
5442 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5443 { "full-screen", 0, QEMU_OPTION_full_screen },
5444 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5445 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5446 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5447 { "smp", HAS_ARG, QEMU_OPTION_smp },
5448 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5450 /* temporary options */
5451 { "usb", 0, QEMU_OPTION_usb },
5452 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
5453 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5454 { NULL },
5457 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5459 /* this stack is only used during signal handling */
5460 #define SIGNAL_STACK_SIZE 32768
5462 static uint8_t *signal_stack;
5464 #endif
5466 /* password input */
5468 static BlockDriverState *get_bdrv(int index)
5470 BlockDriverState *bs;
5472 if (index < 4) {
5473 bs = bs_table[index];
5474 } else if (index < 6) {
5475 bs = fd_table[index - 4];
5476 } else {
5477 bs = NULL;
5479 return bs;
5482 static void read_passwords(void)
5484 BlockDriverState *bs;
5485 int i, j;
5486 char password[256];
5488 for(i = 0; i < 6; i++) {
5489 bs = get_bdrv(i);
5490 if (bs && bdrv_is_encrypted(bs)) {
5491 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5492 for(j = 0; j < 3; j++) {
5493 monitor_readline("Password: ",
5494 1, password, sizeof(password));
5495 if (bdrv_set_key(bs, password) == 0)
5496 break;
5497 term_printf("invalid password\n");
5503 /* XXX: currently we cannot use simultaneously different CPUs */
5504 void register_machines(void)
5506 #if defined(TARGET_I386)
5507 qemu_register_machine(&pc_machine);
5508 qemu_register_machine(&isapc_machine);
5509 #elif defined(TARGET_PPC)
5510 qemu_register_machine(&heathrow_machine);
5511 qemu_register_machine(&core99_machine);
5512 qemu_register_machine(&prep_machine);
5513 #elif defined(TARGET_MIPS)
5514 qemu_register_machine(&mips_machine);
5515 #elif defined(TARGET_SPARC)
5516 #ifdef TARGET_SPARC64
5517 qemu_register_machine(&sun4u_machine);
5518 #else
5519 qemu_register_machine(&sun4m_machine);
5520 #endif
5521 #elif defined(TARGET_ARM)
5522 qemu_register_machine(&integratorcp926_machine);
5523 qemu_register_machine(&integratorcp1026_machine);
5524 qemu_register_machine(&versatilepb_machine);
5525 qemu_register_machine(&versatileab_machine);
5526 #elif defined(TARGET_SH4)
5527 qemu_register_machine(&shix_machine);
5528 #else
5529 #error unsupported CPU
5530 #endif
5533 #ifdef HAS_AUDIO
5534 struct soundhw soundhw[] = {
5535 #ifdef TARGET_I386
5537 "pcspk",
5538 "PC speaker",
5541 { .init_isa = pcspk_audio_init }
5543 #endif
5545 "sb16",
5546 "Creative Sound Blaster 16",
5549 { .init_isa = SB16_init }
5552 #ifdef CONFIG_ADLIB
5554 "adlib",
5555 #ifdef HAS_YMF262
5556 "Yamaha YMF262 (OPL3)",
5557 #else
5558 "Yamaha YM3812 (OPL2)",
5559 #endif
5562 { .init_isa = Adlib_init }
5564 #endif
5566 #ifdef CONFIG_GUS
5568 "gus",
5569 "Gravis Ultrasound GF1",
5572 { .init_isa = GUS_init }
5574 #endif
5577 "es1370",
5578 "ENSONIQ AudioPCI ES1370",
5581 { .init_pci = es1370_init }
5584 { NULL, NULL, 0, 0, { NULL } }
5587 static void select_soundhw (const char *optarg)
5589 struct soundhw *c;
5591 if (*optarg == '?') {
5592 show_valid_cards:
5594 printf ("Valid sound card names (comma separated):\n");
5595 for (c = soundhw; c->name; ++c) {
5596 printf ("%-11s %s\n", c->name, c->descr);
5598 printf ("\n-soundhw all will enable all of the above\n");
5599 exit (*optarg != '?');
5601 else {
5602 size_t l;
5603 const char *p;
5604 char *e;
5605 int bad_card = 0;
5607 if (!strcmp (optarg, "all")) {
5608 for (c = soundhw; c->name; ++c) {
5609 c->enabled = 1;
5611 return;
5614 p = optarg;
5615 while (*p) {
5616 e = strchr (p, ',');
5617 l = !e ? strlen (p) : (size_t) (e - p);
5619 for (c = soundhw; c->name; ++c) {
5620 if (!strncmp (c->name, p, l)) {
5621 c->enabled = 1;
5622 break;
5626 if (!c->name) {
5627 if (l > 80) {
5628 fprintf (stderr,
5629 "Unknown sound card name (too big to show)\n");
5631 else {
5632 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5633 (int) l, p);
5635 bad_card = 1;
5637 p += l + (e != NULL);
5640 if (bad_card)
5641 goto show_valid_cards;
5644 #endif
5646 #ifdef _WIN32
5647 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5649 exit(STATUS_CONTROL_C_EXIT);
5650 return TRUE;
5652 #endif
5654 #define MAX_NET_CLIENTS 32
5656 int main(int argc, char **argv)
5658 #ifdef CONFIG_GDBSTUB
5659 int use_gdbstub, gdbstub_port;
5660 #endif
5661 int i, cdrom_index;
5662 int snapshot, linux_boot;
5663 const char *initrd_filename;
5664 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5665 const char *kernel_filename, *kernel_cmdline;
5666 DisplayState *ds = &display_state;
5667 int cyls, heads, secs, translation;
5668 int start_emulation = 1;
5669 char net_clients[MAX_NET_CLIENTS][256];
5670 int nb_net_clients;
5671 int optind;
5672 const char *r, *optarg;
5673 CharDriverState *monitor_hd;
5674 char monitor_device[128];
5675 char serial_devices[MAX_SERIAL_PORTS][128];
5676 int serial_device_index;
5677 char parallel_devices[MAX_PARALLEL_PORTS][128];
5678 int parallel_device_index;
5679 const char *loadvm = NULL;
5680 QEMUMachine *machine;
5681 char usb_devices[MAX_USB_CMDLINE][128];
5682 int usb_devices_index;
5684 LIST_INIT (&vm_change_state_head);
5685 #ifndef _WIN32
5687 struct sigaction act;
5688 sigfillset(&act.sa_mask);
5689 act.sa_flags = 0;
5690 act.sa_handler = SIG_IGN;
5691 sigaction(SIGPIPE, &act, NULL);
5693 #else
5694 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5695 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5696 QEMU to run on a single CPU */
5698 HANDLE h;
5699 DWORD mask, smask;
5700 int i;
5701 h = GetCurrentProcess();
5702 if (GetProcessAffinityMask(h, &mask, &smask)) {
5703 for(i = 0; i < 32; i++) {
5704 if (mask & (1 << i))
5705 break;
5707 if (i != 32) {
5708 mask = 1 << i;
5709 SetProcessAffinityMask(h, mask);
5713 #endif
5715 register_machines();
5716 machine = first_machine;
5717 initrd_filename = NULL;
5718 for(i = 0; i < MAX_FD; i++)
5719 fd_filename[i] = NULL;
5720 for(i = 0; i < MAX_DISKS; i++)
5721 hd_filename[i] = NULL;
5722 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5723 vga_ram_size = VGA_RAM_SIZE;
5724 bios_size = BIOS_SIZE;
5725 #ifdef CONFIG_GDBSTUB
5726 use_gdbstub = 0;
5727 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5728 #endif
5729 snapshot = 0;
5730 nographic = 0;
5731 kernel_filename = NULL;
5732 kernel_cmdline = "";
5733 #ifdef TARGET_PPC
5734 cdrom_index = 1;
5735 #else
5736 cdrom_index = 2;
5737 #endif
5738 cyls = heads = secs = 0;
5739 translation = BIOS_ATA_TRANSLATION_AUTO;
5740 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5742 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5743 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5744 serial_devices[i][0] = '\0';
5745 serial_device_index = 0;
5747 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5748 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5749 parallel_devices[i][0] = '\0';
5750 parallel_device_index = 0;
5752 usb_devices_index = 0;
5754 nb_net_clients = 0;
5756 nb_nics = 0;
5757 /* default mac address of the first network interface */
5759 optind = 1;
5760 for(;;) {
5761 if (optind >= argc)
5762 break;
5763 r = argv[optind];
5764 if (r[0] != '-') {
5765 hd_filename[0] = argv[optind++];
5766 } else {
5767 const QEMUOption *popt;
5769 optind++;
5770 popt = qemu_options;
5771 for(;;) {
5772 if (!popt->name) {
5773 fprintf(stderr, "%s: invalid option -- '%s'\n",
5774 argv[0], r);
5775 exit(1);
5777 if (!strcmp(popt->name, r + 1))
5778 break;
5779 popt++;
5781 if (popt->flags & HAS_ARG) {
5782 if (optind >= argc) {
5783 fprintf(stderr, "%s: option '%s' requires an argument\n",
5784 argv[0], r);
5785 exit(1);
5787 optarg = argv[optind++];
5788 } else {
5789 optarg = NULL;
5792 switch(popt->index) {
5793 case QEMU_OPTION_M:
5794 machine = find_machine(optarg);
5795 if (!machine) {
5796 QEMUMachine *m;
5797 printf("Supported machines are:\n");
5798 for(m = first_machine; m != NULL; m = m->next) {
5799 printf("%-10s %s%s\n",
5800 m->name, m->desc,
5801 m == first_machine ? " (default)" : "");
5803 exit(1);
5805 break;
5806 case QEMU_OPTION_initrd:
5807 initrd_filename = optarg;
5808 break;
5809 case QEMU_OPTION_hda:
5810 case QEMU_OPTION_hdb:
5811 case QEMU_OPTION_hdc:
5812 case QEMU_OPTION_hdd:
5814 int hd_index;
5815 hd_index = popt->index - QEMU_OPTION_hda;
5816 hd_filename[hd_index] = optarg;
5817 if (hd_index == cdrom_index)
5818 cdrom_index = -1;
5820 break;
5821 case QEMU_OPTION_snapshot:
5822 snapshot = 1;
5823 break;
5824 case QEMU_OPTION_hdachs:
5826 const char *p;
5827 p = optarg;
5828 cyls = strtol(p, (char **)&p, 0);
5829 if (cyls < 1 || cyls > 16383)
5830 goto chs_fail;
5831 if (*p != ',')
5832 goto chs_fail;
5833 p++;
5834 heads = strtol(p, (char **)&p, 0);
5835 if (heads < 1 || heads > 16)
5836 goto chs_fail;
5837 if (*p != ',')
5838 goto chs_fail;
5839 p++;
5840 secs = strtol(p, (char **)&p, 0);
5841 if (secs < 1 || secs > 63)
5842 goto chs_fail;
5843 if (*p == ',') {
5844 p++;
5845 if (!strcmp(p, "none"))
5846 translation = BIOS_ATA_TRANSLATION_NONE;
5847 else if (!strcmp(p, "lba"))
5848 translation = BIOS_ATA_TRANSLATION_LBA;
5849 else if (!strcmp(p, "auto"))
5850 translation = BIOS_ATA_TRANSLATION_AUTO;
5851 else
5852 goto chs_fail;
5853 } else if (*p != '\0') {
5854 chs_fail:
5855 fprintf(stderr, "qemu: invalid physical CHS format\n");
5856 exit(1);
5859 break;
5860 case QEMU_OPTION_nographic:
5861 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5862 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5863 nographic = 1;
5864 break;
5865 case QEMU_OPTION_kernel:
5866 kernel_filename = optarg;
5867 break;
5868 case QEMU_OPTION_append:
5869 kernel_cmdline = optarg;
5870 break;
5871 case QEMU_OPTION_cdrom:
5872 if (cdrom_index >= 0) {
5873 hd_filename[cdrom_index] = optarg;
5875 break;
5876 case QEMU_OPTION_boot:
5877 boot_device = optarg[0];
5878 if (boot_device != 'a' &&
5879 #ifdef TARGET_SPARC
5880 // Network boot
5881 boot_device != 'n' &&
5882 #endif
5883 boot_device != 'c' && boot_device != 'd') {
5884 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5885 exit(1);
5887 break;
5888 case QEMU_OPTION_fda:
5889 fd_filename[0] = optarg;
5890 break;
5891 case QEMU_OPTION_fdb:
5892 fd_filename[1] = optarg;
5893 break;
5894 #ifdef TARGET_I386
5895 case QEMU_OPTION_no_fd_bootchk:
5896 fd_bootchk = 0;
5897 break;
5898 #endif
5899 case QEMU_OPTION_no_code_copy:
5900 code_copy_enabled = 0;
5901 break;
5902 case QEMU_OPTION_net:
5903 if (nb_net_clients >= MAX_NET_CLIENTS) {
5904 fprintf(stderr, "qemu: too many network clients\n");
5905 exit(1);
5907 pstrcpy(net_clients[nb_net_clients],
5908 sizeof(net_clients[0]),
5909 optarg);
5910 nb_net_clients++;
5911 break;
5912 #ifdef CONFIG_SLIRP
5913 case QEMU_OPTION_tftp:
5914 tftp_prefix = optarg;
5915 break;
5916 #ifndef _WIN32
5917 case QEMU_OPTION_smb:
5918 net_slirp_smb(optarg);
5919 break;
5920 #endif
5921 case QEMU_OPTION_redir:
5922 net_slirp_redir(optarg);
5923 break;
5924 #endif
5925 #ifdef HAS_AUDIO
5926 case QEMU_OPTION_audio_help:
5927 AUD_help ();
5928 exit (0);
5929 break;
5930 case QEMU_OPTION_soundhw:
5931 select_soundhw (optarg);
5932 break;
5933 #endif
5934 case QEMU_OPTION_h:
5935 help();
5936 break;
5937 case QEMU_OPTION_m:
5938 ram_size = atoi(optarg) * 1024 * 1024;
5939 if (ram_size <= 0)
5940 help();
5941 if (ram_size > PHYS_RAM_MAX_SIZE) {
5942 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5943 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5944 exit(1);
5946 break;
5947 case QEMU_OPTION_d:
5949 int mask;
5950 CPULogItem *item;
5952 mask = cpu_str_to_log_mask(optarg);
5953 if (!mask) {
5954 printf("Log items (comma separated):\n");
5955 for(item = cpu_log_items; item->mask != 0; item++) {
5956 printf("%-10s %s\n", item->name, item->help);
5958 exit(1);
5960 cpu_set_log(mask);
5962 break;
5963 #ifdef CONFIG_GDBSTUB
5964 case QEMU_OPTION_s:
5965 use_gdbstub = 1;
5966 break;
5967 case QEMU_OPTION_p:
5968 gdbstub_port = atoi(optarg);
5969 break;
5970 #endif
5971 case QEMU_OPTION_L:
5972 bios_dir = optarg;
5973 break;
5974 case QEMU_OPTION_S:
5975 start_emulation = 0;
5976 break;
5977 case QEMU_OPTION_k:
5978 keyboard_layout = optarg;
5979 break;
5980 case QEMU_OPTION_localtime:
5981 rtc_utc = 0;
5982 break;
5983 case QEMU_OPTION_cirrusvga:
5984 cirrus_vga_enabled = 1;
5985 break;
5986 case QEMU_OPTION_std_vga:
5987 cirrus_vga_enabled = 0;
5988 break;
5989 case QEMU_OPTION_g:
5991 const char *p;
5992 int w, h, depth;
5993 p = optarg;
5994 w = strtol(p, (char **)&p, 10);
5995 if (w <= 0) {
5996 graphic_error:
5997 fprintf(stderr, "qemu: invalid resolution or depth\n");
5998 exit(1);
6000 if (*p != 'x')
6001 goto graphic_error;
6002 p++;
6003 h = strtol(p, (char **)&p, 10);
6004 if (h <= 0)
6005 goto graphic_error;
6006 if (*p == 'x') {
6007 p++;
6008 depth = strtol(p, (char **)&p, 10);
6009 if (depth != 8 && depth != 15 && depth != 16 &&
6010 depth != 24 && depth != 32)
6011 goto graphic_error;
6012 } else if (*p == '\0') {
6013 depth = graphic_depth;
6014 } else {
6015 goto graphic_error;
6018 graphic_width = w;
6019 graphic_height = h;
6020 graphic_depth = depth;
6022 break;
6023 case QEMU_OPTION_monitor:
6024 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6025 break;
6026 case QEMU_OPTION_serial:
6027 if (serial_device_index >= MAX_SERIAL_PORTS) {
6028 fprintf(stderr, "qemu: too many serial ports\n");
6029 exit(1);
6031 pstrcpy(serial_devices[serial_device_index],
6032 sizeof(serial_devices[0]), optarg);
6033 serial_device_index++;
6034 break;
6035 case QEMU_OPTION_parallel:
6036 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6037 fprintf(stderr, "qemu: too many parallel ports\n");
6038 exit(1);
6040 pstrcpy(parallel_devices[parallel_device_index],
6041 sizeof(parallel_devices[0]), optarg);
6042 parallel_device_index++;
6043 break;
6044 case QEMU_OPTION_loadvm:
6045 loadvm = optarg;
6046 break;
6047 case QEMU_OPTION_full_screen:
6048 full_screen = 1;
6049 break;
6050 case QEMU_OPTION_pidfile:
6051 create_pidfile(optarg);
6052 break;
6053 #ifdef TARGET_I386
6054 case QEMU_OPTION_win2k_hack:
6055 win2k_install_hack = 1;
6056 break;
6057 #endif
6058 #ifdef USE_KQEMU
6059 case QEMU_OPTION_no_kqemu:
6060 kqemu_allowed = 0;
6061 break;
6062 case QEMU_OPTION_kernel_kqemu:
6063 kqemu_allowed = 2;
6064 break;
6065 #endif
6066 case QEMU_OPTION_usb:
6067 usb_enabled = 1;
6068 break;
6069 case QEMU_OPTION_usbdevice:
6070 usb_enabled = 1;
6071 if (usb_devices_index >= MAX_USB_CMDLINE) {
6072 fprintf(stderr, "Too many USB devices\n");
6073 exit(1);
6075 pstrcpy(usb_devices[usb_devices_index],
6076 sizeof(usb_devices[usb_devices_index]),
6077 optarg);
6078 usb_devices_index++;
6079 break;
6080 case QEMU_OPTION_smp:
6081 smp_cpus = atoi(optarg);
6082 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6083 fprintf(stderr, "Invalid number of CPUs\n");
6084 exit(1);
6086 break;
6087 case QEMU_OPTION_vnc:
6088 vnc_display = atoi(optarg);
6089 if (vnc_display < 0) {
6090 fprintf(stderr, "Invalid VNC display\n");
6091 exit(1);
6093 break;
6094 case QEMU_OPTION_no_acpi:
6095 acpi_enabled = 0;
6096 break;
6101 #ifdef USE_KQEMU
6102 if (smp_cpus > 1)
6103 kqemu_allowed = 0;
6104 #endif
6105 linux_boot = (kernel_filename != NULL);
6107 if (!linux_boot &&
6108 hd_filename[0] == '\0' &&
6109 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6110 fd_filename[0] == '\0')
6111 help();
6113 /* boot to cd by default if no hard disk */
6114 if (hd_filename[0] == '\0' && boot_device == 'c') {
6115 if (fd_filename[0] != '\0')
6116 boot_device = 'a';
6117 else
6118 boot_device = 'd';
6121 setvbuf(stdout, NULL, _IOLBF, 0);
6123 init_timers();
6124 init_timer_alarm();
6125 qemu_aio_init();
6127 #ifdef _WIN32
6128 socket_init();
6129 #endif
6131 /* init network clients */
6132 if (nb_net_clients == 0) {
6133 /* if no clients, we use a default config */
6134 pstrcpy(net_clients[0], sizeof(net_clients[0]),
6135 "nic");
6136 pstrcpy(net_clients[1], sizeof(net_clients[0]),
6137 "user");
6138 nb_net_clients = 2;
6141 for(i = 0;i < nb_net_clients; i++) {
6142 if (net_client_init(net_clients[i]) < 0)
6143 exit(1);
6146 /* init the memory */
6147 phys_ram_size = ram_size + vga_ram_size + bios_size;
6149 phys_ram_base = qemu_vmalloc(phys_ram_size);
6150 if (!phys_ram_base) {
6151 fprintf(stderr, "Could not allocate physical memory\n");
6152 exit(1);
6155 /* we always create the cdrom drive, even if no disk is there */
6156 bdrv_init();
6157 if (cdrom_index >= 0) {
6158 bs_table[cdrom_index] = bdrv_new("cdrom");
6159 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6162 /* open the virtual block devices */
6163 for(i = 0; i < MAX_DISKS; i++) {
6164 if (hd_filename[i]) {
6165 if (!bs_table[i]) {
6166 char buf[64];
6167 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6168 bs_table[i] = bdrv_new(buf);
6170 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
6171 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6172 hd_filename[i]);
6173 exit(1);
6175 if (i == 0 && cyls != 0) {
6176 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6177 bdrv_set_translation_hint(bs_table[i], translation);
6182 /* we always create at least one floppy disk */
6183 fd_table[0] = bdrv_new("fda");
6184 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6186 for(i = 0; i < MAX_FD; i++) {
6187 if (fd_filename[i]) {
6188 if (!fd_table[i]) {
6189 char buf[64];
6190 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6191 fd_table[i] = bdrv_new(buf);
6192 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6194 if (fd_filename[i] != '\0') {
6195 if (bdrv_open(fd_table[i], fd_filename[i],
6196 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
6197 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6198 fd_filename[i]);
6199 exit(1);
6205 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
6206 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
6208 init_ioports();
6210 /* terminal init */
6211 if (nographic) {
6212 dumb_display_init(ds);
6213 } else if (vnc_display != -1) {
6214 vnc_display_init(ds, vnc_display);
6215 } else {
6216 #if defined(CONFIG_SDL)
6217 sdl_display_init(ds, full_screen);
6218 #elif defined(CONFIG_COCOA)
6219 cocoa_display_init(ds, full_screen);
6220 #else
6221 dumb_display_init(ds);
6222 #endif
6225 monitor_hd = qemu_chr_open(monitor_device);
6226 if (!monitor_hd) {
6227 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6228 exit(1);
6230 monitor_init(monitor_hd, !nographic);
6232 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6233 if (serial_devices[i][0] != '\0') {
6234 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6235 if (!serial_hds[i]) {
6236 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6237 serial_devices[i]);
6238 exit(1);
6240 if (!strcmp(serial_devices[i], "vc"))
6241 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6245 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6246 if (parallel_devices[i][0] != '\0') {
6247 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6248 if (!parallel_hds[i]) {
6249 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6250 parallel_devices[i]);
6251 exit(1);
6253 if (!strcmp(parallel_devices[i], "vc"))
6254 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6258 machine->init(ram_size, vga_ram_size, boot_device,
6259 ds, fd_filename, snapshot,
6260 kernel_filename, kernel_cmdline, initrd_filename);
6262 /* init USB devices */
6263 if (usb_enabled) {
6264 for(i = 0; i < usb_devices_index; i++) {
6265 if (usb_device_add(usb_devices[i]) < 0) {
6266 fprintf(stderr, "Warning: could not add USB device %s\n",
6267 usb_devices[i]);
6272 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6273 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6275 #ifdef CONFIG_GDBSTUB
6276 if (use_gdbstub) {
6277 if (gdbserver_start(gdbstub_port) < 0) {
6278 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6279 gdbstub_port);
6280 exit(1);
6281 } else {
6282 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6284 } else
6285 #endif
6286 if (loadvm)
6287 qemu_loadvm(loadvm);
6290 /* XXX: simplify init */
6291 read_passwords();
6292 if (start_emulation) {
6293 vm_start();
6296 main_loop();
6297 quit_timers();
6298 return 0;