Don't include audio.h when building tools.
[qemu/mini2440.git] / vl.c
blobe8780dd08ffae54c8b9c634c8e423fdfac71f9d5
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 /***********************************************************/
486 /* timers */
488 #if defined(__powerpc__)
490 static inline uint32_t get_tbl(void)
492 uint32_t tbl;
493 asm volatile("mftb %0" : "=r" (tbl));
494 return tbl;
497 static inline uint32_t get_tbu(void)
499 uint32_t tbl;
500 asm volatile("mftbu %0" : "=r" (tbl));
501 return tbl;
504 int64_t cpu_get_real_ticks(void)
506 uint32_t l, h, h1;
507 /* NOTE: we test if wrapping has occurred */
508 do {
509 h = get_tbu();
510 l = get_tbl();
511 h1 = get_tbu();
512 } while (h != h1);
513 return ((int64_t)h << 32) | l;
516 #elif defined(__i386__)
518 int64_t cpu_get_real_ticks(void)
520 #ifdef _WIN32
521 LARGE_INTEGER ti;
522 QueryPerformanceCounter(&ti);
523 return ti.QuadPart;
524 #else
525 int64_t val;
526 asm volatile ("rdtsc" : "=A" (val));
527 return val;
528 #endif
531 #elif defined(__x86_64__)
533 int64_t cpu_get_real_ticks(void)
535 uint32_t low,high;
536 int64_t val;
537 asm volatile("rdtsc" : "=a" (low), "=d" (high));
538 val = high;
539 val <<= 32;
540 val |= low;
541 return val;
544 #elif defined(__ia64)
546 int64_t cpu_get_real_ticks(void)
548 int64_t val;
549 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
550 return val;
553 #elif defined(__s390__)
555 int64_t cpu_get_real_ticks(void)
557 int64_t val;
558 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
559 return val;
562 #elif defined(__sparc__) && defined(HOST_SOLARIS)
564 uint64_t cpu_get_real_ticks (void)
566 #if defined(_LP64)
567 uint64_t rval;
568 asm volatile("rd %%tick,%0" : "=r"(rval));
569 return rval;
570 #else
571 union {
572 uint64_t i64;
573 struct {
574 uint32_t high;
575 uint32_t low;
576 } i32;
577 } rval;
578 asm volatile("rd %%tick,%1; srlx %1,32,%0"
579 : "=r"(rval.i32.high), "=r"(rval.i32.low));
580 return rval.i64;
581 #endif
584 #else
585 #error unsupported CPU
586 #endif
588 static int64_t cpu_ticks_prev;
589 static int64_t cpu_ticks_offset;
590 static int cpu_ticks_enabled;
592 static inline int64_t cpu_get_ticks(void)
594 if (!cpu_ticks_enabled) {
595 return cpu_ticks_offset;
596 } else {
597 int64_t ticks;
598 ticks = cpu_get_real_ticks();
599 if (cpu_ticks_prev > ticks) {
600 /* Note: non increasing ticks may happen if the host uses
601 software suspend */
602 cpu_ticks_offset += cpu_ticks_prev - ticks;
604 cpu_ticks_prev = ticks;
605 return ticks + cpu_ticks_offset;
609 /* enable cpu_get_ticks() */
610 void cpu_enable_ticks(void)
612 if (!cpu_ticks_enabled) {
613 cpu_ticks_offset -= cpu_get_real_ticks();
614 cpu_ticks_enabled = 1;
618 /* disable cpu_get_ticks() : the clock is stopped. You must not call
619 cpu_get_ticks() after that. */
620 void cpu_disable_ticks(void)
622 if (cpu_ticks_enabled) {
623 cpu_ticks_offset = cpu_get_ticks();
624 cpu_ticks_enabled = 0;
628 #ifdef _WIN32
629 void cpu_calibrate_ticks(void)
631 LARGE_INTEGER freq;
632 int ret;
634 ret = QueryPerformanceFrequency(&freq);
635 if (ret == 0) {
636 fprintf(stderr, "Could not calibrate ticks\n");
637 exit(1);
639 ticks_per_sec = freq.QuadPart;
642 #else
643 static int64_t get_clock(void)
645 struct timeval tv;
646 gettimeofday(&tv, NULL);
647 return tv.tv_sec * 1000000LL + tv.tv_usec;
650 void cpu_calibrate_ticks(void)
652 int64_t usec, ticks;
654 usec = get_clock();
655 ticks = cpu_get_real_ticks();
656 usleep(50 * 1000);
657 usec = get_clock() - usec;
658 ticks = cpu_get_real_ticks() - ticks;
659 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
661 #endif /* !_WIN32 */
663 /* compute with 96 bit intermediate result: (a*b)/c */
664 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
666 union {
667 uint64_t ll;
668 struct {
669 #ifdef WORDS_BIGENDIAN
670 uint32_t high, low;
671 #else
672 uint32_t low, high;
673 #endif
674 } l;
675 } u, res;
676 uint64_t rl, rh;
678 u.ll = a;
679 rl = (uint64_t)u.l.low * (uint64_t)b;
680 rh = (uint64_t)u.l.high * (uint64_t)b;
681 rh += (rl >> 32);
682 res.l.high = rh / c;
683 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
684 return res.ll;
687 #define QEMU_TIMER_REALTIME 0
688 #define QEMU_TIMER_VIRTUAL 1
690 struct QEMUClock {
691 int type;
692 /* XXX: add frequency */
695 struct QEMUTimer {
696 QEMUClock *clock;
697 int64_t expire_time;
698 QEMUTimerCB *cb;
699 void *opaque;
700 struct QEMUTimer *next;
703 QEMUClock *rt_clock;
704 QEMUClock *vm_clock;
706 static QEMUTimer *active_timers[2];
707 #ifdef _WIN32
708 static MMRESULT timerID;
709 static HANDLE host_alarm = NULL;
710 static unsigned int period = 1;
711 #else
712 /* frequency of the times() clock tick */
713 static int timer_freq;
714 #endif
716 QEMUClock *qemu_new_clock(int type)
718 QEMUClock *clock;
719 clock = qemu_mallocz(sizeof(QEMUClock));
720 if (!clock)
721 return NULL;
722 clock->type = type;
723 return clock;
726 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
728 QEMUTimer *ts;
730 ts = qemu_mallocz(sizeof(QEMUTimer));
731 ts->clock = clock;
732 ts->cb = cb;
733 ts->opaque = opaque;
734 return ts;
737 void qemu_free_timer(QEMUTimer *ts)
739 qemu_free(ts);
742 /* stop a timer, but do not dealloc it */
743 void qemu_del_timer(QEMUTimer *ts)
745 QEMUTimer **pt, *t;
747 /* NOTE: this code must be signal safe because
748 qemu_timer_expired() can be called from a signal. */
749 pt = &active_timers[ts->clock->type];
750 for(;;) {
751 t = *pt;
752 if (!t)
753 break;
754 if (t == ts) {
755 *pt = t->next;
756 break;
758 pt = &t->next;
762 /* modify the current timer so that it will be fired when current_time
763 >= expire_time. The corresponding callback will be called. */
764 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
766 QEMUTimer **pt, *t;
768 qemu_del_timer(ts);
770 /* add the timer in the sorted list */
771 /* NOTE: this code must be signal safe because
772 qemu_timer_expired() can be called from a signal. */
773 pt = &active_timers[ts->clock->type];
774 for(;;) {
775 t = *pt;
776 if (!t)
777 break;
778 if (t->expire_time > expire_time)
779 break;
780 pt = &t->next;
782 ts->expire_time = expire_time;
783 ts->next = *pt;
784 *pt = ts;
787 int qemu_timer_pending(QEMUTimer *ts)
789 QEMUTimer *t;
790 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
791 if (t == ts)
792 return 1;
794 return 0;
797 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
799 if (!timer_head)
800 return 0;
801 return (timer_head->expire_time <= current_time);
804 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
806 QEMUTimer *ts;
808 for(;;) {
809 ts = *ptimer_head;
810 if (!ts || ts->expire_time > current_time)
811 break;
812 /* remove timer from the list before calling the callback */
813 *ptimer_head = ts->next;
814 ts->next = NULL;
816 /* run the callback (the timer list can be modified) */
817 ts->cb(ts->opaque);
821 int64_t qemu_get_clock(QEMUClock *clock)
823 switch(clock->type) {
824 case QEMU_TIMER_REALTIME:
825 #ifdef _WIN32
826 return GetTickCount();
827 #else
829 struct tms tp;
831 /* Note that using gettimeofday() is not a good solution
832 for timers because its value change when the date is
833 modified. */
834 if (timer_freq == 100) {
835 return times(&tp) * 10;
836 } else {
837 return ((int64_t)times(&tp) * 1000) / timer_freq;
840 #endif
841 default:
842 case QEMU_TIMER_VIRTUAL:
843 return cpu_get_ticks();
847 /* save a timer */
848 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
850 uint64_t expire_time;
852 if (qemu_timer_pending(ts)) {
853 expire_time = ts->expire_time;
854 } else {
855 expire_time = -1;
857 qemu_put_be64(f, expire_time);
860 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
862 uint64_t expire_time;
864 expire_time = qemu_get_be64(f);
865 if (expire_time != -1) {
866 qemu_mod_timer(ts, expire_time);
867 } else {
868 qemu_del_timer(ts);
872 static void timer_save(QEMUFile *f, void *opaque)
874 if (cpu_ticks_enabled) {
875 hw_error("cannot save state if virtual timers are running");
877 qemu_put_be64s(f, &cpu_ticks_offset);
878 qemu_put_be64s(f, &ticks_per_sec);
881 static int timer_load(QEMUFile *f, void *opaque, int version_id)
883 if (version_id != 1)
884 return -EINVAL;
885 if (cpu_ticks_enabled) {
886 return -EINVAL;
888 qemu_get_be64s(f, &cpu_ticks_offset);
889 qemu_get_be64s(f, &ticks_per_sec);
890 return 0;
893 #ifdef _WIN32
894 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
895 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
896 #else
897 static void host_alarm_handler(int host_signum)
898 #endif
900 #if 0
901 #define DISP_FREQ 1000
903 static int64_t delta_min = INT64_MAX;
904 static int64_t delta_max, delta_cum, last_clock, delta, ti;
905 static int count;
906 ti = qemu_get_clock(vm_clock);
907 if (last_clock != 0) {
908 delta = ti - last_clock;
909 if (delta < delta_min)
910 delta_min = delta;
911 if (delta > delta_max)
912 delta_max = delta;
913 delta_cum += delta;
914 if (++count == DISP_FREQ) {
915 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
916 muldiv64(delta_min, 1000000, ticks_per_sec),
917 muldiv64(delta_max, 1000000, ticks_per_sec),
918 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
919 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
920 count = 0;
921 delta_min = INT64_MAX;
922 delta_max = 0;
923 delta_cum = 0;
926 last_clock = ti;
928 #endif
929 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
930 qemu_get_clock(vm_clock)) ||
931 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
932 qemu_get_clock(rt_clock))) {
933 #ifdef _WIN32
934 SetEvent(host_alarm);
935 #endif
936 CPUState *env = cpu_single_env;
937 if (env) {
938 /* stop the currently executing cpu because a timer occured */
939 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
940 #ifdef USE_KQEMU
941 if (env->kqemu_enabled) {
942 kqemu_cpu_interrupt(env);
944 #endif
949 #ifndef _WIN32
951 #if defined(__linux__)
953 #define RTC_FREQ 1024
955 static int rtc_fd;
957 static int start_rtc_timer(void)
959 rtc_fd = open("/dev/rtc", O_RDONLY);
960 if (rtc_fd < 0)
961 return -1;
962 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
963 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
964 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
965 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
966 goto fail;
968 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
969 fail:
970 close(rtc_fd);
971 return -1;
973 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
974 return 0;
977 #else
979 static int start_rtc_timer(void)
981 return -1;
984 #endif /* !defined(__linux__) */
986 #endif /* !defined(_WIN32) */
988 static void init_timers(void)
990 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
991 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
993 #ifdef _WIN32
995 int count=0;
996 TIMECAPS tc;
998 ZeroMemory(&tc, sizeof(TIMECAPS));
999 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1000 if (period < tc.wPeriodMin)
1001 period = tc.wPeriodMin;
1002 timeBeginPeriod(period);
1003 timerID = timeSetEvent(1, // interval (ms)
1004 period, // resolution
1005 host_alarm_handler, // function
1006 (DWORD)&count, // user parameter
1007 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1008 if( !timerID ) {
1009 perror("failed timer alarm");
1010 exit(1);
1012 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1013 if (!host_alarm) {
1014 perror("failed CreateEvent");
1015 exit(1);
1017 qemu_add_wait_object(host_alarm, NULL, NULL);
1019 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1020 #else
1022 struct sigaction act;
1023 struct itimerval itv;
1025 /* get times() syscall frequency */
1026 timer_freq = sysconf(_SC_CLK_TCK);
1028 /* timer signal */
1029 sigfillset(&act.sa_mask);
1030 act.sa_flags = 0;
1031 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1032 act.sa_flags |= SA_ONSTACK;
1033 #endif
1034 act.sa_handler = host_alarm_handler;
1035 sigaction(SIGALRM, &act, NULL);
1037 itv.it_interval.tv_sec = 0;
1038 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1039 itv.it_value.tv_sec = 0;
1040 itv.it_value.tv_usec = 10 * 1000;
1041 setitimer(ITIMER_REAL, &itv, NULL);
1042 /* we probe the tick duration of the kernel to inform the user if
1043 the emulated kernel requested a too high timer frequency */
1044 getitimer(ITIMER_REAL, &itv);
1046 #if defined(__linux__)
1047 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1048 have timers with 1 ms resolution. The correct solution will
1049 be to use the POSIX real time timers available in recent
1050 2.6 kernels */
1051 if (itv.it_interval.tv_usec > 1000 || 1) {
1052 /* try to use /dev/rtc to have a faster timer */
1053 if (start_rtc_timer() < 0)
1054 goto use_itimer;
1055 /* disable itimer */
1056 itv.it_interval.tv_sec = 0;
1057 itv.it_interval.tv_usec = 0;
1058 itv.it_value.tv_sec = 0;
1059 itv.it_value.tv_usec = 0;
1060 setitimer(ITIMER_REAL, &itv, NULL);
1062 /* use the RTC */
1063 sigaction(SIGIO, &act, NULL);
1064 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1065 fcntl(rtc_fd, F_SETOWN, getpid());
1066 } else
1067 #endif /* defined(__linux__) */
1069 use_itimer:
1070 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1071 PIT_FREQ) / 1000000;
1074 #endif
1077 void quit_timers(void)
1079 #ifdef _WIN32
1080 timeKillEvent(timerID);
1081 timeEndPeriod(period);
1082 if (host_alarm) {
1083 CloseHandle(host_alarm);
1084 host_alarm = NULL;
1086 #endif
1089 /***********************************************************/
1090 /* character device */
1092 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1094 return s->chr_write(s, buf, len);
1097 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1099 if (!s->chr_ioctl)
1100 return -ENOTSUP;
1101 return s->chr_ioctl(s, cmd, arg);
1104 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1106 char buf[4096];
1107 va_list ap;
1108 va_start(ap, fmt);
1109 vsnprintf(buf, sizeof(buf), fmt, ap);
1110 qemu_chr_write(s, buf, strlen(buf));
1111 va_end(ap);
1114 void qemu_chr_send_event(CharDriverState *s, int event)
1116 if (s->chr_send_event)
1117 s->chr_send_event(s, event);
1120 void qemu_chr_add_read_handler(CharDriverState *s,
1121 IOCanRWHandler *fd_can_read,
1122 IOReadHandler *fd_read, void *opaque)
1124 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1127 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1129 s->chr_event = chr_event;
1132 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1134 return len;
1137 static void null_chr_add_read_handler(CharDriverState *chr,
1138 IOCanRWHandler *fd_can_read,
1139 IOReadHandler *fd_read, void *opaque)
1143 CharDriverState *qemu_chr_open_null(void)
1145 CharDriverState *chr;
1147 chr = qemu_mallocz(sizeof(CharDriverState));
1148 if (!chr)
1149 return NULL;
1150 chr->chr_write = null_chr_write;
1151 chr->chr_add_read_handler = null_chr_add_read_handler;
1152 return chr;
1155 #ifdef _WIN32
1157 static void socket_cleanup(void)
1159 WSACleanup();
1162 static int socket_init(void)
1164 WSADATA Data;
1165 int ret, err;
1167 ret = WSAStartup(MAKEWORD(2,2), &Data);
1168 if (ret != 0) {
1169 err = WSAGetLastError();
1170 fprintf(stderr, "WSAStartup: %d\n", err);
1171 return -1;
1173 atexit(socket_cleanup);
1174 return 0;
1177 static int send_all(int fd, const uint8_t *buf, int len1)
1179 int ret, len;
1181 len = len1;
1182 while (len > 0) {
1183 ret = send(fd, buf, len, 0);
1184 if (ret < 0) {
1185 int errno;
1186 errno = WSAGetLastError();
1187 if (errno != WSAEWOULDBLOCK) {
1188 return -1;
1190 } else if (ret == 0) {
1191 break;
1192 } else {
1193 buf += ret;
1194 len -= ret;
1197 return len1 - len;
1200 void socket_set_nonblock(int fd)
1202 unsigned long opt = 1;
1203 ioctlsocket(fd, FIONBIO, &opt);
1206 #else
1208 static int unix_write(int fd, const uint8_t *buf, int len1)
1210 int ret, len;
1212 len = len1;
1213 while (len > 0) {
1214 ret = write(fd, buf, len);
1215 if (ret < 0) {
1216 if (errno != EINTR && errno != EAGAIN)
1217 return -1;
1218 } else if (ret == 0) {
1219 break;
1220 } else {
1221 buf += ret;
1222 len -= ret;
1225 return len1 - len;
1228 static inline int send_all(int fd, const uint8_t *buf, int len1)
1230 return unix_write(fd, buf, len1);
1233 void socket_set_nonblock(int fd)
1235 fcntl(fd, F_SETFL, O_NONBLOCK);
1237 #endif /* !_WIN32 */
1239 #ifndef _WIN32
1241 typedef struct {
1242 int fd_in, fd_out;
1243 IOCanRWHandler *fd_can_read;
1244 IOReadHandler *fd_read;
1245 void *fd_opaque;
1246 int max_size;
1247 } FDCharDriver;
1249 #define STDIO_MAX_CLIENTS 2
1251 static int stdio_nb_clients;
1252 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1254 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1256 FDCharDriver *s = chr->opaque;
1257 return unix_write(s->fd_out, buf, len);
1260 static int fd_chr_read_poll(void *opaque)
1262 CharDriverState *chr = opaque;
1263 FDCharDriver *s = chr->opaque;
1265 s->max_size = s->fd_can_read(s->fd_opaque);
1266 return s->max_size;
1269 static void fd_chr_read(void *opaque)
1271 CharDriverState *chr = opaque;
1272 FDCharDriver *s = chr->opaque;
1273 int size, len;
1274 uint8_t buf[1024];
1276 len = sizeof(buf);
1277 if (len > s->max_size)
1278 len = s->max_size;
1279 if (len == 0)
1280 return;
1281 size = read(s->fd_in, buf, len);
1282 if (size > 0) {
1283 s->fd_read(s->fd_opaque, buf, size);
1287 static void fd_chr_add_read_handler(CharDriverState *chr,
1288 IOCanRWHandler *fd_can_read,
1289 IOReadHandler *fd_read, void *opaque)
1291 FDCharDriver *s = chr->opaque;
1293 if (s->fd_in >= 0) {
1294 s->fd_can_read = fd_can_read;
1295 s->fd_read = fd_read;
1296 s->fd_opaque = opaque;
1297 if (nographic && s->fd_in == 0) {
1298 } else {
1299 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1300 fd_chr_read, NULL, chr);
1305 /* open a character device to a unix fd */
1306 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1308 CharDriverState *chr;
1309 FDCharDriver *s;
1311 chr = qemu_mallocz(sizeof(CharDriverState));
1312 if (!chr)
1313 return NULL;
1314 s = qemu_mallocz(sizeof(FDCharDriver));
1315 if (!s) {
1316 free(chr);
1317 return NULL;
1319 s->fd_in = fd_in;
1320 s->fd_out = fd_out;
1321 chr->opaque = s;
1322 chr->chr_write = fd_chr_write;
1323 chr->chr_add_read_handler = fd_chr_add_read_handler;
1324 return chr;
1327 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1329 int fd_out;
1331 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1332 if (fd_out < 0)
1333 return NULL;
1334 return qemu_chr_open_fd(-1, fd_out);
1337 CharDriverState *qemu_chr_open_pipe(const char *filename)
1339 int fd;
1341 fd = open(filename, O_RDWR | O_BINARY);
1342 if (fd < 0)
1343 return NULL;
1344 return qemu_chr_open_fd(fd, fd);
1348 /* for STDIO, we handle the case where several clients use it
1349 (nographic mode) */
1351 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1353 #define TERM_FIFO_MAX_SIZE 1
1355 static int term_got_escape, client_index;
1356 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1357 int term_fifo_size;
1359 void term_print_help(void)
1361 printf("\n"
1362 "C-a h print this help\n"
1363 "C-a x exit emulator\n"
1364 "C-a s save disk data back to file (if -snapshot)\n"
1365 "C-a b send break (magic sysrq)\n"
1366 "C-a c switch between console and monitor\n"
1367 "C-a C-a send C-a\n"
1371 /* called when a char is received */
1372 static void stdio_received_byte(int ch)
1374 if (term_got_escape) {
1375 term_got_escape = 0;
1376 switch(ch) {
1377 case 'h':
1378 term_print_help();
1379 break;
1380 case 'x':
1381 exit(0);
1382 break;
1383 case 's':
1385 int i;
1386 for (i = 0; i < MAX_DISKS; i++) {
1387 if (bs_table[i])
1388 bdrv_commit(bs_table[i]);
1391 break;
1392 case 'b':
1393 if (client_index < stdio_nb_clients) {
1394 CharDriverState *chr;
1395 FDCharDriver *s;
1397 chr = stdio_clients[client_index];
1398 s = chr->opaque;
1399 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1401 break;
1402 case 'c':
1403 client_index++;
1404 if (client_index >= stdio_nb_clients)
1405 client_index = 0;
1406 if (client_index == 0) {
1407 /* send a new line in the monitor to get the prompt */
1408 ch = '\r';
1409 goto send_char;
1411 break;
1412 case TERM_ESCAPE:
1413 goto send_char;
1415 } else if (ch == TERM_ESCAPE) {
1416 term_got_escape = 1;
1417 } else {
1418 send_char:
1419 if (client_index < stdio_nb_clients) {
1420 uint8_t buf[1];
1421 CharDriverState *chr;
1422 FDCharDriver *s;
1424 chr = stdio_clients[client_index];
1425 s = chr->opaque;
1426 if (s->fd_can_read(s->fd_opaque) > 0) {
1427 buf[0] = ch;
1428 s->fd_read(s->fd_opaque, buf, 1);
1429 } else if (term_fifo_size == 0) {
1430 term_fifo[term_fifo_size++] = ch;
1436 static int stdio_read_poll(void *opaque)
1438 CharDriverState *chr;
1439 FDCharDriver *s;
1441 if (client_index < stdio_nb_clients) {
1442 chr = stdio_clients[client_index];
1443 s = chr->opaque;
1444 /* try to flush the queue if needed */
1445 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1446 s->fd_read(s->fd_opaque, term_fifo, 1);
1447 term_fifo_size = 0;
1449 /* see if we can absorb more chars */
1450 if (term_fifo_size == 0)
1451 return 1;
1452 else
1453 return 0;
1454 } else {
1455 return 1;
1459 static void stdio_read(void *opaque)
1461 int size;
1462 uint8_t buf[1];
1464 size = read(0, buf, 1);
1465 if (size > 0)
1466 stdio_received_byte(buf[0]);
1469 /* init terminal so that we can grab keys */
1470 static struct termios oldtty;
1471 static int old_fd0_flags;
1473 static void term_exit(void)
1475 tcsetattr (0, TCSANOW, &oldtty);
1476 fcntl(0, F_SETFL, old_fd0_flags);
1479 static void term_init(void)
1481 struct termios tty;
1483 tcgetattr (0, &tty);
1484 oldtty = tty;
1485 old_fd0_flags = fcntl(0, F_GETFL);
1487 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1488 |INLCR|IGNCR|ICRNL|IXON);
1489 tty.c_oflag |= OPOST;
1490 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1491 /* if graphical mode, we allow Ctrl-C handling */
1492 if (nographic)
1493 tty.c_lflag &= ~ISIG;
1494 tty.c_cflag &= ~(CSIZE|PARENB);
1495 tty.c_cflag |= CS8;
1496 tty.c_cc[VMIN] = 1;
1497 tty.c_cc[VTIME] = 0;
1499 tcsetattr (0, TCSANOW, &tty);
1501 atexit(term_exit);
1503 fcntl(0, F_SETFL, O_NONBLOCK);
1506 CharDriverState *qemu_chr_open_stdio(void)
1508 CharDriverState *chr;
1510 if (nographic) {
1511 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1512 return NULL;
1513 chr = qemu_chr_open_fd(0, 1);
1514 if (stdio_nb_clients == 0)
1515 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1516 client_index = stdio_nb_clients;
1517 } else {
1518 if (stdio_nb_clients != 0)
1519 return NULL;
1520 chr = qemu_chr_open_fd(0, 1);
1522 stdio_clients[stdio_nb_clients++] = chr;
1523 if (stdio_nb_clients == 1) {
1524 /* set the terminal in raw mode */
1525 term_init();
1527 return chr;
1530 #if defined(__linux__)
1531 CharDriverState *qemu_chr_open_pty(void)
1533 struct termios tty;
1534 char slave_name[1024];
1535 int master_fd, slave_fd;
1537 /* Not satisfying */
1538 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1539 return NULL;
1542 /* Disabling local echo and line-buffered output */
1543 tcgetattr (master_fd, &tty);
1544 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1545 tty.c_cc[VMIN] = 1;
1546 tty.c_cc[VTIME] = 0;
1547 tcsetattr (master_fd, TCSAFLUSH, &tty);
1549 fprintf(stderr, "char device redirected to %s\n", slave_name);
1550 return qemu_chr_open_fd(master_fd, master_fd);
1553 static void tty_serial_init(int fd, int speed,
1554 int parity, int data_bits, int stop_bits)
1556 struct termios tty;
1557 speed_t spd;
1559 #if 0
1560 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1561 speed, parity, data_bits, stop_bits);
1562 #endif
1563 tcgetattr (fd, &tty);
1565 switch(speed) {
1566 case 50:
1567 spd = B50;
1568 break;
1569 case 75:
1570 spd = B75;
1571 break;
1572 case 300:
1573 spd = B300;
1574 break;
1575 case 600:
1576 spd = B600;
1577 break;
1578 case 1200:
1579 spd = B1200;
1580 break;
1581 case 2400:
1582 spd = B2400;
1583 break;
1584 case 4800:
1585 spd = B4800;
1586 break;
1587 case 9600:
1588 spd = B9600;
1589 break;
1590 case 19200:
1591 spd = B19200;
1592 break;
1593 case 38400:
1594 spd = B38400;
1595 break;
1596 case 57600:
1597 spd = B57600;
1598 break;
1599 default:
1600 case 115200:
1601 spd = B115200;
1602 break;
1605 cfsetispeed(&tty, spd);
1606 cfsetospeed(&tty, spd);
1608 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1609 |INLCR|IGNCR|ICRNL|IXON);
1610 tty.c_oflag |= OPOST;
1611 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1612 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1613 switch(data_bits) {
1614 default:
1615 case 8:
1616 tty.c_cflag |= CS8;
1617 break;
1618 case 7:
1619 tty.c_cflag |= CS7;
1620 break;
1621 case 6:
1622 tty.c_cflag |= CS6;
1623 break;
1624 case 5:
1625 tty.c_cflag |= CS5;
1626 break;
1628 switch(parity) {
1629 default:
1630 case 'N':
1631 break;
1632 case 'E':
1633 tty.c_cflag |= PARENB;
1634 break;
1635 case 'O':
1636 tty.c_cflag |= PARENB | PARODD;
1637 break;
1640 tcsetattr (fd, TCSANOW, &tty);
1643 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1645 FDCharDriver *s = chr->opaque;
1647 switch(cmd) {
1648 case CHR_IOCTL_SERIAL_SET_PARAMS:
1650 QEMUSerialSetParams *ssp = arg;
1651 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1652 ssp->data_bits, ssp->stop_bits);
1654 break;
1655 case CHR_IOCTL_SERIAL_SET_BREAK:
1657 int enable = *(int *)arg;
1658 if (enable)
1659 tcsendbreak(s->fd_in, 1);
1661 break;
1662 default:
1663 return -ENOTSUP;
1665 return 0;
1668 CharDriverState *qemu_chr_open_tty(const char *filename)
1670 CharDriverState *chr;
1671 int fd;
1673 fd = open(filename, O_RDWR | O_NONBLOCK);
1674 if (fd < 0)
1675 return NULL;
1676 fcntl(fd, F_SETFL, O_NONBLOCK);
1677 tty_serial_init(fd, 115200, 'N', 8, 1);
1678 chr = qemu_chr_open_fd(fd, fd);
1679 if (!chr)
1680 return NULL;
1681 chr->chr_ioctl = tty_serial_ioctl;
1682 return chr;
1685 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1687 int fd = (int)chr->opaque;
1688 uint8_t b;
1690 switch(cmd) {
1691 case CHR_IOCTL_PP_READ_DATA:
1692 if (ioctl(fd, PPRDATA, &b) < 0)
1693 return -ENOTSUP;
1694 *(uint8_t *)arg = b;
1695 break;
1696 case CHR_IOCTL_PP_WRITE_DATA:
1697 b = *(uint8_t *)arg;
1698 if (ioctl(fd, PPWDATA, &b) < 0)
1699 return -ENOTSUP;
1700 break;
1701 case CHR_IOCTL_PP_READ_CONTROL:
1702 if (ioctl(fd, PPRCONTROL, &b) < 0)
1703 return -ENOTSUP;
1704 *(uint8_t *)arg = b;
1705 break;
1706 case CHR_IOCTL_PP_WRITE_CONTROL:
1707 b = *(uint8_t *)arg;
1708 if (ioctl(fd, PPWCONTROL, &b) < 0)
1709 return -ENOTSUP;
1710 break;
1711 case CHR_IOCTL_PP_READ_STATUS:
1712 if (ioctl(fd, PPRSTATUS, &b) < 0)
1713 return -ENOTSUP;
1714 *(uint8_t *)arg = b;
1715 break;
1716 default:
1717 return -ENOTSUP;
1719 return 0;
1722 CharDriverState *qemu_chr_open_pp(const char *filename)
1724 CharDriverState *chr;
1725 int fd;
1727 fd = open(filename, O_RDWR);
1728 if (fd < 0)
1729 return NULL;
1731 if (ioctl(fd, PPCLAIM) < 0) {
1732 close(fd);
1733 return NULL;
1736 chr = qemu_mallocz(sizeof(CharDriverState));
1737 if (!chr) {
1738 close(fd);
1739 return NULL;
1741 chr->opaque = (void *)fd;
1742 chr->chr_write = null_chr_write;
1743 chr->chr_add_read_handler = null_chr_add_read_handler;
1744 chr->chr_ioctl = pp_ioctl;
1745 return chr;
1748 #else
1749 CharDriverState *qemu_chr_open_pty(void)
1751 return NULL;
1753 #endif
1755 #endif /* !defined(_WIN32) */
1757 #ifdef _WIN32
1758 typedef struct {
1759 IOCanRWHandler *fd_can_read;
1760 IOReadHandler *fd_read;
1761 void *win_opaque;
1762 int max_size;
1763 HANDLE hcom, hrecv, hsend;
1764 OVERLAPPED orecv, osend;
1765 BOOL fpipe;
1766 DWORD len;
1767 } WinCharState;
1769 #define NSENDBUF 2048
1770 #define NRECVBUF 2048
1771 #define MAXCONNECT 1
1772 #define NTIMEOUT 5000
1774 static int win_chr_poll(void *opaque);
1775 static int win_chr_pipe_poll(void *opaque);
1777 static void win_chr_close2(WinCharState *s)
1779 if (s->hsend) {
1780 CloseHandle(s->hsend);
1781 s->hsend = NULL;
1783 if (s->hrecv) {
1784 CloseHandle(s->hrecv);
1785 s->hrecv = NULL;
1787 if (s->hcom) {
1788 CloseHandle(s->hcom);
1789 s->hcom = NULL;
1791 if (s->fpipe)
1792 qemu_del_polling_cb(win_chr_pipe_poll, s);
1793 else
1794 qemu_del_polling_cb(win_chr_poll, s);
1797 static void win_chr_close(CharDriverState *chr)
1799 WinCharState *s = chr->opaque;
1800 win_chr_close2(s);
1803 static int win_chr_init(WinCharState *s, const char *filename)
1805 COMMCONFIG comcfg;
1806 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1807 COMSTAT comstat;
1808 DWORD size;
1809 DWORD err;
1811 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1812 if (!s->hsend) {
1813 fprintf(stderr, "Failed CreateEvent\n");
1814 goto fail;
1816 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1817 if (!s->hrecv) {
1818 fprintf(stderr, "Failed CreateEvent\n");
1819 goto fail;
1822 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1823 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1824 if (s->hcom == INVALID_HANDLE_VALUE) {
1825 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1826 s->hcom = NULL;
1827 goto fail;
1830 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1831 fprintf(stderr, "Failed SetupComm\n");
1832 goto fail;
1835 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1836 size = sizeof(COMMCONFIG);
1837 GetDefaultCommConfig(filename, &comcfg, &size);
1838 comcfg.dcb.DCBlength = sizeof(DCB);
1839 CommConfigDialog(filename, NULL, &comcfg);
1841 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1842 fprintf(stderr, "Failed SetCommState\n");
1843 goto fail;
1846 if (!SetCommMask(s->hcom, EV_ERR)) {
1847 fprintf(stderr, "Failed SetCommMask\n");
1848 goto fail;
1851 cto.ReadIntervalTimeout = MAXDWORD;
1852 if (!SetCommTimeouts(s->hcom, &cto)) {
1853 fprintf(stderr, "Failed SetCommTimeouts\n");
1854 goto fail;
1857 if (!ClearCommError(s->hcom, &err, &comstat)) {
1858 fprintf(stderr, "Failed ClearCommError\n");
1859 goto fail;
1861 qemu_add_polling_cb(win_chr_poll, s);
1862 return 0;
1864 fail:
1865 win_chr_close2(s);
1866 return -1;
1869 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1871 WinCharState *s = chr->opaque;
1872 DWORD len, ret, size, err;
1874 len = len1;
1875 ZeroMemory(&s->osend, sizeof(s->osend));
1876 s->osend.hEvent = s->hsend;
1877 while (len > 0) {
1878 if (s->hsend)
1879 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1880 else
1881 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1882 if (!ret) {
1883 err = GetLastError();
1884 if (err == ERROR_IO_PENDING) {
1885 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1886 if (ret) {
1887 buf += size;
1888 len -= size;
1889 } else {
1890 break;
1892 } else {
1893 break;
1895 } else {
1896 buf += size;
1897 len -= size;
1900 return len1 - len;
1903 static int win_chr_read_poll(WinCharState *s)
1905 s->max_size = s->fd_can_read(s->win_opaque);
1906 return s->max_size;
1909 static void win_chr_readfile(WinCharState *s)
1911 int ret, err;
1912 uint8_t buf[1024];
1913 DWORD size;
1915 ZeroMemory(&s->orecv, sizeof(s->orecv));
1916 s->orecv.hEvent = s->hrecv;
1917 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1918 if (!ret) {
1919 err = GetLastError();
1920 if (err == ERROR_IO_PENDING) {
1921 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1925 if (size > 0) {
1926 s->fd_read(s->win_opaque, buf, size);
1930 static void win_chr_read(WinCharState *s)
1932 if (s->len > s->max_size)
1933 s->len = s->max_size;
1934 if (s->len == 0)
1935 return;
1937 win_chr_readfile(s);
1940 static int win_chr_poll(void *opaque)
1942 WinCharState *s = opaque;
1943 COMSTAT status;
1944 DWORD comerr;
1946 ClearCommError(s->hcom, &comerr, &status);
1947 if (status.cbInQue > 0) {
1948 s->len = status.cbInQue;
1949 win_chr_read_poll(s);
1950 win_chr_read(s);
1951 return 1;
1953 return 0;
1956 static void win_chr_add_read_handler(CharDriverState *chr,
1957 IOCanRWHandler *fd_can_read,
1958 IOReadHandler *fd_read, void *opaque)
1960 WinCharState *s = chr->opaque;
1962 s->fd_can_read = fd_can_read;
1963 s->fd_read = fd_read;
1964 s->win_opaque = opaque;
1967 CharDriverState *qemu_chr_open_win(const char *filename)
1969 CharDriverState *chr;
1970 WinCharState *s;
1972 chr = qemu_mallocz(sizeof(CharDriverState));
1973 if (!chr)
1974 return NULL;
1975 s = qemu_mallocz(sizeof(WinCharState));
1976 if (!s) {
1977 free(chr);
1978 return NULL;
1980 chr->opaque = s;
1981 chr->chr_write = win_chr_write;
1982 chr->chr_add_read_handler = win_chr_add_read_handler;
1983 chr->chr_close = win_chr_close;
1985 if (win_chr_init(s, filename) < 0) {
1986 free(s);
1987 free(chr);
1988 return NULL;
1990 return chr;
1993 static int win_chr_pipe_poll(void *opaque)
1995 WinCharState *s = opaque;
1996 DWORD size;
1998 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1999 if (size > 0) {
2000 s->len = size;
2001 win_chr_read_poll(s);
2002 win_chr_read(s);
2003 return 1;
2005 return 0;
2008 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2010 OVERLAPPED ov;
2011 int ret;
2012 DWORD size;
2013 char openname[256];
2015 s->fpipe = TRUE;
2017 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2018 if (!s->hsend) {
2019 fprintf(stderr, "Failed CreateEvent\n");
2020 goto fail;
2022 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2023 if (!s->hrecv) {
2024 fprintf(stderr, "Failed CreateEvent\n");
2025 goto fail;
2028 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2029 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2030 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2031 PIPE_WAIT,
2032 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2033 if (s->hcom == INVALID_HANDLE_VALUE) {
2034 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2035 s->hcom = NULL;
2036 goto fail;
2039 ZeroMemory(&ov, sizeof(ov));
2040 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2041 ret = ConnectNamedPipe(s->hcom, &ov);
2042 if (ret) {
2043 fprintf(stderr, "Failed ConnectNamedPipe\n");
2044 goto fail;
2047 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2048 if (!ret) {
2049 fprintf(stderr, "Failed GetOverlappedResult\n");
2050 if (ov.hEvent) {
2051 CloseHandle(ov.hEvent);
2052 ov.hEvent = NULL;
2054 goto fail;
2057 if (ov.hEvent) {
2058 CloseHandle(ov.hEvent);
2059 ov.hEvent = NULL;
2061 qemu_add_polling_cb(win_chr_pipe_poll, s);
2062 return 0;
2064 fail:
2065 win_chr_close2(s);
2066 return -1;
2070 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2072 CharDriverState *chr;
2073 WinCharState *s;
2075 chr = qemu_mallocz(sizeof(CharDriverState));
2076 if (!chr)
2077 return NULL;
2078 s = qemu_mallocz(sizeof(WinCharState));
2079 if (!s) {
2080 free(chr);
2081 return NULL;
2083 chr->opaque = s;
2084 chr->chr_write = win_chr_write;
2085 chr->chr_add_read_handler = win_chr_add_read_handler;
2086 chr->chr_close = win_chr_close;
2088 if (win_chr_pipe_init(s, filename) < 0) {
2089 free(s);
2090 free(chr);
2091 return NULL;
2093 return chr;
2096 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2098 CharDriverState *chr;
2099 WinCharState *s;
2101 chr = qemu_mallocz(sizeof(CharDriverState));
2102 if (!chr)
2103 return NULL;
2104 s = qemu_mallocz(sizeof(WinCharState));
2105 if (!s) {
2106 free(chr);
2107 return NULL;
2109 s->hcom = fd_out;
2110 chr->opaque = s;
2111 chr->chr_write = win_chr_write;
2112 chr->chr_add_read_handler = win_chr_add_read_handler;
2113 return chr;
2116 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2118 HANDLE fd_out;
2120 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2121 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2122 if (fd_out == INVALID_HANDLE_VALUE)
2123 return NULL;
2125 return qemu_chr_open_win_file(fd_out);
2127 #endif
2129 /***********************************************************/
2130 /* UDP Net console */
2132 typedef struct {
2133 IOCanRWHandler *fd_can_read;
2134 IOReadHandler *fd_read;
2135 void *fd_opaque;
2136 int fd;
2137 struct sockaddr_in daddr;
2138 char buf[1024];
2139 int bufcnt;
2140 int bufptr;
2141 int max_size;
2142 } NetCharDriver;
2144 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2146 NetCharDriver *s = chr->opaque;
2148 return sendto(s->fd, buf, len, 0,
2149 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2152 static int udp_chr_read_poll(void *opaque)
2154 CharDriverState *chr = opaque;
2155 NetCharDriver *s = chr->opaque;
2157 s->max_size = s->fd_can_read(s->fd_opaque);
2159 /* If there were any stray characters in the queue process them
2160 * first
2162 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2163 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2164 s->bufptr++;
2165 s->max_size = s->fd_can_read(s->fd_opaque);
2167 return s->max_size;
2170 static void udp_chr_read(void *opaque)
2172 CharDriverState *chr = opaque;
2173 NetCharDriver *s = chr->opaque;
2175 if (s->max_size == 0)
2176 return;
2177 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2178 s->bufptr = s->bufcnt;
2179 if (s->bufcnt <= 0)
2180 return;
2182 s->bufptr = 0;
2183 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2184 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2185 s->bufptr++;
2186 s->max_size = s->fd_can_read(s->fd_opaque);
2190 static void udp_chr_add_read_handler(CharDriverState *chr,
2191 IOCanRWHandler *fd_can_read,
2192 IOReadHandler *fd_read, void *opaque)
2194 NetCharDriver *s = chr->opaque;
2196 if (s->fd >= 0) {
2197 s->fd_can_read = fd_can_read;
2198 s->fd_read = fd_read;
2199 s->fd_opaque = opaque;
2200 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2201 udp_chr_read, NULL, chr);
2205 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2206 int parse_host_src_port(struct sockaddr_in *haddr,
2207 struct sockaddr_in *saddr,
2208 const char *str);
2210 CharDriverState *qemu_chr_open_udp(const char *def)
2212 CharDriverState *chr = NULL;
2213 NetCharDriver *s = NULL;
2214 int fd = -1;
2215 struct sockaddr_in saddr;
2217 chr = qemu_mallocz(sizeof(CharDriverState));
2218 if (!chr)
2219 goto return_err;
2220 s = qemu_mallocz(sizeof(NetCharDriver));
2221 if (!s)
2222 goto return_err;
2224 fd = socket(PF_INET, SOCK_DGRAM, 0);
2225 if (fd < 0) {
2226 perror("socket(PF_INET, SOCK_DGRAM)");
2227 goto return_err;
2230 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2231 printf("Could not parse: %s\n", def);
2232 goto return_err;
2235 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2237 perror("bind");
2238 goto return_err;
2241 s->fd = fd;
2242 s->bufcnt = 0;
2243 s->bufptr = 0;
2244 chr->opaque = s;
2245 chr->chr_write = udp_chr_write;
2246 chr->chr_add_read_handler = udp_chr_add_read_handler;
2247 return chr;
2249 return_err:
2250 if (chr)
2251 free(chr);
2252 if (s)
2253 free(s);
2254 if (fd >= 0)
2255 closesocket(fd);
2256 return NULL;
2259 /***********************************************************/
2260 /* TCP Net console */
2262 typedef struct {
2263 IOCanRWHandler *fd_can_read;
2264 IOReadHandler *fd_read;
2265 void *fd_opaque;
2266 int fd, listen_fd;
2267 int connected;
2268 int max_size;
2269 int do_telnetopt;
2270 } TCPCharDriver;
2272 static void tcp_chr_accept(void *opaque);
2274 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2276 TCPCharDriver *s = chr->opaque;
2277 if (s->connected) {
2278 return send_all(s->fd, buf, len);
2279 } else {
2280 /* XXX: indicate an error ? */
2281 return len;
2285 static int tcp_chr_read_poll(void *opaque)
2287 CharDriverState *chr = opaque;
2288 TCPCharDriver *s = chr->opaque;
2289 if (!s->connected)
2290 return 0;
2291 s->max_size = s->fd_can_read(s->fd_opaque);
2292 return s->max_size;
2295 #define IAC 255
2296 #define IAC_BREAK 243
2297 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2298 TCPCharDriver *s,
2299 char *buf, int *size)
2301 /* Handle any telnet client's basic IAC options to satisfy char by
2302 * char mode with no echo. All IAC options will be removed from
2303 * the buf and the do_telnetopt variable will be used to track the
2304 * state of the width of the IAC information.
2306 * IAC commands come in sets of 3 bytes with the exception of the
2307 * "IAC BREAK" command and the double IAC.
2310 int i;
2311 int j = 0;
2313 for (i = 0; i < *size; i++) {
2314 if (s->do_telnetopt > 1) {
2315 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2316 /* Double IAC means send an IAC */
2317 if (j != i)
2318 buf[j] = buf[i];
2319 j++;
2320 s->do_telnetopt = 1;
2321 } else {
2322 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2323 /* Handle IAC break commands by sending a serial break */
2324 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2325 s->do_telnetopt++;
2327 s->do_telnetopt++;
2329 if (s->do_telnetopt >= 4) {
2330 s->do_telnetopt = 1;
2332 } else {
2333 if ((unsigned char)buf[i] == IAC) {
2334 s->do_telnetopt = 2;
2335 } else {
2336 if (j != i)
2337 buf[j] = buf[i];
2338 j++;
2342 *size = j;
2345 static void tcp_chr_read(void *opaque)
2347 CharDriverState *chr = opaque;
2348 TCPCharDriver *s = chr->opaque;
2349 uint8_t buf[1024];
2350 int len, size;
2352 if (!s->connected || s->max_size <= 0)
2353 return;
2354 len = sizeof(buf);
2355 if (len > s->max_size)
2356 len = s->max_size;
2357 size = recv(s->fd, buf, len, 0);
2358 if (size == 0) {
2359 /* connection closed */
2360 s->connected = 0;
2361 if (s->listen_fd >= 0) {
2362 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2364 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2365 closesocket(s->fd);
2366 s->fd = -1;
2367 } else if (size > 0) {
2368 if (s->do_telnetopt)
2369 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2370 if (size > 0)
2371 s->fd_read(s->fd_opaque, buf, size);
2375 static void tcp_chr_add_read_handler(CharDriverState *chr,
2376 IOCanRWHandler *fd_can_read,
2377 IOReadHandler *fd_read, void *opaque)
2379 TCPCharDriver *s = chr->opaque;
2381 s->fd_can_read = fd_can_read;
2382 s->fd_read = fd_read;
2383 s->fd_opaque = opaque;
2386 static void tcp_chr_connect(void *opaque)
2388 CharDriverState *chr = opaque;
2389 TCPCharDriver *s = chr->opaque;
2391 s->connected = 1;
2392 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2393 tcp_chr_read, NULL, chr);
2396 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2397 static void tcp_chr_telnet_init(int fd)
2399 char buf[3];
2400 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2401 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2402 send(fd, (char *)buf, 3, 0);
2403 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2404 send(fd, (char *)buf, 3, 0);
2405 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2406 send(fd, (char *)buf, 3, 0);
2407 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2408 send(fd, (char *)buf, 3, 0);
2411 static void tcp_chr_accept(void *opaque)
2413 CharDriverState *chr = opaque;
2414 TCPCharDriver *s = chr->opaque;
2415 struct sockaddr_in saddr;
2416 socklen_t len;
2417 int fd;
2419 for(;;) {
2420 len = sizeof(saddr);
2421 fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2422 if (fd < 0 && errno != EINTR) {
2423 return;
2424 } else if (fd >= 0) {
2425 if (s->do_telnetopt)
2426 tcp_chr_telnet_init(fd);
2427 break;
2430 socket_set_nonblock(fd);
2431 s->fd = fd;
2432 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2433 tcp_chr_connect(chr);
2436 static void tcp_chr_close(CharDriverState *chr)
2438 TCPCharDriver *s = chr->opaque;
2439 if (s->fd >= 0)
2440 closesocket(s->fd);
2441 if (s->listen_fd >= 0)
2442 closesocket(s->listen_fd);
2443 qemu_free(s);
2446 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2447 int is_telnet)
2449 CharDriverState *chr = NULL;
2450 TCPCharDriver *s = NULL;
2451 int fd = -1, ret, err, val;
2452 int is_listen = 0;
2453 int is_waitconnect = 1;
2454 const char *ptr;
2455 struct sockaddr_in saddr;
2457 if (parse_host_port(&saddr, host_str) < 0)
2458 goto fail;
2460 ptr = host_str;
2461 while((ptr = strchr(ptr,','))) {
2462 ptr++;
2463 if (!strncmp(ptr,"server",6)) {
2464 is_listen = 1;
2465 } else if (!strncmp(ptr,"nowait",6)) {
2466 is_waitconnect = 0;
2467 } else {
2468 printf("Unknown option: %s\n", ptr);
2469 goto fail;
2472 if (!is_listen)
2473 is_waitconnect = 0;
2475 chr = qemu_mallocz(sizeof(CharDriverState));
2476 if (!chr)
2477 goto fail;
2478 s = qemu_mallocz(sizeof(TCPCharDriver));
2479 if (!s)
2480 goto fail;
2482 fd = socket(PF_INET, SOCK_STREAM, 0);
2483 if (fd < 0)
2484 goto fail;
2486 if (!is_waitconnect)
2487 socket_set_nonblock(fd);
2489 s->connected = 0;
2490 s->fd = -1;
2491 s->listen_fd = -1;
2492 if (is_listen) {
2493 /* allow fast reuse */
2494 val = 1;
2495 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2497 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2498 if (ret < 0)
2499 goto fail;
2500 ret = listen(fd, 0);
2501 if (ret < 0)
2502 goto fail;
2503 s->listen_fd = fd;
2504 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2505 if (is_telnet)
2506 s->do_telnetopt = 1;
2507 } else {
2508 for(;;) {
2509 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2510 if (ret < 0) {
2511 err = socket_error();
2512 if (err == EINTR || err == EWOULDBLOCK) {
2513 } else if (err == EINPROGRESS) {
2514 break;
2515 } else {
2516 goto fail;
2518 } else {
2519 s->connected = 1;
2520 break;
2523 s->fd = fd;
2524 if (s->connected)
2525 tcp_chr_connect(chr);
2526 else
2527 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2530 chr->opaque = s;
2531 chr->chr_write = tcp_chr_write;
2532 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2533 chr->chr_close = tcp_chr_close;
2534 if (is_listen && is_waitconnect) {
2535 printf("QEMU waiting for connection on: %s\n", host_str);
2536 tcp_chr_accept(chr);
2537 socket_set_nonblock(s->listen_fd);
2540 return chr;
2541 fail:
2542 if (fd >= 0)
2543 closesocket(fd);
2544 qemu_free(s);
2545 qemu_free(chr);
2546 return NULL;
2549 CharDriverState *qemu_chr_open(const char *filename)
2551 const char *p;
2553 if (!strcmp(filename, "vc")) {
2554 return text_console_init(&display_state);
2555 } else if (!strcmp(filename, "null")) {
2556 return qemu_chr_open_null();
2557 } else
2558 if (strstart(filename, "tcp:", &p)) {
2559 return qemu_chr_open_tcp(p, 0);
2560 } else
2561 if (strstart(filename, "telnet:", &p)) {
2562 return qemu_chr_open_tcp(p, 1);
2563 } else
2564 if (strstart(filename, "udp:", &p)) {
2565 return qemu_chr_open_udp(p);
2566 } else
2567 #ifndef _WIN32
2568 if (strstart(filename, "file:", &p)) {
2569 return qemu_chr_open_file_out(p);
2570 } else if (strstart(filename, "pipe:", &p)) {
2571 return qemu_chr_open_pipe(p);
2572 } else if (!strcmp(filename, "pty")) {
2573 return qemu_chr_open_pty();
2574 } else if (!strcmp(filename, "stdio")) {
2575 return qemu_chr_open_stdio();
2576 } else
2577 #endif
2578 #if defined(__linux__)
2579 if (strstart(filename, "/dev/parport", NULL)) {
2580 return qemu_chr_open_pp(filename);
2581 } else
2582 if (strstart(filename, "/dev/", NULL)) {
2583 return qemu_chr_open_tty(filename);
2584 } else
2585 #endif
2586 #ifdef _WIN32
2587 if (strstart(filename, "COM", NULL)) {
2588 return qemu_chr_open_win(filename);
2589 } else
2590 if (strstart(filename, "pipe:", &p)) {
2591 return qemu_chr_open_win_pipe(p);
2592 } else
2593 if (strstart(filename, "file:", &p)) {
2594 return qemu_chr_open_win_file_out(p);
2596 #endif
2598 return NULL;
2602 void qemu_chr_close(CharDriverState *chr)
2604 if (chr->chr_close)
2605 chr->chr_close(chr);
2608 /***********************************************************/
2609 /* network device redirectors */
2611 void hex_dump(FILE *f, const uint8_t *buf, int size)
2613 int len, i, j, c;
2615 for(i=0;i<size;i+=16) {
2616 len = size - i;
2617 if (len > 16)
2618 len = 16;
2619 fprintf(f, "%08x ", i);
2620 for(j=0;j<16;j++) {
2621 if (j < len)
2622 fprintf(f, " %02x", buf[i+j]);
2623 else
2624 fprintf(f, " ");
2626 fprintf(f, " ");
2627 for(j=0;j<len;j++) {
2628 c = buf[i+j];
2629 if (c < ' ' || c > '~')
2630 c = '.';
2631 fprintf(f, "%c", c);
2633 fprintf(f, "\n");
2637 static int parse_macaddr(uint8_t *macaddr, const char *p)
2639 int i;
2640 for(i = 0; i < 6; i++) {
2641 macaddr[i] = strtol(p, (char **)&p, 16);
2642 if (i == 5) {
2643 if (*p != '\0')
2644 return -1;
2645 } else {
2646 if (*p != ':')
2647 return -1;
2648 p++;
2651 return 0;
2654 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2656 const char *p, *p1;
2657 int len;
2658 p = *pp;
2659 p1 = strchr(p, sep);
2660 if (!p1)
2661 return -1;
2662 len = p1 - p;
2663 p1++;
2664 if (buf_size > 0) {
2665 if (len > buf_size - 1)
2666 len = buf_size - 1;
2667 memcpy(buf, p, len);
2668 buf[len] = '\0';
2670 *pp = p1;
2671 return 0;
2674 int parse_host_src_port(struct sockaddr_in *haddr,
2675 struct sockaddr_in *saddr,
2676 const char *input_str)
2678 char *str = strdup(input_str);
2679 char *host_str = str;
2680 char *src_str;
2681 char *ptr;
2684 * Chop off any extra arguments at the end of the string which
2685 * would start with a comma, then fill in the src port information
2686 * if it was provided else use the "any address" and "any port".
2688 if ((ptr = strchr(str,',')))
2689 *ptr = '\0';
2691 if ((src_str = strchr(input_str,'@'))) {
2692 *src_str = '\0';
2693 src_str++;
2696 if (parse_host_port(haddr, host_str) < 0)
2697 goto fail;
2699 if (!src_str || *src_str == '\0')
2700 src_str = ":0";
2702 if (parse_host_port(saddr, src_str) < 0)
2703 goto fail;
2705 free(str);
2706 return(0);
2708 fail:
2709 free(str);
2710 return -1;
2713 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2715 char buf[512];
2716 struct hostent *he;
2717 const char *p, *r;
2718 int port;
2720 p = str;
2721 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2722 return -1;
2723 saddr->sin_family = AF_INET;
2724 if (buf[0] == '\0') {
2725 saddr->sin_addr.s_addr = 0;
2726 } else {
2727 if (isdigit(buf[0])) {
2728 if (!inet_aton(buf, &saddr->sin_addr))
2729 return -1;
2730 } else {
2731 if ((he = gethostbyname(buf)) == NULL)
2732 return - 1;
2733 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2736 port = strtol(p, (char **)&r, 0);
2737 if (r == p)
2738 return -1;
2739 saddr->sin_port = htons(port);
2740 return 0;
2743 /* find or alloc a new VLAN */
2744 VLANState *qemu_find_vlan(int id)
2746 VLANState **pvlan, *vlan;
2747 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2748 if (vlan->id == id)
2749 return vlan;
2751 vlan = qemu_mallocz(sizeof(VLANState));
2752 if (!vlan)
2753 return NULL;
2754 vlan->id = id;
2755 vlan->next = NULL;
2756 pvlan = &first_vlan;
2757 while (*pvlan != NULL)
2758 pvlan = &(*pvlan)->next;
2759 *pvlan = vlan;
2760 return vlan;
2763 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2764 IOReadHandler *fd_read,
2765 IOCanRWHandler *fd_can_read,
2766 void *opaque)
2768 VLANClientState *vc, **pvc;
2769 vc = qemu_mallocz(sizeof(VLANClientState));
2770 if (!vc)
2771 return NULL;
2772 vc->fd_read = fd_read;
2773 vc->fd_can_read = fd_can_read;
2774 vc->opaque = opaque;
2775 vc->vlan = vlan;
2777 vc->next = NULL;
2778 pvc = &vlan->first_client;
2779 while (*pvc != NULL)
2780 pvc = &(*pvc)->next;
2781 *pvc = vc;
2782 return vc;
2785 int qemu_can_send_packet(VLANClientState *vc1)
2787 VLANState *vlan = vc1->vlan;
2788 VLANClientState *vc;
2790 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2791 if (vc != vc1) {
2792 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2793 return 0;
2796 return 1;
2799 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2801 VLANState *vlan = vc1->vlan;
2802 VLANClientState *vc;
2804 #if 0
2805 printf("vlan %d send:\n", vlan->id);
2806 hex_dump(stdout, buf, size);
2807 #endif
2808 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2809 if (vc != vc1) {
2810 vc->fd_read(vc->opaque, buf, size);
2815 #if defined(CONFIG_SLIRP)
2817 /* slirp network adapter */
2819 static int slirp_inited;
2820 static VLANClientState *slirp_vc;
2822 int slirp_can_output(void)
2824 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2827 void slirp_output(const uint8_t *pkt, int pkt_len)
2829 #if 0
2830 printf("slirp output:\n");
2831 hex_dump(stdout, pkt, pkt_len);
2832 #endif
2833 if (!slirp_vc)
2834 return;
2835 qemu_send_packet(slirp_vc, pkt, pkt_len);
2838 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2840 #if 0
2841 printf("slirp input:\n");
2842 hex_dump(stdout, buf, size);
2843 #endif
2844 slirp_input(buf, size);
2847 static int net_slirp_init(VLANState *vlan)
2849 if (!slirp_inited) {
2850 slirp_inited = 1;
2851 slirp_init();
2853 slirp_vc = qemu_new_vlan_client(vlan,
2854 slirp_receive, NULL, NULL);
2855 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2856 return 0;
2859 static void net_slirp_redir(const char *redir_str)
2861 int is_udp;
2862 char buf[256], *r;
2863 const char *p;
2864 struct in_addr guest_addr;
2865 int host_port, guest_port;
2867 if (!slirp_inited) {
2868 slirp_inited = 1;
2869 slirp_init();
2872 p = redir_str;
2873 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2874 goto fail;
2875 if (!strcmp(buf, "tcp")) {
2876 is_udp = 0;
2877 } else if (!strcmp(buf, "udp")) {
2878 is_udp = 1;
2879 } else {
2880 goto fail;
2883 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2884 goto fail;
2885 host_port = strtol(buf, &r, 0);
2886 if (r == buf)
2887 goto fail;
2889 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2890 goto fail;
2891 if (buf[0] == '\0') {
2892 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2894 if (!inet_aton(buf, &guest_addr))
2895 goto fail;
2897 guest_port = strtol(p, &r, 0);
2898 if (r == p)
2899 goto fail;
2901 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2902 fprintf(stderr, "qemu: could not set up redirection\n");
2903 exit(1);
2905 return;
2906 fail:
2907 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2908 exit(1);
2911 #ifndef _WIN32
2913 char smb_dir[1024];
2915 static void smb_exit(void)
2917 DIR *d;
2918 struct dirent *de;
2919 char filename[1024];
2921 /* erase all the files in the directory */
2922 d = opendir(smb_dir);
2923 for(;;) {
2924 de = readdir(d);
2925 if (!de)
2926 break;
2927 if (strcmp(de->d_name, ".") != 0 &&
2928 strcmp(de->d_name, "..") != 0) {
2929 snprintf(filename, sizeof(filename), "%s/%s",
2930 smb_dir, de->d_name);
2931 unlink(filename);
2934 closedir(d);
2935 rmdir(smb_dir);
2938 /* automatic user mode samba server configuration */
2939 void net_slirp_smb(const char *exported_dir)
2941 char smb_conf[1024];
2942 char smb_cmdline[1024];
2943 FILE *f;
2945 if (!slirp_inited) {
2946 slirp_inited = 1;
2947 slirp_init();
2950 /* XXX: better tmp dir construction */
2951 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2952 if (mkdir(smb_dir, 0700) < 0) {
2953 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2954 exit(1);
2956 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2958 f = fopen(smb_conf, "w");
2959 if (!f) {
2960 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2961 exit(1);
2963 fprintf(f,
2964 "[global]\n"
2965 "private dir=%s\n"
2966 "smb ports=0\n"
2967 "socket address=127.0.0.1\n"
2968 "pid directory=%s\n"
2969 "lock directory=%s\n"
2970 "log file=%s/log.smbd\n"
2971 "smb passwd file=%s/smbpasswd\n"
2972 "security = share\n"
2973 "[qemu]\n"
2974 "path=%s\n"
2975 "read only=no\n"
2976 "guest ok=yes\n",
2977 smb_dir,
2978 smb_dir,
2979 smb_dir,
2980 smb_dir,
2981 smb_dir,
2982 exported_dir
2984 fclose(f);
2985 atexit(smb_exit);
2987 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2988 smb_conf);
2990 slirp_add_exec(0, smb_cmdline, 4, 139);
2993 #endif /* !defined(_WIN32) */
2995 #endif /* CONFIG_SLIRP */
2997 #if !defined(_WIN32)
2999 typedef struct TAPState {
3000 VLANClientState *vc;
3001 int fd;
3002 } TAPState;
3004 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3006 TAPState *s = opaque;
3007 int ret;
3008 for(;;) {
3009 ret = write(s->fd, buf, size);
3010 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3011 } else {
3012 break;
3017 static void tap_send(void *opaque)
3019 TAPState *s = opaque;
3020 uint8_t buf[4096];
3021 int size;
3023 size = read(s->fd, buf, sizeof(buf));
3024 if (size > 0) {
3025 qemu_send_packet(s->vc, buf, size);
3029 /* fd support */
3031 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3033 TAPState *s;
3035 s = qemu_mallocz(sizeof(TAPState));
3036 if (!s)
3037 return NULL;
3038 s->fd = fd;
3039 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3040 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3041 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3042 return s;
3045 #ifdef _BSD
3046 static int tap_open(char *ifname, int ifname_size)
3048 int fd;
3049 char *dev;
3050 struct stat s;
3052 fd = open("/dev/tap", O_RDWR);
3053 if (fd < 0) {
3054 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3055 return -1;
3058 fstat(fd, &s);
3059 dev = devname(s.st_rdev, S_IFCHR);
3060 pstrcpy(ifname, ifname_size, dev);
3062 fcntl(fd, F_SETFL, O_NONBLOCK);
3063 return fd;
3065 #elif defined(__sun__)
3066 static int tap_open(char *ifname, int ifname_size)
3068 fprintf(stderr, "warning: tap_open not yet implemented\n");
3069 return -1;
3071 #else
3072 static int tap_open(char *ifname, int ifname_size)
3074 struct ifreq ifr;
3075 int fd, ret;
3077 fd = open("/dev/net/tun", O_RDWR);
3078 if (fd < 0) {
3079 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3080 return -1;
3082 memset(&ifr, 0, sizeof(ifr));
3083 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3084 if (ifname[0] != '\0')
3085 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3086 else
3087 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3088 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3089 if (ret != 0) {
3090 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3091 close(fd);
3092 return -1;
3094 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3095 fcntl(fd, F_SETFL, O_NONBLOCK);
3096 return fd;
3098 #endif
3100 static int net_tap_init(VLANState *vlan, const char *ifname1,
3101 const char *setup_script)
3103 TAPState *s;
3104 int pid, status, fd;
3105 char *args[3];
3106 char **parg;
3107 char ifname[128];
3109 if (ifname1 != NULL)
3110 pstrcpy(ifname, sizeof(ifname), ifname1);
3111 else
3112 ifname[0] = '\0';
3113 fd = tap_open(ifname, sizeof(ifname));
3114 if (fd < 0)
3115 return -1;
3117 if (!setup_script)
3118 setup_script = "";
3119 if (setup_script[0] != '\0') {
3120 /* try to launch network init script */
3121 pid = fork();
3122 if (pid >= 0) {
3123 if (pid == 0) {
3124 parg = args;
3125 *parg++ = (char *)setup_script;
3126 *parg++ = ifname;
3127 *parg++ = NULL;
3128 execv(setup_script, args);
3129 _exit(1);
3131 while (waitpid(pid, &status, 0) != pid);
3132 if (!WIFEXITED(status) ||
3133 WEXITSTATUS(status) != 0) {
3134 fprintf(stderr, "%s: could not launch network script\n",
3135 setup_script);
3136 return -1;
3140 s = net_tap_fd_init(vlan, fd);
3141 if (!s)
3142 return -1;
3143 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3144 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3145 return 0;
3148 #endif /* !_WIN32 */
3150 /* network connection */
3151 typedef struct NetSocketState {
3152 VLANClientState *vc;
3153 int fd;
3154 int state; /* 0 = getting length, 1 = getting data */
3155 int index;
3156 int packet_len;
3157 uint8_t buf[4096];
3158 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3159 } NetSocketState;
3161 typedef struct NetSocketListenState {
3162 VLANState *vlan;
3163 int fd;
3164 } NetSocketListenState;
3166 /* XXX: we consider we can send the whole packet without blocking */
3167 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3169 NetSocketState *s = opaque;
3170 uint32_t len;
3171 len = htonl(size);
3173 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3174 send_all(s->fd, buf, size);
3177 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3179 NetSocketState *s = opaque;
3180 sendto(s->fd, buf, size, 0,
3181 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3184 static void net_socket_send(void *opaque)
3186 NetSocketState *s = opaque;
3187 int l, size, err;
3188 uint8_t buf1[4096];
3189 const uint8_t *buf;
3191 size = recv(s->fd, buf1, sizeof(buf1), 0);
3192 if (size < 0) {
3193 err = socket_error();
3194 if (err != EWOULDBLOCK)
3195 goto eoc;
3196 } else if (size == 0) {
3197 /* end of connection */
3198 eoc:
3199 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3200 closesocket(s->fd);
3201 return;
3203 buf = buf1;
3204 while (size > 0) {
3205 /* reassemble a packet from the network */
3206 switch(s->state) {
3207 case 0:
3208 l = 4 - s->index;
3209 if (l > size)
3210 l = size;
3211 memcpy(s->buf + s->index, buf, l);
3212 buf += l;
3213 size -= l;
3214 s->index += l;
3215 if (s->index == 4) {
3216 /* got length */
3217 s->packet_len = ntohl(*(uint32_t *)s->buf);
3218 s->index = 0;
3219 s->state = 1;
3221 break;
3222 case 1:
3223 l = s->packet_len - s->index;
3224 if (l > size)
3225 l = size;
3226 memcpy(s->buf + s->index, buf, l);
3227 s->index += l;
3228 buf += l;
3229 size -= l;
3230 if (s->index >= s->packet_len) {
3231 qemu_send_packet(s->vc, s->buf, s->packet_len);
3232 s->index = 0;
3233 s->state = 0;
3235 break;
3240 static void net_socket_send_dgram(void *opaque)
3242 NetSocketState *s = opaque;
3243 int size;
3245 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3246 if (size < 0)
3247 return;
3248 if (size == 0) {
3249 /* end of connection */
3250 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3251 return;
3253 qemu_send_packet(s->vc, s->buf, size);
3256 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3258 struct ip_mreq imr;
3259 int fd;
3260 int val, ret;
3261 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3262 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3263 inet_ntoa(mcastaddr->sin_addr),
3264 (int)ntohl(mcastaddr->sin_addr.s_addr));
3265 return -1;
3268 fd = socket(PF_INET, SOCK_DGRAM, 0);
3269 if (fd < 0) {
3270 perror("socket(PF_INET, SOCK_DGRAM)");
3271 return -1;
3274 val = 1;
3275 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3276 (const char *)&val, sizeof(val));
3277 if (ret < 0) {
3278 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3279 goto fail;
3282 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3283 if (ret < 0) {
3284 perror("bind");
3285 goto fail;
3288 /* Add host to multicast group */
3289 imr.imr_multiaddr = mcastaddr->sin_addr;
3290 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3292 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3293 (const char *)&imr, sizeof(struct ip_mreq));
3294 if (ret < 0) {
3295 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3296 goto fail;
3299 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3300 val = 1;
3301 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3302 (const char *)&val, sizeof(val));
3303 if (ret < 0) {
3304 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3305 goto fail;
3308 socket_set_nonblock(fd);
3309 return fd;
3310 fail:
3311 if (fd >= 0)
3312 closesocket(fd);
3313 return -1;
3316 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3317 int is_connected)
3319 struct sockaddr_in saddr;
3320 int newfd;
3321 socklen_t saddr_len;
3322 NetSocketState *s;
3324 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3325 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3326 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3329 if (is_connected) {
3330 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3331 /* must be bound */
3332 if (saddr.sin_addr.s_addr==0) {
3333 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3334 fd);
3335 return NULL;
3337 /* clone dgram socket */
3338 newfd = net_socket_mcast_create(&saddr);
3339 if (newfd < 0) {
3340 /* error already reported by net_socket_mcast_create() */
3341 close(fd);
3342 return NULL;
3344 /* clone newfd to fd, close newfd */
3345 dup2(newfd, fd);
3346 close(newfd);
3348 } else {
3349 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3350 fd, strerror(errno));
3351 return NULL;
3355 s = qemu_mallocz(sizeof(NetSocketState));
3356 if (!s)
3357 return NULL;
3358 s->fd = fd;
3360 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3361 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3363 /* mcast: save bound address as dst */
3364 if (is_connected) s->dgram_dst=saddr;
3366 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3367 "socket: fd=%d (%s mcast=%s:%d)",
3368 fd, is_connected? "cloned" : "",
3369 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3370 return s;
3373 static void net_socket_connect(void *opaque)
3375 NetSocketState *s = opaque;
3376 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3379 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3380 int is_connected)
3382 NetSocketState *s;
3383 s = qemu_mallocz(sizeof(NetSocketState));
3384 if (!s)
3385 return NULL;
3386 s->fd = fd;
3387 s->vc = qemu_new_vlan_client(vlan,
3388 net_socket_receive, NULL, s);
3389 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3390 "socket: fd=%d", fd);
3391 if (is_connected) {
3392 net_socket_connect(s);
3393 } else {
3394 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3396 return s;
3399 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3400 int is_connected)
3402 int so_type=-1, optlen=sizeof(so_type);
3404 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3405 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3406 return NULL;
3408 switch(so_type) {
3409 case SOCK_DGRAM:
3410 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3411 case SOCK_STREAM:
3412 return net_socket_fd_init_stream(vlan, fd, is_connected);
3413 default:
3414 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3415 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3416 return net_socket_fd_init_stream(vlan, fd, is_connected);
3418 return NULL;
3421 static void net_socket_accept(void *opaque)
3423 NetSocketListenState *s = opaque;
3424 NetSocketState *s1;
3425 struct sockaddr_in saddr;
3426 socklen_t len;
3427 int fd;
3429 for(;;) {
3430 len = sizeof(saddr);
3431 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3432 if (fd < 0 && errno != EINTR) {
3433 return;
3434 } else if (fd >= 0) {
3435 break;
3438 s1 = net_socket_fd_init(s->vlan, fd, 1);
3439 if (!s1) {
3440 closesocket(fd);
3441 } else {
3442 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3443 "socket: connection from %s:%d",
3444 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3448 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3450 NetSocketListenState *s;
3451 int fd, val, ret;
3452 struct sockaddr_in saddr;
3454 if (parse_host_port(&saddr, host_str) < 0)
3455 return -1;
3457 s = qemu_mallocz(sizeof(NetSocketListenState));
3458 if (!s)
3459 return -1;
3461 fd = socket(PF_INET, SOCK_STREAM, 0);
3462 if (fd < 0) {
3463 perror("socket");
3464 return -1;
3466 socket_set_nonblock(fd);
3468 /* allow fast reuse */
3469 val = 1;
3470 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3472 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3473 if (ret < 0) {
3474 perror("bind");
3475 return -1;
3477 ret = listen(fd, 0);
3478 if (ret < 0) {
3479 perror("listen");
3480 return -1;
3482 s->vlan = vlan;
3483 s->fd = fd;
3484 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3485 return 0;
3488 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3490 NetSocketState *s;
3491 int fd, connected, ret, err;
3492 struct sockaddr_in saddr;
3494 if (parse_host_port(&saddr, host_str) < 0)
3495 return -1;
3497 fd = socket(PF_INET, SOCK_STREAM, 0);
3498 if (fd < 0) {
3499 perror("socket");
3500 return -1;
3502 socket_set_nonblock(fd);
3504 connected = 0;
3505 for(;;) {
3506 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3507 if (ret < 0) {
3508 err = socket_error();
3509 if (err == EINTR || err == EWOULDBLOCK) {
3510 } else if (err == EINPROGRESS) {
3511 break;
3512 } else {
3513 perror("connect");
3514 closesocket(fd);
3515 return -1;
3517 } else {
3518 connected = 1;
3519 break;
3522 s = net_socket_fd_init(vlan, fd, connected);
3523 if (!s)
3524 return -1;
3525 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3526 "socket: connect to %s:%d",
3527 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3528 return 0;
3531 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3533 NetSocketState *s;
3534 int fd;
3535 struct sockaddr_in saddr;
3537 if (parse_host_port(&saddr, host_str) < 0)
3538 return -1;
3541 fd = net_socket_mcast_create(&saddr);
3542 if (fd < 0)
3543 return -1;
3545 s = net_socket_fd_init(vlan, fd, 0);
3546 if (!s)
3547 return -1;
3549 s->dgram_dst = saddr;
3551 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3552 "socket: mcast=%s:%d",
3553 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3554 return 0;
3558 static int get_param_value(char *buf, int buf_size,
3559 const char *tag, const char *str)
3561 const char *p;
3562 char *q;
3563 char option[128];
3565 p = str;
3566 for(;;) {
3567 q = option;
3568 while (*p != '\0' && *p != '=') {
3569 if ((q - option) < sizeof(option) - 1)
3570 *q++ = *p;
3571 p++;
3573 *q = '\0';
3574 if (*p != '=')
3575 break;
3576 p++;
3577 if (!strcmp(tag, option)) {
3578 q = buf;
3579 while (*p != '\0' && *p != ',') {
3580 if ((q - buf) < buf_size - 1)
3581 *q++ = *p;
3582 p++;
3584 *q = '\0';
3585 return q - buf;
3586 } else {
3587 while (*p != '\0' && *p != ',') {
3588 p++;
3591 if (*p != ',')
3592 break;
3593 p++;
3595 return 0;
3598 int net_client_init(const char *str)
3600 const char *p;
3601 char *q;
3602 char device[64];
3603 char buf[1024];
3604 int vlan_id, ret;
3605 VLANState *vlan;
3607 p = str;
3608 q = device;
3609 while (*p != '\0' && *p != ',') {
3610 if ((q - device) < sizeof(device) - 1)
3611 *q++ = *p;
3612 p++;
3614 *q = '\0';
3615 if (*p == ',')
3616 p++;
3617 vlan_id = 0;
3618 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3619 vlan_id = strtol(buf, NULL, 0);
3621 vlan = qemu_find_vlan(vlan_id);
3622 if (!vlan) {
3623 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3624 return -1;
3626 if (!strcmp(device, "nic")) {
3627 NICInfo *nd;
3628 uint8_t *macaddr;
3630 if (nb_nics >= MAX_NICS) {
3631 fprintf(stderr, "Too Many NICs\n");
3632 return -1;
3634 nd = &nd_table[nb_nics];
3635 macaddr = nd->macaddr;
3636 macaddr[0] = 0x52;
3637 macaddr[1] = 0x54;
3638 macaddr[2] = 0x00;
3639 macaddr[3] = 0x12;
3640 macaddr[4] = 0x34;
3641 macaddr[5] = 0x56 + nb_nics;
3643 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3644 if (parse_macaddr(macaddr, buf) < 0) {
3645 fprintf(stderr, "invalid syntax for ethernet address\n");
3646 return -1;
3649 if (get_param_value(buf, sizeof(buf), "model", p)) {
3650 nd->model = strdup(buf);
3652 nd->vlan = vlan;
3653 nb_nics++;
3654 ret = 0;
3655 } else
3656 if (!strcmp(device, "none")) {
3657 /* does nothing. It is needed to signal that no network cards
3658 are wanted */
3659 ret = 0;
3660 } else
3661 #ifdef CONFIG_SLIRP
3662 if (!strcmp(device, "user")) {
3663 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3664 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3666 ret = net_slirp_init(vlan);
3667 } else
3668 #endif
3669 #ifdef _WIN32
3670 if (!strcmp(device, "tap")) {
3671 char ifname[64];
3672 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3673 fprintf(stderr, "tap: no interface name\n");
3674 return -1;
3676 ret = tap_win32_init(vlan, ifname);
3677 } else
3678 #else
3679 if (!strcmp(device, "tap")) {
3680 char ifname[64];
3681 char setup_script[1024];
3682 int fd;
3683 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3684 fd = strtol(buf, NULL, 0);
3685 ret = -1;
3686 if (net_tap_fd_init(vlan, fd))
3687 ret = 0;
3688 } else {
3689 get_param_value(ifname, sizeof(ifname), "ifname", p);
3690 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3691 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3693 ret = net_tap_init(vlan, ifname, setup_script);
3695 } else
3696 #endif
3697 if (!strcmp(device, "socket")) {
3698 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3699 int fd;
3700 fd = strtol(buf, NULL, 0);
3701 ret = -1;
3702 if (net_socket_fd_init(vlan, fd, 1))
3703 ret = 0;
3704 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3705 ret = net_socket_listen_init(vlan, buf);
3706 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3707 ret = net_socket_connect_init(vlan, buf);
3708 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3709 ret = net_socket_mcast_init(vlan, buf);
3710 } else {
3711 fprintf(stderr, "Unknown socket options: %s\n", p);
3712 return -1;
3714 } else
3716 fprintf(stderr, "Unknown network device: %s\n", device);
3717 return -1;
3719 if (ret < 0) {
3720 fprintf(stderr, "Could not initialize device '%s'\n", device);
3723 return ret;
3726 void do_info_network(void)
3728 VLANState *vlan;
3729 VLANClientState *vc;
3731 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3732 term_printf("VLAN %d devices:\n", vlan->id);
3733 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3734 term_printf(" %s\n", vc->info_str);
3738 /***********************************************************/
3739 /* USB devices */
3741 static USBPort *used_usb_ports;
3742 static USBPort *free_usb_ports;
3744 /* ??? Maybe change this to register a hub to keep track of the topology. */
3745 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3746 usb_attachfn attach)
3748 port->opaque = opaque;
3749 port->index = index;
3750 port->attach = attach;
3751 port->next = free_usb_ports;
3752 free_usb_ports = port;
3755 static int usb_device_add(const char *devname)
3757 const char *p;
3758 USBDevice *dev;
3759 USBPort *port;
3761 if (!free_usb_ports)
3762 return -1;
3764 if (strstart(devname, "host:", &p)) {
3765 dev = usb_host_device_open(p);
3766 } else if (!strcmp(devname, "mouse")) {
3767 dev = usb_mouse_init();
3768 } else if (!strcmp(devname, "tablet")) {
3769 dev = usb_tablet_init();
3770 } else if (strstart(devname, "disk:", &p)) {
3771 dev = usb_msd_init(p);
3772 } else {
3773 return -1;
3775 if (!dev)
3776 return -1;
3778 /* Find a USB port to add the device to. */
3779 port = free_usb_ports;
3780 if (!port->next) {
3781 USBDevice *hub;
3783 /* Create a new hub and chain it on. */
3784 free_usb_ports = NULL;
3785 port->next = used_usb_ports;
3786 used_usb_ports = port;
3788 hub = usb_hub_init(VM_USB_HUB_SIZE);
3789 usb_attach(port, hub);
3790 port = free_usb_ports;
3793 free_usb_ports = port->next;
3794 port->next = used_usb_ports;
3795 used_usb_ports = port;
3796 usb_attach(port, dev);
3797 return 0;
3800 static int usb_device_del(const char *devname)
3802 USBPort *port;
3803 USBPort **lastp;
3804 int bus_num, addr;
3805 const char *p;
3807 if (!used_usb_ports)
3808 return -1;
3810 p = strchr(devname, '.');
3811 if (!p)
3812 return -1;
3813 bus_num = strtoul(devname, NULL, 0);
3814 addr = strtoul(p + 1, NULL, 0);
3815 if (bus_num != 0)
3816 return -1;
3818 lastp = &used_usb_ports;
3819 port = used_usb_ports;
3820 while (port && port->dev->addr != addr) {
3821 lastp = &port->next;
3822 port = port->next;
3825 if (!port)
3826 return -1;
3828 *lastp = port->next;
3829 usb_attach(port, NULL);
3830 port->next = free_usb_ports;
3831 free_usb_ports = port;
3832 return 0;
3835 void do_usb_add(const char *devname)
3837 int ret;
3838 ret = usb_device_add(devname);
3839 if (ret < 0)
3840 term_printf("Could not add USB device '%s'\n", devname);
3843 void do_usb_del(const char *devname)
3845 int ret;
3846 ret = usb_device_del(devname);
3847 if (ret < 0)
3848 term_printf("Could not remove USB device '%s'\n", devname);
3851 void usb_info(void)
3853 USBDevice *dev;
3854 USBPort *port;
3855 const char *speed_str;
3857 if (!usb_enabled) {
3858 term_printf("USB support not enabled\n");
3859 return;
3862 for (port = used_usb_ports; port; port = port->next) {
3863 dev = port->dev;
3864 if (!dev)
3865 continue;
3866 switch(dev->speed) {
3867 case USB_SPEED_LOW:
3868 speed_str = "1.5";
3869 break;
3870 case USB_SPEED_FULL:
3871 speed_str = "12";
3872 break;
3873 case USB_SPEED_HIGH:
3874 speed_str = "480";
3875 break;
3876 default:
3877 speed_str = "?";
3878 break;
3880 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
3881 0, dev->addr, speed_str, dev->devname);
3885 /***********************************************************/
3886 /* pid file */
3888 static char *pid_filename;
3890 /* Remove PID file. Called on normal exit */
3892 static void remove_pidfile(void)
3894 unlink (pid_filename);
3897 static void create_pidfile(const char *filename)
3899 struct stat pidstat;
3900 FILE *f;
3902 /* Try to write our PID to the named file */
3903 if (stat(filename, &pidstat) < 0) {
3904 if (errno == ENOENT) {
3905 if ((f = fopen (filename, "w")) == NULL) {
3906 perror("Opening pidfile");
3907 exit(1);
3909 fprintf(f, "%d\n", getpid());
3910 fclose(f);
3911 pid_filename = qemu_strdup(filename);
3912 if (!pid_filename) {
3913 fprintf(stderr, "Could not save PID filename");
3914 exit(1);
3916 atexit(remove_pidfile);
3918 } else {
3919 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3920 filename);
3921 exit(1);
3925 /***********************************************************/
3926 /* dumb display */
3928 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3932 static void dumb_resize(DisplayState *ds, int w, int h)
3936 static void dumb_refresh(DisplayState *ds)
3938 vga_hw_update();
3941 void dumb_display_init(DisplayState *ds)
3943 ds->data = NULL;
3944 ds->linesize = 0;
3945 ds->depth = 0;
3946 ds->dpy_update = dumb_update;
3947 ds->dpy_resize = dumb_resize;
3948 ds->dpy_refresh = dumb_refresh;
3951 /***********************************************************/
3952 /* I/O handling */
3954 #define MAX_IO_HANDLERS 64
3956 typedef struct IOHandlerRecord {
3957 int fd;
3958 IOCanRWHandler *fd_read_poll;
3959 IOHandler *fd_read;
3960 IOHandler *fd_write;
3961 void *opaque;
3962 /* temporary data */
3963 struct pollfd *ufd;
3964 struct IOHandlerRecord *next;
3965 } IOHandlerRecord;
3967 static IOHandlerRecord *first_io_handler;
3969 /* XXX: fd_read_poll should be suppressed, but an API change is
3970 necessary in the character devices to suppress fd_can_read(). */
3971 int qemu_set_fd_handler2(int fd,
3972 IOCanRWHandler *fd_read_poll,
3973 IOHandler *fd_read,
3974 IOHandler *fd_write,
3975 void *opaque)
3977 IOHandlerRecord **pioh, *ioh;
3979 if (!fd_read && !fd_write) {
3980 pioh = &first_io_handler;
3981 for(;;) {
3982 ioh = *pioh;
3983 if (ioh == NULL)
3984 break;
3985 if (ioh->fd == fd) {
3986 *pioh = ioh->next;
3987 qemu_free(ioh);
3988 break;
3990 pioh = &ioh->next;
3992 } else {
3993 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3994 if (ioh->fd == fd)
3995 goto found;
3997 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3998 if (!ioh)
3999 return -1;
4000 ioh->next = first_io_handler;
4001 first_io_handler = ioh;
4002 found:
4003 ioh->fd = fd;
4004 ioh->fd_read_poll = fd_read_poll;
4005 ioh->fd_read = fd_read;
4006 ioh->fd_write = fd_write;
4007 ioh->opaque = opaque;
4009 return 0;
4012 int qemu_set_fd_handler(int fd,
4013 IOHandler *fd_read,
4014 IOHandler *fd_write,
4015 void *opaque)
4017 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4020 /***********************************************************/
4021 /* Polling handling */
4023 typedef struct PollingEntry {
4024 PollingFunc *func;
4025 void *opaque;
4026 struct PollingEntry *next;
4027 } PollingEntry;
4029 static PollingEntry *first_polling_entry;
4031 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4033 PollingEntry **ppe, *pe;
4034 pe = qemu_mallocz(sizeof(PollingEntry));
4035 if (!pe)
4036 return -1;
4037 pe->func = func;
4038 pe->opaque = opaque;
4039 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4040 *ppe = pe;
4041 return 0;
4044 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4046 PollingEntry **ppe, *pe;
4047 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4048 pe = *ppe;
4049 if (pe->func == func && pe->opaque == opaque) {
4050 *ppe = pe->next;
4051 qemu_free(pe);
4052 break;
4057 #ifdef _WIN32
4058 /***********************************************************/
4059 /* Wait objects support */
4060 typedef struct WaitObjects {
4061 int num;
4062 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4063 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4064 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4065 } WaitObjects;
4067 static WaitObjects wait_objects = {0};
4069 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4071 WaitObjects *w = &wait_objects;
4073 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4074 return -1;
4075 w->events[w->num] = handle;
4076 w->func[w->num] = func;
4077 w->opaque[w->num] = opaque;
4078 w->num++;
4079 return 0;
4082 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4084 int i, found;
4085 WaitObjects *w = &wait_objects;
4087 found = 0;
4088 for (i = 0; i < w->num; i++) {
4089 if (w->events[i] == handle)
4090 found = 1;
4091 if (found) {
4092 w->events[i] = w->events[i + 1];
4093 w->func[i] = w->func[i + 1];
4094 w->opaque[i] = w->opaque[i + 1];
4097 if (found)
4098 w->num--;
4100 #endif
4102 /***********************************************************/
4103 /* savevm/loadvm support */
4105 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4107 fwrite(buf, 1, size, f);
4110 void qemu_put_byte(QEMUFile *f, int v)
4112 fputc(v, f);
4115 void qemu_put_be16(QEMUFile *f, unsigned int v)
4117 qemu_put_byte(f, v >> 8);
4118 qemu_put_byte(f, v);
4121 void qemu_put_be32(QEMUFile *f, unsigned int v)
4123 qemu_put_byte(f, v >> 24);
4124 qemu_put_byte(f, v >> 16);
4125 qemu_put_byte(f, v >> 8);
4126 qemu_put_byte(f, v);
4129 void qemu_put_be64(QEMUFile *f, uint64_t v)
4131 qemu_put_be32(f, v >> 32);
4132 qemu_put_be32(f, v);
4135 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4137 return fread(buf, 1, size, f);
4140 int qemu_get_byte(QEMUFile *f)
4142 int v;
4143 v = fgetc(f);
4144 if (v == EOF)
4145 return 0;
4146 else
4147 return v;
4150 unsigned int qemu_get_be16(QEMUFile *f)
4152 unsigned int v;
4153 v = qemu_get_byte(f) << 8;
4154 v |= qemu_get_byte(f);
4155 return v;
4158 unsigned int qemu_get_be32(QEMUFile *f)
4160 unsigned int v;
4161 v = qemu_get_byte(f) << 24;
4162 v |= qemu_get_byte(f) << 16;
4163 v |= qemu_get_byte(f) << 8;
4164 v |= qemu_get_byte(f);
4165 return v;
4168 uint64_t qemu_get_be64(QEMUFile *f)
4170 uint64_t v;
4171 v = (uint64_t)qemu_get_be32(f) << 32;
4172 v |= qemu_get_be32(f);
4173 return v;
4176 int64_t qemu_ftell(QEMUFile *f)
4178 return ftell(f);
4181 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4183 if (fseek(f, pos, whence) < 0)
4184 return -1;
4185 return ftell(f);
4188 typedef struct SaveStateEntry {
4189 char idstr[256];
4190 int instance_id;
4191 int version_id;
4192 SaveStateHandler *save_state;
4193 LoadStateHandler *load_state;
4194 void *opaque;
4195 struct SaveStateEntry *next;
4196 } SaveStateEntry;
4198 static SaveStateEntry *first_se;
4200 int register_savevm(const char *idstr,
4201 int instance_id,
4202 int version_id,
4203 SaveStateHandler *save_state,
4204 LoadStateHandler *load_state,
4205 void *opaque)
4207 SaveStateEntry *se, **pse;
4209 se = qemu_malloc(sizeof(SaveStateEntry));
4210 if (!se)
4211 return -1;
4212 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4213 se->instance_id = instance_id;
4214 se->version_id = version_id;
4215 se->save_state = save_state;
4216 se->load_state = load_state;
4217 se->opaque = opaque;
4218 se->next = NULL;
4220 /* add at the end of list */
4221 pse = &first_se;
4222 while (*pse != NULL)
4223 pse = &(*pse)->next;
4224 *pse = se;
4225 return 0;
4228 #define QEMU_VM_FILE_MAGIC 0x5145564d
4229 #define QEMU_VM_FILE_VERSION 0x00000001
4231 int qemu_savevm(const char *filename)
4233 SaveStateEntry *se;
4234 QEMUFile *f;
4235 int len, len_pos, cur_pos, saved_vm_running, ret;
4237 saved_vm_running = vm_running;
4238 vm_stop(0);
4240 f = fopen(filename, "wb");
4241 if (!f) {
4242 ret = -1;
4243 goto the_end;
4246 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4247 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4249 for(se = first_se; se != NULL; se = se->next) {
4250 /* ID string */
4251 len = strlen(se->idstr);
4252 qemu_put_byte(f, len);
4253 qemu_put_buffer(f, se->idstr, len);
4255 qemu_put_be32(f, se->instance_id);
4256 qemu_put_be32(f, se->version_id);
4258 /* record size: filled later */
4259 len_pos = ftell(f);
4260 qemu_put_be32(f, 0);
4262 se->save_state(f, se->opaque);
4264 /* fill record size */
4265 cur_pos = ftell(f);
4266 len = ftell(f) - len_pos - 4;
4267 fseek(f, len_pos, SEEK_SET);
4268 qemu_put_be32(f, len);
4269 fseek(f, cur_pos, SEEK_SET);
4272 fclose(f);
4273 ret = 0;
4274 the_end:
4275 if (saved_vm_running)
4276 vm_start();
4277 return ret;
4280 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4282 SaveStateEntry *se;
4284 for(se = first_se; se != NULL; se = se->next) {
4285 if (!strcmp(se->idstr, idstr) &&
4286 instance_id == se->instance_id)
4287 return se;
4289 return NULL;
4292 int qemu_loadvm(const char *filename)
4294 SaveStateEntry *se;
4295 QEMUFile *f;
4296 int len, cur_pos, ret, instance_id, record_len, version_id;
4297 int saved_vm_running;
4298 unsigned int v;
4299 char idstr[256];
4301 saved_vm_running = vm_running;
4302 vm_stop(0);
4304 f = fopen(filename, "rb");
4305 if (!f) {
4306 ret = -1;
4307 goto the_end;
4310 v = qemu_get_be32(f);
4311 if (v != QEMU_VM_FILE_MAGIC)
4312 goto fail;
4313 v = qemu_get_be32(f);
4314 if (v != QEMU_VM_FILE_VERSION) {
4315 fail:
4316 fclose(f);
4317 ret = -1;
4318 goto the_end;
4320 for(;;) {
4321 len = qemu_get_byte(f);
4322 if (feof(f))
4323 break;
4324 qemu_get_buffer(f, idstr, len);
4325 idstr[len] = '\0';
4326 instance_id = qemu_get_be32(f);
4327 version_id = qemu_get_be32(f);
4328 record_len = qemu_get_be32(f);
4329 #if 0
4330 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4331 idstr, instance_id, version_id, record_len);
4332 #endif
4333 cur_pos = ftell(f);
4334 se = find_se(idstr, instance_id);
4335 if (!se) {
4336 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4337 instance_id, idstr);
4338 } else {
4339 ret = se->load_state(f, se->opaque, version_id);
4340 if (ret < 0) {
4341 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4342 instance_id, idstr);
4345 /* always seek to exact end of record */
4346 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4348 fclose(f);
4349 ret = 0;
4350 the_end:
4351 if (saved_vm_running)
4352 vm_start();
4353 return ret;
4356 /***********************************************************/
4357 /* cpu save/restore */
4359 #if defined(TARGET_I386)
4361 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4363 qemu_put_be32(f, dt->selector);
4364 qemu_put_betl(f, dt->base);
4365 qemu_put_be32(f, dt->limit);
4366 qemu_put_be32(f, dt->flags);
4369 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4371 dt->selector = qemu_get_be32(f);
4372 dt->base = qemu_get_betl(f);
4373 dt->limit = qemu_get_be32(f);
4374 dt->flags = qemu_get_be32(f);
4377 void cpu_save(QEMUFile *f, void *opaque)
4379 CPUState *env = opaque;
4380 uint16_t fptag, fpus, fpuc, fpregs_format;
4381 uint32_t hflags;
4382 int i;
4384 for(i = 0; i < CPU_NB_REGS; i++)
4385 qemu_put_betls(f, &env->regs[i]);
4386 qemu_put_betls(f, &env->eip);
4387 qemu_put_betls(f, &env->eflags);
4388 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4389 qemu_put_be32s(f, &hflags);
4391 /* FPU */
4392 fpuc = env->fpuc;
4393 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4394 fptag = 0;
4395 for(i = 0; i < 8; i++) {
4396 fptag |= ((!env->fptags[i]) << i);
4399 qemu_put_be16s(f, &fpuc);
4400 qemu_put_be16s(f, &fpus);
4401 qemu_put_be16s(f, &fptag);
4403 #ifdef USE_X86LDOUBLE
4404 fpregs_format = 0;
4405 #else
4406 fpregs_format = 1;
4407 #endif
4408 qemu_put_be16s(f, &fpregs_format);
4410 for(i = 0; i < 8; i++) {
4411 #ifdef USE_X86LDOUBLE
4413 uint64_t mant;
4414 uint16_t exp;
4415 /* we save the real CPU data (in case of MMX usage only 'mant'
4416 contains the MMX register */
4417 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4418 qemu_put_be64(f, mant);
4419 qemu_put_be16(f, exp);
4421 #else
4422 /* if we use doubles for float emulation, we save the doubles to
4423 avoid losing information in case of MMX usage. It can give
4424 problems if the image is restored on a CPU where long
4425 doubles are used instead. */
4426 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4427 #endif
4430 for(i = 0; i < 6; i++)
4431 cpu_put_seg(f, &env->segs[i]);
4432 cpu_put_seg(f, &env->ldt);
4433 cpu_put_seg(f, &env->tr);
4434 cpu_put_seg(f, &env->gdt);
4435 cpu_put_seg(f, &env->idt);
4437 qemu_put_be32s(f, &env->sysenter_cs);
4438 qemu_put_be32s(f, &env->sysenter_esp);
4439 qemu_put_be32s(f, &env->sysenter_eip);
4441 qemu_put_betls(f, &env->cr[0]);
4442 qemu_put_betls(f, &env->cr[2]);
4443 qemu_put_betls(f, &env->cr[3]);
4444 qemu_put_betls(f, &env->cr[4]);
4446 for(i = 0; i < 8; i++)
4447 qemu_put_betls(f, &env->dr[i]);
4449 /* MMU */
4450 qemu_put_be32s(f, &env->a20_mask);
4452 /* XMM */
4453 qemu_put_be32s(f, &env->mxcsr);
4454 for(i = 0; i < CPU_NB_REGS; i++) {
4455 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4456 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4459 #ifdef TARGET_X86_64
4460 qemu_put_be64s(f, &env->efer);
4461 qemu_put_be64s(f, &env->star);
4462 qemu_put_be64s(f, &env->lstar);
4463 qemu_put_be64s(f, &env->cstar);
4464 qemu_put_be64s(f, &env->fmask);
4465 qemu_put_be64s(f, &env->kernelgsbase);
4466 #endif
4469 #ifdef USE_X86LDOUBLE
4470 /* XXX: add that in a FPU generic layer */
4471 union x86_longdouble {
4472 uint64_t mant;
4473 uint16_t exp;
4476 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4477 #define EXPBIAS1 1023
4478 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4479 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4481 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4483 int e;
4484 /* mantissa */
4485 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4486 /* exponent + sign */
4487 e = EXPD1(temp) - EXPBIAS1 + 16383;
4488 e |= SIGND1(temp) >> 16;
4489 p->exp = e;
4491 #endif
4493 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4495 CPUState *env = opaque;
4496 int i, guess_mmx;
4497 uint32_t hflags;
4498 uint16_t fpus, fpuc, fptag, fpregs_format;
4500 if (version_id != 3)
4501 return -EINVAL;
4502 for(i = 0; i < CPU_NB_REGS; i++)
4503 qemu_get_betls(f, &env->regs[i]);
4504 qemu_get_betls(f, &env->eip);
4505 qemu_get_betls(f, &env->eflags);
4506 qemu_get_be32s(f, &hflags);
4508 qemu_get_be16s(f, &fpuc);
4509 qemu_get_be16s(f, &fpus);
4510 qemu_get_be16s(f, &fptag);
4511 qemu_get_be16s(f, &fpregs_format);
4513 /* NOTE: we cannot always restore the FPU state if the image come
4514 from a host with a different 'USE_X86LDOUBLE' define. We guess
4515 if we are in an MMX state to restore correctly in that case. */
4516 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4517 for(i = 0; i < 8; i++) {
4518 uint64_t mant;
4519 uint16_t exp;
4521 switch(fpregs_format) {
4522 case 0:
4523 mant = qemu_get_be64(f);
4524 exp = qemu_get_be16(f);
4525 #ifdef USE_X86LDOUBLE
4526 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4527 #else
4528 /* difficult case */
4529 if (guess_mmx)
4530 env->fpregs[i].mmx.MMX_Q(0) = mant;
4531 else
4532 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4533 #endif
4534 break;
4535 case 1:
4536 mant = qemu_get_be64(f);
4537 #ifdef USE_X86LDOUBLE
4539 union x86_longdouble *p;
4540 /* difficult case */
4541 p = (void *)&env->fpregs[i];
4542 if (guess_mmx) {
4543 p->mant = mant;
4544 p->exp = 0xffff;
4545 } else {
4546 fp64_to_fp80(p, mant);
4549 #else
4550 env->fpregs[i].mmx.MMX_Q(0) = mant;
4551 #endif
4552 break;
4553 default:
4554 return -EINVAL;
4558 env->fpuc = fpuc;
4559 /* XXX: restore FPU round state */
4560 env->fpstt = (fpus >> 11) & 7;
4561 env->fpus = fpus & ~0x3800;
4562 fptag ^= 0xff;
4563 for(i = 0; i < 8; i++) {
4564 env->fptags[i] = (fptag >> i) & 1;
4567 for(i = 0; i < 6; i++)
4568 cpu_get_seg(f, &env->segs[i]);
4569 cpu_get_seg(f, &env->ldt);
4570 cpu_get_seg(f, &env->tr);
4571 cpu_get_seg(f, &env->gdt);
4572 cpu_get_seg(f, &env->idt);
4574 qemu_get_be32s(f, &env->sysenter_cs);
4575 qemu_get_be32s(f, &env->sysenter_esp);
4576 qemu_get_be32s(f, &env->sysenter_eip);
4578 qemu_get_betls(f, &env->cr[0]);
4579 qemu_get_betls(f, &env->cr[2]);
4580 qemu_get_betls(f, &env->cr[3]);
4581 qemu_get_betls(f, &env->cr[4]);
4583 for(i = 0; i < 8; i++)
4584 qemu_get_betls(f, &env->dr[i]);
4586 /* MMU */
4587 qemu_get_be32s(f, &env->a20_mask);
4589 qemu_get_be32s(f, &env->mxcsr);
4590 for(i = 0; i < CPU_NB_REGS; i++) {
4591 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4592 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4595 #ifdef TARGET_X86_64
4596 qemu_get_be64s(f, &env->efer);
4597 qemu_get_be64s(f, &env->star);
4598 qemu_get_be64s(f, &env->lstar);
4599 qemu_get_be64s(f, &env->cstar);
4600 qemu_get_be64s(f, &env->fmask);
4601 qemu_get_be64s(f, &env->kernelgsbase);
4602 #endif
4604 /* XXX: compute hflags from scratch, except for CPL and IIF */
4605 env->hflags = hflags;
4606 tlb_flush(env, 1);
4607 return 0;
4610 #elif defined(TARGET_PPC)
4611 void cpu_save(QEMUFile *f, void *opaque)
4615 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4617 return 0;
4620 #elif defined(TARGET_MIPS)
4621 void cpu_save(QEMUFile *f, void *opaque)
4625 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4627 return 0;
4630 #elif defined(TARGET_SPARC)
4631 void cpu_save(QEMUFile *f, void *opaque)
4633 CPUState *env = opaque;
4634 int i;
4635 uint32_t tmp;
4637 for(i = 0; i < 8; i++)
4638 qemu_put_betls(f, &env->gregs[i]);
4639 for(i = 0; i < NWINDOWS * 16; i++)
4640 qemu_put_betls(f, &env->regbase[i]);
4642 /* FPU */
4643 for(i = 0; i < TARGET_FPREGS; i++) {
4644 union {
4645 float32 f;
4646 uint32_t i;
4647 } u;
4648 u.f = env->fpr[i];
4649 qemu_put_be32(f, u.i);
4652 qemu_put_betls(f, &env->pc);
4653 qemu_put_betls(f, &env->npc);
4654 qemu_put_betls(f, &env->y);
4655 tmp = GET_PSR(env);
4656 qemu_put_be32(f, tmp);
4657 qemu_put_betls(f, &env->fsr);
4658 qemu_put_betls(f, &env->tbr);
4659 #ifndef TARGET_SPARC64
4660 qemu_put_be32s(f, &env->wim);
4661 /* MMU */
4662 for(i = 0; i < 16; i++)
4663 qemu_put_be32s(f, &env->mmuregs[i]);
4664 #endif
4667 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4669 CPUState *env = opaque;
4670 int i;
4671 uint32_t tmp;
4673 for(i = 0; i < 8; i++)
4674 qemu_get_betls(f, &env->gregs[i]);
4675 for(i = 0; i < NWINDOWS * 16; i++)
4676 qemu_get_betls(f, &env->regbase[i]);
4678 /* FPU */
4679 for(i = 0; i < TARGET_FPREGS; i++) {
4680 union {
4681 float32 f;
4682 uint32_t i;
4683 } u;
4684 u.i = qemu_get_be32(f);
4685 env->fpr[i] = u.f;
4688 qemu_get_betls(f, &env->pc);
4689 qemu_get_betls(f, &env->npc);
4690 qemu_get_betls(f, &env->y);
4691 tmp = qemu_get_be32(f);
4692 env->cwp = 0; /* needed to ensure that the wrapping registers are
4693 correctly updated */
4694 PUT_PSR(env, tmp);
4695 qemu_get_betls(f, &env->fsr);
4696 qemu_get_betls(f, &env->tbr);
4697 #ifndef TARGET_SPARC64
4698 qemu_get_be32s(f, &env->wim);
4699 /* MMU */
4700 for(i = 0; i < 16; i++)
4701 qemu_get_be32s(f, &env->mmuregs[i]);
4702 #endif
4703 tlb_flush(env, 1);
4704 return 0;
4707 #elif defined(TARGET_ARM)
4709 /* ??? Need to implement these. */
4710 void cpu_save(QEMUFile *f, void *opaque)
4714 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4716 return 0;
4719 #else
4721 #warning No CPU save/restore functions
4723 #endif
4725 /***********************************************************/
4726 /* ram save/restore */
4728 /* we just avoid storing empty pages */
4729 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4731 int i, v;
4733 v = buf[0];
4734 for(i = 1; i < len; i++) {
4735 if (buf[i] != v)
4736 goto normal_save;
4738 qemu_put_byte(f, 1);
4739 qemu_put_byte(f, v);
4740 return;
4741 normal_save:
4742 qemu_put_byte(f, 0);
4743 qemu_put_buffer(f, buf, len);
4746 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4748 int v;
4750 v = qemu_get_byte(f);
4751 switch(v) {
4752 case 0:
4753 if (qemu_get_buffer(f, buf, len) != len)
4754 return -EIO;
4755 break;
4756 case 1:
4757 v = qemu_get_byte(f);
4758 memset(buf, v, len);
4759 break;
4760 default:
4761 return -EINVAL;
4763 return 0;
4766 static void ram_save(QEMUFile *f, void *opaque)
4768 int i;
4769 qemu_put_be32(f, phys_ram_size);
4770 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4771 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4775 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4777 int i, ret;
4779 if (version_id != 1)
4780 return -EINVAL;
4781 if (qemu_get_be32(f) != phys_ram_size)
4782 return -EINVAL;
4783 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4784 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4785 if (ret)
4786 return ret;
4788 return 0;
4791 /***********************************************************/
4792 /* machine registration */
4794 QEMUMachine *first_machine = NULL;
4796 int qemu_register_machine(QEMUMachine *m)
4798 QEMUMachine **pm;
4799 pm = &first_machine;
4800 while (*pm != NULL)
4801 pm = &(*pm)->next;
4802 m->next = NULL;
4803 *pm = m;
4804 return 0;
4807 QEMUMachine *find_machine(const char *name)
4809 QEMUMachine *m;
4811 for(m = first_machine; m != NULL; m = m->next) {
4812 if (!strcmp(m->name, name))
4813 return m;
4815 return NULL;
4818 /***********************************************************/
4819 /* main execution loop */
4821 void gui_update(void *opaque)
4823 display_state.dpy_refresh(&display_state);
4824 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4827 struct vm_change_state_entry {
4828 VMChangeStateHandler *cb;
4829 void *opaque;
4830 LIST_ENTRY (vm_change_state_entry) entries;
4833 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4835 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4836 void *opaque)
4838 VMChangeStateEntry *e;
4840 e = qemu_mallocz(sizeof (*e));
4841 if (!e)
4842 return NULL;
4844 e->cb = cb;
4845 e->opaque = opaque;
4846 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4847 return e;
4850 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4852 LIST_REMOVE (e, entries);
4853 qemu_free (e);
4856 static void vm_state_notify(int running)
4858 VMChangeStateEntry *e;
4860 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4861 e->cb(e->opaque, running);
4865 /* XXX: support several handlers */
4866 static VMStopHandler *vm_stop_cb;
4867 static void *vm_stop_opaque;
4869 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4871 vm_stop_cb = cb;
4872 vm_stop_opaque = opaque;
4873 return 0;
4876 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4878 vm_stop_cb = NULL;
4881 void vm_start(void)
4883 if (!vm_running) {
4884 cpu_enable_ticks();
4885 vm_running = 1;
4886 vm_state_notify(1);
4890 void vm_stop(int reason)
4892 if (vm_running) {
4893 cpu_disable_ticks();
4894 vm_running = 0;
4895 if (reason != 0) {
4896 if (vm_stop_cb) {
4897 vm_stop_cb(vm_stop_opaque, reason);
4900 vm_state_notify(0);
4904 /* reset/shutdown handler */
4906 typedef struct QEMUResetEntry {
4907 QEMUResetHandler *func;
4908 void *opaque;
4909 struct QEMUResetEntry *next;
4910 } QEMUResetEntry;
4912 static QEMUResetEntry *first_reset_entry;
4913 static int reset_requested;
4914 static int shutdown_requested;
4915 static int powerdown_requested;
4917 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4919 QEMUResetEntry **pre, *re;
4921 pre = &first_reset_entry;
4922 while (*pre != NULL)
4923 pre = &(*pre)->next;
4924 re = qemu_mallocz(sizeof(QEMUResetEntry));
4925 re->func = func;
4926 re->opaque = opaque;
4927 re->next = NULL;
4928 *pre = re;
4931 void qemu_system_reset(void)
4933 QEMUResetEntry *re;
4935 /* reset all devices */
4936 for(re = first_reset_entry; re != NULL; re = re->next) {
4937 re->func(re->opaque);
4941 void qemu_system_reset_request(void)
4943 reset_requested = 1;
4944 if (cpu_single_env)
4945 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4948 void qemu_system_shutdown_request(void)
4950 shutdown_requested = 1;
4951 if (cpu_single_env)
4952 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4955 void qemu_system_powerdown_request(void)
4957 powerdown_requested = 1;
4958 if (cpu_single_env)
4959 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4962 void main_loop_wait(int timeout)
4964 IOHandlerRecord *ioh, *ioh_next;
4965 fd_set rfds, wfds, xfds;
4966 int ret, nfds;
4967 struct timeval tv;
4968 PollingEntry *pe;
4971 /* XXX: need to suppress polling by better using win32 events */
4972 ret = 0;
4973 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4974 ret |= pe->func(pe->opaque);
4976 #ifdef _WIN32
4977 if (ret == 0 && timeout > 0) {
4978 int err;
4979 WaitObjects *w = &wait_objects;
4981 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
4982 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4983 if (w->func[ret - WAIT_OBJECT_0])
4984 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4985 } else if (ret == WAIT_TIMEOUT) {
4986 } else {
4987 err = GetLastError();
4988 fprintf(stderr, "Wait error %d %d\n", ret, err);
4991 #endif
4992 /* poll any events */
4993 /* XXX: separate device handlers from system ones */
4994 nfds = -1;
4995 FD_ZERO(&rfds);
4996 FD_ZERO(&wfds);
4997 FD_ZERO(&xfds);
4998 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4999 if (ioh->fd_read &&
5000 (!ioh->fd_read_poll ||
5001 ioh->fd_read_poll(ioh->opaque) != 0)) {
5002 FD_SET(ioh->fd, &rfds);
5003 if (ioh->fd > nfds)
5004 nfds = ioh->fd;
5006 if (ioh->fd_write) {
5007 FD_SET(ioh->fd, &wfds);
5008 if (ioh->fd > nfds)
5009 nfds = ioh->fd;
5013 tv.tv_sec = 0;
5014 #ifdef _WIN32
5015 tv.tv_usec = 0;
5016 #else
5017 tv.tv_usec = timeout * 1000;
5018 #endif
5019 #if defined(CONFIG_SLIRP)
5020 if (slirp_inited) {
5021 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5023 #endif
5024 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5025 if (ret > 0) {
5026 /* XXX: better handling of removal */
5027 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5028 ioh_next = ioh->next;
5029 if (FD_ISSET(ioh->fd, &rfds)) {
5030 ioh->fd_read(ioh->opaque);
5032 if (FD_ISSET(ioh->fd, &wfds)) {
5033 ioh->fd_write(ioh->opaque);
5037 #if defined(CONFIG_SLIRP)
5038 if (slirp_inited) {
5039 if (ret < 0) {
5040 FD_ZERO(&rfds);
5041 FD_ZERO(&wfds);
5042 FD_ZERO(&xfds);
5044 slirp_select_poll(&rfds, &wfds, &xfds);
5046 #endif
5047 #ifdef _WIN32
5048 tap_win32_poll();
5049 #endif
5051 if (vm_running) {
5052 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5053 qemu_get_clock(vm_clock));
5054 /* run dma transfers, if any */
5055 DMA_run();
5058 /* real time timers */
5059 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5060 qemu_get_clock(rt_clock));
5063 static CPUState *cur_cpu;
5065 int main_loop(void)
5067 int ret, timeout;
5068 #ifdef CONFIG_PROFILER
5069 int64_t ti;
5070 #endif
5071 CPUState *env;
5073 cur_cpu = first_cpu;
5074 for(;;) {
5075 if (vm_running) {
5077 env = cur_cpu;
5078 for(;;) {
5079 /* get next cpu */
5080 env = env->next_cpu;
5081 if (!env)
5082 env = first_cpu;
5083 #ifdef CONFIG_PROFILER
5084 ti = profile_getclock();
5085 #endif
5086 ret = cpu_exec(env);
5087 #ifdef CONFIG_PROFILER
5088 qemu_time += profile_getclock() - ti;
5089 #endif
5090 if (ret != EXCP_HALTED)
5091 break;
5092 /* all CPUs are halted ? */
5093 if (env == cur_cpu) {
5094 ret = EXCP_HLT;
5095 break;
5098 cur_cpu = env;
5100 if (shutdown_requested) {
5101 ret = EXCP_INTERRUPT;
5102 break;
5104 if (reset_requested) {
5105 reset_requested = 0;
5106 qemu_system_reset();
5107 ret = EXCP_INTERRUPT;
5109 if (powerdown_requested) {
5110 powerdown_requested = 0;
5111 qemu_system_powerdown();
5112 ret = EXCP_INTERRUPT;
5114 if (ret == EXCP_DEBUG) {
5115 vm_stop(EXCP_DEBUG);
5117 /* if hlt instruction, we wait until the next IRQ */
5118 /* XXX: use timeout computed from timers */
5119 if (ret == EXCP_HLT)
5120 timeout = 10;
5121 else
5122 timeout = 0;
5123 } else {
5124 timeout = 10;
5126 #ifdef CONFIG_PROFILER
5127 ti = profile_getclock();
5128 #endif
5129 main_loop_wait(timeout);
5130 #ifdef CONFIG_PROFILER
5131 dev_time += profile_getclock() - ti;
5132 #endif
5134 cpu_disable_ticks();
5135 return ret;
5138 void help(void)
5140 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
5141 "usage: %s [options] [disk_image]\n"
5142 "\n"
5143 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5144 "\n"
5145 "Standard options:\n"
5146 "-M machine select emulated machine (-M ? for list)\n"
5147 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5148 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5149 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5150 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5151 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5152 "-snapshot write to temporary files instead of disk image files\n"
5153 #ifdef TARGET_I386
5154 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5155 #endif
5156 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5157 "-smp n set the number of CPUs to 'n' [default=1]\n"
5158 "-nographic disable graphical output and redirect serial I/Os to console\n"
5159 #ifndef _WIN32
5160 "-k language use keyboard layout (for example \"fr\" for French)\n"
5161 #endif
5162 #ifdef HAS_AUDIO
5163 "-audio-help print list of audio drivers and their options\n"
5164 "-soundhw c1,... enable audio support\n"
5165 " and only specified sound cards (comma separated list)\n"
5166 " use -soundhw ? to get the list of supported cards\n"
5167 " use -soundhw all to enable all of them\n"
5168 #endif
5169 "-localtime set the real time clock to local time [default=utc]\n"
5170 "-full-screen start in full screen\n"
5171 #ifdef TARGET_I386
5172 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5173 #endif
5174 "-usb enable the USB driver (will be the default soon)\n"
5175 "-usbdevice name add the host or guest USB device 'name'\n"
5176 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5177 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5178 #endif
5179 "\n"
5180 "Network options:\n"
5181 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5182 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5183 #ifdef CONFIG_SLIRP
5184 "-net user[,vlan=n][,hostname=host]\n"
5185 " connect the user mode network stack to VLAN 'n' and send\n"
5186 " hostname 'host' to DHCP clients\n"
5187 #endif
5188 #ifdef _WIN32
5189 "-net tap[,vlan=n],ifname=name\n"
5190 " connect the host TAP network interface to VLAN 'n'\n"
5191 #else
5192 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
5193 " connect the host TAP network interface to VLAN 'n' and use\n"
5194 " the network script 'file' (default=%s);\n"
5195 " use 'fd=h' to connect to an already opened TAP interface\n"
5196 #endif
5197 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5198 " connect the vlan 'n' to another VLAN using a socket connection\n"
5199 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5200 " connect the vlan 'n' to multicast maddr and port\n"
5201 "-net none use it alone to have zero network devices; if no -net option\n"
5202 " is provided, the default is '-net nic -net user'\n"
5203 "\n"
5204 #ifdef CONFIG_SLIRP
5205 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5206 #ifndef _WIN32
5207 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5208 #endif
5209 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5210 " redirect TCP or UDP connections from host to guest [-net user]\n"
5211 #endif
5212 "\n"
5213 "Linux boot specific:\n"
5214 "-kernel bzImage use 'bzImage' as kernel image\n"
5215 "-append cmdline use 'cmdline' as kernel command line\n"
5216 "-initrd file use 'file' as initial ram disk\n"
5217 "\n"
5218 "Debug/Expert options:\n"
5219 "-monitor dev redirect the monitor to char device 'dev'\n"
5220 "-serial dev redirect the serial port to char device 'dev'\n"
5221 "-parallel dev redirect the parallel port to char device 'dev'\n"
5222 "-pidfile file Write PID to 'file'\n"
5223 "-S freeze CPU at startup (use 'c' to start execution)\n"
5224 "-s wait gdb connection to port %d\n"
5225 "-p port change gdb connection port\n"
5226 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
5227 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5228 " translation (t=none or lba) (usually qemu can guess them)\n"
5229 "-L path set the directory for the BIOS and VGA BIOS\n"
5230 #ifdef USE_KQEMU
5231 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5232 "-no-kqemu disable KQEMU kernel module usage\n"
5233 #endif
5234 #ifdef USE_CODE_COPY
5235 "-no-code-copy disable code copy acceleration\n"
5236 #endif
5237 #ifdef TARGET_I386
5238 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5239 " (default is CL-GD5446 PCI VGA)\n"
5240 "-no-acpi disable ACPI\n"
5241 #endif
5242 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5243 "-vnc display start a VNC server on display\n"
5244 "\n"
5245 "During emulation, the following keys are useful:\n"
5246 "ctrl-alt-f toggle full screen\n"
5247 "ctrl-alt-n switch to virtual console 'n'\n"
5248 "ctrl-alt toggle mouse and keyboard grab\n"
5249 "\n"
5250 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5252 "qemu",
5253 DEFAULT_RAM_SIZE,
5254 #ifndef _WIN32
5255 DEFAULT_NETWORK_SCRIPT,
5256 #endif
5257 DEFAULT_GDBSTUB_PORT,
5258 "/tmp/qemu.log");
5259 exit(1);
5262 #define HAS_ARG 0x0001
5264 enum {
5265 QEMU_OPTION_h,
5267 QEMU_OPTION_M,
5268 QEMU_OPTION_fda,
5269 QEMU_OPTION_fdb,
5270 QEMU_OPTION_hda,
5271 QEMU_OPTION_hdb,
5272 QEMU_OPTION_hdc,
5273 QEMU_OPTION_hdd,
5274 QEMU_OPTION_cdrom,
5275 QEMU_OPTION_boot,
5276 QEMU_OPTION_snapshot,
5277 #ifdef TARGET_I386
5278 QEMU_OPTION_no_fd_bootchk,
5279 #endif
5280 QEMU_OPTION_m,
5281 QEMU_OPTION_nographic,
5282 #ifdef HAS_AUDIO
5283 QEMU_OPTION_audio_help,
5284 QEMU_OPTION_soundhw,
5285 #endif
5287 QEMU_OPTION_net,
5288 QEMU_OPTION_tftp,
5289 QEMU_OPTION_smb,
5290 QEMU_OPTION_redir,
5292 QEMU_OPTION_kernel,
5293 QEMU_OPTION_append,
5294 QEMU_OPTION_initrd,
5296 QEMU_OPTION_S,
5297 QEMU_OPTION_s,
5298 QEMU_OPTION_p,
5299 QEMU_OPTION_d,
5300 QEMU_OPTION_hdachs,
5301 QEMU_OPTION_L,
5302 QEMU_OPTION_no_code_copy,
5303 QEMU_OPTION_k,
5304 QEMU_OPTION_localtime,
5305 QEMU_OPTION_cirrusvga,
5306 QEMU_OPTION_g,
5307 QEMU_OPTION_std_vga,
5308 QEMU_OPTION_monitor,
5309 QEMU_OPTION_serial,
5310 QEMU_OPTION_parallel,
5311 QEMU_OPTION_loadvm,
5312 QEMU_OPTION_full_screen,
5313 QEMU_OPTION_pidfile,
5314 QEMU_OPTION_no_kqemu,
5315 QEMU_OPTION_kernel_kqemu,
5316 QEMU_OPTION_win2k_hack,
5317 QEMU_OPTION_usb,
5318 QEMU_OPTION_usbdevice,
5319 QEMU_OPTION_smp,
5320 QEMU_OPTION_vnc,
5321 QEMU_OPTION_no_acpi,
5324 typedef struct QEMUOption {
5325 const char *name;
5326 int flags;
5327 int index;
5328 } QEMUOption;
5330 const QEMUOption qemu_options[] = {
5331 { "h", 0, QEMU_OPTION_h },
5333 { "M", HAS_ARG, QEMU_OPTION_M },
5334 { "fda", HAS_ARG, QEMU_OPTION_fda },
5335 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5336 { "hda", HAS_ARG, QEMU_OPTION_hda },
5337 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5338 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5339 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5340 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5341 { "boot", HAS_ARG, QEMU_OPTION_boot },
5342 { "snapshot", 0, QEMU_OPTION_snapshot },
5343 #ifdef TARGET_I386
5344 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5345 #endif
5346 { "m", HAS_ARG, QEMU_OPTION_m },
5347 { "nographic", 0, QEMU_OPTION_nographic },
5348 { "k", HAS_ARG, QEMU_OPTION_k },
5349 #ifdef HAS_AUDIO
5350 { "audio-help", 0, QEMU_OPTION_audio_help },
5351 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5352 #endif
5354 { "net", HAS_ARG, QEMU_OPTION_net},
5355 #ifdef CONFIG_SLIRP
5356 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5357 #ifndef _WIN32
5358 { "smb", HAS_ARG, QEMU_OPTION_smb },
5359 #endif
5360 { "redir", HAS_ARG, QEMU_OPTION_redir },
5361 #endif
5363 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5364 { "append", HAS_ARG, QEMU_OPTION_append },
5365 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5367 { "S", 0, QEMU_OPTION_S },
5368 { "s", 0, QEMU_OPTION_s },
5369 { "p", HAS_ARG, QEMU_OPTION_p },
5370 { "d", HAS_ARG, QEMU_OPTION_d },
5371 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5372 { "L", HAS_ARG, QEMU_OPTION_L },
5373 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
5374 #ifdef USE_KQEMU
5375 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5376 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5377 #endif
5378 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5379 { "g", 1, QEMU_OPTION_g },
5380 #endif
5381 { "localtime", 0, QEMU_OPTION_localtime },
5382 { "std-vga", 0, QEMU_OPTION_std_vga },
5383 { "monitor", 1, QEMU_OPTION_monitor },
5384 { "serial", 1, QEMU_OPTION_serial },
5385 { "parallel", 1, QEMU_OPTION_parallel },
5386 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5387 { "full-screen", 0, QEMU_OPTION_full_screen },
5388 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5389 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5390 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5391 { "smp", HAS_ARG, QEMU_OPTION_smp },
5392 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5394 /* temporary options */
5395 { "usb", 0, QEMU_OPTION_usb },
5396 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
5397 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5398 { NULL },
5401 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5403 /* this stack is only used during signal handling */
5404 #define SIGNAL_STACK_SIZE 32768
5406 static uint8_t *signal_stack;
5408 #endif
5410 /* password input */
5412 static BlockDriverState *get_bdrv(int index)
5414 BlockDriverState *bs;
5416 if (index < 4) {
5417 bs = bs_table[index];
5418 } else if (index < 6) {
5419 bs = fd_table[index - 4];
5420 } else {
5421 bs = NULL;
5423 return bs;
5426 static void read_passwords(void)
5428 BlockDriverState *bs;
5429 int i, j;
5430 char password[256];
5432 for(i = 0; i < 6; i++) {
5433 bs = get_bdrv(i);
5434 if (bs && bdrv_is_encrypted(bs)) {
5435 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5436 for(j = 0; j < 3; j++) {
5437 monitor_readline("Password: ",
5438 1, password, sizeof(password));
5439 if (bdrv_set_key(bs, password) == 0)
5440 break;
5441 term_printf("invalid password\n");
5447 /* XXX: currently we cannot use simultaneously different CPUs */
5448 void register_machines(void)
5450 #if defined(TARGET_I386)
5451 qemu_register_machine(&pc_machine);
5452 qemu_register_machine(&isapc_machine);
5453 #elif defined(TARGET_PPC)
5454 qemu_register_machine(&heathrow_machine);
5455 qemu_register_machine(&core99_machine);
5456 qemu_register_machine(&prep_machine);
5457 #elif defined(TARGET_MIPS)
5458 qemu_register_machine(&mips_machine);
5459 #elif defined(TARGET_SPARC)
5460 #ifdef TARGET_SPARC64
5461 qemu_register_machine(&sun4u_machine);
5462 #else
5463 qemu_register_machine(&sun4m_machine);
5464 #endif
5465 #elif defined(TARGET_ARM)
5466 qemu_register_machine(&integratorcp926_machine);
5467 qemu_register_machine(&integratorcp1026_machine);
5468 qemu_register_machine(&versatilepb_machine);
5469 qemu_register_machine(&versatileab_machine);
5470 #elif defined(TARGET_SH4)
5471 qemu_register_machine(&shix_machine);
5472 #else
5473 #error unsupported CPU
5474 #endif
5477 #ifdef HAS_AUDIO
5478 struct soundhw soundhw[] = {
5479 #ifdef TARGET_I386
5481 "pcspk",
5482 "PC speaker",
5485 { .init_isa = pcspk_audio_init }
5487 #endif
5489 "sb16",
5490 "Creative Sound Blaster 16",
5493 { .init_isa = SB16_init }
5496 #ifdef CONFIG_ADLIB
5498 "adlib",
5499 #ifdef HAS_YMF262
5500 "Yamaha YMF262 (OPL3)",
5501 #else
5502 "Yamaha YM3812 (OPL2)",
5503 #endif
5506 { .init_isa = Adlib_init }
5508 #endif
5510 #ifdef CONFIG_GUS
5512 "gus",
5513 "Gravis Ultrasound GF1",
5516 { .init_isa = GUS_init }
5518 #endif
5521 "es1370",
5522 "ENSONIQ AudioPCI ES1370",
5525 { .init_pci = es1370_init }
5528 { NULL, NULL, 0, 0, { NULL } }
5531 static void select_soundhw (const char *optarg)
5533 struct soundhw *c;
5535 if (*optarg == '?') {
5536 show_valid_cards:
5538 printf ("Valid sound card names (comma separated):\n");
5539 for (c = soundhw; c->name; ++c) {
5540 printf ("%-11s %s\n", c->name, c->descr);
5542 printf ("\n-soundhw all will enable all of the above\n");
5543 exit (*optarg != '?');
5545 else {
5546 size_t l;
5547 const char *p;
5548 char *e;
5549 int bad_card = 0;
5551 if (!strcmp (optarg, "all")) {
5552 for (c = soundhw; c->name; ++c) {
5553 c->enabled = 1;
5555 return;
5558 p = optarg;
5559 while (*p) {
5560 e = strchr (p, ',');
5561 l = !e ? strlen (p) : (size_t) (e - p);
5563 for (c = soundhw; c->name; ++c) {
5564 if (!strncmp (c->name, p, l)) {
5565 c->enabled = 1;
5566 break;
5570 if (!c->name) {
5571 if (l > 80) {
5572 fprintf (stderr,
5573 "Unknown sound card name (too big to show)\n");
5575 else {
5576 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5577 (int) l, p);
5579 bad_card = 1;
5581 p += l + (e != NULL);
5584 if (bad_card)
5585 goto show_valid_cards;
5588 #endif
5590 #ifdef _WIN32
5591 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5593 exit(STATUS_CONTROL_C_EXIT);
5594 return TRUE;
5596 #endif
5598 #define MAX_NET_CLIENTS 32
5600 int main(int argc, char **argv)
5602 #ifdef CONFIG_GDBSTUB
5603 int use_gdbstub, gdbstub_port;
5604 #endif
5605 int i, cdrom_index;
5606 int snapshot, linux_boot;
5607 const char *initrd_filename;
5608 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5609 const char *kernel_filename, *kernel_cmdline;
5610 DisplayState *ds = &display_state;
5611 int cyls, heads, secs, translation;
5612 int start_emulation = 1;
5613 char net_clients[MAX_NET_CLIENTS][256];
5614 int nb_net_clients;
5615 int optind;
5616 const char *r, *optarg;
5617 CharDriverState *monitor_hd;
5618 char monitor_device[128];
5619 char serial_devices[MAX_SERIAL_PORTS][128];
5620 int serial_device_index;
5621 char parallel_devices[MAX_PARALLEL_PORTS][128];
5622 int parallel_device_index;
5623 const char *loadvm = NULL;
5624 QEMUMachine *machine;
5625 char usb_devices[MAX_USB_CMDLINE][128];
5626 int usb_devices_index;
5628 LIST_INIT (&vm_change_state_head);
5629 #ifndef _WIN32
5631 struct sigaction act;
5632 sigfillset(&act.sa_mask);
5633 act.sa_flags = 0;
5634 act.sa_handler = SIG_IGN;
5635 sigaction(SIGPIPE, &act, NULL);
5637 #else
5638 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5639 #endif
5640 init_timers();
5642 register_machines();
5643 machine = first_machine;
5644 initrd_filename = NULL;
5645 for(i = 0; i < MAX_FD; i++)
5646 fd_filename[i] = NULL;
5647 for(i = 0; i < MAX_DISKS; i++)
5648 hd_filename[i] = NULL;
5649 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5650 vga_ram_size = VGA_RAM_SIZE;
5651 bios_size = BIOS_SIZE;
5652 #ifdef CONFIG_GDBSTUB
5653 use_gdbstub = 0;
5654 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5655 #endif
5656 snapshot = 0;
5657 nographic = 0;
5658 kernel_filename = NULL;
5659 kernel_cmdline = "";
5660 #ifdef TARGET_PPC
5661 cdrom_index = 1;
5662 #else
5663 cdrom_index = 2;
5664 #endif
5665 cyls = heads = secs = 0;
5666 translation = BIOS_ATA_TRANSLATION_AUTO;
5667 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5669 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5670 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5671 serial_devices[i][0] = '\0';
5672 serial_device_index = 0;
5674 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5675 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5676 parallel_devices[i][0] = '\0';
5677 parallel_device_index = 0;
5679 usb_devices_index = 0;
5681 nb_net_clients = 0;
5683 nb_nics = 0;
5684 /* default mac address of the first network interface */
5686 optind = 1;
5687 for(;;) {
5688 if (optind >= argc)
5689 break;
5690 r = argv[optind];
5691 if (r[0] != '-') {
5692 hd_filename[0] = argv[optind++];
5693 } else {
5694 const QEMUOption *popt;
5696 optind++;
5697 popt = qemu_options;
5698 for(;;) {
5699 if (!popt->name) {
5700 fprintf(stderr, "%s: invalid option -- '%s'\n",
5701 argv[0], r);
5702 exit(1);
5704 if (!strcmp(popt->name, r + 1))
5705 break;
5706 popt++;
5708 if (popt->flags & HAS_ARG) {
5709 if (optind >= argc) {
5710 fprintf(stderr, "%s: option '%s' requires an argument\n",
5711 argv[0], r);
5712 exit(1);
5714 optarg = argv[optind++];
5715 } else {
5716 optarg = NULL;
5719 switch(popt->index) {
5720 case QEMU_OPTION_M:
5721 machine = find_machine(optarg);
5722 if (!machine) {
5723 QEMUMachine *m;
5724 printf("Supported machines are:\n");
5725 for(m = first_machine; m != NULL; m = m->next) {
5726 printf("%-10s %s%s\n",
5727 m->name, m->desc,
5728 m == first_machine ? " (default)" : "");
5730 exit(1);
5732 break;
5733 case QEMU_OPTION_initrd:
5734 initrd_filename = optarg;
5735 break;
5736 case QEMU_OPTION_hda:
5737 case QEMU_OPTION_hdb:
5738 case QEMU_OPTION_hdc:
5739 case QEMU_OPTION_hdd:
5741 int hd_index;
5742 hd_index = popt->index - QEMU_OPTION_hda;
5743 hd_filename[hd_index] = optarg;
5744 if (hd_index == cdrom_index)
5745 cdrom_index = -1;
5747 break;
5748 case QEMU_OPTION_snapshot:
5749 snapshot = 1;
5750 break;
5751 case QEMU_OPTION_hdachs:
5753 const char *p;
5754 p = optarg;
5755 cyls = strtol(p, (char **)&p, 0);
5756 if (cyls < 1 || cyls > 16383)
5757 goto chs_fail;
5758 if (*p != ',')
5759 goto chs_fail;
5760 p++;
5761 heads = strtol(p, (char **)&p, 0);
5762 if (heads < 1 || heads > 16)
5763 goto chs_fail;
5764 if (*p != ',')
5765 goto chs_fail;
5766 p++;
5767 secs = strtol(p, (char **)&p, 0);
5768 if (secs < 1 || secs > 63)
5769 goto chs_fail;
5770 if (*p == ',') {
5771 p++;
5772 if (!strcmp(p, "none"))
5773 translation = BIOS_ATA_TRANSLATION_NONE;
5774 else if (!strcmp(p, "lba"))
5775 translation = BIOS_ATA_TRANSLATION_LBA;
5776 else if (!strcmp(p, "auto"))
5777 translation = BIOS_ATA_TRANSLATION_AUTO;
5778 else
5779 goto chs_fail;
5780 } else if (*p != '\0') {
5781 chs_fail:
5782 fprintf(stderr, "qemu: invalid physical CHS format\n");
5783 exit(1);
5786 break;
5787 case QEMU_OPTION_nographic:
5788 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5789 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5790 nographic = 1;
5791 break;
5792 case QEMU_OPTION_kernel:
5793 kernel_filename = optarg;
5794 break;
5795 case QEMU_OPTION_append:
5796 kernel_cmdline = optarg;
5797 break;
5798 case QEMU_OPTION_cdrom:
5799 if (cdrom_index >= 0) {
5800 hd_filename[cdrom_index] = optarg;
5802 break;
5803 case QEMU_OPTION_boot:
5804 boot_device = optarg[0];
5805 if (boot_device != 'a' &&
5806 #ifdef TARGET_SPARC
5807 // Network boot
5808 boot_device != 'n' &&
5809 #endif
5810 boot_device != 'c' && boot_device != 'd') {
5811 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5812 exit(1);
5814 break;
5815 case QEMU_OPTION_fda:
5816 fd_filename[0] = optarg;
5817 break;
5818 case QEMU_OPTION_fdb:
5819 fd_filename[1] = optarg;
5820 break;
5821 #ifdef TARGET_I386
5822 case QEMU_OPTION_no_fd_bootchk:
5823 fd_bootchk = 0;
5824 break;
5825 #endif
5826 case QEMU_OPTION_no_code_copy:
5827 code_copy_enabled = 0;
5828 break;
5829 case QEMU_OPTION_net:
5830 if (nb_net_clients >= MAX_NET_CLIENTS) {
5831 fprintf(stderr, "qemu: too many network clients\n");
5832 exit(1);
5834 pstrcpy(net_clients[nb_net_clients],
5835 sizeof(net_clients[0]),
5836 optarg);
5837 nb_net_clients++;
5838 break;
5839 #ifdef CONFIG_SLIRP
5840 case QEMU_OPTION_tftp:
5841 tftp_prefix = optarg;
5842 break;
5843 #ifndef _WIN32
5844 case QEMU_OPTION_smb:
5845 net_slirp_smb(optarg);
5846 break;
5847 #endif
5848 case QEMU_OPTION_redir:
5849 net_slirp_redir(optarg);
5850 break;
5851 #endif
5852 #ifdef HAS_AUDIO
5853 case QEMU_OPTION_audio_help:
5854 AUD_help ();
5855 exit (0);
5856 break;
5857 case QEMU_OPTION_soundhw:
5858 select_soundhw (optarg);
5859 break;
5860 #endif
5861 case QEMU_OPTION_h:
5862 help();
5863 break;
5864 case QEMU_OPTION_m:
5865 ram_size = atoi(optarg) * 1024 * 1024;
5866 if (ram_size <= 0)
5867 help();
5868 if (ram_size > PHYS_RAM_MAX_SIZE) {
5869 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5870 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5871 exit(1);
5873 break;
5874 case QEMU_OPTION_d:
5876 int mask;
5877 CPULogItem *item;
5879 mask = cpu_str_to_log_mask(optarg);
5880 if (!mask) {
5881 printf("Log items (comma separated):\n");
5882 for(item = cpu_log_items; item->mask != 0; item++) {
5883 printf("%-10s %s\n", item->name, item->help);
5885 exit(1);
5887 cpu_set_log(mask);
5889 break;
5890 #ifdef CONFIG_GDBSTUB
5891 case QEMU_OPTION_s:
5892 use_gdbstub = 1;
5893 break;
5894 case QEMU_OPTION_p:
5895 gdbstub_port = atoi(optarg);
5896 break;
5897 #endif
5898 case QEMU_OPTION_L:
5899 bios_dir = optarg;
5900 break;
5901 case QEMU_OPTION_S:
5902 start_emulation = 0;
5903 break;
5904 case QEMU_OPTION_k:
5905 keyboard_layout = optarg;
5906 break;
5907 case QEMU_OPTION_localtime:
5908 rtc_utc = 0;
5909 break;
5910 case QEMU_OPTION_cirrusvga:
5911 cirrus_vga_enabled = 1;
5912 break;
5913 case QEMU_OPTION_std_vga:
5914 cirrus_vga_enabled = 0;
5915 break;
5916 case QEMU_OPTION_g:
5918 const char *p;
5919 int w, h, depth;
5920 p = optarg;
5921 w = strtol(p, (char **)&p, 10);
5922 if (w <= 0) {
5923 graphic_error:
5924 fprintf(stderr, "qemu: invalid resolution or depth\n");
5925 exit(1);
5927 if (*p != 'x')
5928 goto graphic_error;
5929 p++;
5930 h = strtol(p, (char **)&p, 10);
5931 if (h <= 0)
5932 goto graphic_error;
5933 if (*p == 'x') {
5934 p++;
5935 depth = strtol(p, (char **)&p, 10);
5936 if (depth != 8 && depth != 15 && depth != 16 &&
5937 depth != 24 && depth != 32)
5938 goto graphic_error;
5939 } else if (*p == '\0') {
5940 depth = graphic_depth;
5941 } else {
5942 goto graphic_error;
5945 graphic_width = w;
5946 graphic_height = h;
5947 graphic_depth = depth;
5949 break;
5950 case QEMU_OPTION_monitor:
5951 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5952 break;
5953 case QEMU_OPTION_serial:
5954 if (serial_device_index >= MAX_SERIAL_PORTS) {
5955 fprintf(stderr, "qemu: too many serial ports\n");
5956 exit(1);
5958 pstrcpy(serial_devices[serial_device_index],
5959 sizeof(serial_devices[0]), optarg);
5960 serial_device_index++;
5961 break;
5962 case QEMU_OPTION_parallel:
5963 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5964 fprintf(stderr, "qemu: too many parallel ports\n");
5965 exit(1);
5967 pstrcpy(parallel_devices[parallel_device_index],
5968 sizeof(parallel_devices[0]), optarg);
5969 parallel_device_index++;
5970 break;
5971 case QEMU_OPTION_loadvm:
5972 loadvm = optarg;
5973 break;
5974 case QEMU_OPTION_full_screen:
5975 full_screen = 1;
5976 break;
5977 case QEMU_OPTION_pidfile:
5978 create_pidfile(optarg);
5979 break;
5980 #ifdef TARGET_I386
5981 case QEMU_OPTION_win2k_hack:
5982 win2k_install_hack = 1;
5983 break;
5984 #endif
5985 #ifdef USE_KQEMU
5986 case QEMU_OPTION_no_kqemu:
5987 kqemu_allowed = 0;
5988 break;
5989 case QEMU_OPTION_kernel_kqemu:
5990 kqemu_allowed = 2;
5991 break;
5992 #endif
5993 case QEMU_OPTION_usb:
5994 usb_enabled = 1;
5995 break;
5996 case QEMU_OPTION_usbdevice:
5997 usb_enabled = 1;
5998 if (usb_devices_index >= MAX_USB_CMDLINE) {
5999 fprintf(stderr, "Too many USB devices\n");
6000 exit(1);
6002 pstrcpy(usb_devices[usb_devices_index],
6003 sizeof(usb_devices[usb_devices_index]),
6004 optarg);
6005 usb_devices_index++;
6006 break;
6007 case QEMU_OPTION_smp:
6008 smp_cpus = atoi(optarg);
6009 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6010 fprintf(stderr, "Invalid number of CPUs\n");
6011 exit(1);
6013 break;
6014 case QEMU_OPTION_vnc:
6015 vnc_display = atoi(optarg);
6016 if (vnc_display < 0) {
6017 fprintf(stderr, "Invalid VNC display\n");
6018 exit(1);
6020 break;
6021 case QEMU_OPTION_no_acpi:
6022 acpi_enabled = 0;
6023 break;
6028 #ifdef USE_KQEMU
6029 if (smp_cpus > 1)
6030 kqemu_allowed = 0;
6031 #endif
6032 linux_boot = (kernel_filename != NULL);
6034 if (!linux_boot &&
6035 hd_filename[0] == '\0' &&
6036 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6037 fd_filename[0] == '\0')
6038 help();
6040 /* boot to cd by default if no hard disk */
6041 if (hd_filename[0] == '\0' && boot_device == 'c') {
6042 if (fd_filename[0] != '\0')
6043 boot_device = 'a';
6044 else
6045 boot_device = 'd';
6048 setvbuf(stdout, NULL, _IOLBF, 0);
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();
6131 cpu_calibrate_ticks();
6133 /* terminal init */
6134 if (nographic) {
6135 dumb_display_init(ds);
6136 } else if (vnc_display != -1) {
6137 vnc_display_init(ds, vnc_display);
6138 } else {
6139 #if defined(CONFIG_SDL)
6140 sdl_display_init(ds, full_screen);
6141 #elif defined(CONFIG_COCOA)
6142 cocoa_display_init(ds, full_screen);
6143 #else
6144 dumb_display_init(ds);
6145 #endif
6148 monitor_hd = qemu_chr_open(monitor_device);
6149 if (!monitor_hd) {
6150 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6151 exit(1);
6153 monitor_init(monitor_hd, !nographic);
6155 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6156 if (serial_devices[i][0] != '\0') {
6157 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6158 if (!serial_hds[i]) {
6159 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6160 serial_devices[i]);
6161 exit(1);
6163 if (!strcmp(serial_devices[i], "vc"))
6164 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
6168 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6169 if (parallel_devices[i][0] != '\0') {
6170 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6171 if (!parallel_hds[i]) {
6172 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6173 parallel_devices[i]);
6174 exit(1);
6176 if (!strcmp(parallel_devices[i], "vc"))
6177 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
6181 machine->init(ram_size, vga_ram_size, boot_device,
6182 ds, fd_filename, snapshot,
6183 kernel_filename, kernel_cmdline, initrd_filename);
6185 /* init USB devices */
6186 if (usb_enabled) {
6187 for(i = 0; i < usb_devices_index; i++) {
6188 if (usb_device_add(usb_devices[i]) < 0) {
6189 fprintf(stderr, "Warning: could not add USB device %s\n",
6190 usb_devices[i]);
6195 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6196 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6198 #ifdef CONFIG_GDBSTUB
6199 if (use_gdbstub) {
6200 if (gdbserver_start(gdbstub_port) < 0) {
6201 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6202 gdbstub_port);
6203 exit(1);
6204 } else {
6205 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6207 } else
6208 #endif
6209 if (loadvm)
6210 qemu_loadvm(loadvm);
6213 /* XXX: simplify init */
6214 read_passwords();
6215 if (start_emulation) {
6216 vm_start();
6219 main_loop();
6220 quit_timers();
6221 return 0;