Insert/remove kvm kernel module on start/stop
[qemu-kvm/fedora.git] / vl.c
blobbc7185ab46b1da494b27817e695d1ad3542fb35d
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 #if USE_KVM
91 #include "qemu-kvm.h"
92 #endif
94 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
96 //#define DEBUG_UNUSED_IOPORT
97 //#define DEBUG_IOPORT
99 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
101 #ifdef TARGET_PPC
102 #define DEFAULT_RAM_SIZE 144
103 #else
104 #define DEFAULT_RAM_SIZE 128
105 #endif
106 /* in ms */
107 #define GUI_REFRESH_INTERVAL 30
109 /* Max number of USB devices that can be specified on the commandline. */
110 #define MAX_USB_CMDLINE 8
112 /* XXX: use a two level table to limit memory usage */
113 #define MAX_IOPORTS 65536
115 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
116 char phys_ram_file[1024];
117 void *ioport_opaque[MAX_IOPORTS];
118 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
119 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
120 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
121 int vga_ram_size;
122 int bios_size;
123 static DisplayState display_state;
124 int nographic;
125 const char* keyboard_layout = NULL;
126 int64_t ticks_per_sec;
127 int boot_device = 'c';
128 int ram_size;
129 int pit_min_timer_count = 0;
130 int nb_nics;
131 NICInfo nd_table[MAX_NICS];
132 QEMUTimer *gui_timer;
133 int vm_running;
134 int rtc_utc = 1;
135 int cirrus_vga_enabled = 1;
136 #ifdef TARGET_SPARC
137 int graphic_width = 1024;
138 int graphic_height = 768;
139 #else
140 int graphic_width = 800;
141 int graphic_height = 600;
142 #endif
143 int graphic_depth = 15;
144 int full_screen = 0;
145 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
146 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
147 #ifdef TARGET_I386
148 int win2k_install_hack = 0;
149 #endif
150 int usb_enabled = 0;
151 static VLANState *first_vlan;
152 int smp_cpus = 1;
153 int vnc_display = -1;
154 #if defined(TARGET_SPARC)
155 #define MAX_CPUS 16
156 #elif defined(TARGET_I386)
157 #define MAX_CPUS 255
158 #else
159 #define MAX_CPUS 1
160 #endif
161 int acpi_enabled = 1;
162 int fd_bootchk = 1;
164 /***********************************************************/
165 /* x86 ISA bus support */
167 target_phys_addr_t isa_mem_base = 0;
168 PicState2 *isa_pic;
170 uint32_t default_ioport_readb(void *opaque, uint32_t address)
172 #ifdef DEBUG_UNUSED_IOPORT
173 fprintf(stderr, "inb: port=0x%04x\n", address);
174 #endif
175 return 0xff;
178 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
180 #ifdef DEBUG_UNUSED_IOPORT
181 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
182 #endif
185 /* default is to make two byte accesses */
186 uint32_t default_ioport_readw(void *opaque, uint32_t address)
188 uint32_t data;
189 data = ioport_read_table[0][address](ioport_opaque[address], address);
190 address = (address + 1) & (MAX_IOPORTS - 1);
191 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
192 return data;
195 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
197 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
198 address = (address + 1) & (MAX_IOPORTS - 1);
199 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
202 uint32_t default_ioport_readl(void *opaque, uint32_t address)
204 #ifdef DEBUG_UNUSED_IOPORT
205 fprintf(stderr, "inl: port=0x%04x\n", address);
206 #endif
207 return 0xffffffff;
210 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
212 #ifdef DEBUG_UNUSED_IOPORT
213 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
214 #endif
217 void init_ioports(void)
219 int i;
221 for(i = 0; i < MAX_IOPORTS; i++) {
222 ioport_read_table[0][i] = default_ioport_readb;
223 ioport_write_table[0][i] = default_ioport_writeb;
224 ioport_read_table[1][i] = default_ioport_readw;
225 ioport_write_table[1][i] = default_ioport_writew;
226 ioport_read_table[2][i] = default_ioport_readl;
227 ioport_write_table[2][i] = default_ioport_writel;
231 /* size is the word size in byte */
232 int register_ioport_read(int start, int length, int size,
233 IOPortReadFunc *func, void *opaque)
235 int i, bsize;
237 if (size == 1) {
238 bsize = 0;
239 } else if (size == 2) {
240 bsize = 1;
241 } else if (size == 4) {
242 bsize = 2;
243 } else {
244 hw_error("register_ioport_read: invalid size");
245 return -1;
247 for(i = start; i < start + length; i += size) {
248 ioport_read_table[bsize][i] = func;
249 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
250 hw_error("register_ioport_read: invalid opaque");
251 ioport_opaque[i] = opaque;
253 return 0;
256 /* size is the word size in byte */
257 int register_ioport_write(int start, int length, int size,
258 IOPortWriteFunc *func, void *opaque)
260 int i, bsize;
262 if (size == 1) {
263 bsize = 0;
264 } else if (size == 2) {
265 bsize = 1;
266 } else if (size == 4) {
267 bsize = 2;
268 } else {
269 hw_error("register_ioport_write: invalid size");
270 return -1;
272 for(i = start; i < start + length; i += size) {
273 ioport_write_table[bsize][i] = func;
274 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
275 hw_error("register_ioport_read: invalid opaque");
276 ioport_opaque[i] = opaque;
278 return 0;
281 void isa_unassign_ioport(int start, int length)
283 int i;
285 for(i = start; i < start + length; i++) {
286 ioport_read_table[0][i] = default_ioport_readb;
287 ioport_read_table[1][i] = default_ioport_readw;
288 ioport_read_table[2][i] = default_ioport_readl;
290 ioport_write_table[0][i] = default_ioport_writeb;
291 ioport_write_table[1][i] = default_ioport_writew;
292 ioport_write_table[2][i] = default_ioport_writel;
296 /***********************************************************/
298 void pstrcpy(char *buf, int buf_size, const char *str)
300 int c;
301 char *q = buf;
303 if (buf_size <= 0)
304 return;
306 for(;;) {
307 c = *str++;
308 if (c == 0 || q >= buf + buf_size - 1)
309 break;
310 *q++ = c;
312 *q = '\0';
315 /* strcat and truncate. */
316 char *pstrcat(char *buf, int buf_size, const char *s)
318 int len;
319 len = strlen(buf);
320 if (len < buf_size)
321 pstrcpy(buf + len, buf_size - len, s);
322 return buf;
325 int strstart(const char *str, const char *val, const char **ptr)
327 const char *p, *q;
328 p = str;
329 q = val;
330 while (*q != '\0') {
331 if (*p != *q)
332 return 0;
333 p++;
334 q++;
336 if (ptr)
337 *ptr = p;
338 return 1;
341 void cpu_outb(CPUState *env, int addr, int val)
343 #ifdef DEBUG_IOPORT
344 if (loglevel & CPU_LOG_IOPORT)
345 fprintf(logfile, "outb: %04x %02x\n", addr, val);
346 #endif
347 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
348 #ifdef USE_KQEMU
349 if (env)
350 env->last_io_time = cpu_get_time_fast();
351 #endif
354 void cpu_outw(CPUState *env, int addr, int val)
356 #ifdef DEBUG_IOPORT
357 if (loglevel & CPU_LOG_IOPORT)
358 fprintf(logfile, "outw: %04x %04x\n", addr, val);
359 #endif
360 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
361 #ifdef USE_KQEMU
362 if (env)
363 env->last_io_time = cpu_get_time_fast();
364 #endif
367 void cpu_outl(CPUState *env, int addr, int val)
369 #ifdef DEBUG_IOPORT
370 if (loglevel & CPU_LOG_IOPORT)
371 fprintf(logfile, "outl: %04x %08x\n", addr, val);
372 #endif
373 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
374 #ifdef USE_KQEMU
375 if (env)
376 env->last_io_time = cpu_get_time_fast();
377 #endif
380 int cpu_inb(CPUState *env, int addr)
382 int val;
383 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
384 #ifdef DEBUG_IOPORT
385 if (loglevel & CPU_LOG_IOPORT)
386 fprintf(logfile, "inb : %04x %02x\n", addr, val);
387 #endif
388 #ifdef USE_KQEMU
389 if (env)
390 env->last_io_time = cpu_get_time_fast();
391 #endif
392 return val;
395 int cpu_inw(CPUState *env, int addr)
397 int val;
398 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
399 #ifdef DEBUG_IOPORT
400 if (loglevel & CPU_LOG_IOPORT)
401 fprintf(logfile, "inw : %04x %04x\n", addr, val);
402 #endif
403 #ifdef USE_KQEMU
404 if (env)
405 env->last_io_time = cpu_get_time_fast();
406 #endif
407 return val;
410 int cpu_inl(CPUState *env, int addr)
412 int val;
413 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
414 #ifdef DEBUG_IOPORT
415 if (loglevel & CPU_LOG_IOPORT)
416 fprintf(logfile, "inl : %04x %08x\n", addr, val);
417 #endif
418 #ifdef USE_KQEMU
419 if (env)
420 env->last_io_time = cpu_get_time_fast();
421 #endif
422 return val;
425 /***********************************************************/
426 void hw_error(const char *fmt, ...)
428 va_list ap;
429 CPUState *env;
431 va_start(ap, fmt);
432 fprintf(stderr, "qemu: hardware error: ");
433 vfprintf(stderr, fmt, ap);
434 fprintf(stderr, "\n");
435 for(env = first_cpu; env != NULL; env = env->next_cpu) {
436 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
437 #ifdef TARGET_I386
438 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
439 #else
440 cpu_dump_state(env, stderr, fprintf, 0);
441 #endif
443 va_end(ap);
444 abort();
447 /***********************************************************/
448 /* keyboard/mouse */
450 static QEMUPutKBDEvent *qemu_put_kbd_event;
451 static void *qemu_put_kbd_event_opaque;
452 static QEMUPutMouseEvent *qemu_put_mouse_event;
453 static void *qemu_put_mouse_event_opaque;
454 static int qemu_put_mouse_event_absolute;
456 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
458 qemu_put_kbd_event_opaque = opaque;
459 qemu_put_kbd_event = func;
462 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
464 qemu_put_mouse_event_opaque = opaque;
465 qemu_put_mouse_event = func;
466 qemu_put_mouse_event_absolute = absolute;
469 void kbd_put_keycode(int keycode)
471 if (qemu_put_kbd_event) {
472 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
476 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
478 if (qemu_put_mouse_event) {
479 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
480 dx, dy, dz, buttons_state);
484 int kbd_mouse_is_absolute(void)
486 return qemu_put_mouse_event_absolute;
489 /* compute with 96 bit intermediate result: (a*b)/c */
490 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
492 union {
493 uint64_t ll;
494 struct {
495 #ifdef WORDS_BIGENDIAN
496 uint32_t high, low;
497 #else
498 uint32_t low, high;
499 #endif
500 } l;
501 } u, res;
502 uint64_t rl, rh;
504 u.ll = a;
505 rl = (uint64_t)u.l.low * (uint64_t)b;
506 rh = (uint64_t)u.l.high * (uint64_t)b;
507 rh += (rl >> 32);
508 res.l.high = rh / c;
509 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
510 return res.ll;
513 /***********************************************************/
514 /* real time host monotonic timer */
516 #define QEMU_TIMER_BASE 1000000000LL
518 #ifdef WIN32
520 static int64_t clock_freq;
522 static void init_get_clock(void)
524 LARGE_INTEGER freq;
525 int ret;
526 ret = QueryPerformanceFrequency(&freq);
527 if (ret == 0) {
528 fprintf(stderr, "Could not calibrate ticks\n");
529 exit(1);
531 clock_freq = freq.QuadPart;
534 static int64_t get_clock(void)
536 LARGE_INTEGER ti;
537 QueryPerformanceCounter(&ti);
538 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
541 #else
543 static int use_rt_clock;
545 static void init_get_clock(void)
547 use_rt_clock = 0;
548 #if defined(__linux__)
550 struct timespec ts;
551 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
552 use_rt_clock = 1;
555 #endif
558 static int64_t get_clock(void)
560 #if defined(__linux__)
561 if (use_rt_clock) {
562 struct timespec ts;
563 clock_gettime(CLOCK_MONOTONIC, &ts);
564 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
565 } else
566 #endif
568 /* XXX: using gettimeofday leads to problems if the date
569 changes, so it should be avoided. */
570 struct timeval tv;
571 gettimeofday(&tv, NULL);
572 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
576 #endif
578 /***********************************************************/
579 /* guest cycle counter */
581 static int64_t cpu_ticks_prev;
582 static int64_t cpu_ticks_offset;
583 static int64_t cpu_clock_offset;
584 static int cpu_ticks_enabled;
586 /* return the host CPU cycle counter and handle stop/restart */
587 int64_t cpu_get_ticks(void)
589 if (!cpu_ticks_enabled) {
590 return cpu_ticks_offset;
591 } else {
592 int64_t ticks;
593 ticks = cpu_get_real_ticks();
594 if (cpu_ticks_prev > ticks) {
595 /* Note: non increasing ticks may happen if the host uses
596 software suspend */
597 cpu_ticks_offset += cpu_ticks_prev - ticks;
599 cpu_ticks_prev = ticks;
600 return ticks + cpu_ticks_offset;
604 /* return the host CPU monotonic timer and handle stop/restart */
605 static int64_t cpu_get_clock(void)
607 int64_t ti;
608 if (!cpu_ticks_enabled) {
609 return cpu_clock_offset;
610 } else {
611 ti = get_clock();
612 return ti + cpu_clock_offset;
616 /* enable cpu_get_ticks() */
617 void cpu_enable_ticks(void)
619 if (!cpu_ticks_enabled) {
620 cpu_ticks_offset -= cpu_get_real_ticks();
621 cpu_clock_offset -= get_clock();
622 cpu_ticks_enabled = 1;
626 /* disable cpu_get_ticks() : the clock is stopped. You must not call
627 cpu_get_ticks() after that. */
628 void cpu_disable_ticks(void)
630 if (cpu_ticks_enabled) {
631 cpu_ticks_offset = cpu_get_ticks();
632 cpu_clock_offset = cpu_get_clock();
633 cpu_ticks_enabled = 0;
637 /***********************************************************/
638 /* timers */
640 #define QEMU_TIMER_REALTIME 0
641 #define QEMU_TIMER_VIRTUAL 1
643 struct QEMUClock {
644 int type;
645 /* XXX: add frequency */
648 struct QEMUTimer {
649 QEMUClock *clock;
650 int64_t expire_time;
651 QEMUTimerCB *cb;
652 void *opaque;
653 struct QEMUTimer *next;
656 QEMUClock *rt_clock;
657 QEMUClock *vm_clock;
659 static QEMUTimer *active_timers[2];
660 #ifdef _WIN32
661 static MMRESULT timerID;
662 static HANDLE host_alarm = NULL;
663 static unsigned int period = 1;
664 #else
665 /* frequency of the times() clock tick */
666 static int timer_freq;
667 #endif
669 QEMUClock *qemu_new_clock(int type)
671 QEMUClock *clock;
672 clock = qemu_mallocz(sizeof(QEMUClock));
673 if (!clock)
674 return NULL;
675 clock->type = type;
676 return clock;
679 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
681 QEMUTimer *ts;
683 ts = qemu_mallocz(sizeof(QEMUTimer));
684 ts->clock = clock;
685 ts->cb = cb;
686 ts->opaque = opaque;
687 return ts;
690 void qemu_free_timer(QEMUTimer *ts)
692 qemu_free(ts);
695 /* stop a timer, but do not dealloc it */
696 void qemu_del_timer(QEMUTimer *ts)
698 QEMUTimer **pt, *t;
700 /* NOTE: this code must be signal safe because
701 qemu_timer_expired() can be called from a signal. */
702 pt = &active_timers[ts->clock->type];
703 for(;;) {
704 t = *pt;
705 if (!t)
706 break;
707 if (t == ts) {
708 *pt = t->next;
709 break;
711 pt = &t->next;
715 /* modify the current timer so that it will be fired when current_time
716 >= expire_time. The corresponding callback will be called. */
717 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
719 QEMUTimer **pt, *t;
721 qemu_del_timer(ts);
723 /* add the timer in the sorted list */
724 /* NOTE: this code must be signal safe because
725 qemu_timer_expired() can be called from a signal. */
726 pt = &active_timers[ts->clock->type];
727 for(;;) {
728 t = *pt;
729 if (!t)
730 break;
731 if (t->expire_time > expire_time)
732 break;
733 pt = &t->next;
735 ts->expire_time = expire_time;
736 ts->next = *pt;
737 *pt = ts;
740 int qemu_timer_pending(QEMUTimer *ts)
742 QEMUTimer *t;
743 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
744 if (t == ts)
745 return 1;
747 return 0;
750 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
752 if (!timer_head)
753 return 0;
754 return (timer_head->expire_time <= current_time);
757 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
759 QEMUTimer *ts;
761 for(;;) {
762 ts = *ptimer_head;
763 if (!ts || ts->expire_time > current_time)
764 break;
765 /* remove timer from the list before calling the callback */
766 *ptimer_head = ts->next;
767 ts->next = NULL;
769 /* run the callback (the timer list can be modified) */
770 ts->cb(ts->opaque);
774 int64_t qemu_get_clock(QEMUClock *clock)
776 switch(clock->type) {
777 case QEMU_TIMER_REALTIME:
778 return get_clock() / 1000000;
779 default:
780 case QEMU_TIMER_VIRTUAL:
781 return cpu_get_clock();
785 static void init_timers(void)
787 init_get_clock();
788 ticks_per_sec = QEMU_TIMER_BASE;
789 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
790 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
793 /* save a timer */
794 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
796 uint64_t expire_time;
798 if (qemu_timer_pending(ts)) {
799 expire_time = ts->expire_time;
800 } else {
801 expire_time = -1;
803 qemu_put_be64(f, expire_time);
806 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
808 uint64_t expire_time;
810 expire_time = qemu_get_be64(f);
811 if (expire_time != -1) {
812 qemu_mod_timer(ts, expire_time);
813 } else {
814 qemu_del_timer(ts);
818 static void timer_save(QEMUFile *f, void *opaque)
820 if (cpu_ticks_enabled) {
821 hw_error("cannot save state if virtual timers are running");
823 qemu_put_be64s(f, &cpu_ticks_offset);
824 qemu_put_be64s(f, &ticks_per_sec);
825 qemu_put_be64s(f, &cpu_clock_offset);
828 static int timer_load(QEMUFile *f, void *opaque, int version_id)
830 if (version_id != 1)
831 return -EINVAL;
832 if (cpu_ticks_enabled) {
833 return -EINVAL;
835 qemu_get_be64s(f, &cpu_ticks_offset);
836 qemu_get_be64s(f, &ticks_per_sec);
837 qemu_get_be64s(f, &cpu_clock_offset);
838 return 0;
841 #ifdef _WIN32
842 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
843 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
844 #else
845 static void host_alarm_handler(int host_signum)
846 #endif
848 #if 0
849 #define DISP_FREQ 1000
851 static int64_t delta_min = INT64_MAX;
852 static int64_t delta_max, delta_cum, last_clock, delta, ti;
853 static int count;
854 ti = qemu_get_clock(vm_clock);
855 if (last_clock != 0) {
856 delta = ti - last_clock;
857 if (delta < delta_min)
858 delta_min = delta;
859 if (delta > delta_max)
860 delta_max = delta;
861 delta_cum += delta;
862 if (++count == DISP_FREQ) {
863 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
864 muldiv64(delta_min, 1000000, ticks_per_sec),
865 muldiv64(delta_max, 1000000, ticks_per_sec),
866 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
867 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
868 count = 0;
869 delta_min = INT64_MAX;
870 delta_max = 0;
871 delta_cum = 0;
874 last_clock = ti;
876 #endif
877 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
878 qemu_get_clock(vm_clock)) ||
879 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
880 qemu_get_clock(rt_clock))) {
881 #ifdef _WIN32
882 SetEvent(host_alarm);
883 #endif
884 CPUState *env = cpu_single_env;
885 if (env) {
886 /* stop the currently executing cpu because a timer occured */
887 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
888 #ifdef USE_KQEMU
889 if (env->kqemu_enabled) {
890 kqemu_cpu_interrupt(env);
892 #endif
897 #ifndef _WIN32
899 #if defined(__linux__)
901 #define RTC_FREQ 1024
903 static int rtc_fd;
905 static int start_rtc_timer(void)
907 rtc_fd = open("/dev/rtc", O_RDONLY);
908 if (rtc_fd < 0)
909 return -1;
910 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
911 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
912 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
913 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
914 goto fail;
916 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
917 fail:
918 close(rtc_fd);
919 return -1;
921 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
922 return 0;
925 #else
927 static int start_rtc_timer(void)
929 return -1;
932 #endif /* !defined(__linux__) */
934 #endif /* !defined(_WIN32) */
936 static void init_timer_alarm(void)
938 #ifdef _WIN32
940 int count=0;
941 TIMECAPS tc;
943 ZeroMemory(&tc, sizeof(TIMECAPS));
944 timeGetDevCaps(&tc, sizeof(TIMECAPS));
945 if (period < tc.wPeriodMin)
946 period = tc.wPeriodMin;
947 timeBeginPeriod(period);
948 timerID = timeSetEvent(1, // interval (ms)
949 period, // resolution
950 host_alarm_handler, // function
951 (DWORD)&count, // user parameter
952 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
953 if( !timerID ) {
954 perror("failed timer alarm");
955 exit(1);
957 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
958 if (!host_alarm) {
959 perror("failed CreateEvent");
960 exit(1);
962 qemu_add_wait_object(host_alarm, NULL, NULL);
964 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
965 #else
967 struct sigaction act;
968 struct itimerval itv;
970 /* get times() syscall frequency */
971 timer_freq = sysconf(_SC_CLK_TCK);
973 /* timer signal */
974 sigfillset(&act.sa_mask);
975 act.sa_flags = 0;
976 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
977 act.sa_flags |= SA_ONSTACK;
978 #endif
979 act.sa_handler = host_alarm_handler;
980 sigaction(SIGALRM, &act, NULL);
982 itv.it_interval.tv_sec = 0;
983 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
984 itv.it_value.tv_sec = 0;
985 itv.it_value.tv_usec = 10 * 1000;
986 setitimer(ITIMER_REAL, &itv, NULL);
987 /* we probe the tick duration of the kernel to inform the user if
988 the emulated kernel requested a too high timer frequency */
989 getitimer(ITIMER_REAL, &itv);
991 #if defined(__linux__)
992 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
993 have timers with 1 ms resolution. The correct solution will
994 be to use the POSIX real time timers available in recent
995 2.6 kernels */
996 if (itv.it_interval.tv_usec > 1000 || 1) {
997 /* try to use /dev/rtc to have a faster timer */
998 if (start_rtc_timer() < 0)
999 goto use_itimer;
1000 /* disable itimer */
1001 itv.it_interval.tv_sec = 0;
1002 itv.it_interval.tv_usec = 0;
1003 itv.it_value.tv_sec = 0;
1004 itv.it_value.tv_usec = 0;
1005 setitimer(ITIMER_REAL, &itv, NULL);
1007 /* use the RTC */
1008 sigaction(SIGIO, &act, NULL);
1009 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1010 fcntl(rtc_fd, F_SETOWN, getpid());
1011 } else
1012 #endif /* defined(__linux__) */
1014 use_itimer:
1015 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1016 PIT_FREQ) / 1000000;
1019 #endif
1022 void quit_timers(void)
1024 #ifdef _WIN32
1025 timeKillEvent(timerID);
1026 timeEndPeriod(period);
1027 if (host_alarm) {
1028 CloseHandle(host_alarm);
1029 host_alarm = NULL;
1031 #endif
1034 /***********************************************************/
1035 /* character device */
1037 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1039 return s->chr_write(s, buf, len);
1042 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1044 if (!s->chr_ioctl)
1045 return -ENOTSUP;
1046 return s->chr_ioctl(s, cmd, arg);
1049 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1051 char buf[4096];
1052 va_list ap;
1053 va_start(ap, fmt);
1054 vsnprintf(buf, sizeof(buf), fmt, ap);
1055 qemu_chr_write(s, buf, strlen(buf));
1056 va_end(ap);
1059 void qemu_chr_send_event(CharDriverState *s, int event)
1061 if (s->chr_send_event)
1062 s->chr_send_event(s, event);
1065 void qemu_chr_add_read_handler(CharDriverState *s,
1066 IOCanRWHandler *fd_can_read,
1067 IOReadHandler *fd_read, void *opaque)
1069 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1072 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1074 s->chr_event = chr_event;
1077 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1079 return len;
1082 static void null_chr_add_read_handler(CharDriverState *chr,
1083 IOCanRWHandler *fd_can_read,
1084 IOReadHandler *fd_read, void *opaque)
1088 CharDriverState *qemu_chr_open_null(void)
1090 CharDriverState *chr;
1092 chr = qemu_mallocz(sizeof(CharDriverState));
1093 if (!chr)
1094 return NULL;
1095 chr->chr_write = null_chr_write;
1096 chr->chr_add_read_handler = null_chr_add_read_handler;
1097 return chr;
1100 #ifdef _WIN32
1102 static void socket_cleanup(void)
1104 WSACleanup();
1107 static int socket_init(void)
1109 WSADATA Data;
1110 int ret, err;
1112 ret = WSAStartup(MAKEWORD(2,2), &Data);
1113 if (ret != 0) {
1114 err = WSAGetLastError();
1115 fprintf(stderr, "WSAStartup: %d\n", err);
1116 return -1;
1118 atexit(socket_cleanup);
1119 return 0;
1122 static int send_all(int fd, const uint8_t *buf, int len1)
1124 int ret, len;
1126 len = len1;
1127 while (len > 0) {
1128 ret = send(fd, buf, len, 0);
1129 if (ret < 0) {
1130 int errno;
1131 errno = WSAGetLastError();
1132 if (errno != WSAEWOULDBLOCK) {
1133 return -1;
1135 } else if (ret == 0) {
1136 break;
1137 } else {
1138 buf += ret;
1139 len -= ret;
1142 return len1 - len;
1145 void socket_set_nonblock(int fd)
1147 unsigned long opt = 1;
1148 ioctlsocket(fd, FIONBIO, &opt);
1151 #else
1153 static int unix_write(int fd, const uint8_t *buf, int len1)
1155 int ret, len;
1157 len = len1;
1158 while (len > 0) {
1159 ret = write(fd, buf, len);
1160 if (ret < 0) {
1161 if (errno != EINTR && errno != EAGAIN)
1162 return -1;
1163 } else if (ret == 0) {
1164 break;
1165 } else {
1166 buf += ret;
1167 len -= ret;
1170 return len1 - len;
1173 static inline int send_all(int fd, const uint8_t *buf, int len1)
1175 return unix_write(fd, buf, len1);
1178 void socket_set_nonblock(int fd)
1180 fcntl(fd, F_SETFL, O_NONBLOCK);
1182 #endif /* !_WIN32 */
1184 #ifndef _WIN32
1186 typedef struct {
1187 int fd_in, fd_out;
1188 IOCanRWHandler *fd_can_read;
1189 IOReadHandler *fd_read;
1190 void *fd_opaque;
1191 int max_size;
1192 } FDCharDriver;
1194 #define STDIO_MAX_CLIENTS 2
1196 static int stdio_nb_clients;
1197 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1199 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1201 FDCharDriver *s = chr->opaque;
1202 return unix_write(s->fd_out, buf, len);
1205 static int fd_chr_read_poll(void *opaque)
1207 CharDriverState *chr = opaque;
1208 FDCharDriver *s = chr->opaque;
1210 s->max_size = s->fd_can_read(s->fd_opaque);
1211 return s->max_size;
1214 static void fd_chr_read(void *opaque)
1216 CharDriverState *chr = opaque;
1217 FDCharDriver *s = chr->opaque;
1218 int size, len;
1219 uint8_t buf[1024];
1221 len = sizeof(buf);
1222 if (len > s->max_size)
1223 len = s->max_size;
1224 if (len == 0)
1225 return;
1226 size = read(s->fd_in, buf, len);
1227 if (size > 0) {
1228 s->fd_read(s->fd_opaque, buf, size);
1232 static void fd_chr_add_read_handler(CharDriverState *chr,
1233 IOCanRWHandler *fd_can_read,
1234 IOReadHandler *fd_read, void *opaque)
1236 FDCharDriver *s = chr->opaque;
1238 if (s->fd_in >= 0) {
1239 s->fd_can_read = fd_can_read;
1240 s->fd_read = fd_read;
1241 s->fd_opaque = opaque;
1242 if (nographic && s->fd_in == 0) {
1243 } else {
1244 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1245 fd_chr_read, NULL, chr);
1250 /* open a character device to a unix fd */
1251 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1253 CharDriverState *chr;
1254 FDCharDriver *s;
1256 chr = qemu_mallocz(sizeof(CharDriverState));
1257 if (!chr)
1258 return NULL;
1259 s = qemu_mallocz(sizeof(FDCharDriver));
1260 if (!s) {
1261 free(chr);
1262 return NULL;
1264 s->fd_in = fd_in;
1265 s->fd_out = fd_out;
1266 chr->opaque = s;
1267 chr->chr_write = fd_chr_write;
1268 chr->chr_add_read_handler = fd_chr_add_read_handler;
1269 return chr;
1272 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1274 int fd_out;
1276 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1277 if (fd_out < 0)
1278 return NULL;
1279 return qemu_chr_open_fd(-1, fd_out);
1282 CharDriverState *qemu_chr_open_pipe(const char *filename)
1284 int fd;
1286 fd = open(filename, O_RDWR | O_BINARY);
1287 if (fd < 0)
1288 return NULL;
1289 return qemu_chr_open_fd(fd, fd);
1293 /* for STDIO, we handle the case where several clients use it
1294 (nographic mode) */
1296 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1298 #define TERM_FIFO_MAX_SIZE 1
1300 static int term_got_escape, client_index;
1301 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1302 static int term_fifo_size;
1303 static int term_timestamps;
1304 static int64_t term_timestamps_start;
1306 void term_print_help(void)
1308 printf("\n"
1309 "C-a h print this help\n"
1310 "C-a x exit emulator\n"
1311 "C-a s save disk data back to file (if -snapshot)\n"
1312 "C-a b send break (magic sysrq)\n"
1313 "C-a t toggle console timestamps\n"
1314 "C-a c switch between console and monitor\n"
1315 "C-a C-a send C-a\n"
1319 /* called when a char is received */
1320 static void stdio_received_byte(int ch)
1322 if (term_got_escape) {
1323 term_got_escape = 0;
1324 switch(ch) {
1325 case 'h':
1326 term_print_help();
1327 break;
1328 case 'x':
1329 exit(0);
1330 break;
1331 case 's':
1333 int i;
1334 for (i = 0; i < MAX_DISKS; i++) {
1335 if (bs_table[i])
1336 bdrv_commit(bs_table[i]);
1339 break;
1340 case 'b':
1341 if (client_index < stdio_nb_clients) {
1342 CharDriverState *chr;
1343 FDCharDriver *s;
1345 chr = stdio_clients[client_index];
1346 s = chr->opaque;
1347 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1349 break;
1350 case 'c':
1351 client_index++;
1352 if (client_index >= stdio_nb_clients)
1353 client_index = 0;
1354 if (client_index == 0) {
1355 /* send a new line in the monitor to get the prompt */
1356 ch = '\r';
1357 goto send_char;
1359 break;
1360 case 't':
1361 term_timestamps = !term_timestamps;
1362 term_timestamps_start = -1;
1363 break;
1364 case TERM_ESCAPE:
1365 goto send_char;
1367 } else if (ch == TERM_ESCAPE) {
1368 term_got_escape = 1;
1369 } else {
1370 send_char:
1371 if (client_index < stdio_nb_clients) {
1372 uint8_t buf[1];
1373 CharDriverState *chr;
1374 FDCharDriver *s;
1376 chr = stdio_clients[client_index];
1377 s = chr->opaque;
1378 if (s->fd_can_read(s->fd_opaque) > 0) {
1379 buf[0] = ch;
1380 s->fd_read(s->fd_opaque, buf, 1);
1381 } else if (term_fifo_size == 0) {
1382 term_fifo[term_fifo_size++] = ch;
1388 static int stdio_read_poll(void *opaque)
1390 CharDriverState *chr;
1391 FDCharDriver *s;
1393 if (client_index < stdio_nb_clients) {
1394 chr = stdio_clients[client_index];
1395 s = chr->opaque;
1396 /* try to flush the queue if needed */
1397 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1398 s->fd_read(s->fd_opaque, term_fifo, 1);
1399 term_fifo_size = 0;
1401 /* see if we can absorb more chars */
1402 if (term_fifo_size == 0)
1403 return 1;
1404 else
1405 return 0;
1406 } else {
1407 return 1;
1411 static void stdio_read(void *opaque)
1413 int size;
1414 uint8_t buf[1];
1416 size = read(0, buf, 1);
1417 if (size > 0)
1418 stdio_received_byte(buf[0]);
1421 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1423 FDCharDriver *s = chr->opaque;
1424 if (!term_timestamps) {
1425 return unix_write(s->fd_out, buf, len);
1426 } else {
1427 int i;
1428 char buf1[64];
1430 for(i = 0; i < len; i++) {
1431 unix_write(s->fd_out, buf + i, 1);
1432 if (buf[i] == '\n') {
1433 int64_t ti;
1434 int secs;
1436 ti = get_clock();
1437 if (term_timestamps_start == -1)
1438 term_timestamps_start = ti;
1439 ti -= term_timestamps_start;
1440 secs = ti / 1000000000;
1441 snprintf(buf1, sizeof(buf1),
1442 "[%02d:%02d:%02d.%03d] ",
1443 secs / 3600,
1444 (secs / 60) % 60,
1445 secs % 60,
1446 (int)((ti / 1000000) % 1000));
1447 unix_write(s->fd_out, buf1, strlen(buf1));
1450 return len;
1454 /* init terminal so that we can grab keys */
1455 static struct termios oldtty;
1456 static int old_fd0_flags;
1458 static void term_exit(void)
1460 tcsetattr (0, TCSANOW, &oldtty);
1461 fcntl(0, F_SETFL, old_fd0_flags);
1464 static void term_init(void)
1466 struct termios tty;
1468 tcgetattr (0, &tty);
1469 oldtty = tty;
1470 old_fd0_flags = fcntl(0, F_GETFL);
1472 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1473 |INLCR|IGNCR|ICRNL|IXON);
1474 tty.c_oflag |= OPOST;
1475 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1476 /* if graphical mode, we allow Ctrl-C handling */
1477 if (nographic)
1478 tty.c_lflag &= ~ISIG;
1479 tty.c_cflag &= ~(CSIZE|PARENB);
1480 tty.c_cflag |= CS8;
1481 tty.c_cc[VMIN] = 1;
1482 tty.c_cc[VTIME] = 0;
1484 tcsetattr (0, TCSANOW, &tty);
1486 atexit(term_exit);
1488 fcntl(0, F_SETFL, O_NONBLOCK);
1491 CharDriverState *qemu_chr_open_stdio(void)
1493 CharDriverState *chr;
1495 if (nographic) {
1496 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1497 return NULL;
1498 chr = qemu_chr_open_fd(0, 1);
1499 chr->chr_write = stdio_write;
1500 if (stdio_nb_clients == 0)
1501 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1502 client_index = stdio_nb_clients;
1503 } else {
1504 if (stdio_nb_clients != 0)
1505 return NULL;
1506 chr = qemu_chr_open_fd(0, 1);
1508 stdio_clients[stdio_nb_clients++] = chr;
1509 if (stdio_nb_clients == 1) {
1510 /* set the terminal in raw mode */
1511 term_init();
1513 return chr;
1516 #if defined(__linux__)
1517 CharDriverState *qemu_chr_open_pty(void)
1519 struct termios tty;
1520 char slave_name[1024];
1521 int master_fd, slave_fd;
1523 /* Not satisfying */
1524 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1525 return NULL;
1528 /* Disabling local echo and line-buffered output */
1529 tcgetattr (master_fd, &tty);
1530 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1531 tty.c_cc[VMIN] = 1;
1532 tty.c_cc[VTIME] = 0;
1533 tcsetattr (master_fd, TCSAFLUSH, &tty);
1535 fprintf(stderr, "char device redirected to %s\n", slave_name);
1536 return qemu_chr_open_fd(master_fd, master_fd);
1539 static void tty_serial_init(int fd, int speed,
1540 int parity, int data_bits, int stop_bits)
1542 struct termios tty;
1543 speed_t spd;
1545 #if 0
1546 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1547 speed, parity, data_bits, stop_bits);
1548 #endif
1549 tcgetattr (fd, &tty);
1551 switch(speed) {
1552 case 50:
1553 spd = B50;
1554 break;
1555 case 75:
1556 spd = B75;
1557 break;
1558 case 300:
1559 spd = B300;
1560 break;
1561 case 600:
1562 spd = B600;
1563 break;
1564 case 1200:
1565 spd = B1200;
1566 break;
1567 case 2400:
1568 spd = B2400;
1569 break;
1570 case 4800:
1571 spd = B4800;
1572 break;
1573 case 9600:
1574 spd = B9600;
1575 break;
1576 case 19200:
1577 spd = B19200;
1578 break;
1579 case 38400:
1580 spd = B38400;
1581 break;
1582 case 57600:
1583 spd = B57600;
1584 break;
1585 default:
1586 case 115200:
1587 spd = B115200;
1588 break;
1591 cfsetispeed(&tty, spd);
1592 cfsetospeed(&tty, spd);
1594 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1595 |INLCR|IGNCR|ICRNL|IXON);
1596 tty.c_oflag |= OPOST;
1597 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1598 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1599 switch(data_bits) {
1600 default:
1601 case 8:
1602 tty.c_cflag |= CS8;
1603 break;
1604 case 7:
1605 tty.c_cflag |= CS7;
1606 break;
1607 case 6:
1608 tty.c_cflag |= CS6;
1609 break;
1610 case 5:
1611 tty.c_cflag |= CS5;
1612 break;
1614 switch(parity) {
1615 default:
1616 case 'N':
1617 break;
1618 case 'E':
1619 tty.c_cflag |= PARENB;
1620 break;
1621 case 'O':
1622 tty.c_cflag |= PARENB | PARODD;
1623 break;
1626 tcsetattr (fd, TCSANOW, &tty);
1629 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1631 FDCharDriver *s = chr->opaque;
1633 switch(cmd) {
1634 case CHR_IOCTL_SERIAL_SET_PARAMS:
1636 QEMUSerialSetParams *ssp = arg;
1637 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1638 ssp->data_bits, ssp->stop_bits);
1640 break;
1641 case CHR_IOCTL_SERIAL_SET_BREAK:
1643 int enable = *(int *)arg;
1644 if (enable)
1645 tcsendbreak(s->fd_in, 1);
1647 break;
1648 default:
1649 return -ENOTSUP;
1651 return 0;
1654 CharDriverState *qemu_chr_open_tty(const char *filename)
1656 CharDriverState *chr;
1657 int fd;
1659 fd = open(filename, O_RDWR | O_NONBLOCK);
1660 if (fd < 0)
1661 return NULL;
1662 fcntl(fd, F_SETFL, O_NONBLOCK);
1663 tty_serial_init(fd, 115200, 'N', 8, 1);
1664 chr = qemu_chr_open_fd(fd, fd);
1665 if (!chr)
1666 return NULL;
1667 chr->chr_ioctl = tty_serial_ioctl;
1668 return chr;
1671 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1673 int fd = (int)chr->opaque;
1674 uint8_t b;
1676 switch(cmd) {
1677 case CHR_IOCTL_PP_READ_DATA:
1678 if (ioctl(fd, PPRDATA, &b) < 0)
1679 return -ENOTSUP;
1680 *(uint8_t *)arg = b;
1681 break;
1682 case CHR_IOCTL_PP_WRITE_DATA:
1683 b = *(uint8_t *)arg;
1684 if (ioctl(fd, PPWDATA, &b) < 0)
1685 return -ENOTSUP;
1686 break;
1687 case CHR_IOCTL_PP_READ_CONTROL:
1688 if (ioctl(fd, PPRCONTROL, &b) < 0)
1689 return -ENOTSUP;
1690 *(uint8_t *)arg = b;
1691 break;
1692 case CHR_IOCTL_PP_WRITE_CONTROL:
1693 b = *(uint8_t *)arg;
1694 if (ioctl(fd, PPWCONTROL, &b) < 0)
1695 return -ENOTSUP;
1696 break;
1697 case CHR_IOCTL_PP_READ_STATUS:
1698 if (ioctl(fd, PPRSTATUS, &b) < 0)
1699 return -ENOTSUP;
1700 *(uint8_t *)arg = b;
1701 break;
1702 default:
1703 return -ENOTSUP;
1705 return 0;
1708 CharDriverState *qemu_chr_open_pp(const char *filename)
1710 CharDriverState *chr;
1711 int fd;
1713 fd = open(filename, O_RDWR);
1714 if (fd < 0)
1715 return NULL;
1717 if (ioctl(fd, PPCLAIM) < 0) {
1718 close(fd);
1719 return NULL;
1722 chr = qemu_mallocz(sizeof(CharDriverState));
1723 if (!chr) {
1724 close(fd);
1725 return NULL;
1727 chr->opaque = (void *)fd;
1728 chr->chr_write = null_chr_write;
1729 chr->chr_add_read_handler = null_chr_add_read_handler;
1730 chr->chr_ioctl = pp_ioctl;
1731 return chr;
1734 #else
1735 CharDriverState *qemu_chr_open_pty(void)
1737 return NULL;
1739 #endif
1741 #endif /* !defined(_WIN32) */
1743 #ifdef _WIN32
1744 typedef struct {
1745 IOCanRWHandler *fd_can_read;
1746 IOReadHandler *fd_read;
1747 void *win_opaque;
1748 int max_size;
1749 HANDLE hcom, hrecv, hsend;
1750 OVERLAPPED orecv, osend;
1751 BOOL fpipe;
1752 DWORD len;
1753 } WinCharState;
1755 #define NSENDBUF 2048
1756 #define NRECVBUF 2048
1757 #define MAXCONNECT 1
1758 #define NTIMEOUT 5000
1760 static int win_chr_poll(void *opaque);
1761 static int win_chr_pipe_poll(void *opaque);
1763 static void win_chr_close2(WinCharState *s)
1765 if (s->hsend) {
1766 CloseHandle(s->hsend);
1767 s->hsend = NULL;
1769 if (s->hrecv) {
1770 CloseHandle(s->hrecv);
1771 s->hrecv = NULL;
1773 if (s->hcom) {
1774 CloseHandle(s->hcom);
1775 s->hcom = NULL;
1777 if (s->fpipe)
1778 qemu_del_polling_cb(win_chr_pipe_poll, s);
1779 else
1780 qemu_del_polling_cb(win_chr_poll, s);
1783 static void win_chr_close(CharDriverState *chr)
1785 WinCharState *s = chr->opaque;
1786 win_chr_close2(s);
1789 static int win_chr_init(WinCharState *s, const char *filename)
1791 COMMCONFIG comcfg;
1792 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1793 COMSTAT comstat;
1794 DWORD size;
1795 DWORD err;
1797 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1798 if (!s->hsend) {
1799 fprintf(stderr, "Failed CreateEvent\n");
1800 goto fail;
1802 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1803 if (!s->hrecv) {
1804 fprintf(stderr, "Failed CreateEvent\n");
1805 goto fail;
1808 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1809 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1810 if (s->hcom == INVALID_HANDLE_VALUE) {
1811 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1812 s->hcom = NULL;
1813 goto fail;
1816 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1817 fprintf(stderr, "Failed SetupComm\n");
1818 goto fail;
1821 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1822 size = sizeof(COMMCONFIG);
1823 GetDefaultCommConfig(filename, &comcfg, &size);
1824 comcfg.dcb.DCBlength = sizeof(DCB);
1825 CommConfigDialog(filename, NULL, &comcfg);
1827 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1828 fprintf(stderr, "Failed SetCommState\n");
1829 goto fail;
1832 if (!SetCommMask(s->hcom, EV_ERR)) {
1833 fprintf(stderr, "Failed SetCommMask\n");
1834 goto fail;
1837 cto.ReadIntervalTimeout = MAXDWORD;
1838 if (!SetCommTimeouts(s->hcom, &cto)) {
1839 fprintf(stderr, "Failed SetCommTimeouts\n");
1840 goto fail;
1843 if (!ClearCommError(s->hcom, &err, &comstat)) {
1844 fprintf(stderr, "Failed ClearCommError\n");
1845 goto fail;
1847 qemu_add_polling_cb(win_chr_poll, s);
1848 return 0;
1850 fail:
1851 win_chr_close2(s);
1852 return -1;
1855 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1857 WinCharState *s = chr->opaque;
1858 DWORD len, ret, size, err;
1860 len = len1;
1861 ZeroMemory(&s->osend, sizeof(s->osend));
1862 s->osend.hEvent = s->hsend;
1863 while (len > 0) {
1864 if (s->hsend)
1865 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1866 else
1867 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1868 if (!ret) {
1869 err = GetLastError();
1870 if (err == ERROR_IO_PENDING) {
1871 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1872 if (ret) {
1873 buf += size;
1874 len -= size;
1875 } else {
1876 break;
1878 } else {
1879 break;
1881 } else {
1882 buf += size;
1883 len -= size;
1886 return len1 - len;
1889 static int win_chr_read_poll(WinCharState *s)
1891 s->max_size = s->fd_can_read(s->win_opaque);
1892 return s->max_size;
1895 static void win_chr_readfile(WinCharState *s)
1897 int ret, err;
1898 uint8_t buf[1024];
1899 DWORD size;
1901 ZeroMemory(&s->orecv, sizeof(s->orecv));
1902 s->orecv.hEvent = s->hrecv;
1903 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1904 if (!ret) {
1905 err = GetLastError();
1906 if (err == ERROR_IO_PENDING) {
1907 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1911 if (size > 0) {
1912 s->fd_read(s->win_opaque, buf, size);
1916 static void win_chr_read(WinCharState *s)
1918 if (s->len > s->max_size)
1919 s->len = s->max_size;
1920 if (s->len == 0)
1921 return;
1923 win_chr_readfile(s);
1926 static int win_chr_poll(void *opaque)
1928 WinCharState *s = opaque;
1929 COMSTAT status;
1930 DWORD comerr;
1932 ClearCommError(s->hcom, &comerr, &status);
1933 if (status.cbInQue > 0) {
1934 s->len = status.cbInQue;
1935 win_chr_read_poll(s);
1936 win_chr_read(s);
1937 return 1;
1939 return 0;
1942 static void win_chr_add_read_handler(CharDriverState *chr,
1943 IOCanRWHandler *fd_can_read,
1944 IOReadHandler *fd_read, void *opaque)
1946 WinCharState *s = chr->opaque;
1948 s->fd_can_read = fd_can_read;
1949 s->fd_read = fd_read;
1950 s->win_opaque = opaque;
1953 CharDriverState *qemu_chr_open_win(const char *filename)
1955 CharDriverState *chr;
1956 WinCharState *s;
1958 chr = qemu_mallocz(sizeof(CharDriverState));
1959 if (!chr)
1960 return NULL;
1961 s = qemu_mallocz(sizeof(WinCharState));
1962 if (!s) {
1963 free(chr);
1964 return NULL;
1966 chr->opaque = s;
1967 chr->chr_write = win_chr_write;
1968 chr->chr_add_read_handler = win_chr_add_read_handler;
1969 chr->chr_close = win_chr_close;
1971 if (win_chr_init(s, filename) < 0) {
1972 free(s);
1973 free(chr);
1974 return NULL;
1976 return chr;
1979 static int win_chr_pipe_poll(void *opaque)
1981 WinCharState *s = opaque;
1982 DWORD size;
1984 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1985 if (size > 0) {
1986 s->len = size;
1987 win_chr_read_poll(s);
1988 win_chr_read(s);
1989 return 1;
1991 return 0;
1994 static int win_chr_pipe_init(WinCharState *s, const char *filename)
1996 OVERLAPPED ov;
1997 int ret;
1998 DWORD size;
1999 char openname[256];
2001 s->fpipe = TRUE;
2003 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2004 if (!s->hsend) {
2005 fprintf(stderr, "Failed CreateEvent\n");
2006 goto fail;
2008 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2009 if (!s->hrecv) {
2010 fprintf(stderr, "Failed CreateEvent\n");
2011 goto fail;
2014 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2015 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2016 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2017 PIPE_WAIT,
2018 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2019 if (s->hcom == INVALID_HANDLE_VALUE) {
2020 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2021 s->hcom = NULL;
2022 goto fail;
2025 ZeroMemory(&ov, sizeof(ov));
2026 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2027 ret = ConnectNamedPipe(s->hcom, &ov);
2028 if (ret) {
2029 fprintf(stderr, "Failed ConnectNamedPipe\n");
2030 goto fail;
2033 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2034 if (!ret) {
2035 fprintf(stderr, "Failed GetOverlappedResult\n");
2036 if (ov.hEvent) {
2037 CloseHandle(ov.hEvent);
2038 ov.hEvent = NULL;
2040 goto fail;
2043 if (ov.hEvent) {
2044 CloseHandle(ov.hEvent);
2045 ov.hEvent = NULL;
2047 qemu_add_polling_cb(win_chr_pipe_poll, s);
2048 return 0;
2050 fail:
2051 win_chr_close2(s);
2052 return -1;
2056 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2058 CharDriverState *chr;
2059 WinCharState *s;
2061 chr = qemu_mallocz(sizeof(CharDriverState));
2062 if (!chr)
2063 return NULL;
2064 s = qemu_mallocz(sizeof(WinCharState));
2065 if (!s) {
2066 free(chr);
2067 return NULL;
2069 chr->opaque = s;
2070 chr->chr_write = win_chr_write;
2071 chr->chr_add_read_handler = win_chr_add_read_handler;
2072 chr->chr_close = win_chr_close;
2074 if (win_chr_pipe_init(s, filename) < 0) {
2075 free(s);
2076 free(chr);
2077 return NULL;
2079 return chr;
2082 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2084 CharDriverState *chr;
2085 WinCharState *s;
2087 chr = qemu_mallocz(sizeof(CharDriverState));
2088 if (!chr)
2089 return NULL;
2090 s = qemu_mallocz(sizeof(WinCharState));
2091 if (!s) {
2092 free(chr);
2093 return NULL;
2095 s->hcom = fd_out;
2096 chr->opaque = s;
2097 chr->chr_write = win_chr_write;
2098 chr->chr_add_read_handler = win_chr_add_read_handler;
2099 return chr;
2102 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2104 HANDLE fd_out;
2106 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2107 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2108 if (fd_out == INVALID_HANDLE_VALUE)
2109 return NULL;
2111 return qemu_chr_open_win_file(fd_out);
2113 #endif
2115 /***********************************************************/
2116 /* UDP Net console */
2118 typedef struct {
2119 IOCanRWHandler *fd_can_read;
2120 IOReadHandler *fd_read;
2121 void *fd_opaque;
2122 int fd;
2123 struct sockaddr_in daddr;
2124 char buf[1024];
2125 int bufcnt;
2126 int bufptr;
2127 int max_size;
2128 } NetCharDriver;
2130 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2132 NetCharDriver *s = chr->opaque;
2134 return sendto(s->fd, buf, len, 0,
2135 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2138 static int udp_chr_read_poll(void *opaque)
2140 CharDriverState *chr = opaque;
2141 NetCharDriver *s = chr->opaque;
2143 s->max_size = s->fd_can_read(s->fd_opaque);
2145 /* If there were any stray characters in the queue process them
2146 * first
2148 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2149 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2150 s->bufptr++;
2151 s->max_size = s->fd_can_read(s->fd_opaque);
2153 return s->max_size;
2156 static void udp_chr_read(void *opaque)
2158 CharDriverState *chr = opaque;
2159 NetCharDriver *s = chr->opaque;
2161 if (s->max_size == 0)
2162 return;
2163 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2164 s->bufptr = s->bufcnt;
2165 if (s->bufcnt <= 0)
2166 return;
2168 s->bufptr = 0;
2169 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2170 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2171 s->bufptr++;
2172 s->max_size = s->fd_can_read(s->fd_opaque);
2176 static void udp_chr_add_read_handler(CharDriverState *chr,
2177 IOCanRWHandler *fd_can_read,
2178 IOReadHandler *fd_read, void *opaque)
2180 NetCharDriver *s = chr->opaque;
2182 if (s->fd >= 0) {
2183 s->fd_can_read = fd_can_read;
2184 s->fd_read = fd_read;
2185 s->fd_opaque = opaque;
2186 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2187 udp_chr_read, NULL, chr);
2191 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2192 int parse_host_src_port(struct sockaddr_in *haddr,
2193 struct sockaddr_in *saddr,
2194 const char *str);
2196 CharDriverState *qemu_chr_open_udp(const char *def)
2198 CharDriverState *chr = NULL;
2199 NetCharDriver *s = NULL;
2200 int fd = -1;
2201 struct sockaddr_in saddr;
2203 chr = qemu_mallocz(sizeof(CharDriverState));
2204 if (!chr)
2205 goto return_err;
2206 s = qemu_mallocz(sizeof(NetCharDriver));
2207 if (!s)
2208 goto return_err;
2210 fd = socket(PF_INET, SOCK_DGRAM, 0);
2211 if (fd < 0) {
2212 perror("socket(PF_INET, SOCK_DGRAM)");
2213 goto return_err;
2216 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2217 printf("Could not parse: %s\n", def);
2218 goto return_err;
2221 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2223 perror("bind");
2224 goto return_err;
2227 s->fd = fd;
2228 s->bufcnt = 0;
2229 s->bufptr = 0;
2230 chr->opaque = s;
2231 chr->chr_write = udp_chr_write;
2232 chr->chr_add_read_handler = udp_chr_add_read_handler;
2233 return chr;
2235 return_err:
2236 if (chr)
2237 free(chr);
2238 if (s)
2239 free(s);
2240 if (fd >= 0)
2241 closesocket(fd);
2242 return NULL;
2245 /***********************************************************/
2246 /* TCP Net console */
2248 typedef struct {
2249 IOCanRWHandler *fd_can_read;
2250 IOReadHandler *fd_read;
2251 void *fd_opaque;
2252 int fd, listen_fd;
2253 int connected;
2254 int max_size;
2255 int do_telnetopt;
2256 } TCPCharDriver;
2258 static void tcp_chr_accept(void *opaque);
2260 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2262 TCPCharDriver *s = chr->opaque;
2263 if (s->connected) {
2264 return send_all(s->fd, buf, len);
2265 } else {
2266 /* XXX: indicate an error ? */
2267 return len;
2271 static int tcp_chr_read_poll(void *opaque)
2273 CharDriverState *chr = opaque;
2274 TCPCharDriver *s = chr->opaque;
2275 if (!s->connected)
2276 return 0;
2277 s->max_size = s->fd_can_read(s->fd_opaque);
2278 return s->max_size;
2281 #define IAC 255
2282 #define IAC_BREAK 243
2283 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2284 TCPCharDriver *s,
2285 char *buf, int *size)
2287 /* Handle any telnet client's basic IAC options to satisfy char by
2288 * char mode with no echo. All IAC options will be removed from
2289 * the buf and the do_telnetopt variable will be used to track the
2290 * state of the width of the IAC information.
2292 * IAC commands come in sets of 3 bytes with the exception of the
2293 * "IAC BREAK" command and the double IAC.
2296 int i;
2297 int j = 0;
2299 for (i = 0; i < *size; i++) {
2300 if (s->do_telnetopt > 1) {
2301 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2302 /* Double IAC means send an IAC */
2303 if (j != i)
2304 buf[j] = buf[i];
2305 j++;
2306 s->do_telnetopt = 1;
2307 } else {
2308 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2309 /* Handle IAC break commands by sending a serial break */
2310 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2311 s->do_telnetopt++;
2313 s->do_telnetopt++;
2315 if (s->do_telnetopt >= 4) {
2316 s->do_telnetopt = 1;
2318 } else {
2319 if ((unsigned char)buf[i] == IAC) {
2320 s->do_telnetopt = 2;
2321 } else {
2322 if (j != i)
2323 buf[j] = buf[i];
2324 j++;
2328 *size = j;
2331 static void tcp_chr_read(void *opaque)
2333 CharDriverState *chr = opaque;
2334 TCPCharDriver *s = chr->opaque;
2335 uint8_t buf[1024];
2336 int len, size;
2338 if (!s->connected || s->max_size <= 0)
2339 return;
2340 len = sizeof(buf);
2341 if (len > s->max_size)
2342 len = s->max_size;
2343 size = recv(s->fd, buf, len, 0);
2344 if (size == 0) {
2345 /* connection closed */
2346 s->connected = 0;
2347 if (s->listen_fd >= 0) {
2348 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2350 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2351 closesocket(s->fd);
2352 s->fd = -1;
2353 } else if (size > 0) {
2354 if (s->do_telnetopt)
2355 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2356 if (size > 0)
2357 s->fd_read(s->fd_opaque, buf, size);
2361 static void tcp_chr_add_read_handler(CharDriverState *chr,
2362 IOCanRWHandler *fd_can_read,
2363 IOReadHandler *fd_read, void *opaque)
2365 TCPCharDriver *s = chr->opaque;
2367 s->fd_can_read = fd_can_read;
2368 s->fd_read = fd_read;
2369 s->fd_opaque = opaque;
2372 static void tcp_chr_connect(void *opaque)
2374 CharDriverState *chr = opaque;
2375 TCPCharDriver *s = chr->opaque;
2377 s->connected = 1;
2378 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2379 tcp_chr_read, NULL, chr);
2382 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2383 static void tcp_chr_telnet_init(int fd)
2385 char buf[3];
2386 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2387 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2388 send(fd, (char *)buf, 3, 0);
2389 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2390 send(fd, (char *)buf, 3, 0);
2391 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2392 send(fd, (char *)buf, 3, 0);
2393 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2394 send(fd, (char *)buf, 3, 0);
2397 static void tcp_chr_accept(void *opaque)
2399 CharDriverState *chr = opaque;
2400 TCPCharDriver *s = chr->opaque;
2401 struct sockaddr_in saddr;
2402 socklen_t len;
2403 int fd;
2405 for(;;) {
2406 len = sizeof(saddr);
2407 fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2408 if (fd < 0 && errno != EINTR) {
2409 return;
2410 } else if (fd >= 0) {
2411 if (s->do_telnetopt)
2412 tcp_chr_telnet_init(fd);
2413 break;
2416 socket_set_nonblock(fd);
2417 s->fd = fd;
2418 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2419 tcp_chr_connect(chr);
2422 static void tcp_chr_close(CharDriverState *chr)
2424 TCPCharDriver *s = chr->opaque;
2425 if (s->fd >= 0)
2426 closesocket(s->fd);
2427 if (s->listen_fd >= 0)
2428 closesocket(s->listen_fd);
2429 qemu_free(s);
2432 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2433 int is_telnet)
2435 CharDriverState *chr = NULL;
2436 TCPCharDriver *s = NULL;
2437 int fd = -1, ret, err, val;
2438 int is_listen = 0;
2439 int is_waitconnect = 1;
2440 const char *ptr;
2441 struct sockaddr_in saddr;
2443 if (parse_host_port(&saddr, host_str) < 0)
2444 goto fail;
2446 ptr = host_str;
2447 while((ptr = strchr(ptr,','))) {
2448 ptr++;
2449 if (!strncmp(ptr,"server",6)) {
2450 is_listen = 1;
2451 } else if (!strncmp(ptr,"nowait",6)) {
2452 is_waitconnect = 0;
2453 } else {
2454 printf("Unknown option: %s\n", ptr);
2455 goto fail;
2458 if (!is_listen)
2459 is_waitconnect = 0;
2461 chr = qemu_mallocz(sizeof(CharDriverState));
2462 if (!chr)
2463 goto fail;
2464 s = qemu_mallocz(sizeof(TCPCharDriver));
2465 if (!s)
2466 goto fail;
2468 fd = socket(PF_INET, SOCK_STREAM, 0);
2469 if (fd < 0)
2470 goto fail;
2472 if (!is_waitconnect)
2473 socket_set_nonblock(fd);
2475 s->connected = 0;
2476 s->fd = -1;
2477 s->listen_fd = -1;
2478 if (is_listen) {
2479 /* allow fast reuse */
2480 val = 1;
2481 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2483 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2484 if (ret < 0)
2485 goto fail;
2486 ret = listen(fd, 0);
2487 if (ret < 0)
2488 goto fail;
2489 s->listen_fd = fd;
2490 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2491 if (is_telnet)
2492 s->do_telnetopt = 1;
2493 } else {
2494 for(;;) {
2495 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2496 if (ret < 0) {
2497 err = socket_error();
2498 if (err == EINTR || err == EWOULDBLOCK) {
2499 } else if (err == EINPROGRESS) {
2500 break;
2501 } else {
2502 goto fail;
2504 } else {
2505 s->connected = 1;
2506 break;
2509 s->fd = fd;
2510 if (s->connected)
2511 tcp_chr_connect(chr);
2512 else
2513 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2516 chr->opaque = s;
2517 chr->chr_write = tcp_chr_write;
2518 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2519 chr->chr_close = tcp_chr_close;
2520 if (is_listen && is_waitconnect) {
2521 printf("QEMU waiting for connection on: %s\n", host_str);
2522 tcp_chr_accept(chr);
2523 socket_set_nonblock(s->listen_fd);
2526 return chr;
2527 fail:
2528 if (fd >= 0)
2529 closesocket(fd);
2530 qemu_free(s);
2531 qemu_free(chr);
2532 return NULL;
2535 CharDriverState *qemu_chr_open(const char *filename)
2537 const char *p;
2539 if (!strcmp(filename, "vc")) {
2540 return text_console_init(&display_state);
2541 } else if (!strcmp(filename, "null")) {
2542 return qemu_chr_open_null();
2543 } else
2544 if (strstart(filename, "tcp:", &p)) {
2545 return qemu_chr_open_tcp(p, 0);
2546 } else
2547 if (strstart(filename, "telnet:", &p)) {
2548 return qemu_chr_open_tcp(p, 1);
2549 } else
2550 if (strstart(filename, "udp:", &p)) {
2551 return qemu_chr_open_udp(p);
2552 } else
2553 #ifndef _WIN32
2554 if (strstart(filename, "file:", &p)) {
2555 return qemu_chr_open_file_out(p);
2556 } else if (strstart(filename, "pipe:", &p)) {
2557 return qemu_chr_open_pipe(p);
2558 } else if (!strcmp(filename, "pty")) {
2559 return qemu_chr_open_pty();
2560 } else if (!strcmp(filename, "stdio")) {
2561 return qemu_chr_open_stdio();
2562 } else
2563 #endif
2564 #if defined(__linux__)
2565 if (strstart(filename, "/dev/parport", NULL)) {
2566 return qemu_chr_open_pp(filename);
2567 } else
2568 if (strstart(filename, "/dev/", NULL)) {
2569 return qemu_chr_open_tty(filename);
2570 } else
2571 #endif
2572 #ifdef _WIN32
2573 if (strstart(filename, "COM", NULL)) {
2574 return qemu_chr_open_win(filename);
2575 } else
2576 if (strstart(filename, "pipe:", &p)) {
2577 return qemu_chr_open_win_pipe(p);
2578 } else
2579 if (strstart(filename, "file:", &p)) {
2580 return qemu_chr_open_win_file_out(p);
2582 #endif
2584 return NULL;
2588 void qemu_chr_close(CharDriverState *chr)
2590 if (chr->chr_close)
2591 chr->chr_close(chr);
2594 /***********************************************************/
2595 /* network device redirectors */
2597 void hex_dump(FILE *f, const uint8_t *buf, int size)
2599 int len, i, j, c;
2601 for(i=0;i<size;i+=16) {
2602 len = size - i;
2603 if (len > 16)
2604 len = 16;
2605 fprintf(f, "%08x ", i);
2606 for(j=0;j<16;j++) {
2607 if (j < len)
2608 fprintf(f, " %02x", buf[i+j]);
2609 else
2610 fprintf(f, " ");
2612 fprintf(f, " ");
2613 for(j=0;j<len;j++) {
2614 c = buf[i+j];
2615 if (c < ' ' || c > '~')
2616 c = '.';
2617 fprintf(f, "%c", c);
2619 fprintf(f, "\n");
2623 static int parse_macaddr(uint8_t *macaddr, const char *p)
2625 int i;
2626 for(i = 0; i < 6; i++) {
2627 macaddr[i] = strtol(p, (char **)&p, 16);
2628 if (i == 5) {
2629 if (*p != '\0')
2630 return -1;
2631 } else {
2632 if (*p != ':')
2633 return -1;
2634 p++;
2637 return 0;
2640 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2642 const char *p, *p1;
2643 int len;
2644 p = *pp;
2645 p1 = strchr(p, sep);
2646 if (!p1)
2647 return -1;
2648 len = p1 - p;
2649 p1++;
2650 if (buf_size > 0) {
2651 if (len > buf_size - 1)
2652 len = buf_size - 1;
2653 memcpy(buf, p, len);
2654 buf[len] = '\0';
2656 *pp = p1;
2657 return 0;
2660 int parse_host_src_port(struct sockaddr_in *haddr,
2661 struct sockaddr_in *saddr,
2662 const char *input_str)
2664 char *str = strdup(input_str);
2665 char *host_str = str;
2666 char *src_str;
2667 char *ptr;
2670 * Chop off any extra arguments at the end of the string which
2671 * would start with a comma, then fill in the src port information
2672 * if it was provided else use the "any address" and "any port".
2674 if ((ptr = strchr(str,',')))
2675 *ptr = '\0';
2677 if ((src_str = strchr(input_str,'@'))) {
2678 *src_str = '\0';
2679 src_str++;
2682 if (parse_host_port(haddr, host_str) < 0)
2683 goto fail;
2685 if (!src_str || *src_str == '\0')
2686 src_str = ":0";
2688 if (parse_host_port(saddr, src_str) < 0)
2689 goto fail;
2691 free(str);
2692 return(0);
2694 fail:
2695 free(str);
2696 return -1;
2699 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2701 char buf[512];
2702 struct hostent *he;
2703 const char *p, *r;
2704 int port;
2706 p = str;
2707 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2708 return -1;
2709 saddr->sin_family = AF_INET;
2710 if (buf[0] == '\0') {
2711 saddr->sin_addr.s_addr = 0;
2712 } else {
2713 if (isdigit(buf[0])) {
2714 if (!inet_aton(buf, &saddr->sin_addr))
2715 return -1;
2716 } else {
2717 if ((he = gethostbyname(buf)) == NULL)
2718 return - 1;
2719 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2722 port = strtol(p, (char **)&r, 0);
2723 if (r == p)
2724 return -1;
2725 saddr->sin_port = htons(port);
2726 return 0;
2729 /* find or alloc a new VLAN */
2730 VLANState *qemu_find_vlan(int id)
2732 VLANState **pvlan, *vlan;
2733 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2734 if (vlan->id == id)
2735 return vlan;
2737 vlan = qemu_mallocz(sizeof(VLANState));
2738 if (!vlan)
2739 return NULL;
2740 vlan->id = id;
2741 vlan->next = NULL;
2742 pvlan = &first_vlan;
2743 while (*pvlan != NULL)
2744 pvlan = &(*pvlan)->next;
2745 *pvlan = vlan;
2746 return vlan;
2749 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2750 IOReadHandler *fd_read,
2751 IOCanRWHandler *fd_can_read,
2752 void *opaque)
2754 VLANClientState *vc, **pvc;
2755 vc = qemu_mallocz(sizeof(VLANClientState));
2756 if (!vc)
2757 return NULL;
2758 vc->fd_read = fd_read;
2759 vc->fd_can_read = fd_can_read;
2760 vc->opaque = opaque;
2761 vc->vlan = vlan;
2763 vc->next = NULL;
2764 pvc = &vlan->first_client;
2765 while (*pvc != NULL)
2766 pvc = &(*pvc)->next;
2767 *pvc = vc;
2768 return vc;
2771 int qemu_can_send_packet(VLANClientState *vc1)
2773 VLANState *vlan = vc1->vlan;
2774 VLANClientState *vc;
2776 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2777 if (vc != vc1) {
2778 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2779 return 0;
2782 return 1;
2785 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2787 VLANState *vlan = vc1->vlan;
2788 VLANClientState *vc;
2790 #if 0
2791 printf("vlan %d send:\n", vlan->id);
2792 hex_dump(stdout, buf, size);
2793 #endif
2794 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2795 if (vc != vc1) {
2796 vc->fd_read(vc->opaque, buf, size);
2801 #if defined(CONFIG_SLIRP)
2803 /* slirp network adapter */
2805 static int slirp_inited;
2806 static VLANClientState *slirp_vc;
2808 int slirp_can_output(void)
2810 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2813 void slirp_output(const uint8_t *pkt, int pkt_len)
2815 #if 0
2816 printf("slirp output:\n");
2817 hex_dump(stdout, pkt, pkt_len);
2818 #endif
2819 if (!slirp_vc)
2820 return;
2821 qemu_send_packet(slirp_vc, pkt, pkt_len);
2824 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2826 #if 0
2827 printf("slirp input:\n");
2828 hex_dump(stdout, buf, size);
2829 #endif
2830 slirp_input(buf, size);
2833 static int net_slirp_init(VLANState *vlan)
2835 if (!slirp_inited) {
2836 slirp_inited = 1;
2837 slirp_init();
2839 slirp_vc = qemu_new_vlan_client(vlan,
2840 slirp_receive, NULL, NULL);
2841 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2842 return 0;
2845 static void net_slirp_redir(const char *redir_str)
2847 int is_udp;
2848 char buf[256], *r;
2849 const char *p;
2850 struct in_addr guest_addr;
2851 int host_port, guest_port;
2853 if (!slirp_inited) {
2854 slirp_inited = 1;
2855 slirp_init();
2858 p = redir_str;
2859 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2860 goto fail;
2861 if (!strcmp(buf, "tcp")) {
2862 is_udp = 0;
2863 } else if (!strcmp(buf, "udp")) {
2864 is_udp = 1;
2865 } else {
2866 goto fail;
2869 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2870 goto fail;
2871 host_port = strtol(buf, &r, 0);
2872 if (r == buf)
2873 goto fail;
2875 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2876 goto fail;
2877 if (buf[0] == '\0') {
2878 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2880 if (!inet_aton(buf, &guest_addr))
2881 goto fail;
2883 guest_port = strtol(p, &r, 0);
2884 if (r == p)
2885 goto fail;
2887 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2888 fprintf(stderr, "qemu: could not set up redirection\n");
2889 exit(1);
2891 return;
2892 fail:
2893 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2894 exit(1);
2897 #ifndef _WIN32
2899 char smb_dir[1024];
2901 static void smb_exit(void)
2903 DIR *d;
2904 struct dirent *de;
2905 char filename[1024];
2907 /* erase all the files in the directory */
2908 d = opendir(smb_dir);
2909 for(;;) {
2910 de = readdir(d);
2911 if (!de)
2912 break;
2913 if (strcmp(de->d_name, ".") != 0 &&
2914 strcmp(de->d_name, "..") != 0) {
2915 snprintf(filename, sizeof(filename), "%s/%s",
2916 smb_dir, de->d_name);
2917 unlink(filename);
2920 closedir(d);
2921 rmdir(smb_dir);
2924 /* automatic user mode samba server configuration */
2925 void net_slirp_smb(const char *exported_dir)
2927 char smb_conf[1024];
2928 char smb_cmdline[1024];
2929 FILE *f;
2931 if (!slirp_inited) {
2932 slirp_inited = 1;
2933 slirp_init();
2936 /* XXX: better tmp dir construction */
2937 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2938 if (mkdir(smb_dir, 0700) < 0) {
2939 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2940 exit(1);
2942 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2944 f = fopen(smb_conf, "w");
2945 if (!f) {
2946 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2947 exit(1);
2949 fprintf(f,
2950 "[global]\n"
2951 "private dir=%s\n"
2952 "smb ports=0\n"
2953 "socket address=127.0.0.1\n"
2954 "pid directory=%s\n"
2955 "lock directory=%s\n"
2956 "log file=%s/log.smbd\n"
2957 "smb passwd file=%s/smbpasswd\n"
2958 "security = share\n"
2959 "[qemu]\n"
2960 "path=%s\n"
2961 "read only=no\n"
2962 "guest ok=yes\n",
2963 smb_dir,
2964 smb_dir,
2965 smb_dir,
2966 smb_dir,
2967 smb_dir,
2968 exported_dir
2970 fclose(f);
2971 atexit(smb_exit);
2973 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2974 smb_conf);
2976 slirp_add_exec(0, smb_cmdline, 4, 139);
2979 #endif /* !defined(_WIN32) */
2981 #endif /* CONFIG_SLIRP */
2983 #if !defined(_WIN32)
2985 typedef struct TAPState {
2986 VLANClientState *vc;
2987 int fd;
2988 } TAPState;
2990 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2992 TAPState *s = opaque;
2993 int ret;
2994 for(;;) {
2995 ret = write(s->fd, buf, size);
2996 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2997 } else {
2998 break;
3003 static void tap_send(void *opaque)
3005 TAPState *s = opaque;
3006 uint8_t buf[4096];
3007 int size;
3009 size = read(s->fd, buf, sizeof(buf));
3010 if (size > 0) {
3011 qemu_send_packet(s->vc, buf, size);
3015 /* fd support */
3017 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3019 TAPState *s;
3021 s = qemu_mallocz(sizeof(TAPState));
3022 if (!s)
3023 return NULL;
3024 s->fd = fd;
3025 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3026 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3027 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3028 return s;
3031 #ifdef _BSD
3032 static int tap_open(char *ifname, int ifname_size)
3034 int fd;
3035 char *dev;
3036 struct stat s;
3038 fd = open("/dev/tap", O_RDWR);
3039 if (fd < 0) {
3040 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3041 return -1;
3044 fstat(fd, &s);
3045 dev = devname(s.st_rdev, S_IFCHR);
3046 pstrcpy(ifname, ifname_size, dev);
3048 fcntl(fd, F_SETFL, O_NONBLOCK);
3049 return fd;
3051 #elif defined(__sun__)
3052 static int tap_open(char *ifname, int ifname_size)
3054 fprintf(stderr, "warning: tap_open not yet implemented\n");
3055 return -1;
3057 #else
3058 static int tap_open(char *ifname, int ifname_size)
3060 struct ifreq ifr;
3061 int fd, ret;
3063 fd = open("/dev/net/tun", O_RDWR);
3064 if (fd < 0) {
3065 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3066 return -1;
3068 memset(&ifr, 0, sizeof(ifr));
3069 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3070 if (ifname[0] != '\0')
3071 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3072 else
3073 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3074 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3075 if (ret != 0) {
3076 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3077 close(fd);
3078 return -1;
3080 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3081 fcntl(fd, F_SETFL, O_NONBLOCK);
3082 return fd;
3084 #endif
3086 static int net_tap_init(VLANState *vlan, const char *ifname1,
3087 const char *setup_script)
3089 TAPState *s;
3090 int pid, status, fd;
3091 char *args[3];
3092 char **parg;
3093 char ifname[128];
3095 if (ifname1 != NULL)
3096 pstrcpy(ifname, sizeof(ifname), ifname1);
3097 else
3098 ifname[0] = '\0';
3099 fd = tap_open(ifname, sizeof(ifname));
3100 if (fd < 0)
3101 return -1;
3103 if (!setup_script)
3104 setup_script = "";
3105 if (setup_script[0] != '\0') {
3106 /* try to launch network init script */
3107 pid = fork();
3108 if (pid >= 0) {
3109 if (pid == 0) {
3110 parg = args;
3111 *parg++ = (char *)setup_script;
3112 *parg++ = ifname;
3113 *parg++ = NULL;
3114 execv(setup_script, args);
3115 _exit(1);
3117 while (waitpid(pid, &status, 0) != pid);
3118 if (!WIFEXITED(status) ||
3119 WEXITSTATUS(status) != 0) {
3120 fprintf(stderr, "%s: could not launch network script\n",
3121 setup_script);
3122 return -1;
3126 s = net_tap_fd_init(vlan, fd);
3127 if (!s)
3128 return -1;
3129 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3130 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3131 return 0;
3134 #endif /* !_WIN32 */
3136 /* network connection */
3137 typedef struct NetSocketState {
3138 VLANClientState *vc;
3139 int fd;
3140 int state; /* 0 = getting length, 1 = getting data */
3141 int index;
3142 int packet_len;
3143 uint8_t buf[4096];
3144 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3145 } NetSocketState;
3147 typedef struct NetSocketListenState {
3148 VLANState *vlan;
3149 int fd;
3150 } NetSocketListenState;
3152 /* XXX: we consider we can send the whole packet without blocking */
3153 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3155 NetSocketState *s = opaque;
3156 uint32_t len;
3157 len = htonl(size);
3159 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3160 send_all(s->fd, buf, size);
3163 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3165 NetSocketState *s = opaque;
3166 sendto(s->fd, buf, size, 0,
3167 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3170 static void net_socket_send(void *opaque)
3172 NetSocketState *s = opaque;
3173 int l, size, err;
3174 uint8_t buf1[4096];
3175 const uint8_t *buf;
3177 size = recv(s->fd, buf1, sizeof(buf1), 0);
3178 if (size < 0) {
3179 err = socket_error();
3180 if (err != EWOULDBLOCK)
3181 goto eoc;
3182 } else if (size == 0) {
3183 /* end of connection */
3184 eoc:
3185 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3186 closesocket(s->fd);
3187 return;
3189 buf = buf1;
3190 while (size > 0) {
3191 /* reassemble a packet from the network */
3192 switch(s->state) {
3193 case 0:
3194 l = 4 - s->index;
3195 if (l > size)
3196 l = size;
3197 memcpy(s->buf + s->index, buf, l);
3198 buf += l;
3199 size -= l;
3200 s->index += l;
3201 if (s->index == 4) {
3202 /* got length */
3203 s->packet_len = ntohl(*(uint32_t *)s->buf);
3204 s->index = 0;
3205 s->state = 1;
3207 break;
3208 case 1:
3209 l = s->packet_len - s->index;
3210 if (l > size)
3211 l = size;
3212 memcpy(s->buf + s->index, buf, l);
3213 s->index += l;
3214 buf += l;
3215 size -= l;
3216 if (s->index >= s->packet_len) {
3217 qemu_send_packet(s->vc, s->buf, s->packet_len);
3218 s->index = 0;
3219 s->state = 0;
3221 break;
3226 static void net_socket_send_dgram(void *opaque)
3228 NetSocketState *s = opaque;
3229 int size;
3231 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3232 if (size < 0)
3233 return;
3234 if (size == 0) {
3235 /* end of connection */
3236 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3237 return;
3239 qemu_send_packet(s->vc, s->buf, size);
3242 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3244 struct ip_mreq imr;
3245 int fd;
3246 int val, ret;
3247 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3248 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3249 inet_ntoa(mcastaddr->sin_addr),
3250 (int)ntohl(mcastaddr->sin_addr.s_addr));
3251 return -1;
3254 fd = socket(PF_INET, SOCK_DGRAM, 0);
3255 if (fd < 0) {
3256 perror("socket(PF_INET, SOCK_DGRAM)");
3257 return -1;
3260 val = 1;
3261 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3262 (const char *)&val, sizeof(val));
3263 if (ret < 0) {
3264 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3265 goto fail;
3268 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3269 if (ret < 0) {
3270 perror("bind");
3271 goto fail;
3274 /* Add host to multicast group */
3275 imr.imr_multiaddr = mcastaddr->sin_addr;
3276 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3278 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3279 (const char *)&imr, sizeof(struct ip_mreq));
3280 if (ret < 0) {
3281 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3282 goto fail;
3285 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3286 val = 1;
3287 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3288 (const char *)&val, sizeof(val));
3289 if (ret < 0) {
3290 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3291 goto fail;
3294 socket_set_nonblock(fd);
3295 return fd;
3296 fail:
3297 if (fd >= 0)
3298 closesocket(fd);
3299 return -1;
3302 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3303 int is_connected)
3305 struct sockaddr_in saddr;
3306 int newfd;
3307 socklen_t saddr_len;
3308 NetSocketState *s;
3310 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3311 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3312 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3315 if (is_connected) {
3316 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3317 /* must be bound */
3318 if (saddr.sin_addr.s_addr==0) {
3319 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3320 fd);
3321 return NULL;
3323 /* clone dgram socket */
3324 newfd = net_socket_mcast_create(&saddr);
3325 if (newfd < 0) {
3326 /* error already reported by net_socket_mcast_create() */
3327 close(fd);
3328 return NULL;
3330 /* clone newfd to fd, close newfd */
3331 dup2(newfd, fd);
3332 close(newfd);
3334 } else {
3335 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3336 fd, strerror(errno));
3337 return NULL;
3341 s = qemu_mallocz(sizeof(NetSocketState));
3342 if (!s)
3343 return NULL;
3344 s->fd = fd;
3346 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3347 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3349 /* mcast: save bound address as dst */
3350 if (is_connected) s->dgram_dst=saddr;
3352 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3353 "socket: fd=%d (%s mcast=%s:%d)",
3354 fd, is_connected? "cloned" : "",
3355 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3356 return s;
3359 static void net_socket_connect(void *opaque)
3361 NetSocketState *s = opaque;
3362 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3365 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3366 int is_connected)
3368 NetSocketState *s;
3369 s = qemu_mallocz(sizeof(NetSocketState));
3370 if (!s)
3371 return NULL;
3372 s->fd = fd;
3373 s->vc = qemu_new_vlan_client(vlan,
3374 net_socket_receive, NULL, s);
3375 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3376 "socket: fd=%d", fd);
3377 if (is_connected) {
3378 net_socket_connect(s);
3379 } else {
3380 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3382 return s;
3385 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3386 int is_connected)
3388 int so_type=-1, optlen=sizeof(so_type);
3390 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3391 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3392 return NULL;
3394 switch(so_type) {
3395 case SOCK_DGRAM:
3396 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3397 case SOCK_STREAM:
3398 return net_socket_fd_init_stream(vlan, fd, is_connected);
3399 default:
3400 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3401 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3402 return net_socket_fd_init_stream(vlan, fd, is_connected);
3404 return NULL;
3407 static void net_socket_accept(void *opaque)
3409 NetSocketListenState *s = opaque;
3410 NetSocketState *s1;
3411 struct sockaddr_in saddr;
3412 socklen_t len;
3413 int fd;
3415 for(;;) {
3416 len = sizeof(saddr);
3417 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3418 if (fd < 0 && errno != EINTR) {
3419 return;
3420 } else if (fd >= 0) {
3421 break;
3424 s1 = net_socket_fd_init(s->vlan, fd, 1);
3425 if (!s1) {
3426 closesocket(fd);
3427 } else {
3428 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3429 "socket: connection from %s:%d",
3430 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3434 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3436 NetSocketListenState *s;
3437 int fd, val, ret;
3438 struct sockaddr_in saddr;
3440 if (parse_host_port(&saddr, host_str) < 0)
3441 return -1;
3443 s = qemu_mallocz(sizeof(NetSocketListenState));
3444 if (!s)
3445 return -1;
3447 fd = socket(PF_INET, SOCK_STREAM, 0);
3448 if (fd < 0) {
3449 perror("socket");
3450 return -1;
3452 socket_set_nonblock(fd);
3454 /* allow fast reuse */
3455 val = 1;
3456 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3458 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3459 if (ret < 0) {
3460 perror("bind");
3461 return -1;
3463 ret = listen(fd, 0);
3464 if (ret < 0) {
3465 perror("listen");
3466 return -1;
3468 s->vlan = vlan;
3469 s->fd = fd;
3470 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3471 return 0;
3474 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3476 NetSocketState *s;
3477 int fd, connected, ret, err;
3478 struct sockaddr_in saddr;
3480 if (parse_host_port(&saddr, host_str) < 0)
3481 return -1;
3483 fd = socket(PF_INET, SOCK_STREAM, 0);
3484 if (fd < 0) {
3485 perror("socket");
3486 return -1;
3488 socket_set_nonblock(fd);
3490 connected = 0;
3491 for(;;) {
3492 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3493 if (ret < 0) {
3494 err = socket_error();
3495 if (err == EINTR || err == EWOULDBLOCK) {
3496 } else if (err == EINPROGRESS) {
3497 break;
3498 } else {
3499 perror("connect");
3500 closesocket(fd);
3501 return -1;
3503 } else {
3504 connected = 1;
3505 break;
3508 s = net_socket_fd_init(vlan, fd, connected);
3509 if (!s)
3510 return -1;
3511 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3512 "socket: connect to %s:%d",
3513 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3514 return 0;
3517 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3519 NetSocketState *s;
3520 int fd;
3521 struct sockaddr_in saddr;
3523 if (parse_host_port(&saddr, host_str) < 0)
3524 return -1;
3527 fd = net_socket_mcast_create(&saddr);
3528 if (fd < 0)
3529 return -1;
3531 s = net_socket_fd_init(vlan, fd, 0);
3532 if (!s)
3533 return -1;
3535 s->dgram_dst = saddr;
3537 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3538 "socket: mcast=%s:%d",
3539 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3540 return 0;
3544 static int get_param_value(char *buf, int buf_size,
3545 const char *tag, const char *str)
3547 const char *p;
3548 char *q;
3549 char option[128];
3551 p = str;
3552 for(;;) {
3553 q = option;
3554 while (*p != '\0' && *p != '=') {
3555 if ((q - option) < sizeof(option) - 1)
3556 *q++ = *p;
3557 p++;
3559 *q = '\0';
3560 if (*p != '=')
3561 break;
3562 p++;
3563 if (!strcmp(tag, option)) {
3564 q = buf;
3565 while (*p != '\0' && *p != ',') {
3566 if ((q - buf) < buf_size - 1)
3567 *q++ = *p;
3568 p++;
3570 *q = '\0';
3571 return q - buf;
3572 } else {
3573 while (*p != '\0' && *p != ',') {
3574 p++;
3577 if (*p != ',')
3578 break;
3579 p++;
3581 return 0;
3584 int net_client_init(const char *str)
3586 const char *p;
3587 char *q;
3588 char device[64];
3589 char buf[1024];
3590 int vlan_id, ret;
3591 VLANState *vlan;
3593 p = str;
3594 q = device;
3595 while (*p != '\0' && *p != ',') {
3596 if ((q - device) < sizeof(device) - 1)
3597 *q++ = *p;
3598 p++;
3600 *q = '\0';
3601 if (*p == ',')
3602 p++;
3603 vlan_id = 0;
3604 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3605 vlan_id = strtol(buf, NULL, 0);
3607 vlan = qemu_find_vlan(vlan_id);
3608 if (!vlan) {
3609 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3610 return -1;
3612 if (!strcmp(device, "nic")) {
3613 NICInfo *nd;
3614 uint8_t *macaddr;
3616 if (nb_nics >= MAX_NICS) {
3617 fprintf(stderr, "Too Many NICs\n");
3618 return -1;
3620 nd = &nd_table[nb_nics];
3621 macaddr = nd->macaddr;
3622 macaddr[0] = 0x52;
3623 macaddr[1] = 0x54;
3624 macaddr[2] = 0x00;
3625 macaddr[3] = 0x12;
3626 macaddr[4] = 0x34;
3627 macaddr[5] = 0x56 + nb_nics;
3629 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3630 if (parse_macaddr(macaddr, buf) < 0) {
3631 fprintf(stderr, "invalid syntax for ethernet address\n");
3632 return -1;
3635 if (get_param_value(buf, sizeof(buf), "model", p)) {
3636 nd->model = strdup(buf);
3638 nd->vlan = vlan;
3639 nb_nics++;
3640 ret = 0;
3641 } else
3642 if (!strcmp(device, "none")) {
3643 /* does nothing. It is needed to signal that no network cards
3644 are wanted */
3645 ret = 0;
3646 } else
3647 #ifdef CONFIG_SLIRP
3648 if (!strcmp(device, "user")) {
3649 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3650 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3652 ret = net_slirp_init(vlan);
3653 } else
3654 #endif
3655 #ifdef _WIN32
3656 if (!strcmp(device, "tap")) {
3657 char ifname[64];
3658 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3659 fprintf(stderr, "tap: no interface name\n");
3660 return -1;
3662 ret = tap_win32_init(vlan, ifname);
3663 } else
3664 #else
3665 if (!strcmp(device, "tap")) {
3666 char ifname[64];
3667 char setup_script[1024];
3668 int fd;
3669 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3670 fd = strtol(buf, NULL, 0);
3671 ret = -1;
3672 if (net_tap_fd_init(vlan, fd))
3673 ret = 0;
3674 } else {
3675 get_param_value(ifname, sizeof(ifname), "ifname", p);
3676 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3677 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3679 ret = net_tap_init(vlan, ifname, setup_script);
3681 } else
3682 #endif
3683 if (!strcmp(device, "socket")) {
3684 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3685 int fd;
3686 fd = strtol(buf, NULL, 0);
3687 ret = -1;
3688 if (net_socket_fd_init(vlan, fd, 1))
3689 ret = 0;
3690 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3691 ret = net_socket_listen_init(vlan, buf);
3692 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3693 ret = net_socket_connect_init(vlan, buf);
3694 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3695 ret = net_socket_mcast_init(vlan, buf);
3696 } else {
3697 fprintf(stderr, "Unknown socket options: %s\n", p);
3698 return -1;
3700 } else
3702 fprintf(stderr, "Unknown network device: %s\n", device);
3703 return -1;
3705 if (ret < 0) {
3706 fprintf(stderr, "Could not initialize device '%s'\n", device);
3709 return ret;
3712 void do_info_network(void)
3714 VLANState *vlan;
3715 VLANClientState *vc;
3717 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3718 term_printf("VLAN %d devices:\n", vlan->id);
3719 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3720 term_printf(" %s\n", vc->info_str);
3724 /***********************************************************/
3725 /* USB devices */
3727 static USBPort *used_usb_ports;
3728 static USBPort *free_usb_ports;
3730 /* ??? Maybe change this to register a hub to keep track of the topology. */
3731 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3732 usb_attachfn attach)
3734 port->opaque = opaque;
3735 port->index = index;
3736 port->attach = attach;
3737 port->next = free_usb_ports;
3738 free_usb_ports = port;
3741 static int usb_device_add(const char *devname)
3743 const char *p;
3744 USBDevice *dev;
3745 USBPort *port;
3747 if (!free_usb_ports)
3748 return -1;
3750 if (strstart(devname, "host:", &p)) {
3751 dev = usb_host_device_open(p);
3752 } else if (!strcmp(devname, "mouse")) {
3753 dev = usb_mouse_init();
3754 } else if (!strcmp(devname, "tablet")) {
3755 dev = usb_tablet_init();
3756 } else if (strstart(devname, "disk:", &p)) {
3757 dev = usb_msd_init(p);
3758 } else {
3759 return -1;
3761 if (!dev)
3762 return -1;
3764 /* Find a USB port to add the device to. */
3765 port = free_usb_ports;
3766 if (!port->next) {
3767 USBDevice *hub;
3769 /* Create a new hub and chain it on. */
3770 free_usb_ports = NULL;
3771 port->next = used_usb_ports;
3772 used_usb_ports = port;
3774 hub = usb_hub_init(VM_USB_HUB_SIZE);
3775 usb_attach(port, hub);
3776 port = free_usb_ports;
3779 free_usb_ports = port->next;
3780 port->next = used_usb_ports;
3781 used_usb_ports = port;
3782 usb_attach(port, dev);
3783 return 0;
3786 static int usb_device_del(const char *devname)
3788 USBPort *port;
3789 USBPort **lastp;
3790 USBDevice *dev;
3791 int bus_num, addr;
3792 const char *p;
3794 if (!used_usb_ports)
3795 return -1;
3797 p = strchr(devname, '.');
3798 if (!p)
3799 return -1;
3800 bus_num = strtoul(devname, NULL, 0);
3801 addr = strtoul(p + 1, NULL, 0);
3802 if (bus_num != 0)
3803 return -1;
3805 lastp = &used_usb_ports;
3806 port = used_usb_ports;
3807 while (port && port->dev->addr != addr) {
3808 lastp = &port->next;
3809 port = port->next;
3812 if (!port)
3813 return -1;
3815 dev = port->dev;
3816 *lastp = port->next;
3817 usb_attach(port, NULL);
3818 dev->handle_destroy(dev);
3819 port->next = free_usb_ports;
3820 free_usb_ports = port;
3821 return 0;
3824 void do_usb_add(const char *devname)
3826 int ret;
3827 ret = usb_device_add(devname);
3828 if (ret < 0)
3829 term_printf("Could not add USB device '%s'\n", devname);
3832 void do_usb_del(const char *devname)
3834 int ret;
3835 ret = usb_device_del(devname);
3836 if (ret < 0)
3837 term_printf("Could not remove USB device '%s'\n", devname);
3840 void usb_info(void)
3842 USBDevice *dev;
3843 USBPort *port;
3844 const char *speed_str;
3846 if (!usb_enabled) {
3847 term_printf("USB support not enabled\n");
3848 return;
3851 for (port = used_usb_ports; port; port = port->next) {
3852 dev = port->dev;
3853 if (!dev)
3854 continue;
3855 switch(dev->speed) {
3856 case USB_SPEED_LOW:
3857 speed_str = "1.5";
3858 break;
3859 case USB_SPEED_FULL:
3860 speed_str = "12";
3861 break;
3862 case USB_SPEED_HIGH:
3863 speed_str = "480";
3864 break;
3865 default:
3866 speed_str = "?";
3867 break;
3869 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
3870 0, dev->addr, speed_str, dev->devname);
3874 /***********************************************************/
3875 /* pid file */
3877 static char *pid_filename;
3879 /* Remove PID file. Called on normal exit */
3881 static void remove_pidfile(void)
3883 unlink (pid_filename);
3886 static void create_pidfile(const char *filename)
3888 struct stat pidstat;
3889 FILE *f;
3891 /* Try to write our PID to the named file */
3892 if (stat(filename, &pidstat) < 0) {
3893 if (errno == ENOENT) {
3894 if ((f = fopen (filename, "w")) == NULL) {
3895 perror("Opening pidfile");
3896 exit(1);
3898 fprintf(f, "%d\n", getpid());
3899 fclose(f);
3900 pid_filename = qemu_strdup(filename);
3901 if (!pid_filename) {
3902 fprintf(stderr, "Could not save PID filename");
3903 exit(1);
3905 atexit(remove_pidfile);
3907 } else {
3908 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3909 filename);
3910 exit(1);
3914 /***********************************************************/
3915 /* dumb display */
3917 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3921 static void dumb_resize(DisplayState *ds, int w, int h)
3925 static void dumb_refresh(DisplayState *ds)
3927 vga_hw_update();
3930 void dumb_display_init(DisplayState *ds)
3932 ds->data = NULL;
3933 ds->linesize = 0;
3934 ds->depth = 0;
3935 ds->dpy_update = dumb_update;
3936 ds->dpy_resize = dumb_resize;
3937 ds->dpy_refresh = dumb_refresh;
3940 /***********************************************************/
3941 /* I/O handling */
3943 #define MAX_IO_HANDLERS 64
3945 typedef struct IOHandlerRecord {
3946 int fd;
3947 IOCanRWHandler *fd_read_poll;
3948 IOHandler *fd_read;
3949 IOHandler *fd_write;
3950 void *opaque;
3951 /* temporary data */
3952 struct pollfd *ufd;
3953 struct IOHandlerRecord *next;
3954 } IOHandlerRecord;
3956 static IOHandlerRecord *first_io_handler;
3958 /* XXX: fd_read_poll should be suppressed, but an API change is
3959 necessary in the character devices to suppress fd_can_read(). */
3960 int qemu_set_fd_handler2(int fd,
3961 IOCanRWHandler *fd_read_poll,
3962 IOHandler *fd_read,
3963 IOHandler *fd_write,
3964 void *opaque)
3966 IOHandlerRecord **pioh, *ioh;
3968 if (!fd_read && !fd_write) {
3969 pioh = &first_io_handler;
3970 for(;;) {
3971 ioh = *pioh;
3972 if (ioh == NULL)
3973 break;
3974 if (ioh->fd == fd) {
3975 *pioh = ioh->next;
3976 qemu_free(ioh);
3977 break;
3979 pioh = &ioh->next;
3981 } else {
3982 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3983 if (ioh->fd == fd)
3984 goto found;
3986 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3987 if (!ioh)
3988 return -1;
3989 ioh->next = first_io_handler;
3990 first_io_handler = ioh;
3991 found:
3992 ioh->fd = fd;
3993 ioh->fd_read_poll = fd_read_poll;
3994 ioh->fd_read = fd_read;
3995 ioh->fd_write = fd_write;
3996 ioh->opaque = opaque;
3998 return 0;
4001 int qemu_set_fd_handler(int fd,
4002 IOHandler *fd_read,
4003 IOHandler *fd_write,
4004 void *opaque)
4006 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4009 /***********************************************************/
4010 /* Polling handling */
4012 typedef struct PollingEntry {
4013 PollingFunc *func;
4014 void *opaque;
4015 struct PollingEntry *next;
4016 } PollingEntry;
4018 static PollingEntry *first_polling_entry;
4020 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4022 PollingEntry **ppe, *pe;
4023 pe = qemu_mallocz(sizeof(PollingEntry));
4024 if (!pe)
4025 return -1;
4026 pe->func = func;
4027 pe->opaque = opaque;
4028 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4029 *ppe = pe;
4030 return 0;
4033 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4035 PollingEntry **ppe, *pe;
4036 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4037 pe = *ppe;
4038 if (pe->func == func && pe->opaque == opaque) {
4039 *ppe = pe->next;
4040 qemu_free(pe);
4041 break;
4046 #ifdef _WIN32
4047 /***********************************************************/
4048 /* Wait objects support */
4049 typedef struct WaitObjects {
4050 int num;
4051 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4052 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4053 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4054 } WaitObjects;
4056 static WaitObjects wait_objects = {0};
4058 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4060 WaitObjects *w = &wait_objects;
4062 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4063 return -1;
4064 w->events[w->num] = handle;
4065 w->func[w->num] = func;
4066 w->opaque[w->num] = opaque;
4067 w->num++;
4068 return 0;
4071 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4073 int i, found;
4074 WaitObjects *w = &wait_objects;
4076 found = 0;
4077 for (i = 0; i < w->num; i++) {
4078 if (w->events[i] == handle)
4079 found = 1;
4080 if (found) {
4081 w->events[i] = w->events[i + 1];
4082 w->func[i] = w->func[i + 1];
4083 w->opaque[i] = w->opaque[i + 1];
4086 if (found)
4087 w->num--;
4089 #endif
4091 /***********************************************************/
4092 /* savevm/loadvm support */
4094 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4096 fwrite(buf, 1, size, f);
4099 void qemu_put_byte(QEMUFile *f, int v)
4101 fputc(v, f);
4104 void qemu_put_be16(QEMUFile *f, unsigned int v)
4106 qemu_put_byte(f, v >> 8);
4107 qemu_put_byte(f, v);
4110 void qemu_put_be32(QEMUFile *f, unsigned int v)
4112 qemu_put_byte(f, v >> 24);
4113 qemu_put_byte(f, v >> 16);
4114 qemu_put_byte(f, v >> 8);
4115 qemu_put_byte(f, v);
4118 void qemu_put_be64(QEMUFile *f, uint64_t v)
4120 qemu_put_be32(f, v >> 32);
4121 qemu_put_be32(f, v);
4124 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4126 return fread(buf, 1, size, f);
4129 int qemu_get_byte(QEMUFile *f)
4131 int v;
4132 v = fgetc(f);
4133 if (v == EOF)
4134 return 0;
4135 else
4136 return v;
4139 unsigned int qemu_get_be16(QEMUFile *f)
4141 unsigned int v;
4142 v = qemu_get_byte(f) << 8;
4143 v |= qemu_get_byte(f);
4144 return v;
4147 unsigned int qemu_get_be32(QEMUFile *f)
4149 unsigned int v;
4150 v = qemu_get_byte(f) << 24;
4151 v |= qemu_get_byte(f) << 16;
4152 v |= qemu_get_byte(f) << 8;
4153 v |= qemu_get_byte(f);
4154 return v;
4157 uint64_t qemu_get_be64(QEMUFile *f)
4159 uint64_t v;
4160 v = (uint64_t)qemu_get_be32(f) << 32;
4161 v |= qemu_get_be32(f);
4162 return v;
4165 int64_t qemu_ftell(QEMUFile *f)
4167 return ftell(f);
4170 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4172 if (fseek(f, pos, whence) < 0)
4173 return -1;
4174 return ftell(f);
4177 typedef struct SaveStateEntry {
4178 char idstr[256];
4179 int instance_id;
4180 int version_id;
4181 SaveStateHandler *save_state;
4182 LoadStateHandler *load_state;
4183 void *opaque;
4184 struct SaveStateEntry *next;
4185 } SaveStateEntry;
4187 static SaveStateEntry *first_se;
4189 int register_savevm(const char *idstr,
4190 int instance_id,
4191 int version_id,
4192 SaveStateHandler *save_state,
4193 LoadStateHandler *load_state,
4194 void *opaque)
4196 SaveStateEntry *se, **pse;
4198 se = qemu_malloc(sizeof(SaveStateEntry));
4199 if (!se)
4200 return -1;
4201 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4202 se->instance_id = instance_id;
4203 se->version_id = version_id;
4204 se->save_state = save_state;
4205 se->load_state = load_state;
4206 se->opaque = opaque;
4207 se->next = NULL;
4209 /* add at the end of list */
4210 pse = &first_se;
4211 while (*pse != NULL)
4212 pse = &(*pse)->next;
4213 *pse = se;
4214 return 0;
4217 #define QEMU_VM_FILE_MAGIC 0x5145564d
4218 #define QEMU_VM_FILE_VERSION 0x00000001
4220 int qemu_savevm(const char *filename)
4222 SaveStateEntry *se;
4223 QEMUFile *f;
4224 int len, len_pos, cur_pos, saved_vm_running, ret;
4226 saved_vm_running = vm_running;
4227 vm_stop(0);
4229 f = fopen(filename, "wb");
4230 if (!f) {
4231 ret = -1;
4232 goto the_end;
4235 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4236 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4238 for(se = first_se; se != NULL; se = se->next) {
4239 /* ID string */
4240 len = strlen(se->idstr);
4241 qemu_put_byte(f, len);
4242 qemu_put_buffer(f, se->idstr, len);
4244 qemu_put_be32(f, se->instance_id);
4245 qemu_put_be32(f, se->version_id);
4247 /* record size: filled later */
4248 len_pos = ftell(f);
4249 qemu_put_be32(f, 0);
4251 se->save_state(f, se->opaque);
4253 /* fill record size */
4254 cur_pos = ftell(f);
4255 len = ftell(f) - len_pos - 4;
4256 fseek(f, len_pos, SEEK_SET);
4257 qemu_put_be32(f, len);
4258 fseek(f, cur_pos, SEEK_SET);
4261 fclose(f);
4262 ret = 0;
4263 the_end:
4264 if (saved_vm_running)
4265 vm_start();
4266 return ret;
4269 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4271 SaveStateEntry *se;
4273 for(se = first_se; se != NULL; se = se->next) {
4274 if (!strcmp(se->idstr, idstr) &&
4275 instance_id == se->instance_id)
4276 return se;
4278 return NULL;
4281 int qemu_loadvm(const char *filename)
4283 SaveStateEntry *se;
4284 QEMUFile *f;
4285 int len, cur_pos, ret, instance_id, record_len, version_id;
4286 int saved_vm_running;
4287 unsigned int v;
4288 char idstr[256];
4290 saved_vm_running = vm_running;
4291 vm_stop(0);
4293 f = fopen(filename, "rb");
4294 if (!f) {
4295 ret = -1;
4296 goto the_end;
4299 v = qemu_get_be32(f);
4300 if (v != QEMU_VM_FILE_MAGIC)
4301 goto fail;
4302 v = qemu_get_be32(f);
4303 if (v != QEMU_VM_FILE_VERSION) {
4304 fail:
4305 fclose(f);
4306 ret = -1;
4307 goto the_end;
4309 for(;;) {
4310 len = qemu_get_byte(f);
4311 if (feof(f))
4312 break;
4313 qemu_get_buffer(f, idstr, len);
4314 idstr[len] = '\0';
4315 instance_id = qemu_get_be32(f);
4316 version_id = qemu_get_be32(f);
4317 record_len = qemu_get_be32(f);
4318 #if 0
4319 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4320 idstr, instance_id, version_id, record_len);
4321 #endif
4322 cur_pos = ftell(f);
4323 se = find_se(idstr, instance_id);
4324 if (!se) {
4325 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4326 instance_id, idstr);
4327 } else {
4328 ret = se->load_state(f, se->opaque, version_id);
4329 if (ret < 0) {
4330 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4331 instance_id, idstr);
4334 /* always seek to exact end of record */
4335 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4337 fclose(f);
4338 ret = 0;
4339 the_end:
4340 if (saved_vm_running)
4341 vm_start();
4342 return ret;
4345 /***********************************************************/
4346 /* cpu save/restore */
4348 #if defined(TARGET_I386)
4350 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4352 qemu_put_be32(f, dt->selector);
4353 qemu_put_betl(f, dt->base);
4354 qemu_put_be32(f, dt->limit);
4355 qemu_put_be32(f, dt->flags);
4358 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4360 dt->selector = qemu_get_be32(f);
4361 dt->base = qemu_get_betl(f);
4362 dt->limit = qemu_get_be32(f);
4363 dt->flags = qemu_get_be32(f);
4366 void cpu_save(QEMUFile *f, void *opaque)
4368 CPUState *env = opaque;
4369 uint16_t fptag, fpus, fpuc, fpregs_format;
4370 uint32_t hflags;
4371 int i;
4373 for(i = 0; i < CPU_NB_REGS; i++)
4374 qemu_put_betls(f, &env->regs[i]);
4375 qemu_put_betls(f, &env->eip);
4376 qemu_put_betls(f, &env->eflags);
4377 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4378 qemu_put_be32s(f, &hflags);
4380 /* FPU */
4381 fpuc = env->fpuc;
4382 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4383 fptag = 0;
4384 for(i = 0; i < 8; i++) {
4385 fptag |= ((!env->fptags[i]) << i);
4388 qemu_put_be16s(f, &fpuc);
4389 qemu_put_be16s(f, &fpus);
4390 qemu_put_be16s(f, &fptag);
4392 #ifdef USE_X86LDOUBLE
4393 fpregs_format = 0;
4394 #else
4395 fpregs_format = 1;
4396 #endif
4397 qemu_put_be16s(f, &fpregs_format);
4399 for(i = 0; i < 8; i++) {
4400 #ifdef USE_X86LDOUBLE
4402 uint64_t mant;
4403 uint16_t exp;
4404 /* we save the real CPU data (in case of MMX usage only 'mant'
4405 contains the MMX register */
4406 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4407 qemu_put_be64(f, mant);
4408 qemu_put_be16(f, exp);
4410 #else
4411 /* if we use doubles for float emulation, we save the doubles to
4412 avoid losing information in case of MMX usage. It can give
4413 problems if the image is restored on a CPU where long
4414 doubles are used instead. */
4415 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4416 #endif
4419 for(i = 0; i < 6; i++)
4420 cpu_put_seg(f, &env->segs[i]);
4421 cpu_put_seg(f, &env->ldt);
4422 cpu_put_seg(f, &env->tr);
4423 cpu_put_seg(f, &env->gdt);
4424 cpu_put_seg(f, &env->idt);
4426 qemu_put_be32s(f, &env->sysenter_cs);
4427 qemu_put_be32s(f, &env->sysenter_esp);
4428 qemu_put_be32s(f, &env->sysenter_eip);
4430 qemu_put_betls(f, &env->cr[0]);
4431 qemu_put_betls(f, &env->cr[2]);
4432 qemu_put_betls(f, &env->cr[3]);
4433 qemu_put_betls(f, &env->cr[4]);
4435 for(i = 0; i < 8; i++)
4436 qemu_put_betls(f, &env->dr[i]);
4438 /* MMU */
4439 qemu_put_be32s(f, &env->a20_mask);
4441 /* XMM */
4442 qemu_put_be32s(f, &env->mxcsr);
4443 for(i = 0; i < CPU_NB_REGS; i++) {
4444 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4445 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4448 #ifdef TARGET_X86_64
4449 qemu_put_be64s(f, &env->efer);
4450 qemu_put_be64s(f, &env->star);
4451 qemu_put_be64s(f, &env->lstar);
4452 qemu_put_be64s(f, &env->cstar);
4453 qemu_put_be64s(f, &env->fmask);
4454 qemu_put_be64s(f, &env->kernelgsbase);
4455 #endif
4457 #ifdef USE_KVM
4458 qemu_put_be32s(f, &env->kvm_interrupt_summary);
4459 for (i = 0; i < NR_IRQ_WORDS ; i++) {
4460 qemu_put_betls(f, &env->kvm_interrupt_bitmap[i]);
4462 #endif
4465 #ifdef USE_X86LDOUBLE
4466 /* XXX: add that in a FPU generic layer */
4467 union x86_longdouble {
4468 uint64_t mant;
4469 uint16_t exp;
4472 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4473 #define EXPBIAS1 1023
4474 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4475 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4477 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4479 int e;
4480 /* mantissa */
4481 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4482 /* exponent + sign */
4483 e = EXPD1(temp) - EXPBIAS1 + 16383;
4484 e |= SIGND1(temp) >> 16;
4485 p->exp = e;
4487 #endif
4489 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4491 CPUState *env = opaque;
4492 int i, guess_mmx;
4493 uint32_t hflags;
4494 uint16_t fpus, fpuc, fptag, fpregs_format;
4496 if (version_id != 3)
4497 return -EINVAL;
4498 for(i = 0; i < CPU_NB_REGS; i++)
4499 qemu_get_betls(f, &env->regs[i]);
4500 qemu_get_betls(f, &env->eip);
4501 qemu_get_betls(f, &env->eflags);
4502 qemu_get_be32s(f, &hflags);
4504 qemu_get_be16s(f, &fpuc);
4505 qemu_get_be16s(f, &fpus);
4506 qemu_get_be16s(f, &fptag);
4507 qemu_get_be16s(f, &fpregs_format);
4509 /* NOTE: we cannot always restore the FPU state if the image come
4510 from a host with a different 'USE_X86LDOUBLE' define. We guess
4511 if we are in an MMX state to restore correctly in that case. */
4512 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4513 for(i = 0; i < 8; i++) {
4514 uint64_t mant;
4515 uint16_t exp;
4517 switch(fpregs_format) {
4518 case 0:
4519 mant = qemu_get_be64(f);
4520 exp = qemu_get_be16(f);
4521 #ifdef USE_X86LDOUBLE
4522 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4523 #else
4524 /* difficult case */
4525 if (guess_mmx)
4526 env->fpregs[i].mmx.MMX_Q(0) = mant;
4527 else
4528 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4529 #endif
4530 break;
4531 case 1:
4532 mant = qemu_get_be64(f);
4533 #ifdef USE_X86LDOUBLE
4535 union x86_longdouble *p;
4536 /* difficult case */
4537 p = (void *)&env->fpregs[i];
4538 if (guess_mmx) {
4539 p->mant = mant;
4540 p->exp = 0xffff;
4541 } else {
4542 fp64_to_fp80(p, mant);
4545 #else
4546 env->fpregs[i].mmx.MMX_Q(0) = mant;
4547 #endif
4548 break;
4549 default:
4550 return -EINVAL;
4554 env->fpuc = fpuc;
4555 /* XXX: restore FPU round state */
4556 env->fpstt = (fpus >> 11) & 7;
4557 env->fpus = fpus & ~0x3800;
4558 fptag ^= 0xff;
4559 for(i = 0; i < 8; i++) {
4560 env->fptags[i] = (fptag >> i) & 1;
4563 for(i = 0; i < 6; i++)
4564 cpu_get_seg(f, &env->segs[i]);
4565 cpu_get_seg(f, &env->ldt);
4566 cpu_get_seg(f, &env->tr);
4567 cpu_get_seg(f, &env->gdt);
4568 cpu_get_seg(f, &env->idt);
4570 qemu_get_be32s(f, &env->sysenter_cs);
4571 qemu_get_be32s(f, &env->sysenter_esp);
4572 qemu_get_be32s(f, &env->sysenter_eip);
4574 qemu_get_betls(f, &env->cr[0]);
4575 qemu_get_betls(f, &env->cr[2]);
4576 qemu_get_betls(f, &env->cr[3]);
4577 qemu_get_betls(f, &env->cr[4]);
4579 for(i = 0; i < 8; i++)
4580 qemu_get_betls(f, &env->dr[i]);
4582 /* MMU */
4583 qemu_get_be32s(f, &env->a20_mask);
4585 qemu_get_be32s(f, &env->mxcsr);
4586 for(i = 0; i < CPU_NB_REGS; i++) {
4587 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4588 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4591 #ifdef TARGET_X86_64
4592 qemu_get_be64s(f, &env->efer);
4593 qemu_get_be64s(f, &env->star);
4594 qemu_get_be64s(f, &env->lstar);
4595 qemu_get_be64s(f, &env->cstar);
4596 qemu_get_be64s(f, &env->fmask);
4597 qemu_get_be64s(f, &env->kernelgsbase);
4598 #endif
4600 /* XXX: compute hflags from scratch, except for CPL and IIF */
4601 env->hflags = hflags;
4602 tlb_flush(env, 1);
4603 #ifdef USE_KVM
4604 qemu_get_be32s(f, &env->kvm_interrupt_summary);
4605 for (i = 0; i < NR_IRQ_WORDS ; i++) {
4606 qemu_get_betls(f, &env->kvm_interrupt_bitmap[i]);
4608 kvm_load_registers(env);
4609 #endif
4610 return 0;
4613 #elif defined(TARGET_PPC)
4614 void cpu_save(QEMUFile *f, void *opaque)
4618 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4620 return 0;
4623 #elif defined(TARGET_MIPS)
4624 void cpu_save(QEMUFile *f, void *opaque)
4628 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4630 return 0;
4633 #elif defined(TARGET_SPARC)
4634 void cpu_save(QEMUFile *f, void *opaque)
4636 CPUState *env = opaque;
4637 int i;
4638 uint32_t tmp;
4640 for(i = 0; i < 8; i++)
4641 qemu_put_betls(f, &env->gregs[i]);
4642 for(i = 0; i < NWINDOWS * 16; i++)
4643 qemu_put_betls(f, &env->regbase[i]);
4645 /* FPU */
4646 for(i = 0; i < TARGET_FPREGS; i++) {
4647 union {
4648 float32 f;
4649 uint32_t i;
4650 } u;
4651 u.f = env->fpr[i];
4652 qemu_put_be32(f, u.i);
4655 qemu_put_betls(f, &env->pc);
4656 qemu_put_betls(f, &env->npc);
4657 qemu_put_betls(f, &env->y);
4658 tmp = GET_PSR(env);
4659 qemu_put_be32(f, tmp);
4660 qemu_put_betls(f, &env->fsr);
4661 qemu_put_betls(f, &env->tbr);
4662 #ifndef TARGET_SPARC64
4663 qemu_put_be32s(f, &env->wim);
4664 /* MMU */
4665 for(i = 0; i < 16; i++)
4666 qemu_put_be32s(f, &env->mmuregs[i]);
4667 #endif
4670 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4672 CPUState *env = opaque;
4673 int i;
4674 uint32_t tmp;
4676 for(i = 0; i < 8; i++)
4677 qemu_get_betls(f, &env->gregs[i]);
4678 for(i = 0; i < NWINDOWS * 16; i++)
4679 qemu_get_betls(f, &env->regbase[i]);
4681 /* FPU */
4682 for(i = 0; i < TARGET_FPREGS; i++) {
4683 union {
4684 float32 f;
4685 uint32_t i;
4686 } u;
4687 u.i = qemu_get_be32(f);
4688 env->fpr[i] = u.f;
4691 qemu_get_betls(f, &env->pc);
4692 qemu_get_betls(f, &env->npc);
4693 qemu_get_betls(f, &env->y);
4694 tmp = qemu_get_be32(f);
4695 env->cwp = 0; /* needed to ensure that the wrapping registers are
4696 correctly updated */
4697 PUT_PSR(env, tmp);
4698 qemu_get_betls(f, &env->fsr);
4699 qemu_get_betls(f, &env->tbr);
4700 #ifndef TARGET_SPARC64
4701 qemu_get_be32s(f, &env->wim);
4702 /* MMU */
4703 for(i = 0; i < 16; i++)
4704 qemu_get_be32s(f, &env->mmuregs[i]);
4705 #endif
4706 tlb_flush(env, 1);
4707 return 0;
4710 #elif defined(TARGET_ARM)
4712 /* ??? Need to implement these. */
4713 void cpu_save(QEMUFile *f, void *opaque)
4717 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4719 return 0;
4722 #else
4724 #warning No CPU save/restore functions
4726 #endif
4728 /***********************************************************/
4729 /* ram save/restore */
4731 /* we just avoid storing empty pages */
4732 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4734 int i, v;
4736 v = buf[0];
4737 for(i = 1; i < len; i++) {
4738 if (buf[i] != v)
4739 goto normal_save;
4741 qemu_put_byte(f, 1);
4742 qemu_put_byte(f, v);
4743 return;
4744 normal_save:
4745 qemu_put_byte(f, 0);
4746 qemu_put_buffer(f, buf, len);
4749 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4751 int v;
4753 v = qemu_get_byte(f);
4754 switch(v) {
4755 case 0:
4756 if (qemu_get_buffer(f, buf, len) != len)
4757 return -EIO;
4758 break;
4759 case 1:
4760 v = qemu_get_byte(f);
4761 memset(buf, v, len);
4762 break;
4763 default:
4764 return -EINVAL;
4766 return 0;
4769 static void ram_save(QEMUFile *f, void *opaque)
4771 int i;
4772 qemu_put_be32(f, phys_ram_size);
4773 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4774 #ifdef USE_KVM
4775 if ((i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
4776 continue;
4777 #endif
4778 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4782 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4784 int i, ret;
4786 if (version_id != 1)
4787 return -EINVAL;
4788 if (qemu_get_be32(f) != phys_ram_size)
4789 return -EINVAL;
4790 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4791 #ifdef USE_KVM
4792 if ((i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
4793 continue;
4794 #endif
4795 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4796 if (ret)
4797 return ret;
4799 return 0;
4802 /***********************************************************/
4803 /* machine registration */
4805 QEMUMachine *first_machine = NULL;
4807 int qemu_register_machine(QEMUMachine *m)
4809 QEMUMachine **pm;
4810 pm = &first_machine;
4811 while (*pm != NULL)
4812 pm = &(*pm)->next;
4813 m->next = NULL;
4814 *pm = m;
4815 return 0;
4818 QEMUMachine *find_machine(const char *name)
4820 QEMUMachine *m;
4822 for(m = first_machine; m != NULL; m = m->next) {
4823 if (!strcmp(m->name, name))
4824 return m;
4826 return NULL;
4829 /***********************************************************/
4830 /* main execution loop */
4832 void gui_update(void *opaque)
4834 display_state.dpy_refresh(&display_state);
4835 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4838 struct vm_change_state_entry {
4839 VMChangeStateHandler *cb;
4840 void *opaque;
4841 LIST_ENTRY (vm_change_state_entry) entries;
4844 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4846 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4847 void *opaque)
4849 VMChangeStateEntry *e;
4851 e = qemu_mallocz(sizeof (*e));
4852 if (!e)
4853 return NULL;
4855 e->cb = cb;
4856 e->opaque = opaque;
4857 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4858 return e;
4861 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4863 LIST_REMOVE (e, entries);
4864 qemu_free (e);
4867 static void vm_state_notify(int running)
4869 VMChangeStateEntry *e;
4871 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4872 e->cb(e->opaque, running);
4876 /* XXX: support several handlers */
4877 static VMStopHandler *vm_stop_cb;
4878 static void *vm_stop_opaque;
4880 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4882 vm_stop_cb = cb;
4883 vm_stop_opaque = opaque;
4884 return 0;
4887 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4889 vm_stop_cb = NULL;
4892 void vm_start(void)
4894 if (!vm_running) {
4895 cpu_enable_ticks();
4896 vm_running = 1;
4897 vm_state_notify(1);
4901 void vm_stop(int reason)
4903 if (vm_running) {
4904 cpu_disable_ticks();
4905 vm_running = 0;
4906 if (reason != 0) {
4907 if (vm_stop_cb) {
4908 vm_stop_cb(vm_stop_opaque, reason);
4911 vm_state_notify(0);
4915 /* reset/shutdown handler */
4917 typedef struct QEMUResetEntry {
4918 QEMUResetHandler *func;
4919 void *opaque;
4920 struct QEMUResetEntry *next;
4921 } QEMUResetEntry;
4923 static QEMUResetEntry *first_reset_entry;
4924 static int reset_requested;
4925 static int shutdown_requested;
4926 static int powerdown_requested;
4928 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4930 QEMUResetEntry **pre, *re;
4932 pre = &first_reset_entry;
4933 while (*pre != NULL)
4934 pre = &(*pre)->next;
4935 re = qemu_mallocz(sizeof(QEMUResetEntry));
4936 re->func = func;
4937 re->opaque = opaque;
4938 re->next = NULL;
4939 *pre = re;
4942 void qemu_system_reset(void)
4944 QEMUResetEntry *re;
4946 /* reset all devices */
4947 for(re = first_reset_entry; re != NULL; re = re->next) {
4948 re->func(re->opaque);
4952 void qemu_system_reset_request(void)
4954 reset_requested = 1;
4955 if (cpu_single_env)
4956 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4959 void qemu_system_shutdown_request(void)
4961 shutdown_requested = 1;
4962 if (cpu_single_env)
4963 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4966 void qemu_system_powerdown_request(void)
4968 powerdown_requested = 1;
4969 if (cpu_single_env)
4970 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4973 void main_loop_wait(int timeout)
4975 IOHandlerRecord *ioh, *ioh_next;
4976 fd_set rfds, wfds, xfds;
4977 int ret, nfds;
4978 struct timeval tv;
4979 PollingEntry *pe;
4982 /* XXX: need to suppress polling by better using win32 events */
4983 ret = 0;
4984 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4985 ret |= pe->func(pe->opaque);
4987 #ifdef _WIN32
4988 if (ret == 0 && timeout > 0) {
4989 int err;
4990 WaitObjects *w = &wait_objects;
4992 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
4993 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4994 if (w->func[ret - WAIT_OBJECT_0])
4995 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4996 } else if (ret == WAIT_TIMEOUT) {
4997 } else {
4998 err = GetLastError();
4999 fprintf(stderr, "Wait error %d %d\n", ret, err);
5002 #endif
5003 /* poll any events */
5004 /* XXX: separate device handlers from system ones */
5005 nfds = -1;
5006 FD_ZERO(&rfds);
5007 FD_ZERO(&wfds);
5008 FD_ZERO(&xfds);
5009 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5010 if (ioh->fd_read &&
5011 (!ioh->fd_read_poll ||
5012 ioh->fd_read_poll(ioh->opaque) != 0)) {
5013 FD_SET(ioh->fd, &rfds);
5014 if (ioh->fd > nfds)
5015 nfds = ioh->fd;
5017 if (ioh->fd_write) {
5018 FD_SET(ioh->fd, &wfds);
5019 if (ioh->fd > nfds)
5020 nfds = ioh->fd;
5024 tv.tv_sec = 0;
5025 #ifdef _WIN32
5026 tv.tv_usec = 0;
5027 #else
5028 tv.tv_usec = timeout * 1000;
5029 #endif
5030 #if defined(CONFIG_SLIRP)
5031 if (slirp_inited) {
5032 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5034 #endif
5035 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5036 if (ret > 0) {
5037 /* XXX: better handling of removal */
5038 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5039 ioh_next = ioh->next;
5040 if (FD_ISSET(ioh->fd, &rfds)) {
5041 ioh->fd_read(ioh->opaque);
5043 if (FD_ISSET(ioh->fd, &wfds)) {
5044 ioh->fd_write(ioh->opaque);
5048 #if defined(CONFIG_SLIRP)
5049 if (slirp_inited) {
5050 if (ret < 0) {
5051 FD_ZERO(&rfds);
5052 FD_ZERO(&wfds);
5053 FD_ZERO(&xfds);
5055 slirp_select_poll(&rfds, &wfds, &xfds);
5057 #endif
5058 #ifdef _WIN32
5059 tap_win32_poll();
5060 #endif
5062 if (vm_running) {
5063 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5064 qemu_get_clock(vm_clock));
5065 /* run dma transfers, if any */
5066 DMA_run();
5069 /* real time timers */
5070 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5071 qemu_get_clock(rt_clock));
5074 static CPUState *cur_cpu;
5076 int main_loop(void)
5078 int ret, timeout;
5079 #ifdef CONFIG_PROFILER
5080 int64_t ti;
5081 #endif
5082 CPUState *env;
5084 cur_cpu = first_cpu;
5085 for(;;) {
5086 if (vm_running) {
5088 env = cur_cpu;
5089 for(;;) {
5090 /* get next cpu */
5091 env = env->next_cpu;
5092 if (!env)
5093 env = first_cpu;
5094 #ifdef CONFIG_PROFILER
5095 ti = profile_getclock();
5096 #endif
5097 ret = cpu_exec(env);
5098 #ifdef CONFIG_PROFILER
5099 qemu_time += profile_getclock() - ti;
5100 #endif
5101 if (ret != EXCP_HALTED)
5102 break;
5103 /* all CPUs are halted ? */
5104 if (env == cur_cpu) {
5105 ret = EXCP_HLT;
5106 break;
5109 cur_cpu = env;
5111 if (shutdown_requested) {
5112 ret = EXCP_INTERRUPT;
5113 break;
5115 if (reset_requested) {
5116 reset_requested = 0;
5117 qemu_system_reset();
5118 ret = EXCP_INTERRUPT;
5120 if (powerdown_requested) {
5121 powerdown_requested = 0;
5122 qemu_system_powerdown();
5123 ret = EXCP_INTERRUPT;
5125 if (ret == EXCP_DEBUG) {
5126 vm_stop(EXCP_DEBUG);
5128 /* if hlt instruction, we wait until the next IRQ */
5129 /* XXX: use timeout computed from timers */
5130 if (ret == EXCP_HLT)
5131 timeout = 10;
5132 else
5133 timeout = 0;
5134 } else {
5135 timeout = 10;
5137 #ifdef CONFIG_PROFILER
5138 ti = profile_getclock();
5139 #endif
5140 main_loop_wait(timeout);
5141 #ifdef CONFIG_PROFILER
5142 dev_time += profile_getclock() - ti;
5143 #endif
5145 cpu_disable_ticks();
5146 return ret;
5149 void help(void)
5151 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
5152 "usage: %s [options] [disk_image]\n"
5153 "\n"
5154 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5155 "\n"
5156 "Standard options:\n"
5157 "-M machine select emulated machine (-M ? for list)\n"
5158 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5159 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5160 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5161 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5162 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5163 "-snapshot write to temporary files instead of disk image files\n"
5164 #ifdef TARGET_I386
5165 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5166 #endif
5167 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5168 "-smp n set the number of CPUs to 'n' [default=1]\n"
5169 "-nographic disable graphical output and redirect serial I/Os to console\n"
5170 #ifndef _WIN32
5171 "-k language use keyboard layout (for example \"fr\" for French)\n"
5172 #endif
5173 #ifdef HAS_AUDIO
5174 "-audio-help print list of audio drivers and their options\n"
5175 "-soundhw c1,... enable audio support\n"
5176 " and only specified sound cards (comma separated list)\n"
5177 " use -soundhw ? to get the list of supported cards\n"
5178 " use -soundhw all to enable all of them\n"
5179 #endif
5180 "-localtime set the real time clock to local time [default=utc]\n"
5181 "-full-screen start in full screen\n"
5182 #ifdef TARGET_I386
5183 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5184 #endif
5185 "-usb enable the USB driver (will be the default soon)\n"
5186 "-usbdevice name add the host or guest USB device 'name'\n"
5187 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5188 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5189 #endif
5190 "\n"
5191 "Network options:\n"
5192 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5193 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5194 #ifdef CONFIG_SLIRP
5195 "-net user[,vlan=n][,hostname=host]\n"
5196 " connect the user mode network stack to VLAN 'n' and send\n"
5197 " hostname 'host' to DHCP clients\n"
5198 #endif
5199 #ifdef _WIN32
5200 "-net tap[,vlan=n],ifname=name\n"
5201 " connect the host TAP network interface to VLAN 'n'\n"
5202 #else
5203 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
5204 " connect the host TAP network interface to VLAN 'n' and use\n"
5205 " the network script 'file' (default=%s);\n"
5206 " use 'fd=h' to connect to an already opened TAP interface\n"
5207 #endif
5208 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5209 " connect the vlan 'n' to another VLAN using a socket connection\n"
5210 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5211 " connect the vlan 'n' to multicast maddr and port\n"
5212 "-net none use it alone to have zero network devices; if no -net option\n"
5213 " is provided, the default is '-net nic -net user'\n"
5214 "\n"
5215 #ifdef CONFIG_SLIRP
5216 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5217 #ifndef _WIN32
5218 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5219 #endif
5220 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5221 " redirect TCP or UDP connections from host to guest [-net user]\n"
5222 #endif
5223 "\n"
5224 "Linux boot specific:\n"
5225 "-kernel bzImage use 'bzImage' as kernel image\n"
5226 "-append cmdline use 'cmdline' as kernel command line\n"
5227 "-initrd file use 'file' as initial ram disk\n"
5228 "\n"
5229 "Debug/Expert options:\n"
5230 "-monitor dev redirect the monitor to char device 'dev'\n"
5231 "-serial dev redirect the serial port to char device 'dev'\n"
5232 "-parallel dev redirect the parallel port to char device 'dev'\n"
5233 "-pidfile file Write PID to 'file'\n"
5234 "-S freeze CPU at startup (use 'c' to start execution)\n"
5235 "-s wait gdb connection to port %d\n"
5236 "-p port change gdb connection port\n"
5237 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
5238 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5239 " translation (t=none or lba) (usually qemu can guess them)\n"
5240 "-L path set the directory for the BIOS and VGA BIOS\n"
5241 #ifdef USE_KQEMU
5242 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5243 "-no-kqemu disable KQEMU kernel module usage\n"
5244 #endif
5245 #ifdef USE_CODE_COPY
5246 "-no-code-copy disable code copy acceleration\n"
5247 #endif
5248 #ifdef TARGET_I386
5249 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5250 " (default is CL-GD5446 PCI VGA)\n"
5251 "-no-acpi disable ACPI\n"
5252 #endif
5253 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5254 "-vnc display start a VNC server on display\n"
5255 "\n"
5256 "During emulation, the following keys are useful:\n"
5257 "ctrl-alt-f toggle full screen\n"
5258 "ctrl-alt-n switch to virtual console 'n'\n"
5259 "ctrl-alt toggle mouse and keyboard grab\n"
5260 "\n"
5261 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5263 "qemu",
5264 DEFAULT_RAM_SIZE,
5265 #ifndef _WIN32
5266 DEFAULT_NETWORK_SCRIPT,
5267 #endif
5268 DEFAULT_GDBSTUB_PORT,
5269 "/tmp/qemu.log");
5270 exit(1);
5273 #define HAS_ARG 0x0001
5275 enum {
5276 QEMU_OPTION_h,
5278 QEMU_OPTION_M,
5279 QEMU_OPTION_fda,
5280 QEMU_OPTION_fdb,
5281 QEMU_OPTION_hda,
5282 QEMU_OPTION_hdb,
5283 QEMU_OPTION_hdc,
5284 QEMU_OPTION_hdd,
5285 QEMU_OPTION_cdrom,
5286 QEMU_OPTION_boot,
5287 QEMU_OPTION_snapshot,
5288 #ifdef TARGET_I386
5289 QEMU_OPTION_no_fd_bootchk,
5290 #endif
5291 QEMU_OPTION_m,
5292 QEMU_OPTION_nographic,
5293 #ifdef HAS_AUDIO
5294 QEMU_OPTION_audio_help,
5295 QEMU_OPTION_soundhw,
5296 #endif
5298 QEMU_OPTION_net,
5299 QEMU_OPTION_tftp,
5300 QEMU_OPTION_smb,
5301 QEMU_OPTION_redir,
5303 QEMU_OPTION_kernel,
5304 QEMU_OPTION_append,
5305 QEMU_OPTION_initrd,
5307 QEMU_OPTION_S,
5308 QEMU_OPTION_s,
5309 QEMU_OPTION_p,
5310 QEMU_OPTION_d,
5311 QEMU_OPTION_hdachs,
5312 QEMU_OPTION_L,
5313 QEMU_OPTION_no_code_copy,
5314 QEMU_OPTION_k,
5315 QEMU_OPTION_localtime,
5316 QEMU_OPTION_cirrusvga,
5317 QEMU_OPTION_g,
5318 QEMU_OPTION_std_vga,
5319 QEMU_OPTION_monitor,
5320 QEMU_OPTION_serial,
5321 QEMU_OPTION_parallel,
5322 QEMU_OPTION_loadvm,
5323 QEMU_OPTION_full_screen,
5324 QEMU_OPTION_pidfile,
5325 QEMU_OPTION_no_kqemu,
5326 QEMU_OPTION_kernel_kqemu,
5327 QEMU_OPTION_win2k_hack,
5328 QEMU_OPTION_usb,
5329 QEMU_OPTION_usbdevice,
5330 QEMU_OPTION_smp,
5331 QEMU_OPTION_vnc,
5332 QEMU_OPTION_no_acpi,
5335 typedef struct QEMUOption {
5336 const char *name;
5337 int flags;
5338 int index;
5339 } QEMUOption;
5341 const QEMUOption qemu_options[] = {
5342 { "h", 0, QEMU_OPTION_h },
5344 { "M", HAS_ARG, QEMU_OPTION_M },
5345 { "fda", HAS_ARG, QEMU_OPTION_fda },
5346 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5347 { "hda", HAS_ARG, QEMU_OPTION_hda },
5348 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5349 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5350 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5351 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5352 { "boot", HAS_ARG, QEMU_OPTION_boot },
5353 { "snapshot", 0, QEMU_OPTION_snapshot },
5354 #ifdef TARGET_I386
5355 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5356 #endif
5357 { "m", HAS_ARG, QEMU_OPTION_m },
5358 { "nographic", 0, QEMU_OPTION_nographic },
5359 { "k", HAS_ARG, QEMU_OPTION_k },
5360 #ifdef HAS_AUDIO
5361 { "audio-help", 0, QEMU_OPTION_audio_help },
5362 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5363 #endif
5365 { "net", HAS_ARG, QEMU_OPTION_net},
5366 #ifdef CONFIG_SLIRP
5367 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5368 #ifndef _WIN32
5369 { "smb", HAS_ARG, QEMU_OPTION_smb },
5370 #endif
5371 { "redir", HAS_ARG, QEMU_OPTION_redir },
5372 #endif
5374 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5375 { "append", HAS_ARG, QEMU_OPTION_append },
5376 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5378 { "S", 0, QEMU_OPTION_S },
5379 { "s", 0, QEMU_OPTION_s },
5380 { "p", HAS_ARG, QEMU_OPTION_p },
5381 { "d", HAS_ARG, QEMU_OPTION_d },
5382 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5383 { "L", HAS_ARG, QEMU_OPTION_L },
5384 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
5385 #ifdef USE_KQEMU
5386 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5387 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5388 #endif
5389 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5390 { "g", 1, QEMU_OPTION_g },
5391 #endif
5392 { "localtime", 0, QEMU_OPTION_localtime },
5393 { "std-vga", 0, QEMU_OPTION_std_vga },
5394 { "monitor", 1, QEMU_OPTION_monitor },
5395 { "serial", 1, QEMU_OPTION_serial },
5396 { "parallel", 1, QEMU_OPTION_parallel },
5397 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5398 { "full-screen", 0, QEMU_OPTION_full_screen },
5399 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5400 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5401 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5402 { "smp", HAS_ARG, QEMU_OPTION_smp },
5403 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5405 /* temporary options */
5406 { "usb", 0, QEMU_OPTION_usb },
5407 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
5408 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5409 { NULL },
5412 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5414 /* this stack is only used during signal handling */
5415 #define SIGNAL_STACK_SIZE 32768
5417 static uint8_t *signal_stack;
5419 #endif
5421 /* password input */
5423 static BlockDriverState *get_bdrv(int index)
5425 BlockDriverState *bs;
5427 if (index < 4) {
5428 bs = bs_table[index];
5429 } else if (index < 6) {
5430 bs = fd_table[index - 4];
5431 } else {
5432 bs = NULL;
5434 return bs;
5437 static void read_passwords(void)
5439 BlockDriverState *bs;
5440 int i, j;
5441 char password[256];
5443 for(i = 0; i < 6; i++) {
5444 bs = get_bdrv(i);
5445 if (bs && bdrv_is_encrypted(bs)) {
5446 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5447 for(j = 0; j < 3; j++) {
5448 monitor_readline("Password: ",
5449 1, password, sizeof(password));
5450 if (bdrv_set_key(bs, password) == 0)
5451 break;
5452 term_printf("invalid password\n");
5458 /* XXX: currently we cannot use simultaneously different CPUs */
5459 void register_machines(void)
5461 #if defined(TARGET_I386)
5462 qemu_register_machine(&pc_machine);
5463 qemu_register_machine(&isapc_machine);
5464 #elif defined(TARGET_PPC)
5465 qemu_register_machine(&heathrow_machine);
5466 qemu_register_machine(&core99_machine);
5467 qemu_register_machine(&prep_machine);
5468 #elif defined(TARGET_MIPS)
5469 qemu_register_machine(&mips_machine);
5470 #elif defined(TARGET_SPARC)
5471 #ifdef TARGET_SPARC64
5472 qemu_register_machine(&sun4u_machine);
5473 #else
5474 qemu_register_machine(&sun4m_machine);
5475 #endif
5476 #elif defined(TARGET_ARM)
5477 qemu_register_machine(&integratorcp926_machine);
5478 qemu_register_machine(&integratorcp1026_machine);
5479 qemu_register_machine(&versatilepb_machine);
5480 qemu_register_machine(&versatileab_machine);
5481 #elif defined(TARGET_SH4)
5482 qemu_register_machine(&shix_machine);
5483 #else
5484 #error unsupported CPU
5485 #endif
5488 #ifdef HAS_AUDIO
5489 struct soundhw soundhw[] = {
5490 #ifdef TARGET_I386
5492 "pcspk",
5493 "PC speaker",
5496 { .init_isa = pcspk_audio_init }
5498 #endif
5500 "sb16",
5501 "Creative Sound Blaster 16",
5504 { .init_isa = SB16_init }
5507 #ifdef CONFIG_ADLIB
5509 "adlib",
5510 #ifdef HAS_YMF262
5511 "Yamaha YMF262 (OPL3)",
5512 #else
5513 "Yamaha YM3812 (OPL2)",
5514 #endif
5517 { .init_isa = Adlib_init }
5519 #endif
5521 #ifdef CONFIG_GUS
5523 "gus",
5524 "Gravis Ultrasound GF1",
5527 { .init_isa = GUS_init }
5529 #endif
5532 "es1370",
5533 "ENSONIQ AudioPCI ES1370",
5536 { .init_pci = es1370_init }
5539 { NULL, NULL, 0, 0, { NULL } }
5542 static void select_soundhw (const char *optarg)
5544 struct soundhw *c;
5546 if (*optarg == '?') {
5547 show_valid_cards:
5549 printf ("Valid sound card names (comma separated):\n");
5550 for (c = soundhw; c->name; ++c) {
5551 printf ("%-11s %s\n", c->name, c->descr);
5553 printf ("\n-soundhw all will enable all of the above\n");
5554 exit (*optarg != '?');
5556 else {
5557 size_t l;
5558 const char *p;
5559 char *e;
5560 int bad_card = 0;
5562 if (!strcmp (optarg, "all")) {
5563 for (c = soundhw; c->name; ++c) {
5564 c->enabled = 1;
5566 return;
5569 p = optarg;
5570 while (*p) {
5571 e = strchr (p, ',');
5572 l = !e ? strlen (p) : (size_t) (e - p);
5574 for (c = soundhw; c->name; ++c) {
5575 if (!strncmp (c->name, p, l)) {
5576 c->enabled = 1;
5577 break;
5581 if (!c->name) {
5582 if (l > 80) {
5583 fprintf (stderr,
5584 "Unknown sound card name (too big to show)\n");
5586 else {
5587 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5588 (int) l, p);
5590 bad_card = 1;
5592 p += l + (e != NULL);
5595 if (bad_card)
5596 goto show_valid_cards;
5599 #endif
5601 #ifdef _WIN32
5602 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5604 exit(STATUS_CONTROL_C_EXIT);
5605 return TRUE;
5607 #endif
5609 #define MAX_NET_CLIENTS 32
5611 int main(int argc, char **argv)
5613 #ifdef CONFIG_GDBSTUB
5614 int use_gdbstub, gdbstub_port;
5615 #endif
5616 int i, cdrom_index;
5617 int snapshot, linux_boot;
5618 const char *initrd_filename;
5619 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5620 const char *kernel_filename, *kernel_cmdline;
5621 DisplayState *ds = &display_state;
5622 int cyls, heads, secs, translation;
5623 int start_emulation = 1;
5624 char net_clients[MAX_NET_CLIENTS][256];
5625 int nb_net_clients;
5626 int optind;
5627 const char *r, *optarg;
5628 CharDriverState *monitor_hd;
5629 char monitor_device[128];
5630 char serial_devices[MAX_SERIAL_PORTS][128];
5631 int serial_device_index;
5632 char parallel_devices[MAX_PARALLEL_PORTS][128];
5633 int parallel_device_index;
5634 const char *loadvm = NULL;
5635 QEMUMachine *machine;
5636 char usb_devices[MAX_USB_CMDLINE][128];
5637 int usb_devices_index;
5639 LIST_INIT (&vm_change_state_head);
5640 #ifndef _WIN32
5642 struct sigaction act;
5643 sigfillset(&act.sa_mask);
5644 act.sa_flags = 0;
5645 act.sa_handler = SIG_IGN;
5646 sigaction(SIGPIPE, &act, NULL);
5648 #else
5649 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5650 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5651 QEMU to run on a single CPU */
5653 HANDLE h;
5654 DWORD mask, smask;
5655 int i;
5656 h = GetCurrentProcess();
5657 if (GetProcessAffinityMask(h, &mask, &smask)) {
5658 for(i = 0; i < 32; i++) {
5659 if (mask & (1 << i))
5660 break;
5662 if (i != 32) {
5663 mask = 1 << i;
5664 SetProcessAffinityMask(h, mask);
5668 #endif
5670 register_machines();
5671 machine = first_machine;
5672 initrd_filename = NULL;
5673 for(i = 0; i < MAX_FD; i++)
5674 fd_filename[i] = NULL;
5675 for(i = 0; i < MAX_DISKS; i++)
5676 hd_filename[i] = NULL;
5677 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5678 vga_ram_size = VGA_RAM_SIZE;
5679 bios_size = BIOS_SIZE;
5680 #ifdef CONFIG_GDBSTUB
5681 use_gdbstub = 0;
5682 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5683 #endif
5684 snapshot = 0;
5685 nographic = 0;
5686 kernel_filename = NULL;
5687 kernel_cmdline = "";
5688 #ifdef TARGET_PPC
5689 cdrom_index = 1;
5690 #else
5691 cdrom_index = 2;
5692 #endif
5693 cyls = heads = secs = 0;
5694 translation = BIOS_ATA_TRANSLATION_AUTO;
5695 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5697 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5698 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5699 serial_devices[i][0] = '\0';
5700 serial_device_index = 0;
5702 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5703 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5704 parallel_devices[i][0] = '\0';
5705 parallel_device_index = 0;
5707 usb_devices_index = 0;
5709 nb_net_clients = 0;
5711 nb_nics = 0;
5712 /* default mac address of the first network interface */
5714 optind = 1;
5715 for(;;) {
5716 if (optind >= argc)
5717 break;
5718 r = argv[optind];
5719 if (r[0] != '-') {
5720 hd_filename[0] = argv[optind++];
5721 } else {
5722 const QEMUOption *popt;
5724 optind++;
5725 popt = qemu_options;
5726 for(;;) {
5727 if (!popt->name) {
5728 fprintf(stderr, "%s: invalid option -- '%s'\n",
5729 argv[0], r);
5730 exit(1);
5732 if (!strcmp(popt->name, r + 1))
5733 break;
5734 popt++;
5736 if (popt->flags & HAS_ARG) {
5737 if (optind >= argc) {
5738 fprintf(stderr, "%s: option '%s' requires an argument\n",
5739 argv[0], r);
5740 exit(1);
5742 optarg = argv[optind++];
5743 } else {
5744 optarg = NULL;
5747 switch(popt->index) {
5748 case QEMU_OPTION_M:
5749 machine = find_machine(optarg);
5750 if (!machine) {
5751 QEMUMachine *m;
5752 printf("Supported machines are:\n");
5753 for(m = first_machine; m != NULL; m = m->next) {
5754 printf("%-10s %s%s\n",
5755 m->name, m->desc,
5756 m == first_machine ? " (default)" : "");
5758 exit(1);
5760 break;
5761 case QEMU_OPTION_initrd:
5762 initrd_filename = optarg;
5763 break;
5764 case QEMU_OPTION_hda:
5765 case QEMU_OPTION_hdb:
5766 case QEMU_OPTION_hdc:
5767 case QEMU_OPTION_hdd:
5769 int hd_index;
5770 hd_index = popt->index - QEMU_OPTION_hda;
5771 hd_filename[hd_index] = optarg;
5772 if (hd_index == cdrom_index)
5773 cdrom_index = -1;
5775 break;
5776 case QEMU_OPTION_snapshot:
5777 snapshot = 1;
5778 break;
5779 case QEMU_OPTION_hdachs:
5781 const char *p;
5782 p = optarg;
5783 cyls = strtol(p, (char **)&p, 0);
5784 if (cyls < 1 || cyls > 16383)
5785 goto chs_fail;
5786 if (*p != ',')
5787 goto chs_fail;
5788 p++;
5789 heads = strtol(p, (char **)&p, 0);
5790 if (heads < 1 || heads > 16)
5791 goto chs_fail;
5792 if (*p != ',')
5793 goto chs_fail;
5794 p++;
5795 secs = strtol(p, (char **)&p, 0);
5796 if (secs < 1 || secs > 63)
5797 goto chs_fail;
5798 if (*p == ',') {
5799 p++;
5800 if (!strcmp(p, "none"))
5801 translation = BIOS_ATA_TRANSLATION_NONE;
5802 else if (!strcmp(p, "lba"))
5803 translation = BIOS_ATA_TRANSLATION_LBA;
5804 else if (!strcmp(p, "auto"))
5805 translation = BIOS_ATA_TRANSLATION_AUTO;
5806 else
5807 goto chs_fail;
5808 } else if (*p != '\0') {
5809 chs_fail:
5810 fprintf(stderr, "qemu: invalid physical CHS format\n");
5811 exit(1);
5814 break;
5815 case QEMU_OPTION_nographic:
5816 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5817 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5818 nographic = 1;
5819 break;
5820 case QEMU_OPTION_kernel:
5821 kernel_filename = optarg;
5822 break;
5823 case QEMU_OPTION_append:
5824 kernel_cmdline = optarg;
5825 break;
5826 case QEMU_OPTION_cdrom:
5827 if (cdrom_index >= 0) {
5828 hd_filename[cdrom_index] = optarg;
5830 break;
5831 case QEMU_OPTION_boot:
5832 boot_device = optarg[0];
5833 if (boot_device != 'a' &&
5834 #ifdef TARGET_SPARC
5835 // Network boot
5836 boot_device != 'n' &&
5837 #endif
5838 boot_device != 'c' && boot_device != 'd') {
5839 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5840 exit(1);
5842 break;
5843 case QEMU_OPTION_fda:
5844 fd_filename[0] = optarg;
5845 break;
5846 case QEMU_OPTION_fdb:
5847 fd_filename[1] = optarg;
5848 break;
5849 #ifdef TARGET_I386
5850 case QEMU_OPTION_no_fd_bootchk:
5851 fd_bootchk = 0;
5852 break;
5853 #endif
5854 case QEMU_OPTION_no_code_copy:
5855 code_copy_enabled = 0;
5856 break;
5857 case QEMU_OPTION_net:
5858 if (nb_net_clients >= MAX_NET_CLIENTS) {
5859 fprintf(stderr, "qemu: too many network clients\n");
5860 exit(1);
5862 pstrcpy(net_clients[nb_net_clients],
5863 sizeof(net_clients[0]),
5864 optarg);
5865 nb_net_clients++;
5866 break;
5867 #ifdef CONFIG_SLIRP
5868 case QEMU_OPTION_tftp:
5869 tftp_prefix = optarg;
5870 break;
5871 #ifndef _WIN32
5872 case QEMU_OPTION_smb:
5873 net_slirp_smb(optarg);
5874 break;
5875 #endif
5876 case QEMU_OPTION_redir:
5877 net_slirp_redir(optarg);
5878 break;
5879 #endif
5880 #ifdef HAS_AUDIO
5881 case QEMU_OPTION_audio_help:
5882 AUD_help ();
5883 exit (0);
5884 break;
5885 case QEMU_OPTION_soundhw:
5886 select_soundhw (optarg);
5887 break;
5888 #endif
5889 case QEMU_OPTION_h:
5890 help();
5891 break;
5892 case QEMU_OPTION_m:
5893 ram_size = atoi(optarg) * 1024 * 1024;
5894 if (ram_size <= 0)
5895 help();
5896 if (ram_size > PHYS_RAM_MAX_SIZE) {
5897 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5898 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5899 exit(1);
5901 break;
5902 case QEMU_OPTION_d:
5904 int mask;
5905 CPULogItem *item;
5907 mask = cpu_str_to_log_mask(optarg);
5908 if (!mask) {
5909 printf("Log items (comma separated):\n");
5910 for(item = cpu_log_items; item->mask != 0; item++) {
5911 printf("%-10s %s\n", item->name, item->help);
5913 exit(1);
5915 cpu_set_log(mask);
5917 break;
5918 #ifdef CONFIG_GDBSTUB
5919 case QEMU_OPTION_s:
5920 use_gdbstub = 1;
5921 break;
5922 case QEMU_OPTION_p:
5923 gdbstub_port = atoi(optarg);
5924 break;
5925 #endif
5926 case QEMU_OPTION_L:
5927 bios_dir = optarg;
5928 break;
5929 case QEMU_OPTION_S:
5930 start_emulation = 0;
5931 break;
5932 case QEMU_OPTION_k:
5933 keyboard_layout = optarg;
5934 break;
5935 case QEMU_OPTION_localtime:
5936 rtc_utc = 0;
5937 break;
5938 case QEMU_OPTION_cirrusvga:
5939 cirrus_vga_enabled = 1;
5940 break;
5941 case QEMU_OPTION_std_vga:
5942 cirrus_vga_enabled = 0;
5943 break;
5944 case QEMU_OPTION_g:
5946 const char *p;
5947 int w, h, depth;
5948 p = optarg;
5949 w = strtol(p, (char **)&p, 10);
5950 if (w <= 0) {
5951 graphic_error:
5952 fprintf(stderr, "qemu: invalid resolution or depth\n");
5953 exit(1);
5955 if (*p != 'x')
5956 goto graphic_error;
5957 p++;
5958 h = strtol(p, (char **)&p, 10);
5959 if (h <= 0)
5960 goto graphic_error;
5961 if (*p == 'x') {
5962 p++;
5963 depth = strtol(p, (char **)&p, 10);
5964 if (depth != 8 && depth != 15 && depth != 16 &&
5965 depth != 24 && depth != 32)
5966 goto graphic_error;
5967 } else if (*p == '\0') {
5968 depth = graphic_depth;
5969 } else {
5970 goto graphic_error;
5973 graphic_width = w;
5974 graphic_height = h;
5975 graphic_depth = depth;
5977 break;
5978 case QEMU_OPTION_monitor:
5979 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5980 break;
5981 case QEMU_OPTION_serial:
5982 if (serial_device_index >= MAX_SERIAL_PORTS) {
5983 fprintf(stderr, "qemu: too many serial ports\n");
5984 exit(1);
5986 pstrcpy(serial_devices[serial_device_index],
5987 sizeof(serial_devices[0]), optarg);
5988 serial_device_index++;
5989 break;
5990 case QEMU_OPTION_parallel:
5991 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5992 fprintf(stderr, "qemu: too many parallel ports\n");
5993 exit(1);
5995 pstrcpy(parallel_devices[parallel_device_index],
5996 sizeof(parallel_devices[0]), optarg);
5997 parallel_device_index++;
5998 break;
5999 case QEMU_OPTION_loadvm:
6000 loadvm = optarg;
6001 break;
6002 case QEMU_OPTION_full_screen:
6003 full_screen = 1;
6004 break;
6005 case QEMU_OPTION_pidfile:
6006 create_pidfile(optarg);
6007 break;
6008 #ifdef TARGET_I386
6009 case QEMU_OPTION_win2k_hack:
6010 win2k_install_hack = 1;
6011 break;
6012 #endif
6013 #ifdef USE_KQEMU
6014 case QEMU_OPTION_no_kqemu:
6015 kqemu_allowed = 0;
6016 break;
6017 case QEMU_OPTION_kernel_kqemu:
6018 kqemu_allowed = 2;
6019 break;
6020 #endif
6021 case QEMU_OPTION_usb:
6022 usb_enabled = 1;
6023 break;
6024 case QEMU_OPTION_usbdevice:
6025 usb_enabled = 1;
6026 if (usb_devices_index >= MAX_USB_CMDLINE) {
6027 fprintf(stderr, "Too many USB devices\n");
6028 exit(1);
6030 pstrcpy(usb_devices[usb_devices_index],
6031 sizeof(usb_devices[usb_devices_index]),
6032 optarg);
6033 usb_devices_index++;
6034 break;
6035 case QEMU_OPTION_smp:
6036 smp_cpus = atoi(optarg);
6037 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6038 fprintf(stderr, "Invalid number of CPUs\n");
6039 exit(1);
6041 break;
6042 case QEMU_OPTION_vnc:
6043 vnc_display = atoi(optarg);
6044 if (vnc_display < 0) {
6045 fprintf(stderr, "Invalid VNC display\n");
6046 exit(1);
6048 break;
6049 case QEMU_OPTION_no_acpi:
6050 acpi_enabled = 0;
6051 break;
6056 #ifdef USE_KQEMU
6057 if (smp_cpus > 1)
6058 kqemu_allowed = 0;
6059 #endif
6060 linux_boot = (kernel_filename != NULL);
6062 if (!linux_boot &&
6063 hd_filename[0] == '\0' &&
6064 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6065 fd_filename[0] == '\0')
6066 help();
6068 /* boot to cd by default if no hard disk */
6069 if (hd_filename[0] == '\0' && boot_device == 'c') {
6070 if (fd_filename[0] != '\0')
6071 boot_device = 'a';
6072 else
6073 boot_device = 'd';
6076 setvbuf(stdout, NULL, _IOLBF, 0);
6078 init_timers();
6079 init_timer_alarm();
6081 #ifdef _WIN32
6082 socket_init();
6083 #endif
6085 /* init network clients */
6086 if (nb_net_clients == 0) {
6087 /* if no clients, we use a default config */
6088 pstrcpy(net_clients[0], sizeof(net_clients[0]),
6089 "nic");
6090 pstrcpy(net_clients[1], sizeof(net_clients[0]),
6091 "user");
6092 nb_net_clients = 2;
6095 for(i = 0;i < nb_net_clients; i++) {
6096 if (net_client_init(net_clients[i]) < 0)
6097 exit(1);
6100 /* init the memory */
6101 #if USE_KVM
6102 phys_ram_size = ram_size + vga_ram_size + bios_size + KVM_EXTRA_PAGES * 4096;
6103 kvm_qemu_init();
6104 #else
6105 phys_ram_size = ram_size + vga_ram_size + bios_size;
6106 phys_ram_base = qemu_vmalloc(phys_ram_size);
6107 if (!phys_ram_base) {
6108 fprintf(stderr, "Could not allocate physical memory\n");
6109 exit(1);
6111 #endif
6113 /* we always create the cdrom drive, even if no disk is there */
6114 bdrv_init();
6115 if (cdrom_index >= 0) {
6116 bs_table[cdrom_index] = bdrv_new("cdrom");
6117 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6120 /* open the virtual block devices */
6121 for(i = 0; i < MAX_DISKS; i++) {
6122 if (hd_filename[i]) {
6123 if (!bs_table[i]) {
6124 char buf[64];
6125 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6126 bs_table[i] = bdrv_new(buf);
6128 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
6129 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6130 hd_filename[i]);
6131 exit(1);
6133 if (i == 0 && cyls != 0) {
6134 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6135 bdrv_set_translation_hint(bs_table[i], translation);
6140 /* we always create at least one floppy disk */
6141 fd_table[0] = bdrv_new("fda");
6142 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6144 for(i = 0; i < MAX_FD; i++) {
6145 if (fd_filename[i]) {
6146 if (!fd_table[i]) {
6147 char buf[64];
6148 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6149 fd_table[i] = bdrv_new(buf);
6150 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6152 if (fd_filename[i] != '\0') {
6153 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
6154 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6155 fd_filename[i]);
6156 exit(1);
6162 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
6163 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
6165 init_ioports();
6167 /* terminal init */
6168 if (nographic) {
6169 dumb_display_init(ds);
6170 } else if (vnc_display != -1) {
6171 vnc_display_init(ds, vnc_display);
6172 } else {
6173 #if defined(CONFIG_SDL)
6174 sdl_display_init(ds, full_screen);
6175 #elif defined(CONFIG_COCOA)
6176 cocoa_display_init(ds, full_screen);
6177 #else
6178 dumb_display_init(ds);
6179 #endif
6182 monitor_hd = qemu_chr_open(monitor_device);
6183 if (!monitor_hd) {
6184 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6185 exit(1);
6187 monitor_init(monitor_hd, !nographic);
6189 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6190 if (serial_devices[i][0] != '\0') {
6191 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6192 if (!serial_hds[i]) {
6193 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6194 serial_devices[i]);
6195 exit(1);
6197 if (!strcmp(serial_devices[i], "vc"))
6198 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6202 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6203 if (parallel_devices[i][0] != '\0') {
6204 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6205 if (!parallel_hds[i]) {
6206 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6207 parallel_devices[i]);
6208 exit(1);
6210 if (!strcmp(parallel_devices[i], "vc"))
6211 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6215 machine->init(ram_size, vga_ram_size, boot_device,
6216 ds, fd_filename, snapshot,
6217 kernel_filename, kernel_cmdline, initrd_filename);
6219 /* init USB devices */
6220 if (usb_enabled) {
6221 for(i = 0; i < usb_devices_index; i++) {
6222 if (usb_device_add(usb_devices[i]) < 0) {
6223 fprintf(stderr, "Warning: could not add USB device %s\n",
6224 usb_devices[i]);
6229 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6230 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6232 #ifdef CONFIG_GDBSTUB
6233 if (use_gdbstub) {
6234 if (gdbserver_start(gdbstub_port) < 0) {
6235 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6236 gdbstub_port);
6237 exit(1);
6238 } else {
6239 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6241 } else
6242 #endif
6243 if (loadvm)
6244 qemu_loadvm(loadvm);
6247 /* XXX: simplify init */
6248 read_passwords();
6249 if (start_emulation) {
6250 vm_start();
6253 main_loop();
6254 quit_timers();
6255 return 0;