update
[qemu/mini2440.git] / vl.c
blob042e12180f88c4c163e933a1eaab371e51b019a1
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 int bus_num, addr;
3785 const char *p;
3787 if (!used_usb_ports)
3788 return -1;
3790 p = strchr(devname, '.');
3791 if (!p)
3792 return -1;
3793 bus_num = strtoul(devname, NULL, 0);
3794 addr = strtoul(p + 1, NULL, 0);
3795 if (bus_num != 0)
3796 return -1;
3798 lastp = &used_usb_ports;
3799 port = used_usb_ports;
3800 while (port && port->dev->addr != addr) {
3801 lastp = &port->next;
3802 port = port->next;
3805 if (!port)
3806 return -1;
3808 *lastp = port->next;
3809 usb_attach(port, NULL);
3810 port->next = free_usb_ports;
3811 free_usb_ports = port;
3812 return 0;
3815 void do_usb_add(const char *devname)
3817 int ret;
3818 ret = usb_device_add(devname);
3819 if (ret < 0)
3820 term_printf("Could not add USB device '%s'\n", devname);
3823 void do_usb_del(const char *devname)
3825 int ret;
3826 ret = usb_device_del(devname);
3827 if (ret < 0)
3828 term_printf("Could not remove USB device '%s'\n", devname);
3831 void usb_info(void)
3833 USBDevice *dev;
3834 USBPort *port;
3835 const char *speed_str;
3837 if (!usb_enabled) {
3838 term_printf("USB support not enabled\n");
3839 return;
3842 for (port = used_usb_ports; port; port = port->next) {
3843 dev = port->dev;
3844 if (!dev)
3845 continue;
3846 switch(dev->speed) {
3847 case USB_SPEED_LOW:
3848 speed_str = "1.5";
3849 break;
3850 case USB_SPEED_FULL:
3851 speed_str = "12";
3852 break;
3853 case USB_SPEED_HIGH:
3854 speed_str = "480";
3855 break;
3856 default:
3857 speed_str = "?";
3858 break;
3860 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
3861 0, dev->addr, speed_str, dev->devname);
3865 /***********************************************************/
3866 /* pid file */
3868 static char *pid_filename;
3870 /* Remove PID file. Called on normal exit */
3872 static void remove_pidfile(void)
3874 unlink (pid_filename);
3877 static void create_pidfile(const char *filename)
3879 struct stat pidstat;
3880 FILE *f;
3882 /* Try to write our PID to the named file */
3883 if (stat(filename, &pidstat) < 0) {
3884 if (errno == ENOENT) {
3885 if ((f = fopen (filename, "w")) == NULL) {
3886 perror("Opening pidfile");
3887 exit(1);
3889 fprintf(f, "%d\n", getpid());
3890 fclose(f);
3891 pid_filename = qemu_strdup(filename);
3892 if (!pid_filename) {
3893 fprintf(stderr, "Could not save PID filename");
3894 exit(1);
3896 atexit(remove_pidfile);
3898 } else {
3899 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3900 filename);
3901 exit(1);
3905 /***********************************************************/
3906 /* dumb display */
3908 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3912 static void dumb_resize(DisplayState *ds, int w, int h)
3916 static void dumb_refresh(DisplayState *ds)
3918 vga_hw_update();
3921 void dumb_display_init(DisplayState *ds)
3923 ds->data = NULL;
3924 ds->linesize = 0;
3925 ds->depth = 0;
3926 ds->dpy_update = dumb_update;
3927 ds->dpy_resize = dumb_resize;
3928 ds->dpy_refresh = dumb_refresh;
3931 /***********************************************************/
3932 /* I/O handling */
3934 #define MAX_IO_HANDLERS 64
3936 typedef struct IOHandlerRecord {
3937 int fd;
3938 IOCanRWHandler *fd_read_poll;
3939 IOHandler *fd_read;
3940 IOHandler *fd_write;
3941 void *opaque;
3942 /* temporary data */
3943 struct pollfd *ufd;
3944 struct IOHandlerRecord *next;
3945 } IOHandlerRecord;
3947 static IOHandlerRecord *first_io_handler;
3949 /* XXX: fd_read_poll should be suppressed, but an API change is
3950 necessary in the character devices to suppress fd_can_read(). */
3951 int qemu_set_fd_handler2(int fd,
3952 IOCanRWHandler *fd_read_poll,
3953 IOHandler *fd_read,
3954 IOHandler *fd_write,
3955 void *opaque)
3957 IOHandlerRecord **pioh, *ioh;
3959 if (!fd_read && !fd_write) {
3960 pioh = &first_io_handler;
3961 for(;;) {
3962 ioh = *pioh;
3963 if (ioh == NULL)
3964 break;
3965 if (ioh->fd == fd) {
3966 *pioh = ioh->next;
3967 qemu_free(ioh);
3968 break;
3970 pioh = &ioh->next;
3972 } else {
3973 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3974 if (ioh->fd == fd)
3975 goto found;
3977 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3978 if (!ioh)
3979 return -1;
3980 ioh->next = first_io_handler;
3981 first_io_handler = ioh;
3982 found:
3983 ioh->fd = fd;
3984 ioh->fd_read_poll = fd_read_poll;
3985 ioh->fd_read = fd_read;
3986 ioh->fd_write = fd_write;
3987 ioh->opaque = opaque;
3989 return 0;
3992 int qemu_set_fd_handler(int fd,
3993 IOHandler *fd_read,
3994 IOHandler *fd_write,
3995 void *opaque)
3997 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4000 /***********************************************************/
4001 /* Polling handling */
4003 typedef struct PollingEntry {
4004 PollingFunc *func;
4005 void *opaque;
4006 struct PollingEntry *next;
4007 } PollingEntry;
4009 static PollingEntry *first_polling_entry;
4011 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4013 PollingEntry **ppe, *pe;
4014 pe = qemu_mallocz(sizeof(PollingEntry));
4015 if (!pe)
4016 return -1;
4017 pe->func = func;
4018 pe->opaque = opaque;
4019 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4020 *ppe = pe;
4021 return 0;
4024 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4026 PollingEntry **ppe, *pe;
4027 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4028 pe = *ppe;
4029 if (pe->func == func && pe->opaque == opaque) {
4030 *ppe = pe->next;
4031 qemu_free(pe);
4032 break;
4037 #ifdef _WIN32
4038 /***********************************************************/
4039 /* Wait objects support */
4040 typedef struct WaitObjects {
4041 int num;
4042 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4043 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4044 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4045 } WaitObjects;
4047 static WaitObjects wait_objects = {0};
4049 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4051 WaitObjects *w = &wait_objects;
4053 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4054 return -1;
4055 w->events[w->num] = handle;
4056 w->func[w->num] = func;
4057 w->opaque[w->num] = opaque;
4058 w->num++;
4059 return 0;
4062 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4064 int i, found;
4065 WaitObjects *w = &wait_objects;
4067 found = 0;
4068 for (i = 0; i < w->num; i++) {
4069 if (w->events[i] == handle)
4070 found = 1;
4071 if (found) {
4072 w->events[i] = w->events[i + 1];
4073 w->func[i] = w->func[i + 1];
4074 w->opaque[i] = w->opaque[i + 1];
4077 if (found)
4078 w->num--;
4080 #endif
4082 /***********************************************************/
4083 /* savevm/loadvm support */
4085 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4087 fwrite(buf, 1, size, f);
4090 void qemu_put_byte(QEMUFile *f, int v)
4092 fputc(v, f);
4095 void qemu_put_be16(QEMUFile *f, unsigned int v)
4097 qemu_put_byte(f, v >> 8);
4098 qemu_put_byte(f, v);
4101 void qemu_put_be32(QEMUFile *f, unsigned int v)
4103 qemu_put_byte(f, v >> 24);
4104 qemu_put_byte(f, v >> 16);
4105 qemu_put_byte(f, v >> 8);
4106 qemu_put_byte(f, v);
4109 void qemu_put_be64(QEMUFile *f, uint64_t v)
4111 qemu_put_be32(f, v >> 32);
4112 qemu_put_be32(f, v);
4115 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4117 return fread(buf, 1, size, f);
4120 int qemu_get_byte(QEMUFile *f)
4122 int v;
4123 v = fgetc(f);
4124 if (v == EOF)
4125 return 0;
4126 else
4127 return v;
4130 unsigned int qemu_get_be16(QEMUFile *f)
4132 unsigned int v;
4133 v = qemu_get_byte(f) << 8;
4134 v |= qemu_get_byte(f);
4135 return v;
4138 unsigned int qemu_get_be32(QEMUFile *f)
4140 unsigned int v;
4141 v = qemu_get_byte(f) << 24;
4142 v |= qemu_get_byte(f) << 16;
4143 v |= qemu_get_byte(f) << 8;
4144 v |= qemu_get_byte(f);
4145 return v;
4148 uint64_t qemu_get_be64(QEMUFile *f)
4150 uint64_t v;
4151 v = (uint64_t)qemu_get_be32(f) << 32;
4152 v |= qemu_get_be32(f);
4153 return v;
4156 int64_t qemu_ftell(QEMUFile *f)
4158 return ftell(f);
4161 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4163 if (fseek(f, pos, whence) < 0)
4164 return -1;
4165 return ftell(f);
4168 typedef struct SaveStateEntry {
4169 char idstr[256];
4170 int instance_id;
4171 int version_id;
4172 SaveStateHandler *save_state;
4173 LoadStateHandler *load_state;
4174 void *opaque;
4175 struct SaveStateEntry *next;
4176 } SaveStateEntry;
4178 static SaveStateEntry *first_se;
4180 int register_savevm(const char *idstr,
4181 int instance_id,
4182 int version_id,
4183 SaveStateHandler *save_state,
4184 LoadStateHandler *load_state,
4185 void *opaque)
4187 SaveStateEntry *se, **pse;
4189 se = qemu_malloc(sizeof(SaveStateEntry));
4190 if (!se)
4191 return -1;
4192 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4193 se->instance_id = instance_id;
4194 se->version_id = version_id;
4195 se->save_state = save_state;
4196 se->load_state = load_state;
4197 se->opaque = opaque;
4198 se->next = NULL;
4200 /* add at the end of list */
4201 pse = &first_se;
4202 while (*pse != NULL)
4203 pse = &(*pse)->next;
4204 *pse = se;
4205 return 0;
4208 #define QEMU_VM_FILE_MAGIC 0x5145564d
4209 #define QEMU_VM_FILE_VERSION 0x00000001
4211 int qemu_savevm(const char *filename)
4213 SaveStateEntry *se;
4214 QEMUFile *f;
4215 int len, len_pos, cur_pos, saved_vm_running, ret;
4217 saved_vm_running = vm_running;
4218 vm_stop(0);
4220 f = fopen(filename, "wb");
4221 if (!f) {
4222 ret = -1;
4223 goto the_end;
4226 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4227 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4229 for(se = first_se; se != NULL; se = se->next) {
4230 /* ID string */
4231 len = strlen(se->idstr);
4232 qemu_put_byte(f, len);
4233 qemu_put_buffer(f, se->idstr, len);
4235 qemu_put_be32(f, se->instance_id);
4236 qemu_put_be32(f, se->version_id);
4238 /* record size: filled later */
4239 len_pos = ftell(f);
4240 qemu_put_be32(f, 0);
4242 se->save_state(f, se->opaque);
4244 /* fill record size */
4245 cur_pos = ftell(f);
4246 len = ftell(f) - len_pos - 4;
4247 fseek(f, len_pos, SEEK_SET);
4248 qemu_put_be32(f, len);
4249 fseek(f, cur_pos, SEEK_SET);
4252 fclose(f);
4253 ret = 0;
4254 the_end:
4255 if (saved_vm_running)
4256 vm_start();
4257 return ret;
4260 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4262 SaveStateEntry *se;
4264 for(se = first_se; se != NULL; se = se->next) {
4265 if (!strcmp(se->idstr, idstr) &&
4266 instance_id == se->instance_id)
4267 return se;
4269 return NULL;
4272 int qemu_loadvm(const char *filename)
4274 SaveStateEntry *se;
4275 QEMUFile *f;
4276 int len, cur_pos, ret, instance_id, record_len, version_id;
4277 int saved_vm_running;
4278 unsigned int v;
4279 char idstr[256];
4281 saved_vm_running = vm_running;
4282 vm_stop(0);
4284 f = fopen(filename, "rb");
4285 if (!f) {
4286 ret = -1;
4287 goto the_end;
4290 v = qemu_get_be32(f);
4291 if (v != QEMU_VM_FILE_MAGIC)
4292 goto fail;
4293 v = qemu_get_be32(f);
4294 if (v != QEMU_VM_FILE_VERSION) {
4295 fail:
4296 fclose(f);
4297 ret = -1;
4298 goto the_end;
4300 for(;;) {
4301 len = qemu_get_byte(f);
4302 if (feof(f))
4303 break;
4304 qemu_get_buffer(f, idstr, len);
4305 idstr[len] = '\0';
4306 instance_id = qemu_get_be32(f);
4307 version_id = qemu_get_be32(f);
4308 record_len = qemu_get_be32(f);
4309 #if 0
4310 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4311 idstr, instance_id, version_id, record_len);
4312 #endif
4313 cur_pos = ftell(f);
4314 se = find_se(idstr, instance_id);
4315 if (!se) {
4316 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4317 instance_id, idstr);
4318 } else {
4319 ret = se->load_state(f, se->opaque, version_id);
4320 if (ret < 0) {
4321 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4322 instance_id, idstr);
4325 /* always seek to exact end of record */
4326 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4328 fclose(f);
4329 ret = 0;
4330 the_end:
4331 if (saved_vm_running)
4332 vm_start();
4333 return ret;
4336 /***********************************************************/
4337 /* cpu save/restore */
4339 #if defined(TARGET_I386)
4341 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4343 qemu_put_be32(f, dt->selector);
4344 qemu_put_betl(f, dt->base);
4345 qemu_put_be32(f, dt->limit);
4346 qemu_put_be32(f, dt->flags);
4349 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4351 dt->selector = qemu_get_be32(f);
4352 dt->base = qemu_get_betl(f);
4353 dt->limit = qemu_get_be32(f);
4354 dt->flags = qemu_get_be32(f);
4357 void cpu_save(QEMUFile *f, void *opaque)
4359 CPUState *env = opaque;
4360 uint16_t fptag, fpus, fpuc, fpregs_format;
4361 uint32_t hflags;
4362 int i;
4364 for(i = 0; i < CPU_NB_REGS; i++)
4365 qemu_put_betls(f, &env->regs[i]);
4366 qemu_put_betls(f, &env->eip);
4367 qemu_put_betls(f, &env->eflags);
4368 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4369 qemu_put_be32s(f, &hflags);
4371 /* FPU */
4372 fpuc = env->fpuc;
4373 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4374 fptag = 0;
4375 for(i = 0; i < 8; i++) {
4376 fptag |= ((!env->fptags[i]) << i);
4379 qemu_put_be16s(f, &fpuc);
4380 qemu_put_be16s(f, &fpus);
4381 qemu_put_be16s(f, &fptag);
4383 #ifdef USE_X86LDOUBLE
4384 fpregs_format = 0;
4385 #else
4386 fpregs_format = 1;
4387 #endif
4388 qemu_put_be16s(f, &fpregs_format);
4390 for(i = 0; i < 8; i++) {
4391 #ifdef USE_X86LDOUBLE
4393 uint64_t mant;
4394 uint16_t exp;
4395 /* we save the real CPU data (in case of MMX usage only 'mant'
4396 contains the MMX register */
4397 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4398 qemu_put_be64(f, mant);
4399 qemu_put_be16(f, exp);
4401 #else
4402 /* if we use doubles for float emulation, we save the doubles to
4403 avoid losing information in case of MMX usage. It can give
4404 problems if the image is restored on a CPU where long
4405 doubles are used instead. */
4406 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4407 #endif
4410 for(i = 0; i < 6; i++)
4411 cpu_put_seg(f, &env->segs[i]);
4412 cpu_put_seg(f, &env->ldt);
4413 cpu_put_seg(f, &env->tr);
4414 cpu_put_seg(f, &env->gdt);
4415 cpu_put_seg(f, &env->idt);
4417 qemu_put_be32s(f, &env->sysenter_cs);
4418 qemu_put_be32s(f, &env->sysenter_esp);
4419 qemu_put_be32s(f, &env->sysenter_eip);
4421 qemu_put_betls(f, &env->cr[0]);
4422 qemu_put_betls(f, &env->cr[2]);
4423 qemu_put_betls(f, &env->cr[3]);
4424 qemu_put_betls(f, &env->cr[4]);
4426 for(i = 0; i < 8; i++)
4427 qemu_put_betls(f, &env->dr[i]);
4429 /* MMU */
4430 qemu_put_be32s(f, &env->a20_mask);
4432 /* XMM */
4433 qemu_put_be32s(f, &env->mxcsr);
4434 for(i = 0; i < CPU_NB_REGS; i++) {
4435 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4436 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4439 #ifdef TARGET_X86_64
4440 qemu_put_be64s(f, &env->efer);
4441 qemu_put_be64s(f, &env->star);
4442 qemu_put_be64s(f, &env->lstar);
4443 qemu_put_be64s(f, &env->cstar);
4444 qemu_put_be64s(f, &env->fmask);
4445 qemu_put_be64s(f, &env->kernelgsbase);
4446 #endif
4449 #ifdef USE_X86LDOUBLE
4450 /* XXX: add that in a FPU generic layer */
4451 union x86_longdouble {
4452 uint64_t mant;
4453 uint16_t exp;
4456 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4457 #define EXPBIAS1 1023
4458 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4459 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4461 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4463 int e;
4464 /* mantissa */
4465 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4466 /* exponent + sign */
4467 e = EXPD1(temp) - EXPBIAS1 + 16383;
4468 e |= SIGND1(temp) >> 16;
4469 p->exp = e;
4471 #endif
4473 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4475 CPUState *env = opaque;
4476 int i, guess_mmx;
4477 uint32_t hflags;
4478 uint16_t fpus, fpuc, fptag, fpregs_format;
4480 if (version_id != 3)
4481 return -EINVAL;
4482 for(i = 0; i < CPU_NB_REGS; i++)
4483 qemu_get_betls(f, &env->regs[i]);
4484 qemu_get_betls(f, &env->eip);
4485 qemu_get_betls(f, &env->eflags);
4486 qemu_get_be32s(f, &hflags);
4488 qemu_get_be16s(f, &fpuc);
4489 qemu_get_be16s(f, &fpus);
4490 qemu_get_be16s(f, &fptag);
4491 qemu_get_be16s(f, &fpregs_format);
4493 /* NOTE: we cannot always restore the FPU state if the image come
4494 from a host with a different 'USE_X86LDOUBLE' define. We guess
4495 if we are in an MMX state to restore correctly in that case. */
4496 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4497 for(i = 0; i < 8; i++) {
4498 uint64_t mant;
4499 uint16_t exp;
4501 switch(fpregs_format) {
4502 case 0:
4503 mant = qemu_get_be64(f);
4504 exp = qemu_get_be16(f);
4505 #ifdef USE_X86LDOUBLE
4506 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4507 #else
4508 /* difficult case */
4509 if (guess_mmx)
4510 env->fpregs[i].mmx.MMX_Q(0) = mant;
4511 else
4512 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4513 #endif
4514 break;
4515 case 1:
4516 mant = qemu_get_be64(f);
4517 #ifdef USE_X86LDOUBLE
4519 union x86_longdouble *p;
4520 /* difficult case */
4521 p = (void *)&env->fpregs[i];
4522 if (guess_mmx) {
4523 p->mant = mant;
4524 p->exp = 0xffff;
4525 } else {
4526 fp64_to_fp80(p, mant);
4529 #else
4530 env->fpregs[i].mmx.MMX_Q(0) = mant;
4531 #endif
4532 break;
4533 default:
4534 return -EINVAL;
4538 env->fpuc = fpuc;
4539 /* XXX: restore FPU round state */
4540 env->fpstt = (fpus >> 11) & 7;
4541 env->fpus = fpus & ~0x3800;
4542 fptag ^= 0xff;
4543 for(i = 0; i < 8; i++) {
4544 env->fptags[i] = (fptag >> i) & 1;
4547 for(i = 0; i < 6; i++)
4548 cpu_get_seg(f, &env->segs[i]);
4549 cpu_get_seg(f, &env->ldt);
4550 cpu_get_seg(f, &env->tr);
4551 cpu_get_seg(f, &env->gdt);
4552 cpu_get_seg(f, &env->idt);
4554 qemu_get_be32s(f, &env->sysenter_cs);
4555 qemu_get_be32s(f, &env->sysenter_esp);
4556 qemu_get_be32s(f, &env->sysenter_eip);
4558 qemu_get_betls(f, &env->cr[0]);
4559 qemu_get_betls(f, &env->cr[2]);
4560 qemu_get_betls(f, &env->cr[3]);
4561 qemu_get_betls(f, &env->cr[4]);
4563 for(i = 0; i < 8; i++)
4564 qemu_get_betls(f, &env->dr[i]);
4566 /* MMU */
4567 qemu_get_be32s(f, &env->a20_mask);
4569 qemu_get_be32s(f, &env->mxcsr);
4570 for(i = 0; i < CPU_NB_REGS; i++) {
4571 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4572 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4575 #ifdef TARGET_X86_64
4576 qemu_get_be64s(f, &env->efer);
4577 qemu_get_be64s(f, &env->star);
4578 qemu_get_be64s(f, &env->lstar);
4579 qemu_get_be64s(f, &env->cstar);
4580 qemu_get_be64s(f, &env->fmask);
4581 qemu_get_be64s(f, &env->kernelgsbase);
4582 #endif
4584 /* XXX: compute hflags from scratch, except for CPL and IIF */
4585 env->hflags = hflags;
4586 tlb_flush(env, 1);
4587 return 0;
4590 #elif defined(TARGET_PPC)
4591 void cpu_save(QEMUFile *f, void *opaque)
4595 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4597 return 0;
4600 #elif defined(TARGET_MIPS)
4601 void cpu_save(QEMUFile *f, void *opaque)
4605 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4607 return 0;
4610 #elif defined(TARGET_SPARC)
4611 void cpu_save(QEMUFile *f, void *opaque)
4613 CPUState *env = opaque;
4614 int i;
4615 uint32_t tmp;
4617 for(i = 0; i < 8; i++)
4618 qemu_put_betls(f, &env->gregs[i]);
4619 for(i = 0; i < NWINDOWS * 16; i++)
4620 qemu_put_betls(f, &env->regbase[i]);
4622 /* FPU */
4623 for(i = 0; i < TARGET_FPREGS; i++) {
4624 union {
4625 float32 f;
4626 uint32_t i;
4627 } u;
4628 u.f = env->fpr[i];
4629 qemu_put_be32(f, u.i);
4632 qemu_put_betls(f, &env->pc);
4633 qemu_put_betls(f, &env->npc);
4634 qemu_put_betls(f, &env->y);
4635 tmp = GET_PSR(env);
4636 qemu_put_be32(f, tmp);
4637 qemu_put_betls(f, &env->fsr);
4638 qemu_put_betls(f, &env->tbr);
4639 #ifndef TARGET_SPARC64
4640 qemu_put_be32s(f, &env->wim);
4641 /* MMU */
4642 for(i = 0; i < 16; i++)
4643 qemu_put_be32s(f, &env->mmuregs[i]);
4644 #endif
4647 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4649 CPUState *env = opaque;
4650 int i;
4651 uint32_t tmp;
4653 for(i = 0; i < 8; i++)
4654 qemu_get_betls(f, &env->gregs[i]);
4655 for(i = 0; i < NWINDOWS * 16; i++)
4656 qemu_get_betls(f, &env->regbase[i]);
4658 /* FPU */
4659 for(i = 0; i < TARGET_FPREGS; i++) {
4660 union {
4661 float32 f;
4662 uint32_t i;
4663 } u;
4664 u.i = qemu_get_be32(f);
4665 env->fpr[i] = u.f;
4668 qemu_get_betls(f, &env->pc);
4669 qemu_get_betls(f, &env->npc);
4670 qemu_get_betls(f, &env->y);
4671 tmp = qemu_get_be32(f);
4672 env->cwp = 0; /* needed to ensure that the wrapping registers are
4673 correctly updated */
4674 PUT_PSR(env, tmp);
4675 qemu_get_betls(f, &env->fsr);
4676 qemu_get_betls(f, &env->tbr);
4677 #ifndef TARGET_SPARC64
4678 qemu_get_be32s(f, &env->wim);
4679 /* MMU */
4680 for(i = 0; i < 16; i++)
4681 qemu_get_be32s(f, &env->mmuregs[i]);
4682 #endif
4683 tlb_flush(env, 1);
4684 return 0;
4687 #elif defined(TARGET_ARM)
4689 /* ??? Need to implement these. */
4690 void cpu_save(QEMUFile *f, void *opaque)
4694 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4696 return 0;
4699 #else
4701 #warning No CPU save/restore functions
4703 #endif
4705 /***********************************************************/
4706 /* ram save/restore */
4708 /* we just avoid storing empty pages */
4709 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4711 int i, v;
4713 v = buf[0];
4714 for(i = 1; i < len; i++) {
4715 if (buf[i] != v)
4716 goto normal_save;
4718 qemu_put_byte(f, 1);
4719 qemu_put_byte(f, v);
4720 return;
4721 normal_save:
4722 qemu_put_byte(f, 0);
4723 qemu_put_buffer(f, buf, len);
4726 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4728 int v;
4730 v = qemu_get_byte(f);
4731 switch(v) {
4732 case 0:
4733 if (qemu_get_buffer(f, buf, len) != len)
4734 return -EIO;
4735 break;
4736 case 1:
4737 v = qemu_get_byte(f);
4738 memset(buf, v, len);
4739 break;
4740 default:
4741 return -EINVAL;
4743 return 0;
4746 static void ram_save(QEMUFile *f, void *opaque)
4748 int i;
4749 qemu_put_be32(f, phys_ram_size);
4750 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4751 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4755 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4757 int i, ret;
4759 if (version_id != 1)
4760 return -EINVAL;
4761 if (qemu_get_be32(f) != phys_ram_size)
4762 return -EINVAL;
4763 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4764 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4765 if (ret)
4766 return ret;
4768 return 0;
4771 /***********************************************************/
4772 /* machine registration */
4774 QEMUMachine *first_machine = NULL;
4776 int qemu_register_machine(QEMUMachine *m)
4778 QEMUMachine **pm;
4779 pm = &first_machine;
4780 while (*pm != NULL)
4781 pm = &(*pm)->next;
4782 m->next = NULL;
4783 *pm = m;
4784 return 0;
4787 QEMUMachine *find_machine(const char *name)
4789 QEMUMachine *m;
4791 for(m = first_machine; m != NULL; m = m->next) {
4792 if (!strcmp(m->name, name))
4793 return m;
4795 return NULL;
4798 /***********************************************************/
4799 /* main execution loop */
4801 void gui_update(void *opaque)
4803 display_state.dpy_refresh(&display_state);
4804 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4807 struct vm_change_state_entry {
4808 VMChangeStateHandler *cb;
4809 void *opaque;
4810 LIST_ENTRY (vm_change_state_entry) entries;
4813 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4815 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4816 void *opaque)
4818 VMChangeStateEntry *e;
4820 e = qemu_mallocz(sizeof (*e));
4821 if (!e)
4822 return NULL;
4824 e->cb = cb;
4825 e->opaque = opaque;
4826 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4827 return e;
4830 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4832 LIST_REMOVE (e, entries);
4833 qemu_free (e);
4836 static void vm_state_notify(int running)
4838 VMChangeStateEntry *e;
4840 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4841 e->cb(e->opaque, running);
4845 /* XXX: support several handlers */
4846 static VMStopHandler *vm_stop_cb;
4847 static void *vm_stop_opaque;
4849 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4851 vm_stop_cb = cb;
4852 vm_stop_opaque = opaque;
4853 return 0;
4856 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4858 vm_stop_cb = NULL;
4861 void vm_start(void)
4863 if (!vm_running) {
4864 cpu_enable_ticks();
4865 vm_running = 1;
4866 vm_state_notify(1);
4870 void vm_stop(int reason)
4872 if (vm_running) {
4873 cpu_disable_ticks();
4874 vm_running = 0;
4875 if (reason != 0) {
4876 if (vm_stop_cb) {
4877 vm_stop_cb(vm_stop_opaque, reason);
4880 vm_state_notify(0);
4884 /* reset/shutdown handler */
4886 typedef struct QEMUResetEntry {
4887 QEMUResetHandler *func;
4888 void *opaque;
4889 struct QEMUResetEntry *next;
4890 } QEMUResetEntry;
4892 static QEMUResetEntry *first_reset_entry;
4893 static int reset_requested;
4894 static int shutdown_requested;
4895 static int powerdown_requested;
4897 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4899 QEMUResetEntry **pre, *re;
4901 pre = &first_reset_entry;
4902 while (*pre != NULL)
4903 pre = &(*pre)->next;
4904 re = qemu_mallocz(sizeof(QEMUResetEntry));
4905 re->func = func;
4906 re->opaque = opaque;
4907 re->next = NULL;
4908 *pre = re;
4911 void qemu_system_reset(void)
4913 QEMUResetEntry *re;
4915 /* reset all devices */
4916 for(re = first_reset_entry; re != NULL; re = re->next) {
4917 re->func(re->opaque);
4921 void qemu_system_reset_request(void)
4923 reset_requested = 1;
4924 if (cpu_single_env)
4925 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4928 void qemu_system_shutdown_request(void)
4930 shutdown_requested = 1;
4931 if (cpu_single_env)
4932 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4935 void qemu_system_powerdown_request(void)
4937 powerdown_requested = 1;
4938 if (cpu_single_env)
4939 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4942 void main_loop_wait(int timeout)
4944 IOHandlerRecord *ioh, *ioh_next;
4945 fd_set rfds, wfds, xfds;
4946 int ret, nfds;
4947 struct timeval tv;
4948 PollingEntry *pe;
4951 /* XXX: need to suppress polling by better using win32 events */
4952 ret = 0;
4953 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4954 ret |= pe->func(pe->opaque);
4956 #ifdef _WIN32
4957 if (ret == 0 && timeout > 0) {
4958 int err;
4959 WaitObjects *w = &wait_objects;
4961 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
4962 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4963 if (w->func[ret - WAIT_OBJECT_0])
4964 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4965 } else if (ret == WAIT_TIMEOUT) {
4966 } else {
4967 err = GetLastError();
4968 fprintf(stderr, "Wait error %d %d\n", ret, err);
4971 #endif
4972 /* poll any events */
4973 /* XXX: separate device handlers from system ones */
4974 nfds = -1;
4975 FD_ZERO(&rfds);
4976 FD_ZERO(&wfds);
4977 FD_ZERO(&xfds);
4978 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4979 if (ioh->fd_read &&
4980 (!ioh->fd_read_poll ||
4981 ioh->fd_read_poll(ioh->opaque) != 0)) {
4982 FD_SET(ioh->fd, &rfds);
4983 if (ioh->fd > nfds)
4984 nfds = ioh->fd;
4986 if (ioh->fd_write) {
4987 FD_SET(ioh->fd, &wfds);
4988 if (ioh->fd > nfds)
4989 nfds = ioh->fd;
4993 tv.tv_sec = 0;
4994 #ifdef _WIN32
4995 tv.tv_usec = 0;
4996 #else
4997 tv.tv_usec = timeout * 1000;
4998 #endif
4999 #if defined(CONFIG_SLIRP)
5000 if (slirp_inited) {
5001 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5003 #endif
5004 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5005 if (ret > 0) {
5006 /* XXX: better handling of removal */
5007 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5008 ioh_next = ioh->next;
5009 if (FD_ISSET(ioh->fd, &rfds)) {
5010 ioh->fd_read(ioh->opaque);
5012 if (FD_ISSET(ioh->fd, &wfds)) {
5013 ioh->fd_write(ioh->opaque);
5017 #if defined(CONFIG_SLIRP)
5018 if (slirp_inited) {
5019 if (ret < 0) {
5020 FD_ZERO(&rfds);
5021 FD_ZERO(&wfds);
5022 FD_ZERO(&xfds);
5024 slirp_select_poll(&rfds, &wfds, &xfds);
5026 #endif
5027 #ifdef _WIN32
5028 tap_win32_poll();
5029 #endif
5031 if (vm_running) {
5032 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5033 qemu_get_clock(vm_clock));
5034 /* run dma transfers, if any */
5035 DMA_run();
5038 /* real time timers */
5039 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5040 qemu_get_clock(rt_clock));
5043 static CPUState *cur_cpu;
5045 int main_loop(void)
5047 int ret, timeout;
5048 #ifdef CONFIG_PROFILER
5049 int64_t ti;
5050 #endif
5051 CPUState *env;
5053 cur_cpu = first_cpu;
5054 for(;;) {
5055 if (vm_running) {
5057 env = cur_cpu;
5058 for(;;) {
5059 /* get next cpu */
5060 env = env->next_cpu;
5061 if (!env)
5062 env = first_cpu;
5063 #ifdef CONFIG_PROFILER
5064 ti = profile_getclock();
5065 #endif
5066 ret = cpu_exec(env);
5067 #ifdef CONFIG_PROFILER
5068 qemu_time += profile_getclock() - ti;
5069 #endif
5070 if (ret != EXCP_HALTED)
5071 break;
5072 /* all CPUs are halted ? */
5073 if (env == cur_cpu) {
5074 ret = EXCP_HLT;
5075 break;
5078 cur_cpu = env;
5080 if (shutdown_requested) {
5081 ret = EXCP_INTERRUPT;
5082 break;
5084 if (reset_requested) {
5085 reset_requested = 0;
5086 qemu_system_reset();
5087 ret = EXCP_INTERRUPT;
5089 if (powerdown_requested) {
5090 powerdown_requested = 0;
5091 qemu_system_powerdown();
5092 ret = EXCP_INTERRUPT;
5094 if (ret == EXCP_DEBUG) {
5095 vm_stop(EXCP_DEBUG);
5097 /* if hlt instruction, we wait until the next IRQ */
5098 /* XXX: use timeout computed from timers */
5099 if (ret == EXCP_HLT)
5100 timeout = 10;
5101 else
5102 timeout = 0;
5103 } else {
5104 timeout = 10;
5106 #ifdef CONFIG_PROFILER
5107 ti = profile_getclock();
5108 #endif
5109 main_loop_wait(timeout);
5110 #ifdef CONFIG_PROFILER
5111 dev_time += profile_getclock() - ti;
5112 #endif
5114 cpu_disable_ticks();
5115 return ret;
5118 void help(void)
5120 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
5121 "usage: %s [options] [disk_image]\n"
5122 "\n"
5123 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5124 "\n"
5125 "Standard options:\n"
5126 "-M machine select emulated machine (-M ? for list)\n"
5127 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5128 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5129 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5130 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5131 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5132 "-snapshot write to temporary files instead of disk image files\n"
5133 #ifdef TARGET_I386
5134 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5135 #endif
5136 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5137 "-smp n set the number of CPUs to 'n' [default=1]\n"
5138 "-nographic disable graphical output and redirect serial I/Os to console\n"
5139 #ifndef _WIN32
5140 "-k language use keyboard layout (for example \"fr\" for French)\n"
5141 #endif
5142 #ifdef HAS_AUDIO
5143 "-audio-help print list of audio drivers and their options\n"
5144 "-soundhw c1,... enable audio support\n"
5145 " and only specified sound cards (comma separated list)\n"
5146 " use -soundhw ? to get the list of supported cards\n"
5147 " use -soundhw all to enable all of them\n"
5148 #endif
5149 "-localtime set the real time clock to local time [default=utc]\n"
5150 "-full-screen start in full screen\n"
5151 #ifdef TARGET_I386
5152 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5153 #endif
5154 "-usb enable the USB driver (will be the default soon)\n"
5155 "-usbdevice name add the host or guest USB device 'name'\n"
5156 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5157 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5158 #endif
5159 "\n"
5160 "Network options:\n"
5161 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5162 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5163 #ifdef CONFIG_SLIRP
5164 "-net user[,vlan=n][,hostname=host]\n"
5165 " connect the user mode network stack to VLAN 'n' and send\n"
5166 " hostname 'host' to DHCP clients\n"
5167 #endif
5168 #ifdef _WIN32
5169 "-net tap[,vlan=n],ifname=name\n"
5170 " connect the host TAP network interface to VLAN 'n'\n"
5171 #else
5172 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
5173 " connect the host TAP network interface to VLAN 'n' and use\n"
5174 " the network script 'file' (default=%s);\n"
5175 " use 'fd=h' to connect to an already opened TAP interface\n"
5176 #endif
5177 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5178 " connect the vlan 'n' to another VLAN using a socket connection\n"
5179 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5180 " connect the vlan 'n' to multicast maddr and port\n"
5181 "-net none use it alone to have zero network devices; if no -net option\n"
5182 " is provided, the default is '-net nic -net user'\n"
5183 "\n"
5184 #ifdef CONFIG_SLIRP
5185 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5186 #ifndef _WIN32
5187 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5188 #endif
5189 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5190 " redirect TCP or UDP connections from host to guest [-net user]\n"
5191 #endif
5192 "\n"
5193 "Linux boot specific:\n"
5194 "-kernel bzImage use 'bzImage' as kernel image\n"
5195 "-append cmdline use 'cmdline' as kernel command line\n"
5196 "-initrd file use 'file' as initial ram disk\n"
5197 "\n"
5198 "Debug/Expert options:\n"
5199 "-monitor dev redirect the monitor to char device 'dev'\n"
5200 "-serial dev redirect the serial port to char device 'dev'\n"
5201 "-parallel dev redirect the parallel port to char device 'dev'\n"
5202 "-pidfile file Write PID to 'file'\n"
5203 "-S freeze CPU at startup (use 'c' to start execution)\n"
5204 "-s wait gdb connection to port %d\n"
5205 "-p port change gdb connection port\n"
5206 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
5207 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5208 " translation (t=none or lba) (usually qemu can guess them)\n"
5209 "-L path set the directory for the BIOS and VGA BIOS\n"
5210 #ifdef USE_KQEMU
5211 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5212 "-no-kqemu disable KQEMU kernel module usage\n"
5213 #endif
5214 #ifdef USE_CODE_COPY
5215 "-no-code-copy disable code copy acceleration\n"
5216 #endif
5217 #ifdef TARGET_I386
5218 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5219 " (default is CL-GD5446 PCI VGA)\n"
5220 "-no-acpi disable ACPI\n"
5221 #endif
5222 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5223 "-vnc display start a VNC server on display\n"
5224 "\n"
5225 "During emulation, the following keys are useful:\n"
5226 "ctrl-alt-f toggle full screen\n"
5227 "ctrl-alt-n switch to virtual console 'n'\n"
5228 "ctrl-alt toggle mouse and keyboard grab\n"
5229 "\n"
5230 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5232 "qemu",
5233 DEFAULT_RAM_SIZE,
5234 #ifndef _WIN32
5235 DEFAULT_NETWORK_SCRIPT,
5236 #endif
5237 DEFAULT_GDBSTUB_PORT,
5238 "/tmp/qemu.log");
5239 exit(1);
5242 #define HAS_ARG 0x0001
5244 enum {
5245 QEMU_OPTION_h,
5247 QEMU_OPTION_M,
5248 QEMU_OPTION_fda,
5249 QEMU_OPTION_fdb,
5250 QEMU_OPTION_hda,
5251 QEMU_OPTION_hdb,
5252 QEMU_OPTION_hdc,
5253 QEMU_OPTION_hdd,
5254 QEMU_OPTION_cdrom,
5255 QEMU_OPTION_boot,
5256 QEMU_OPTION_snapshot,
5257 #ifdef TARGET_I386
5258 QEMU_OPTION_no_fd_bootchk,
5259 #endif
5260 QEMU_OPTION_m,
5261 QEMU_OPTION_nographic,
5262 #ifdef HAS_AUDIO
5263 QEMU_OPTION_audio_help,
5264 QEMU_OPTION_soundhw,
5265 #endif
5267 QEMU_OPTION_net,
5268 QEMU_OPTION_tftp,
5269 QEMU_OPTION_smb,
5270 QEMU_OPTION_redir,
5272 QEMU_OPTION_kernel,
5273 QEMU_OPTION_append,
5274 QEMU_OPTION_initrd,
5276 QEMU_OPTION_S,
5277 QEMU_OPTION_s,
5278 QEMU_OPTION_p,
5279 QEMU_OPTION_d,
5280 QEMU_OPTION_hdachs,
5281 QEMU_OPTION_L,
5282 QEMU_OPTION_no_code_copy,
5283 QEMU_OPTION_k,
5284 QEMU_OPTION_localtime,
5285 QEMU_OPTION_cirrusvga,
5286 QEMU_OPTION_g,
5287 QEMU_OPTION_std_vga,
5288 QEMU_OPTION_monitor,
5289 QEMU_OPTION_serial,
5290 QEMU_OPTION_parallel,
5291 QEMU_OPTION_loadvm,
5292 QEMU_OPTION_full_screen,
5293 QEMU_OPTION_pidfile,
5294 QEMU_OPTION_no_kqemu,
5295 QEMU_OPTION_kernel_kqemu,
5296 QEMU_OPTION_win2k_hack,
5297 QEMU_OPTION_usb,
5298 QEMU_OPTION_usbdevice,
5299 QEMU_OPTION_smp,
5300 QEMU_OPTION_vnc,
5301 QEMU_OPTION_no_acpi,
5304 typedef struct QEMUOption {
5305 const char *name;
5306 int flags;
5307 int index;
5308 } QEMUOption;
5310 const QEMUOption qemu_options[] = {
5311 { "h", 0, QEMU_OPTION_h },
5313 { "M", HAS_ARG, QEMU_OPTION_M },
5314 { "fda", HAS_ARG, QEMU_OPTION_fda },
5315 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5316 { "hda", HAS_ARG, QEMU_OPTION_hda },
5317 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5318 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5319 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5320 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5321 { "boot", HAS_ARG, QEMU_OPTION_boot },
5322 { "snapshot", 0, QEMU_OPTION_snapshot },
5323 #ifdef TARGET_I386
5324 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5325 #endif
5326 { "m", HAS_ARG, QEMU_OPTION_m },
5327 { "nographic", 0, QEMU_OPTION_nographic },
5328 { "k", HAS_ARG, QEMU_OPTION_k },
5329 #ifdef HAS_AUDIO
5330 { "audio-help", 0, QEMU_OPTION_audio_help },
5331 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5332 #endif
5334 { "net", HAS_ARG, QEMU_OPTION_net},
5335 #ifdef CONFIG_SLIRP
5336 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5337 #ifndef _WIN32
5338 { "smb", HAS_ARG, QEMU_OPTION_smb },
5339 #endif
5340 { "redir", HAS_ARG, QEMU_OPTION_redir },
5341 #endif
5343 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5344 { "append", HAS_ARG, QEMU_OPTION_append },
5345 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5347 { "S", 0, QEMU_OPTION_S },
5348 { "s", 0, QEMU_OPTION_s },
5349 { "p", HAS_ARG, QEMU_OPTION_p },
5350 { "d", HAS_ARG, QEMU_OPTION_d },
5351 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5352 { "L", HAS_ARG, QEMU_OPTION_L },
5353 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
5354 #ifdef USE_KQEMU
5355 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5356 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5357 #endif
5358 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5359 { "g", 1, QEMU_OPTION_g },
5360 #endif
5361 { "localtime", 0, QEMU_OPTION_localtime },
5362 { "std-vga", 0, QEMU_OPTION_std_vga },
5363 { "monitor", 1, QEMU_OPTION_monitor },
5364 { "serial", 1, QEMU_OPTION_serial },
5365 { "parallel", 1, QEMU_OPTION_parallel },
5366 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5367 { "full-screen", 0, QEMU_OPTION_full_screen },
5368 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5369 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5370 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5371 { "smp", HAS_ARG, QEMU_OPTION_smp },
5372 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5374 /* temporary options */
5375 { "usb", 0, QEMU_OPTION_usb },
5376 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
5377 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5378 { NULL },
5381 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5383 /* this stack is only used during signal handling */
5384 #define SIGNAL_STACK_SIZE 32768
5386 static uint8_t *signal_stack;
5388 #endif
5390 /* password input */
5392 static BlockDriverState *get_bdrv(int index)
5394 BlockDriverState *bs;
5396 if (index < 4) {
5397 bs = bs_table[index];
5398 } else if (index < 6) {
5399 bs = fd_table[index - 4];
5400 } else {
5401 bs = NULL;
5403 return bs;
5406 static void read_passwords(void)
5408 BlockDriverState *bs;
5409 int i, j;
5410 char password[256];
5412 for(i = 0; i < 6; i++) {
5413 bs = get_bdrv(i);
5414 if (bs && bdrv_is_encrypted(bs)) {
5415 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5416 for(j = 0; j < 3; j++) {
5417 monitor_readline("Password: ",
5418 1, password, sizeof(password));
5419 if (bdrv_set_key(bs, password) == 0)
5420 break;
5421 term_printf("invalid password\n");
5427 /* XXX: currently we cannot use simultaneously different CPUs */
5428 void register_machines(void)
5430 #if defined(TARGET_I386)
5431 qemu_register_machine(&pc_machine);
5432 qemu_register_machine(&isapc_machine);
5433 #elif defined(TARGET_PPC)
5434 qemu_register_machine(&heathrow_machine);
5435 qemu_register_machine(&core99_machine);
5436 qemu_register_machine(&prep_machine);
5437 #elif defined(TARGET_MIPS)
5438 qemu_register_machine(&mips_machine);
5439 #elif defined(TARGET_SPARC)
5440 #ifdef TARGET_SPARC64
5441 qemu_register_machine(&sun4u_machine);
5442 #else
5443 qemu_register_machine(&sun4m_machine);
5444 #endif
5445 #elif defined(TARGET_ARM)
5446 qemu_register_machine(&integratorcp926_machine);
5447 qemu_register_machine(&integratorcp1026_machine);
5448 qemu_register_machine(&versatilepb_machine);
5449 qemu_register_machine(&versatileab_machine);
5450 #elif defined(TARGET_SH4)
5451 qemu_register_machine(&shix_machine);
5452 #else
5453 #error unsupported CPU
5454 #endif
5457 #ifdef HAS_AUDIO
5458 struct soundhw soundhw[] = {
5459 #ifdef TARGET_I386
5461 "pcspk",
5462 "PC speaker",
5465 { .init_isa = pcspk_audio_init }
5467 #endif
5469 "sb16",
5470 "Creative Sound Blaster 16",
5473 { .init_isa = SB16_init }
5476 #ifdef CONFIG_ADLIB
5478 "adlib",
5479 #ifdef HAS_YMF262
5480 "Yamaha YMF262 (OPL3)",
5481 #else
5482 "Yamaha YM3812 (OPL2)",
5483 #endif
5486 { .init_isa = Adlib_init }
5488 #endif
5490 #ifdef CONFIG_GUS
5492 "gus",
5493 "Gravis Ultrasound GF1",
5496 { .init_isa = GUS_init }
5498 #endif
5501 "es1370",
5502 "ENSONIQ AudioPCI ES1370",
5505 { .init_pci = es1370_init }
5508 { NULL, NULL, 0, 0, { NULL } }
5511 static void select_soundhw (const char *optarg)
5513 struct soundhw *c;
5515 if (*optarg == '?') {
5516 show_valid_cards:
5518 printf ("Valid sound card names (comma separated):\n");
5519 for (c = soundhw; c->name; ++c) {
5520 printf ("%-11s %s\n", c->name, c->descr);
5522 printf ("\n-soundhw all will enable all of the above\n");
5523 exit (*optarg != '?');
5525 else {
5526 size_t l;
5527 const char *p;
5528 char *e;
5529 int bad_card = 0;
5531 if (!strcmp (optarg, "all")) {
5532 for (c = soundhw; c->name; ++c) {
5533 c->enabled = 1;
5535 return;
5538 p = optarg;
5539 while (*p) {
5540 e = strchr (p, ',');
5541 l = !e ? strlen (p) : (size_t) (e - p);
5543 for (c = soundhw; c->name; ++c) {
5544 if (!strncmp (c->name, p, l)) {
5545 c->enabled = 1;
5546 break;
5550 if (!c->name) {
5551 if (l > 80) {
5552 fprintf (stderr,
5553 "Unknown sound card name (too big to show)\n");
5555 else {
5556 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5557 (int) l, p);
5559 bad_card = 1;
5561 p += l + (e != NULL);
5564 if (bad_card)
5565 goto show_valid_cards;
5568 #endif
5570 #ifdef _WIN32
5571 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5573 exit(STATUS_CONTROL_C_EXIT);
5574 return TRUE;
5576 #endif
5578 #define MAX_NET_CLIENTS 32
5580 int main(int argc, char **argv)
5582 #ifdef CONFIG_GDBSTUB
5583 int use_gdbstub, gdbstub_port;
5584 #endif
5585 int i, cdrom_index;
5586 int snapshot, linux_boot;
5587 const char *initrd_filename;
5588 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5589 const char *kernel_filename, *kernel_cmdline;
5590 DisplayState *ds = &display_state;
5591 int cyls, heads, secs, translation;
5592 int start_emulation = 1;
5593 char net_clients[MAX_NET_CLIENTS][256];
5594 int nb_net_clients;
5595 int optind;
5596 const char *r, *optarg;
5597 CharDriverState *monitor_hd;
5598 char monitor_device[128];
5599 char serial_devices[MAX_SERIAL_PORTS][128];
5600 int serial_device_index;
5601 char parallel_devices[MAX_PARALLEL_PORTS][128];
5602 int parallel_device_index;
5603 const char *loadvm = NULL;
5604 QEMUMachine *machine;
5605 char usb_devices[MAX_USB_CMDLINE][128];
5606 int usb_devices_index;
5608 LIST_INIT (&vm_change_state_head);
5609 #ifndef _WIN32
5611 struct sigaction act;
5612 sigfillset(&act.sa_mask);
5613 act.sa_flags = 0;
5614 act.sa_handler = SIG_IGN;
5615 sigaction(SIGPIPE, &act, NULL);
5617 #else
5618 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5619 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5620 QEMU to run on a single CPU */
5622 HANDLE h;
5623 DWORD mask, smask;
5624 int i;
5625 h = GetCurrentProcess();
5626 if (GetProcessAffinityMask(h, &mask, &smask)) {
5627 for(i = 0; i < 32; i++) {
5628 if (mask & (1 << i))
5629 break;
5631 if (i != 32) {
5632 mask = 1 << i;
5633 SetProcessAffinityMask(h, mask);
5637 #endif
5639 register_machines();
5640 machine = first_machine;
5641 initrd_filename = NULL;
5642 for(i = 0; i < MAX_FD; i++)
5643 fd_filename[i] = NULL;
5644 for(i = 0; i < MAX_DISKS; i++)
5645 hd_filename[i] = NULL;
5646 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5647 vga_ram_size = VGA_RAM_SIZE;
5648 bios_size = BIOS_SIZE;
5649 #ifdef CONFIG_GDBSTUB
5650 use_gdbstub = 0;
5651 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5652 #endif
5653 snapshot = 0;
5654 nographic = 0;
5655 kernel_filename = NULL;
5656 kernel_cmdline = "";
5657 #ifdef TARGET_PPC
5658 cdrom_index = 1;
5659 #else
5660 cdrom_index = 2;
5661 #endif
5662 cyls = heads = secs = 0;
5663 translation = BIOS_ATA_TRANSLATION_AUTO;
5664 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5666 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5667 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5668 serial_devices[i][0] = '\0';
5669 serial_device_index = 0;
5671 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5672 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5673 parallel_devices[i][0] = '\0';
5674 parallel_device_index = 0;
5676 usb_devices_index = 0;
5678 nb_net_clients = 0;
5680 nb_nics = 0;
5681 /* default mac address of the first network interface */
5683 optind = 1;
5684 for(;;) {
5685 if (optind >= argc)
5686 break;
5687 r = argv[optind];
5688 if (r[0] != '-') {
5689 hd_filename[0] = argv[optind++];
5690 } else {
5691 const QEMUOption *popt;
5693 optind++;
5694 popt = qemu_options;
5695 for(;;) {
5696 if (!popt->name) {
5697 fprintf(stderr, "%s: invalid option -- '%s'\n",
5698 argv[0], r);
5699 exit(1);
5701 if (!strcmp(popt->name, r + 1))
5702 break;
5703 popt++;
5705 if (popt->flags & HAS_ARG) {
5706 if (optind >= argc) {
5707 fprintf(stderr, "%s: option '%s' requires an argument\n",
5708 argv[0], r);
5709 exit(1);
5711 optarg = argv[optind++];
5712 } else {
5713 optarg = NULL;
5716 switch(popt->index) {
5717 case QEMU_OPTION_M:
5718 machine = find_machine(optarg);
5719 if (!machine) {
5720 QEMUMachine *m;
5721 printf("Supported machines are:\n");
5722 for(m = first_machine; m != NULL; m = m->next) {
5723 printf("%-10s %s%s\n",
5724 m->name, m->desc,
5725 m == first_machine ? " (default)" : "");
5727 exit(1);
5729 break;
5730 case QEMU_OPTION_initrd:
5731 initrd_filename = optarg;
5732 break;
5733 case QEMU_OPTION_hda:
5734 case QEMU_OPTION_hdb:
5735 case QEMU_OPTION_hdc:
5736 case QEMU_OPTION_hdd:
5738 int hd_index;
5739 hd_index = popt->index - QEMU_OPTION_hda;
5740 hd_filename[hd_index] = optarg;
5741 if (hd_index == cdrom_index)
5742 cdrom_index = -1;
5744 break;
5745 case QEMU_OPTION_snapshot:
5746 snapshot = 1;
5747 break;
5748 case QEMU_OPTION_hdachs:
5750 const char *p;
5751 p = optarg;
5752 cyls = strtol(p, (char **)&p, 0);
5753 if (cyls < 1 || cyls > 16383)
5754 goto chs_fail;
5755 if (*p != ',')
5756 goto chs_fail;
5757 p++;
5758 heads = strtol(p, (char **)&p, 0);
5759 if (heads < 1 || heads > 16)
5760 goto chs_fail;
5761 if (*p != ',')
5762 goto chs_fail;
5763 p++;
5764 secs = strtol(p, (char **)&p, 0);
5765 if (secs < 1 || secs > 63)
5766 goto chs_fail;
5767 if (*p == ',') {
5768 p++;
5769 if (!strcmp(p, "none"))
5770 translation = BIOS_ATA_TRANSLATION_NONE;
5771 else if (!strcmp(p, "lba"))
5772 translation = BIOS_ATA_TRANSLATION_LBA;
5773 else if (!strcmp(p, "auto"))
5774 translation = BIOS_ATA_TRANSLATION_AUTO;
5775 else
5776 goto chs_fail;
5777 } else if (*p != '\0') {
5778 chs_fail:
5779 fprintf(stderr, "qemu: invalid physical CHS format\n");
5780 exit(1);
5783 break;
5784 case QEMU_OPTION_nographic:
5785 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5786 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5787 nographic = 1;
5788 break;
5789 case QEMU_OPTION_kernel:
5790 kernel_filename = optarg;
5791 break;
5792 case QEMU_OPTION_append:
5793 kernel_cmdline = optarg;
5794 break;
5795 case QEMU_OPTION_cdrom:
5796 if (cdrom_index >= 0) {
5797 hd_filename[cdrom_index] = optarg;
5799 break;
5800 case QEMU_OPTION_boot:
5801 boot_device = optarg[0];
5802 if (boot_device != 'a' &&
5803 #ifdef TARGET_SPARC
5804 // Network boot
5805 boot_device != 'n' &&
5806 #endif
5807 boot_device != 'c' && boot_device != 'd') {
5808 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5809 exit(1);
5811 break;
5812 case QEMU_OPTION_fda:
5813 fd_filename[0] = optarg;
5814 break;
5815 case QEMU_OPTION_fdb:
5816 fd_filename[1] = optarg;
5817 break;
5818 #ifdef TARGET_I386
5819 case QEMU_OPTION_no_fd_bootchk:
5820 fd_bootchk = 0;
5821 break;
5822 #endif
5823 case QEMU_OPTION_no_code_copy:
5824 code_copy_enabled = 0;
5825 break;
5826 case QEMU_OPTION_net:
5827 if (nb_net_clients >= MAX_NET_CLIENTS) {
5828 fprintf(stderr, "qemu: too many network clients\n");
5829 exit(1);
5831 pstrcpy(net_clients[nb_net_clients],
5832 sizeof(net_clients[0]),
5833 optarg);
5834 nb_net_clients++;
5835 break;
5836 #ifdef CONFIG_SLIRP
5837 case QEMU_OPTION_tftp:
5838 tftp_prefix = optarg;
5839 break;
5840 #ifndef _WIN32
5841 case QEMU_OPTION_smb:
5842 net_slirp_smb(optarg);
5843 break;
5844 #endif
5845 case QEMU_OPTION_redir:
5846 net_slirp_redir(optarg);
5847 break;
5848 #endif
5849 #ifdef HAS_AUDIO
5850 case QEMU_OPTION_audio_help:
5851 AUD_help ();
5852 exit (0);
5853 break;
5854 case QEMU_OPTION_soundhw:
5855 select_soundhw (optarg);
5856 break;
5857 #endif
5858 case QEMU_OPTION_h:
5859 help();
5860 break;
5861 case QEMU_OPTION_m:
5862 ram_size = atoi(optarg) * 1024 * 1024;
5863 if (ram_size <= 0)
5864 help();
5865 if (ram_size > PHYS_RAM_MAX_SIZE) {
5866 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5867 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5868 exit(1);
5870 break;
5871 case QEMU_OPTION_d:
5873 int mask;
5874 CPULogItem *item;
5876 mask = cpu_str_to_log_mask(optarg);
5877 if (!mask) {
5878 printf("Log items (comma separated):\n");
5879 for(item = cpu_log_items; item->mask != 0; item++) {
5880 printf("%-10s %s\n", item->name, item->help);
5882 exit(1);
5884 cpu_set_log(mask);
5886 break;
5887 #ifdef CONFIG_GDBSTUB
5888 case QEMU_OPTION_s:
5889 use_gdbstub = 1;
5890 break;
5891 case QEMU_OPTION_p:
5892 gdbstub_port = atoi(optarg);
5893 break;
5894 #endif
5895 case QEMU_OPTION_L:
5896 bios_dir = optarg;
5897 break;
5898 case QEMU_OPTION_S:
5899 start_emulation = 0;
5900 break;
5901 case QEMU_OPTION_k:
5902 keyboard_layout = optarg;
5903 break;
5904 case QEMU_OPTION_localtime:
5905 rtc_utc = 0;
5906 break;
5907 case QEMU_OPTION_cirrusvga:
5908 cirrus_vga_enabled = 1;
5909 break;
5910 case QEMU_OPTION_std_vga:
5911 cirrus_vga_enabled = 0;
5912 break;
5913 case QEMU_OPTION_g:
5915 const char *p;
5916 int w, h, depth;
5917 p = optarg;
5918 w = strtol(p, (char **)&p, 10);
5919 if (w <= 0) {
5920 graphic_error:
5921 fprintf(stderr, "qemu: invalid resolution or depth\n");
5922 exit(1);
5924 if (*p != 'x')
5925 goto graphic_error;
5926 p++;
5927 h = strtol(p, (char **)&p, 10);
5928 if (h <= 0)
5929 goto graphic_error;
5930 if (*p == 'x') {
5931 p++;
5932 depth = strtol(p, (char **)&p, 10);
5933 if (depth != 8 && depth != 15 && depth != 16 &&
5934 depth != 24 && depth != 32)
5935 goto graphic_error;
5936 } else if (*p == '\0') {
5937 depth = graphic_depth;
5938 } else {
5939 goto graphic_error;
5942 graphic_width = w;
5943 graphic_height = h;
5944 graphic_depth = depth;
5946 break;
5947 case QEMU_OPTION_monitor:
5948 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5949 break;
5950 case QEMU_OPTION_serial:
5951 if (serial_device_index >= MAX_SERIAL_PORTS) {
5952 fprintf(stderr, "qemu: too many serial ports\n");
5953 exit(1);
5955 pstrcpy(serial_devices[serial_device_index],
5956 sizeof(serial_devices[0]), optarg);
5957 serial_device_index++;
5958 break;
5959 case QEMU_OPTION_parallel:
5960 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5961 fprintf(stderr, "qemu: too many parallel ports\n");
5962 exit(1);
5964 pstrcpy(parallel_devices[parallel_device_index],
5965 sizeof(parallel_devices[0]), optarg);
5966 parallel_device_index++;
5967 break;
5968 case QEMU_OPTION_loadvm:
5969 loadvm = optarg;
5970 break;
5971 case QEMU_OPTION_full_screen:
5972 full_screen = 1;
5973 break;
5974 case QEMU_OPTION_pidfile:
5975 create_pidfile(optarg);
5976 break;
5977 #ifdef TARGET_I386
5978 case QEMU_OPTION_win2k_hack:
5979 win2k_install_hack = 1;
5980 break;
5981 #endif
5982 #ifdef USE_KQEMU
5983 case QEMU_OPTION_no_kqemu:
5984 kqemu_allowed = 0;
5985 break;
5986 case QEMU_OPTION_kernel_kqemu:
5987 kqemu_allowed = 2;
5988 break;
5989 #endif
5990 case QEMU_OPTION_usb:
5991 usb_enabled = 1;
5992 break;
5993 case QEMU_OPTION_usbdevice:
5994 usb_enabled = 1;
5995 if (usb_devices_index >= MAX_USB_CMDLINE) {
5996 fprintf(stderr, "Too many USB devices\n");
5997 exit(1);
5999 pstrcpy(usb_devices[usb_devices_index],
6000 sizeof(usb_devices[usb_devices_index]),
6001 optarg);
6002 usb_devices_index++;
6003 break;
6004 case QEMU_OPTION_smp:
6005 smp_cpus = atoi(optarg);
6006 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6007 fprintf(stderr, "Invalid number of CPUs\n");
6008 exit(1);
6010 break;
6011 case QEMU_OPTION_vnc:
6012 vnc_display = atoi(optarg);
6013 if (vnc_display < 0) {
6014 fprintf(stderr, "Invalid VNC display\n");
6015 exit(1);
6017 break;
6018 case QEMU_OPTION_no_acpi:
6019 acpi_enabled = 0;
6020 break;
6025 #ifdef USE_KQEMU
6026 if (smp_cpus > 1)
6027 kqemu_allowed = 0;
6028 #endif
6029 linux_boot = (kernel_filename != NULL);
6031 if (!linux_boot &&
6032 hd_filename[0] == '\0' &&
6033 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6034 fd_filename[0] == '\0')
6035 help();
6037 /* boot to cd by default if no hard disk */
6038 if (hd_filename[0] == '\0' && boot_device == 'c') {
6039 if (fd_filename[0] != '\0')
6040 boot_device = 'a';
6041 else
6042 boot_device = 'd';
6045 setvbuf(stdout, NULL, _IOLBF, 0);
6047 init_timers();
6048 init_timer_alarm();
6050 #ifdef _WIN32
6051 socket_init();
6052 #endif
6054 /* init network clients */
6055 if (nb_net_clients == 0) {
6056 /* if no clients, we use a default config */
6057 pstrcpy(net_clients[0], sizeof(net_clients[0]),
6058 "nic");
6059 pstrcpy(net_clients[1], sizeof(net_clients[0]),
6060 "user");
6061 nb_net_clients = 2;
6064 for(i = 0;i < nb_net_clients; i++) {
6065 if (net_client_init(net_clients[i]) < 0)
6066 exit(1);
6069 /* init the memory */
6070 phys_ram_size = ram_size + vga_ram_size + bios_size;
6072 phys_ram_base = qemu_vmalloc(phys_ram_size);
6073 if (!phys_ram_base) {
6074 fprintf(stderr, "Could not allocate physical memory\n");
6075 exit(1);
6078 /* we always create the cdrom drive, even if no disk is there */
6079 bdrv_init();
6080 if (cdrom_index >= 0) {
6081 bs_table[cdrom_index] = bdrv_new("cdrom");
6082 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6085 /* open the virtual block devices */
6086 for(i = 0; i < MAX_DISKS; i++) {
6087 if (hd_filename[i]) {
6088 if (!bs_table[i]) {
6089 char buf[64];
6090 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6091 bs_table[i] = bdrv_new(buf);
6093 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
6094 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6095 hd_filename[i]);
6096 exit(1);
6098 if (i == 0 && cyls != 0) {
6099 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6100 bdrv_set_translation_hint(bs_table[i], translation);
6105 /* we always create at least one floppy disk */
6106 fd_table[0] = bdrv_new("fda");
6107 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6109 for(i = 0; i < MAX_FD; i++) {
6110 if (fd_filename[i]) {
6111 if (!fd_table[i]) {
6112 char buf[64];
6113 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6114 fd_table[i] = bdrv_new(buf);
6115 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6117 if (fd_filename[i] != '\0') {
6118 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
6119 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6120 fd_filename[i]);
6121 exit(1);
6127 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
6128 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
6130 init_ioports();
6132 /* terminal init */
6133 if (nographic) {
6134 dumb_display_init(ds);
6135 } else if (vnc_display != -1) {
6136 vnc_display_init(ds, vnc_display);
6137 } else {
6138 #if defined(CONFIG_SDL)
6139 sdl_display_init(ds, full_screen);
6140 #elif defined(CONFIG_COCOA)
6141 cocoa_display_init(ds, full_screen);
6142 #else
6143 dumb_display_init(ds);
6144 #endif
6147 monitor_hd = qemu_chr_open(monitor_device);
6148 if (!monitor_hd) {
6149 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6150 exit(1);
6152 monitor_init(monitor_hd, !nographic);
6154 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6155 if (serial_devices[i][0] != '\0') {
6156 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6157 if (!serial_hds[i]) {
6158 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6159 serial_devices[i]);
6160 exit(1);
6162 if (!strcmp(serial_devices[i], "vc"))
6163 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6167 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6168 if (parallel_devices[i][0] != '\0') {
6169 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6170 if (!parallel_hds[i]) {
6171 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6172 parallel_devices[i]);
6173 exit(1);
6175 if (!strcmp(parallel_devices[i], "vc"))
6176 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6180 machine->init(ram_size, vga_ram_size, boot_device,
6181 ds, fd_filename, snapshot,
6182 kernel_filename, kernel_cmdline, initrd_filename);
6184 /* init USB devices */
6185 if (usb_enabled) {
6186 for(i = 0; i < usb_devices_index; i++) {
6187 if (usb_device_add(usb_devices[i]) < 0) {
6188 fprintf(stderr, "Warning: could not add USB device %s\n",
6189 usb_devices[i]);
6194 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6195 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6197 #ifdef CONFIG_GDBSTUB
6198 if (use_gdbstub) {
6199 if (gdbserver_start(gdbstub_port) < 0) {
6200 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6201 gdbstub_port);
6202 exit(1);
6203 } else {
6204 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6206 } else
6207 #endif
6208 if (loadvm)
6209 qemu_loadvm(loadvm);
6212 /* XXX: simplify init */
6213 read_passwords();
6214 if (start_emulation) {
6215 vm_start();
6218 main_loop();
6219 quit_timers();
6220 return 0;