Better names for kvm_adjust function, thank to Avi.
[qemu-kvm/fedora.git] / vl.c
blob88ee0e79b53d81b0c5e6002f6ecc236b4ffb2064
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);
827 static int timer_load(QEMUFile *f, void *opaque, int version_id)
829 if (version_id != 1)
830 return -EINVAL;
831 if (cpu_ticks_enabled) {
832 return -EINVAL;
834 qemu_get_be64s(f, &cpu_ticks_offset);
835 qemu_get_be64s(f, &ticks_per_sec);
836 return 0;
839 #ifdef _WIN32
840 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
841 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
842 #else
843 static void host_alarm_handler(int host_signum)
844 #endif
846 #if 0
847 #define DISP_FREQ 1000
849 static int64_t delta_min = INT64_MAX;
850 static int64_t delta_max, delta_cum, last_clock, delta, ti;
851 static int count;
852 ti = qemu_get_clock(vm_clock);
853 if (last_clock != 0) {
854 delta = ti - last_clock;
855 if (delta < delta_min)
856 delta_min = delta;
857 if (delta > delta_max)
858 delta_max = delta;
859 delta_cum += delta;
860 if (++count == DISP_FREQ) {
861 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
862 muldiv64(delta_min, 1000000, ticks_per_sec),
863 muldiv64(delta_max, 1000000, ticks_per_sec),
864 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
865 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
866 count = 0;
867 delta_min = INT64_MAX;
868 delta_max = 0;
869 delta_cum = 0;
872 last_clock = ti;
874 #endif
875 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
876 qemu_get_clock(vm_clock)) ||
877 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
878 qemu_get_clock(rt_clock))) {
879 #ifdef _WIN32
880 SetEvent(host_alarm);
881 #endif
882 CPUState *env = cpu_single_env;
883 if (env) {
884 /* stop the currently executing cpu because a timer occured */
885 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
886 #ifdef USE_KQEMU
887 if (env->kqemu_enabled) {
888 kqemu_cpu_interrupt(env);
890 #endif
895 #ifndef _WIN32
897 #if defined(__linux__)
899 #define RTC_FREQ 1024
901 static int rtc_fd;
903 static int start_rtc_timer(void)
905 rtc_fd = open("/dev/rtc", O_RDONLY);
906 if (rtc_fd < 0)
907 return -1;
908 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
909 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
910 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
911 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
912 goto fail;
914 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
915 fail:
916 close(rtc_fd);
917 return -1;
919 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
920 return 0;
923 #else
925 static int start_rtc_timer(void)
927 return -1;
930 #endif /* !defined(__linux__) */
932 #endif /* !defined(_WIN32) */
934 static void init_timer_alarm(void)
936 #ifdef _WIN32
938 int count=0;
939 TIMECAPS tc;
941 ZeroMemory(&tc, sizeof(TIMECAPS));
942 timeGetDevCaps(&tc, sizeof(TIMECAPS));
943 if (period < tc.wPeriodMin)
944 period = tc.wPeriodMin;
945 timeBeginPeriod(period);
946 timerID = timeSetEvent(1, // interval (ms)
947 period, // resolution
948 host_alarm_handler, // function
949 (DWORD)&count, // user parameter
950 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
951 if( !timerID ) {
952 perror("failed timer alarm");
953 exit(1);
955 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
956 if (!host_alarm) {
957 perror("failed CreateEvent");
958 exit(1);
960 qemu_add_wait_object(host_alarm, NULL, NULL);
962 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
963 #else
965 struct sigaction act;
966 struct itimerval itv;
968 /* get times() syscall frequency */
969 timer_freq = sysconf(_SC_CLK_TCK);
971 /* timer signal */
972 sigfillset(&act.sa_mask);
973 act.sa_flags = 0;
974 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
975 act.sa_flags |= SA_ONSTACK;
976 #endif
977 act.sa_handler = host_alarm_handler;
978 sigaction(SIGALRM, &act, NULL);
980 itv.it_interval.tv_sec = 0;
981 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
982 itv.it_value.tv_sec = 0;
983 itv.it_value.tv_usec = 10 * 1000;
984 setitimer(ITIMER_REAL, &itv, NULL);
985 /* we probe the tick duration of the kernel to inform the user if
986 the emulated kernel requested a too high timer frequency */
987 getitimer(ITIMER_REAL, &itv);
989 #if defined(__linux__)
990 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
991 have timers with 1 ms resolution. The correct solution will
992 be to use the POSIX real time timers available in recent
993 2.6 kernels */
994 if (itv.it_interval.tv_usec > 1000 || 1) {
995 /* try to use /dev/rtc to have a faster timer */
996 if (start_rtc_timer() < 0)
997 goto use_itimer;
998 /* disable itimer */
999 itv.it_interval.tv_sec = 0;
1000 itv.it_interval.tv_usec = 0;
1001 itv.it_value.tv_sec = 0;
1002 itv.it_value.tv_usec = 0;
1003 setitimer(ITIMER_REAL, &itv, NULL);
1005 /* use the RTC */
1006 sigaction(SIGIO, &act, NULL);
1007 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1008 fcntl(rtc_fd, F_SETOWN, getpid());
1009 } else
1010 #endif /* defined(__linux__) */
1012 use_itimer:
1013 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1014 PIT_FREQ) / 1000000;
1017 #endif
1020 void quit_timers(void)
1022 #ifdef _WIN32
1023 timeKillEvent(timerID);
1024 timeEndPeriod(period);
1025 if (host_alarm) {
1026 CloseHandle(host_alarm);
1027 host_alarm = NULL;
1029 #endif
1032 /***********************************************************/
1033 /* character device */
1035 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1037 return s->chr_write(s, buf, len);
1040 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1042 if (!s->chr_ioctl)
1043 return -ENOTSUP;
1044 return s->chr_ioctl(s, cmd, arg);
1047 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1049 char buf[4096];
1050 va_list ap;
1051 va_start(ap, fmt);
1052 vsnprintf(buf, sizeof(buf), fmt, ap);
1053 qemu_chr_write(s, buf, strlen(buf));
1054 va_end(ap);
1057 void qemu_chr_send_event(CharDriverState *s, int event)
1059 if (s->chr_send_event)
1060 s->chr_send_event(s, event);
1063 void qemu_chr_add_read_handler(CharDriverState *s,
1064 IOCanRWHandler *fd_can_read,
1065 IOReadHandler *fd_read, void *opaque)
1067 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1070 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1072 s->chr_event = chr_event;
1075 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1077 return len;
1080 static void null_chr_add_read_handler(CharDriverState *chr,
1081 IOCanRWHandler *fd_can_read,
1082 IOReadHandler *fd_read, void *opaque)
1086 CharDriverState *qemu_chr_open_null(void)
1088 CharDriverState *chr;
1090 chr = qemu_mallocz(sizeof(CharDriverState));
1091 if (!chr)
1092 return NULL;
1093 chr->chr_write = null_chr_write;
1094 chr->chr_add_read_handler = null_chr_add_read_handler;
1095 return chr;
1098 #ifdef _WIN32
1100 static void socket_cleanup(void)
1102 WSACleanup();
1105 static int socket_init(void)
1107 WSADATA Data;
1108 int ret, err;
1110 ret = WSAStartup(MAKEWORD(2,2), &Data);
1111 if (ret != 0) {
1112 err = WSAGetLastError();
1113 fprintf(stderr, "WSAStartup: %d\n", err);
1114 return -1;
1116 atexit(socket_cleanup);
1117 return 0;
1120 static int send_all(int fd, const uint8_t *buf, int len1)
1122 int ret, len;
1124 len = len1;
1125 while (len > 0) {
1126 ret = send(fd, buf, len, 0);
1127 if (ret < 0) {
1128 int errno;
1129 errno = WSAGetLastError();
1130 if (errno != WSAEWOULDBLOCK) {
1131 return -1;
1133 } else if (ret == 0) {
1134 break;
1135 } else {
1136 buf += ret;
1137 len -= ret;
1140 return len1 - len;
1143 void socket_set_nonblock(int fd)
1145 unsigned long opt = 1;
1146 ioctlsocket(fd, FIONBIO, &opt);
1149 #else
1151 static int unix_write(int fd, const uint8_t *buf, int len1)
1153 int ret, len;
1155 len = len1;
1156 while (len > 0) {
1157 ret = write(fd, buf, len);
1158 if (ret < 0) {
1159 if (errno != EINTR && errno != EAGAIN)
1160 return -1;
1161 } else if (ret == 0) {
1162 break;
1163 } else {
1164 buf += ret;
1165 len -= ret;
1168 return len1 - len;
1171 static inline int send_all(int fd, const uint8_t *buf, int len1)
1173 return unix_write(fd, buf, len1);
1176 void socket_set_nonblock(int fd)
1178 fcntl(fd, F_SETFL, O_NONBLOCK);
1180 #endif /* !_WIN32 */
1182 #ifndef _WIN32
1184 typedef struct {
1185 int fd_in, fd_out;
1186 IOCanRWHandler *fd_can_read;
1187 IOReadHandler *fd_read;
1188 void *fd_opaque;
1189 int max_size;
1190 } FDCharDriver;
1192 #define STDIO_MAX_CLIENTS 2
1194 static int stdio_nb_clients;
1195 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1197 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1199 FDCharDriver *s = chr->opaque;
1200 return unix_write(s->fd_out, buf, len);
1203 static int fd_chr_read_poll(void *opaque)
1205 CharDriverState *chr = opaque;
1206 FDCharDriver *s = chr->opaque;
1208 s->max_size = s->fd_can_read(s->fd_opaque);
1209 return s->max_size;
1212 static void fd_chr_read(void *opaque)
1214 CharDriverState *chr = opaque;
1215 FDCharDriver *s = chr->opaque;
1216 int size, len;
1217 uint8_t buf[1024];
1219 len = sizeof(buf);
1220 if (len > s->max_size)
1221 len = s->max_size;
1222 if (len == 0)
1223 return;
1224 size = read(s->fd_in, buf, len);
1225 if (size > 0) {
1226 s->fd_read(s->fd_opaque, buf, size);
1230 static void fd_chr_add_read_handler(CharDriverState *chr,
1231 IOCanRWHandler *fd_can_read,
1232 IOReadHandler *fd_read, void *opaque)
1234 FDCharDriver *s = chr->opaque;
1236 if (s->fd_in >= 0) {
1237 s->fd_can_read = fd_can_read;
1238 s->fd_read = fd_read;
1239 s->fd_opaque = opaque;
1240 if (nographic && s->fd_in == 0) {
1241 } else {
1242 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1243 fd_chr_read, NULL, chr);
1248 /* open a character device to a unix fd */
1249 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1251 CharDriverState *chr;
1252 FDCharDriver *s;
1254 chr = qemu_mallocz(sizeof(CharDriverState));
1255 if (!chr)
1256 return NULL;
1257 s = qemu_mallocz(sizeof(FDCharDriver));
1258 if (!s) {
1259 free(chr);
1260 return NULL;
1262 s->fd_in = fd_in;
1263 s->fd_out = fd_out;
1264 chr->opaque = s;
1265 chr->chr_write = fd_chr_write;
1266 chr->chr_add_read_handler = fd_chr_add_read_handler;
1267 return chr;
1270 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1272 int fd_out;
1274 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1275 if (fd_out < 0)
1276 return NULL;
1277 return qemu_chr_open_fd(-1, fd_out);
1280 CharDriverState *qemu_chr_open_pipe(const char *filename)
1282 int fd;
1284 fd = open(filename, O_RDWR | O_BINARY);
1285 if (fd < 0)
1286 return NULL;
1287 return qemu_chr_open_fd(fd, fd);
1291 /* for STDIO, we handle the case where several clients use it
1292 (nographic mode) */
1294 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1296 #define TERM_FIFO_MAX_SIZE 1
1298 static int term_got_escape, client_index;
1299 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1300 static int term_fifo_size;
1301 static int term_timestamps;
1302 static int64_t term_timestamps_start;
1304 void term_print_help(void)
1306 printf("\n"
1307 "C-a h print this help\n"
1308 "C-a x exit emulator\n"
1309 "C-a s save disk data back to file (if -snapshot)\n"
1310 "C-a b send break (magic sysrq)\n"
1311 "C-a t toggle console timestamps\n"
1312 "C-a c switch between console and monitor\n"
1313 "C-a C-a send C-a\n"
1317 /* called when a char is received */
1318 static void stdio_received_byte(int ch)
1320 if (term_got_escape) {
1321 term_got_escape = 0;
1322 switch(ch) {
1323 case 'h':
1324 term_print_help();
1325 break;
1326 case 'x':
1327 exit(0);
1328 break;
1329 case 's':
1331 int i;
1332 for (i = 0; i < MAX_DISKS; i++) {
1333 if (bs_table[i])
1334 bdrv_commit(bs_table[i]);
1337 break;
1338 case 'b':
1339 if (client_index < stdio_nb_clients) {
1340 CharDriverState *chr;
1341 FDCharDriver *s;
1343 chr = stdio_clients[client_index];
1344 s = chr->opaque;
1345 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1347 break;
1348 case 'c':
1349 client_index++;
1350 if (client_index >= stdio_nb_clients)
1351 client_index = 0;
1352 if (client_index == 0) {
1353 /* send a new line in the monitor to get the prompt */
1354 ch = '\r';
1355 goto send_char;
1357 break;
1358 case 't':
1359 term_timestamps = !term_timestamps;
1360 term_timestamps_start = -1;
1361 break;
1362 case TERM_ESCAPE:
1363 goto send_char;
1365 } else if (ch == TERM_ESCAPE) {
1366 term_got_escape = 1;
1367 } else {
1368 send_char:
1369 if (client_index < stdio_nb_clients) {
1370 uint8_t buf[1];
1371 CharDriverState *chr;
1372 FDCharDriver *s;
1374 chr = stdio_clients[client_index];
1375 s = chr->opaque;
1376 if (s->fd_can_read(s->fd_opaque) > 0) {
1377 buf[0] = ch;
1378 s->fd_read(s->fd_opaque, buf, 1);
1379 } else if (term_fifo_size == 0) {
1380 term_fifo[term_fifo_size++] = ch;
1386 static int stdio_read_poll(void *opaque)
1388 CharDriverState *chr;
1389 FDCharDriver *s;
1391 if (client_index < stdio_nb_clients) {
1392 chr = stdio_clients[client_index];
1393 s = chr->opaque;
1394 /* try to flush the queue if needed */
1395 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1396 s->fd_read(s->fd_opaque, term_fifo, 1);
1397 term_fifo_size = 0;
1399 /* see if we can absorb more chars */
1400 if (term_fifo_size == 0)
1401 return 1;
1402 else
1403 return 0;
1404 } else {
1405 return 1;
1409 static void stdio_read(void *opaque)
1411 int size;
1412 uint8_t buf[1];
1414 size = read(0, buf, 1);
1415 if (size > 0)
1416 stdio_received_byte(buf[0]);
1419 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1421 FDCharDriver *s = chr->opaque;
1422 if (!term_timestamps) {
1423 return unix_write(s->fd_out, buf, len);
1424 } else {
1425 int i;
1426 char buf1[64];
1428 for(i = 0; i < len; i++) {
1429 unix_write(s->fd_out, buf + i, 1);
1430 if (buf[i] == '\n') {
1431 int64_t ti;
1432 int secs;
1434 ti = get_clock();
1435 if (term_timestamps_start == -1)
1436 term_timestamps_start = ti;
1437 ti -= term_timestamps_start;
1438 secs = ti / 1000000000;
1439 snprintf(buf1, sizeof(buf1),
1440 "[%02d:%02d:%02d.%03d] ",
1441 secs / 3600,
1442 (secs / 60) % 60,
1443 secs % 60,
1444 (int)((ti / 1000000) % 1000));
1445 unix_write(s->fd_out, buf1, strlen(buf1));
1448 return len;
1452 /* init terminal so that we can grab keys */
1453 static struct termios oldtty;
1454 static int old_fd0_flags;
1456 static void term_exit(void)
1458 tcsetattr (0, TCSANOW, &oldtty);
1459 fcntl(0, F_SETFL, old_fd0_flags);
1462 static void term_init(void)
1464 struct termios tty;
1466 tcgetattr (0, &tty);
1467 oldtty = tty;
1468 old_fd0_flags = fcntl(0, F_GETFL);
1470 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1471 |INLCR|IGNCR|ICRNL|IXON);
1472 tty.c_oflag |= OPOST;
1473 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1474 /* if graphical mode, we allow Ctrl-C handling */
1475 if (nographic)
1476 tty.c_lflag &= ~ISIG;
1477 tty.c_cflag &= ~(CSIZE|PARENB);
1478 tty.c_cflag |= CS8;
1479 tty.c_cc[VMIN] = 1;
1480 tty.c_cc[VTIME] = 0;
1482 tcsetattr (0, TCSANOW, &tty);
1484 atexit(term_exit);
1486 fcntl(0, F_SETFL, O_NONBLOCK);
1489 CharDriverState *qemu_chr_open_stdio(void)
1491 CharDriverState *chr;
1493 if (nographic) {
1494 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1495 return NULL;
1496 chr = qemu_chr_open_fd(0, 1);
1497 chr->chr_write = stdio_write;
1498 if (stdio_nb_clients == 0)
1499 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1500 client_index = stdio_nb_clients;
1501 } else {
1502 if (stdio_nb_clients != 0)
1503 return NULL;
1504 chr = qemu_chr_open_fd(0, 1);
1506 stdio_clients[stdio_nb_clients++] = chr;
1507 if (stdio_nb_clients == 1) {
1508 /* set the terminal in raw mode */
1509 term_init();
1511 return chr;
1514 #if defined(__linux__)
1515 CharDriverState *qemu_chr_open_pty(void)
1517 struct termios tty;
1518 char slave_name[1024];
1519 int master_fd, slave_fd;
1521 /* Not satisfying */
1522 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1523 return NULL;
1526 /* Disabling local echo and line-buffered output */
1527 tcgetattr (master_fd, &tty);
1528 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1529 tty.c_cc[VMIN] = 1;
1530 tty.c_cc[VTIME] = 0;
1531 tcsetattr (master_fd, TCSAFLUSH, &tty);
1533 fprintf(stderr, "char device redirected to %s\n", slave_name);
1534 return qemu_chr_open_fd(master_fd, master_fd);
1537 static void tty_serial_init(int fd, int speed,
1538 int parity, int data_bits, int stop_bits)
1540 struct termios tty;
1541 speed_t spd;
1543 #if 0
1544 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1545 speed, parity, data_bits, stop_bits);
1546 #endif
1547 tcgetattr (fd, &tty);
1549 switch(speed) {
1550 case 50:
1551 spd = B50;
1552 break;
1553 case 75:
1554 spd = B75;
1555 break;
1556 case 300:
1557 spd = B300;
1558 break;
1559 case 600:
1560 spd = B600;
1561 break;
1562 case 1200:
1563 spd = B1200;
1564 break;
1565 case 2400:
1566 spd = B2400;
1567 break;
1568 case 4800:
1569 spd = B4800;
1570 break;
1571 case 9600:
1572 spd = B9600;
1573 break;
1574 case 19200:
1575 spd = B19200;
1576 break;
1577 case 38400:
1578 spd = B38400;
1579 break;
1580 case 57600:
1581 spd = B57600;
1582 break;
1583 default:
1584 case 115200:
1585 spd = B115200;
1586 break;
1589 cfsetispeed(&tty, spd);
1590 cfsetospeed(&tty, spd);
1592 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1593 |INLCR|IGNCR|ICRNL|IXON);
1594 tty.c_oflag |= OPOST;
1595 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1596 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1597 switch(data_bits) {
1598 default:
1599 case 8:
1600 tty.c_cflag |= CS8;
1601 break;
1602 case 7:
1603 tty.c_cflag |= CS7;
1604 break;
1605 case 6:
1606 tty.c_cflag |= CS6;
1607 break;
1608 case 5:
1609 tty.c_cflag |= CS5;
1610 break;
1612 switch(parity) {
1613 default:
1614 case 'N':
1615 break;
1616 case 'E':
1617 tty.c_cflag |= PARENB;
1618 break;
1619 case 'O':
1620 tty.c_cflag |= PARENB | PARODD;
1621 break;
1624 tcsetattr (fd, TCSANOW, &tty);
1627 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1629 FDCharDriver *s = chr->opaque;
1631 switch(cmd) {
1632 case CHR_IOCTL_SERIAL_SET_PARAMS:
1634 QEMUSerialSetParams *ssp = arg;
1635 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1636 ssp->data_bits, ssp->stop_bits);
1638 break;
1639 case CHR_IOCTL_SERIAL_SET_BREAK:
1641 int enable = *(int *)arg;
1642 if (enable)
1643 tcsendbreak(s->fd_in, 1);
1645 break;
1646 default:
1647 return -ENOTSUP;
1649 return 0;
1652 CharDriverState *qemu_chr_open_tty(const char *filename)
1654 CharDriverState *chr;
1655 int fd;
1657 fd = open(filename, O_RDWR | O_NONBLOCK);
1658 if (fd < 0)
1659 return NULL;
1660 fcntl(fd, F_SETFL, O_NONBLOCK);
1661 tty_serial_init(fd, 115200, 'N', 8, 1);
1662 chr = qemu_chr_open_fd(fd, fd);
1663 if (!chr)
1664 return NULL;
1665 chr->chr_ioctl = tty_serial_ioctl;
1666 return chr;
1669 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1671 int fd = (int)chr->opaque;
1672 uint8_t b;
1674 switch(cmd) {
1675 case CHR_IOCTL_PP_READ_DATA:
1676 if (ioctl(fd, PPRDATA, &b) < 0)
1677 return -ENOTSUP;
1678 *(uint8_t *)arg = b;
1679 break;
1680 case CHR_IOCTL_PP_WRITE_DATA:
1681 b = *(uint8_t *)arg;
1682 if (ioctl(fd, PPWDATA, &b) < 0)
1683 return -ENOTSUP;
1684 break;
1685 case CHR_IOCTL_PP_READ_CONTROL:
1686 if (ioctl(fd, PPRCONTROL, &b) < 0)
1687 return -ENOTSUP;
1688 *(uint8_t *)arg = b;
1689 break;
1690 case CHR_IOCTL_PP_WRITE_CONTROL:
1691 b = *(uint8_t *)arg;
1692 if (ioctl(fd, PPWCONTROL, &b) < 0)
1693 return -ENOTSUP;
1694 break;
1695 case CHR_IOCTL_PP_READ_STATUS:
1696 if (ioctl(fd, PPRSTATUS, &b) < 0)
1697 return -ENOTSUP;
1698 *(uint8_t *)arg = b;
1699 break;
1700 default:
1701 return -ENOTSUP;
1703 return 0;
1706 CharDriverState *qemu_chr_open_pp(const char *filename)
1708 CharDriverState *chr;
1709 int fd;
1711 fd = open(filename, O_RDWR);
1712 if (fd < 0)
1713 return NULL;
1715 if (ioctl(fd, PPCLAIM) < 0) {
1716 close(fd);
1717 return NULL;
1720 chr = qemu_mallocz(sizeof(CharDriverState));
1721 if (!chr) {
1722 close(fd);
1723 return NULL;
1725 chr->opaque = (void *)fd;
1726 chr->chr_write = null_chr_write;
1727 chr->chr_add_read_handler = null_chr_add_read_handler;
1728 chr->chr_ioctl = pp_ioctl;
1729 return chr;
1732 #else
1733 CharDriverState *qemu_chr_open_pty(void)
1735 return NULL;
1737 #endif
1739 #endif /* !defined(_WIN32) */
1741 #ifdef _WIN32
1742 typedef struct {
1743 IOCanRWHandler *fd_can_read;
1744 IOReadHandler *fd_read;
1745 void *win_opaque;
1746 int max_size;
1747 HANDLE hcom, hrecv, hsend;
1748 OVERLAPPED orecv, osend;
1749 BOOL fpipe;
1750 DWORD len;
1751 } WinCharState;
1753 #define NSENDBUF 2048
1754 #define NRECVBUF 2048
1755 #define MAXCONNECT 1
1756 #define NTIMEOUT 5000
1758 static int win_chr_poll(void *opaque);
1759 static int win_chr_pipe_poll(void *opaque);
1761 static void win_chr_close2(WinCharState *s)
1763 if (s->hsend) {
1764 CloseHandle(s->hsend);
1765 s->hsend = NULL;
1767 if (s->hrecv) {
1768 CloseHandle(s->hrecv);
1769 s->hrecv = NULL;
1771 if (s->hcom) {
1772 CloseHandle(s->hcom);
1773 s->hcom = NULL;
1775 if (s->fpipe)
1776 qemu_del_polling_cb(win_chr_pipe_poll, s);
1777 else
1778 qemu_del_polling_cb(win_chr_poll, s);
1781 static void win_chr_close(CharDriverState *chr)
1783 WinCharState *s = chr->opaque;
1784 win_chr_close2(s);
1787 static int win_chr_init(WinCharState *s, const char *filename)
1789 COMMCONFIG comcfg;
1790 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1791 COMSTAT comstat;
1792 DWORD size;
1793 DWORD err;
1795 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1796 if (!s->hsend) {
1797 fprintf(stderr, "Failed CreateEvent\n");
1798 goto fail;
1800 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1801 if (!s->hrecv) {
1802 fprintf(stderr, "Failed CreateEvent\n");
1803 goto fail;
1806 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1807 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1808 if (s->hcom == INVALID_HANDLE_VALUE) {
1809 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1810 s->hcom = NULL;
1811 goto fail;
1814 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1815 fprintf(stderr, "Failed SetupComm\n");
1816 goto fail;
1819 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1820 size = sizeof(COMMCONFIG);
1821 GetDefaultCommConfig(filename, &comcfg, &size);
1822 comcfg.dcb.DCBlength = sizeof(DCB);
1823 CommConfigDialog(filename, NULL, &comcfg);
1825 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1826 fprintf(stderr, "Failed SetCommState\n");
1827 goto fail;
1830 if (!SetCommMask(s->hcom, EV_ERR)) {
1831 fprintf(stderr, "Failed SetCommMask\n");
1832 goto fail;
1835 cto.ReadIntervalTimeout = MAXDWORD;
1836 if (!SetCommTimeouts(s->hcom, &cto)) {
1837 fprintf(stderr, "Failed SetCommTimeouts\n");
1838 goto fail;
1841 if (!ClearCommError(s->hcom, &err, &comstat)) {
1842 fprintf(stderr, "Failed ClearCommError\n");
1843 goto fail;
1845 qemu_add_polling_cb(win_chr_poll, s);
1846 return 0;
1848 fail:
1849 win_chr_close2(s);
1850 return -1;
1853 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1855 WinCharState *s = chr->opaque;
1856 DWORD len, ret, size, err;
1858 len = len1;
1859 ZeroMemory(&s->osend, sizeof(s->osend));
1860 s->osend.hEvent = s->hsend;
1861 while (len > 0) {
1862 if (s->hsend)
1863 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1864 else
1865 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1866 if (!ret) {
1867 err = GetLastError();
1868 if (err == ERROR_IO_PENDING) {
1869 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1870 if (ret) {
1871 buf += size;
1872 len -= size;
1873 } else {
1874 break;
1876 } else {
1877 break;
1879 } else {
1880 buf += size;
1881 len -= size;
1884 return len1 - len;
1887 static int win_chr_read_poll(WinCharState *s)
1889 s->max_size = s->fd_can_read(s->win_opaque);
1890 return s->max_size;
1893 static void win_chr_readfile(WinCharState *s)
1895 int ret, err;
1896 uint8_t buf[1024];
1897 DWORD size;
1899 ZeroMemory(&s->orecv, sizeof(s->orecv));
1900 s->orecv.hEvent = s->hrecv;
1901 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1902 if (!ret) {
1903 err = GetLastError();
1904 if (err == ERROR_IO_PENDING) {
1905 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1909 if (size > 0) {
1910 s->fd_read(s->win_opaque, buf, size);
1914 static void win_chr_read(WinCharState *s)
1916 if (s->len > s->max_size)
1917 s->len = s->max_size;
1918 if (s->len == 0)
1919 return;
1921 win_chr_readfile(s);
1924 static int win_chr_poll(void *opaque)
1926 WinCharState *s = opaque;
1927 COMSTAT status;
1928 DWORD comerr;
1930 ClearCommError(s->hcom, &comerr, &status);
1931 if (status.cbInQue > 0) {
1932 s->len = status.cbInQue;
1933 win_chr_read_poll(s);
1934 win_chr_read(s);
1935 return 1;
1937 return 0;
1940 static void win_chr_add_read_handler(CharDriverState *chr,
1941 IOCanRWHandler *fd_can_read,
1942 IOReadHandler *fd_read, void *opaque)
1944 WinCharState *s = chr->opaque;
1946 s->fd_can_read = fd_can_read;
1947 s->fd_read = fd_read;
1948 s->win_opaque = opaque;
1951 CharDriverState *qemu_chr_open_win(const char *filename)
1953 CharDriverState *chr;
1954 WinCharState *s;
1956 chr = qemu_mallocz(sizeof(CharDriverState));
1957 if (!chr)
1958 return NULL;
1959 s = qemu_mallocz(sizeof(WinCharState));
1960 if (!s) {
1961 free(chr);
1962 return NULL;
1964 chr->opaque = s;
1965 chr->chr_write = win_chr_write;
1966 chr->chr_add_read_handler = win_chr_add_read_handler;
1967 chr->chr_close = win_chr_close;
1969 if (win_chr_init(s, filename) < 0) {
1970 free(s);
1971 free(chr);
1972 return NULL;
1974 return chr;
1977 static int win_chr_pipe_poll(void *opaque)
1979 WinCharState *s = opaque;
1980 DWORD size;
1982 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1983 if (size > 0) {
1984 s->len = size;
1985 win_chr_read_poll(s);
1986 win_chr_read(s);
1987 return 1;
1989 return 0;
1992 static int win_chr_pipe_init(WinCharState *s, const char *filename)
1994 OVERLAPPED ov;
1995 int ret;
1996 DWORD size;
1997 char openname[256];
1999 s->fpipe = TRUE;
2001 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2002 if (!s->hsend) {
2003 fprintf(stderr, "Failed CreateEvent\n");
2004 goto fail;
2006 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2007 if (!s->hrecv) {
2008 fprintf(stderr, "Failed CreateEvent\n");
2009 goto fail;
2012 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2013 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2014 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2015 PIPE_WAIT,
2016 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2017 if (s->hcom == INVALID_HANDLE_VALUE) {
2018 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2019 s->hcom = NULL;
2020 goto fail;
2023 ZeroMemory(&ov, sizeof(ov));
2024 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2025 ret = ConnectNamedPipe(s->hcom, &ov);
2026 if (ret) {
2027 fprintf(stderr, "Failed ConnectNamedPipe\n");
2028 goto fail;
2031 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2032 if (!ret) {
2033 fprintf(stderr, "Failed GetOverlappedResult\n");
2034 if (ov.hEvent) {
2035 CloseHandle(ov.hEvent);
2036 ov.hEvent = NULL;
2038 goto fail;
2041 if (ov.hEvent) {
2042 CloseHandle(ov.hEvent);
2043 ov.hEvent = NULL;
2045 qemu_add_polling_cb(win_chr_pipe_poll, s);
2046 return 0;
2048 fail:
2049 win_chr_close2(s);
2050 return -1;
2054 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2056 CharDriverState *chr;
2057 WinCharState *s;
2059 chr = qemu_mallocz(sizeof(CharDriverState));
2060 if (!chr)
2061 return NULL;
2062 s = qemu_mallocz(sizeof(WinCharState));
2063 if (!s) {
2064 free(chr);
2065 return NULL;
2067 chr->opaque = s;
2068 chr->chr_write = win_chr_write;
2069 chr->chr_add_read_handler = win_chr_add_read_handler;
2070 chr->chr_close = win_chr_close;
2072 if (win_chr_pipe_init(s, filename) < 0) {
2073 free(s);
2074 free(chr);
2075 return NULL;
2077 return chr;
2080 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2082 CharDriverState *chr;
2083 WinCharState *s;
2085 chr = qemu_mallocz(sizeof(CharDriverState));
2086 if (!chr)
2087 return NULL;
2088 s = qemu_mallocz(sizeof(WinCharState));
2089 if (!s) {
2090 free(chr);
2091 return NULL;
2093 s->hcom = fd_out;
2094 chr->opaque = s;
2095 chr->chr_write = win_chr_write;
2096 chr->chr_add_read_handler = win_chr_add_read_handler;
2097 return chr;
2100 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2102 HANDLE fd_out;
2104 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2105 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2106 if (fd_out == INVALID_HANDLE_VALUE)
2107 return NULL;
2109 return qemu_chr_open_win_file(fd_out);
2111 #endif
2113 /***********************************************************/
2114 /* UDP Net console */
2116 typedef struct {
2117 IOCanRWHandler *fd_can_read;
2118 IOReadHandler *fd_read;
2119 void *fd_opaque;
2120 int fd;
2121 struct sockaddr_in daddr;
2122 char buf[1024];
2123 int bufcnt;
2124 int bufptr;
2125 int max_size;
2126 } NetCharDriver;
2128 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2130 NetCharDriver *s = chr->opaque;
2132 return sendto(s->fd, buf, len, 0,
2133 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2136 static int udp_chr_read_poll(void *opaque)
2138 CharDriverState *chr = opaque;
2139 NetCharDriver *s = chr->opaque;
2141 s->max_size = s->fd_can_read(s->fd_opaque);
2143 /* If there were any stray characters in the queue process them
2144 * first
2146 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2147 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2148 s->bufptr++;
2149 s->max_size = s->fd_can_read(s->fd_opaque);
2151 return s->max_size;
2154 static void udp_chr_read(void *opaque)
2156 CharDriverState *chr = opaque;
2157 NetCharDriver *s = chr->opaque;
2159 if (s->max_size == 0)
2160 return;
2161 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2162 s->bufptr = s->bufcnt;
2163 if (s->bufcnt <= 0)
2164 return;
2166 s->bufptr = 0;
2167 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2168 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2169 s->bufptr++;
2170 s->max_size = s->fd_can_read(s->fd_opaque);
2174 static void udp_chr_add_read_handler(CharDriverState *chr,
2175 IOCanRWHandler *fd_can_read,
2176 IOReadHandler *fd_read, void *opaque)
2178 NetCharDriver *s = chr->opaque;
2180 if (s->fd >= 0) {
2181 s->fd_can_read = fd_can_read;
2182 s->fd_read = fd_read;
2183 s->fd_opaque = opaque;
2184 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2185 udp_chr_read, NULL, chr);
2189 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2190 int parse_host_src_port(struct sockaddr_in *haddr,
2191 struct sockaddr_in *saddr,
2192 const char *str);
2194 CharDriverState *qemu_chr_open_udp(const char *def)
2196 CharDriverState *chr = NULL;
2197 NetCharDriver *s = NULL;
2198 int fd = -1;
2199 struct sockaddr_in saddr;
2201 chr = qemu_mallocz(sizeof(CharDriverState));
2202 if (!chr)
2203 goto return_err;
2204 s = qemu_mallocz(sizeof(NetCharDriver));
2205 if (!s)
2206 goto return_err;
2208 fd = socket(PF_INET, SOCK_DGRAM, 0);
2209 if (fd < 0) {
2210 perror("socket(PF_INET, SOCK_DGRAM)");
2211 goto return_err;
2214 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2215 printf("Could not parse: %s\n", def);
2216 goto return_err;
2219 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2221 perror("bind");
2222 goto return_err;
2225 s->fd = fd;
2226 s->bufcnt = 0;
2227 s->bufptr = 0;
2228 chr->opaque = s;
2229 chr->chr_write = udp_chr_write;
2230 chr->chr_add_read_handler = udp_chr_add_read_handler;
2231 return chr;
2233 return_err:
2234 if (chr)
2235 free(chr);
2236 if (s)
2237 free(s);
2238 if (fd >= 0)
2239 closesocket(fd);
2240 return NULL;
2243 /***********************************************************/
2244 /* TCP Net console */
2246 typedef struct {
2247 IOCanRWHandler *fd_can_read;
2248 IOReadHandler *fd_read;
2249 void *fd_opaque;
2250 int fd, listen_fd;
2251 int connected;
2252 int max_size;
2253 int do_telnetopt;
2254 } TCPCharDriver;
2256 static void tcp_chr_accept(void *opaque);
2258 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2260 TCPCharDriver *s = chr->opaque;
2261 if (s->connected) {
2262 return send_all(s->fd, buf, len);
2263 } else {
2264 /* XXX: indicate an error ? */
2265 return len;
2269 static int tcp_chr_read_poll(void *opaque)
2271 CharDriverState *chr = opaque;
2272 TCPCharDriver *s = chr->opaque;
2273 if (!s->connected)
2274 return 0;
2275 s->max_size = s->fd_can_read(s->fd_opaque);
2276 return s->max_size;
2279 #define IAC 255
2280 #define IAC_BREAK 243
2281 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2282 TCPCharDriver *s,
2283 char *buf, int *size)
2285 /* Handle any telnet client's basic IAC options to satisfy char by
2286 * char mode with no echo. All IAC options will be removed from
2287 * the buf and the do_telnetopt variable will be used to track the
2288 * state of the width of the IAC information.
2290 * IAC commands come in sets of 3 bytes with the exception of the
2291 * "IAC BREAK" command and the double IAC.
2294 int i;
2295 int j = 0;
2297 for (i = 0; i < *size; i++) {
2298 if (s->do_telnetopt > 1) {
2299 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2300 /* Double IAC means send an IAC */
2301 if (j != i)
2302 buf[j] = buf[i];
2303 j++;
2304 s->do_telnetopt = 1;
2305 } else {
2306 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2307 /* Handle IAC break commands by sending a serial break */
2308 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2309 s->do_telnetopt++;
2311 s->do_telnetopt++;
2313 if (s->do_telnetopt >= 4) {
2314 s->do_telnetopt = 1;
2316 } else {
2317 if ((unsigned char)buf[i] == IAC) {
2318 s->do_telnetopt = 2;
2319 } else {
2320 if (j != i)
2321 buf[j] = buf[i];
2322 j++;
2326 *size = j;
2329 static void tcp_chr_read(void *opaque)
2331 CharDriverState *chr = opaque;
2332 TCPCharDriver *s = chr->opaque;
2333 uint8_t buf[1024];
2334 int len, size;
2336 if (!s->connected || s->max_size <= 0)
2337 return;
2338 len = sizeof(buf);
2339 if (len > s->max_size)
2340 len = s->max_size;
2341 size = recv(s->fd, buf, len, 0);
2342 if (size == 0) {
2343 /* connection closed */
2344 s->connected = 0;
2345 if (s->listen_fd >= 0) {
2346 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2348 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2349 closesocket(s->fd);
2350 s->fd = -1;
2351 } else if (size > 0) {
2352 if (s->do_telnetopt)
2353 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2354 if (size > 0)
2355 s->fd_read(s->fd_opaque, buf, size);
2359 static void tcp_chr_add_read_handler(CharDriverState *chr,
2360 IOCanRWHandler *fd_can_read,
2361 IOReadHandler *fd_read, void *opaque)
2363 TCPCharDriver *s = chr->opaque;
2365 s->fd_can_read = fd_can_read;
2366 s->fd_read = fd_read;
2367 s->fd_opaque = opaque;
2370 static void tcp_chr_connect(void *opaque)
2372 CharDriverState *chr = opaque;
2373 TCPCharDriver *s = chr->opaque;
2375 s->connected = 1;
2376 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2377 tcp_chr_read, NULL, chr);
2380 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2381 static void tcp_chr_telnet_init(int fd)
2383 char buf[3];
2384 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2385 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2386 send(fd, (char *)buf, 3, 0);
2387 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2388 send(fd, (char *)buf, 3, 0);
2389 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2390 send(fd, (char *)buf, 3, 0);
2391 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2392 send(fd, (char *)buf, 3, 0);
2395 static void tcp_chr_accept(void *opaque)
2397 CharDriverState *chr = opaque;
2398 TCPCharDriver *s = chr->opaque;
2399 struct sockaddr_in saddr;
2400 socklen_t len;
2401 int fd;
2403 for(;;) {
2404 len = sizeof(saddr);
2405 fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2406 if (fd < 0 && errno != EINTR) {
2407 return;
2408 } else if (fd >= 0) {
2409 if (s->do_telnetopt)
2410 tcp_chr_telnet_init(fd);
2411 break;
2414 socket_set_nonblock(fd);
2415 s->fd = fd;
2416 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2417 tcp_chr_connect(chr);
2420 static void tcp_chr_close(CharDriverState *chr)
2422 TCPCharDriver *s = chr->opaque;
2423 if (s->fd >= 0)
2424 closesocket(s->fd);
2425 if (s->listen_fd >= 0)
2426 closesocket(s->listen_fd);
2427 qemu_free(s);
2430 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2431 int is_telnet)
2433 CharDriverState *chr = NULL;
2434 TCPCharDriver *s = NULL;
2435 int fd = -1, ret, err, val;
2436 int is_listen = 0;
2437 int is_waitconnect = 1;
2438 const char *ptr;
2439 struct sockaddr_in saddr;
2441 if (parse_host_port(&saddr, host_str) < 0)
2442 goto fail;
2444 ptr = host_str;
2445 while((ptr = strchr(ptr,','))) {
2446 ptr++;
2447 if (!strncmp(ptr,"server",6)) {
2448 is_listen = 1;
2449 } else if (!strncmp(ptr,"nowait",6)) {
2450 is_waitconnect = 0;
2451 } else {
2452 printf("Unknown option: %s\n", ptr);
2453 goto fail;
2456 if (!is_listen)
2457 is_waitconnect = 0;
2459 chr = qemu_mallocz(sizeof(CharDriverState));
2460 if (!chr)
2461 goto fail;
2462 s = qemu_mallocz(sizeof(TCPCharDriver));
2463 if (!s)
2464 goto fail;
2466 fd = socket(PF_INET, SOCK_STREAM, 0);
2467 if (fd < 0)
2468 goto fail;
2470 if (!is_waitconnect)
2471 socket_set_nonblock(fd);
2473 s->connected = 0;
2474 s->fd = -1;
2475 s->listen_fd = -1;
2476 if (is_listen) {
2477 /* allow fast reuse */
2478 val = 1;
2479 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2481 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2482 if (ret < 0)
2483 goto fail;
2484 ret = listen(fd, 0);
2485 if (ret < 0)
2486 goto fail;
2487 s->listen_fd = fd;
2488 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2489 if (is_telnet)
2490 s->do_telnetopt = 1;
2491 } else {
2492 for(;;) {
2493 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2494 if (ret < 0) {
2495 err = socket_error();
2496 if (err == EINTR || err == EWOULDBLOCK) {
2497 } else if (err == EINPROGRESS) {
2498 break;
2499 } else {
2500 goto fail;
2502 } else {
2503 s->connected = 1;
2504 break;
2507 s->fd = fd;
2508 if (s->connected)
2509 tcp_chr_connect(chr);
2510 else
2511 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2514 chr->opaque = s;
2515 chr->chr_write = tcp_chr_write;
2516 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2517 chr->chr_close = tcp_chr_close;
2518 if (is_listen && is_waitconnect) {
2519 printf("QEMU waiting for connection on: %s\n", host_str);
2520 tcp_chr_accept(chr);
2521 socket_set_nonblock(s->listen_fd);
2524 return chr;
2525 fail:
2526 if (fd >= 0)
2527 closesocket(fd);
2528 qemu_free(s);
2529 qemu_free(chr);
2530 return NULL;
2533 CharDriverState *qemu_chr_open(const char *filename)
2535 const char *p;
2537 if (!strcmp(filename, "vc")) {
2538 return text_console_init(&display_state);
2539 } else if (!strcmp(filename, "null")) {
2540 return qemu_chr_open_null();
2541 } else
2542 if (strstart(filename, "tcp:", &p)) {
2543 return qemu_chr_open_tcp(p, 0);
2544 } else
2545 if (strstart(filename, "telnet:", &p)) {
2546 return qemu_chr_open_tcp(p, 1);
2547 } else
2548 if (strstart(filename, "udp:", &p)) {
2549 return qemu_chr_open_udp(p);
2550 } else
2551 #ifndef _WIN32
2552 if (strstart(filename, "file:", &p)) {
2553 return qemu_chr_open_file_out(p);
2554 } else if (strstart(filename, "pipe:", &p)) {
2555 return qemu_chr_open_pipe(p);
2556 } else if (!strcmp(filename, "pty")) {
2557 return qemu_chr_open_pty();
2558 } else if (!strcmp(filename, "stdio")) {
2559 return qemu_chr_open_stdio();
2560 } else
2561 #endif
2562 #if defined(__linux__)
2563 if (strstart(filename, "/dev/parport", NULL)) {
2564 return qemu_chr_open_pp(filename);
2565 } else
2566 if (strstart(filename, "/dev/", NULL)) {
2567 return qemu_chr_open_tty(filename);
2568 } else
2569 #endif
2570 #ifdef _WIN32
2571 if (strstart(filename, "COM", NULL)) {
2572 return qemu_chr_open_win(filename);
2573 } else
2574 if (strstart(filename, "pipe:", &p)) {
2575 return qemu_chr_open_win_pipe(p);
2576 } else
2577 if (strstart(filename, "file:", &p)) {
2578 return qemu_chr_open_win_file_out(p);
2580 #endif
2582 return NULL;
2586 void qemu_chr_close(CharDriverState *chr)
2588 if (chr->chr_close)
2589 chr->chr_close(chr);
2592 /***********************************************************/
2593 /* network device redirectors */
2595 void hex_dump(FILE *f, const uint8_t *buf, int size)
2597 int len, i, j, c;
2599 for(i=0;i<size;i+=16) {
2600 len = size - i;
2601 if (len > 16)
2602 len = 16;
2603 fprintf(f, "%08x ", i);
2604 for(j=0;j<16;j++) {
2605 if (j < len)
2606 fprintf(f, " %02x", buf[i+j]);
2607 else
2608 fprintf(f, " ");
2610 fprintf(f, " ");
2611 for(j=0;j<len;j++) {
2612 c = buf[i+j];
2613 if (c < ' ' || c > '~')
2614 c = '.';
2615 fprintf(f, "%c", c);
2617 fprintf(f, "\n");
2621 static int parse_macaddr(uint8_t *macaddr, const char *p)
2623 int i;
2624 for(i = 0; i < 6; i++) {
2625 macaddr[i] = strtol(p, (char **)&p, 16);
2626 if (i == 5) {
2627 if (*p != '\0')
2628 return -1;
2629 } else {
2630 if (*p != ':')
2631 return -1;
2632 p++;
2635 return 0;
2638 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2640 const char *p, *p1;
2641 int len;
2642 p = *pp;
2643 p1 = strchr(p, sep);
2644 if (!p1)
2645 return -1;
2646 len = p1 - p;
2647 p1++;
2648 if (buf_size > 0) {
2649 if (len > buf_size - 1)
2650 len = buf_size - 1;
2651 memcpy(buf, p, len);
2652 buf[len] = '\0';
2654 *pp = p1;
2655 return 0;
2658 int parse_host_src_port(struct sockaddr_in *haddr,
2659 struct sockaddr_in *saddr,
2660 const char *input_str)
2662 char *str = strdup(input_str);
2663 char *host_str = str;
2664 char *src_str;
2665 char *ptr;
2668 * Chop off any extra arguments at the end of the string which
2669 * would start with a comma, then fill in the src port information
2670 * if it was provided else use the "any address" and "any port".
2672 if ((ptr = strchr(str,',')))
2673 *ptr = '\0';
2675 if ((src_str = strchr(input_str,'@'))) {
2676 *src_str = '\0';
2677 src_str++;
2680 if (parse_host_port(haddr, host_str) < 0)
2681 goto fail;
2683 if (!src_str || *src_str == '\0')
2684 src_str = ":0";
2686 if (parse_host_port(saddr, src_str) < 0)
2687 goto fail;
2689 free(str);
2690 return(0);
2692 fail:
2693 free(str);
2694 return -1;
2697 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2699 char buf[512];
2700 struct hostent *he;
2701 const char *p, *r;
2702 int port;
2704 p = str;
2705 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2706 return -1;
2707 saddr->sin_family = AF_INET;
2708 if (buf[0] == '\0') {
2709 saddr->sin_addr.s_addr = 0;
2710 } else {
2711 if (isdigit(buf[0])) {
2712 if (!inet_aton(buf, &saddr->sin_addr))
2713 return -1;
2714 } else {
2715 if ((he = gethostbyname(buf)) == NULL)
2716 return - 1;
2717 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2720 port = strtol(p, (char **)&r, 0);
2721 if (r == p)
2722 return -1;
2723 saddr->sin_port = htons(port);
2724 return 0;
2727 /* find or alloc a new VLAN */
2728 VLANState *qemu_find_vlan(int id)
2730 VLANState **pvlan, *vlan;
2731 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2732 if (vlan->id == id)
2733 return vlan;
2735 vlan = qemu_mallocz(sizeof(VLANState));
2736 if (!vlan)
2737 return NULL;
2738 vlan->id = id;
2739 vlan->next = NULL;
2740 pvlan = &first_vlan;
2741 while (*pvlan != NULL)
2742 pvlan = &(*pvlan)->next;
2743 *pvlan = vlan;
2744 return vlan;
2747 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2748 IOReadHandler *fd_read,
2749 IOCanRWHandler *fd_can_read,
2750 void *opaque)
2752 VLANClientState *vc, **pvc;
2753 vc = qemu_mallocz(sizeof(VLANClientState));
2754 if (!vc)
2755 return NULL;
2756 vc->fd_read = fd_read;
2757 vc->fd_can_read = fd_can_read;
2758 vc->opaque = opaque;
2759 vc->vlan = vlan;
2761 vc->next = NULL;
2762 pvc = &vlan->first_client;
2763 while (*pvc != NULL)
2764 pvc = &(*pvc)->next;
2765 *pvc = vc;
2766 return vc;
2769 int qemu_can_send_packet(VLANClientState *vc1)
2771 VLANState *vlan = vc1->vlan;
2772 VLANClientState *vc;
2774 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2775 if (vc != vc1) {
2776 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2777 return 0;
2780 return 1;
2783 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2785 VLANState *vlan = vc1->vlan;
2786 VLANClientState *vc;
2788 #if 0
2789 printf("vlan %d send:\n", vlan->id);
2790 hex_dump(stdout, buf, size);
2791 #endif
2792 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2793 if (vc != vc1) {
2794 vc->fd_read(vc->opaque, buf, size);
2799 #if defined(CONFIG_SLIRP)
2801 /* slirp network adapter */
2803 static int slirp_inited;
2804 static VLANClientState *slirp_vc;
2806 int slirp_can_output(void)
2808 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2811 void slirp_output(const uint8_t *pkt, int pkt_len)
2813 #if 0
2814 printf("slirp output:\n");
2815 hex_dump(stdout, pkt, pkt_len);
2816 #endif
2817 if (!slirp_vc)
2818 return;
2819 qemu_send_packet(slirp_vc, pkt, pkt_len);
2822 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2824 #if 0
2825 printf("slirp input:\n");
2826 hex_dump(stdout, buf, size);
2827 #endif
2828 slirp_input(buf, size);
2831 static int net_slirp_init(VLANState *vlan)
2833 if (!slirp_inited) {
2834 slirp_inited = 1;
2835 slirp_init();
2837 slirp_vc = qemu_new_vlan_client(vlan,
2838 slirp_receive, NULL, NULL);
2839 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2840 return 0;
2843 static void net_slirp_redir(const char *redir_str)
2845 int is_udp;
2846 char buf[256], *r;
2847 const char *p;
2848 struct in_addr guest_addr;
2849 int host_port, guest_port;
2851 if (!slirp_inited) {
2852 slirp_inited = 1;
2853 slirp_init();
2856 p = redir_str;
2857 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2858 goto fail;
2859 if (!strcmp(buf, "tcp")) {
2860 is_udp = 0;
2861 } else if (!strcmp(buf, "udp")) {
2862 is_udp = 1;
2863 } else {
2864 goto fail;
2867 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2868 goto fail;
2869 host_port = strtol(buf, &r, 0);
2870 if (r == buf)
2871 goto fail;
2873 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2874 goto fail;
2875 if (buf[0] == '\0') {
2876 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2878 if (!inet_aton(buf, &guest_addr))
2879 goto fail;
2881 guest_port = strtol(p, &r, 0);
2882 if (r == p)
2883 goto fail;
2885 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2886 fprintf(stderr, "qemu: could not set up redirection\n");
2887 exit(1);
2889 return;
2890 fail:
2891 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2892 exit(1);
2895 #ifndef _WIN32
2897 char smb_dir[1024];
2899 static void smb_exit(void)
2901 DIR *d;
2902 struct dirent *de;
2903 char filename[1024];
2905 /* erase all the files in the directory */
2906 d = opendir(smb_dir);
2907 for(;;) {
2908 de = readdir(d);
2909 if (!de)
2910 break;
2911 if (strcmp(de->d_name, ".") != 0 &&
2912 strcmp(de->d_name, "..") != 0) {
2913 snprintf(filename, sizeof(filename), "%s/%s",
2914 smb_dir, de->d_name);
2915 unlink(filename);
2918 closedir(d);
2919 rmdir(smb_dir);
2922 /* automatic user mode samba server configuration */
2923 void net_slirp_smb(const char *exported_dir)
2925 char smb_conf[1024];
2926 char smb_cmdline[1024];
2927 FILE *f;
2929 if (!slirp_inited) {
2930 slirp_inited = 1;
2931 slirp_init();
2934 /* XXX: better tmp dir construction */
2935 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2936 if (mkdir(smb_dir, 0700) < 0) {
2937 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2938 exit(1);
2940 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2942 f = fopen(smb_conf, "w");
2943 if (!f) {
2944 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2945 exit(1);
2947 fprintf(f,
2948 "[global]\n"
2949 "private dir=%s\n"
2950 "smb ports=0\n"
2951 "socket address=127.0.0.1\n"
2952 "pid directory=%s\n"
2953 "lock directory=%s\n"
2954 "log file=%s/log.smbd\n"
2955 "smb passwd file=%s/smbpasswd\n"
2956 "security = share\n"
2957 "[qemu]\n"
2958 "path=%s\n"
2959 "read only=no\n"
2960 "guest ok=yes\n",
2961 smb_dir,
2962 smb_dir,
2963 smb_dir,
2964 smb_dir,
2965 smb_dir,
2966 exported_dir
2968 fclose(f);
2969 atexit(smb_exit);
2971 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2972 smb_conf);
2974 slirp_add_exec(0, smb_cmdline, 4, 139);
2977 #endif /* !defined(_WIN32) */
2979 #endif /* CONFIG_SLIRP */
2981 #if !defined(_WIN32)
2983 typedef struct TAPState {
2984 VLANClientState *vc;
2985 int fd;
2986 } TAPState;
2988 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2990 TAPState *s = opaque;
2991 int ret;
2992 for(;;) {
2993 ret = write(s->fd, buf, size);
2994 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2995 } else {
2996 break;
3001 static void tap_send(void *opaque)
3003 TAPState *s = opaque;
3004 uint8_t buf[4096];
3005 int size;
3007 size = read(s->fd, buf, sizeof(buf));
3008 if (size > 0) {
3009 qemu_send_packet(s->vc, buf, size);
3013 /* fd support */
3015 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3017 TAPState *s;
3019 s = qemu_mallocz(sizeof(TAPState));
3020 if (!s)
3021 return NULL;
3022 s->fd = fd;
3023 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3024 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3025 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3026 return s;
3029 #ifdef _BSD
3030 static int tap_open(char *ifname, int ifname_size)
3032 int fd;
3033 char *dev;
3034 struct stat s;
3036 fd = open("/dev/tap", O_RDWR);
3037 if (fd < 0) {
3038 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3039 return -1;
3042 fstat(fd, &s);
3043 dev = devname(s.st_rdev, S_IFCHR);
3044 pstrcpy(ifname, ifname_size, dev);
3046 fcntl(fd, F_SETFL, O_NONBLOCK);
3047 return fd;
3049 #elif defined(__sun__)
3050 static int tap_open(char *ifname, int ifname_size)
3052 fprintf(stderr, "warning: tap_open not yet implemented\n");
3053 return -1;
3055 #else
3056 static int tap_open(char *ifname, int ifname_size)
3058 struct ifreq ifr;
3059 int fd, ret;
3061 fd = open("/dev/net/tun", O_RDWR);
3062 if (fd < 0) {
3063 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3064 return -1;
3066 memset(&ifr, 0, sizeof(ifr));
3067 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3068 if (ifname[0] != '\0')
3069 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3070 else
3071 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3072 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3073 if (ret != 0) {
3074 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3075 close(fd);
3076 return -1;
3078 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3079 fcntl(fd, F_SETFL, O_NONBLOCK);
3080 return fd;
3082 #endif
3084 static int net_tap_init(VLANState *vlan, const char *ifname1,
3085 const char *setup_script)
3087 TAPState *s;
3088 int pid, status, fd;
3089 char *args[3];
3090 char **parg;
3091 char ifname[128];
3093 if (ifname1 != NULL)
3094 pstrcpy(ifname, sizeof(ifname), ifname1);
3095 else
3096 ifname[0] = '\0';
3097 fd = tap_open(ifname, sizeof(ifname));
3098 if (fd < 0)
3099 return -1;
3101 if (!setup_script)
3102 setup_script = "";
3103 if (setup_script[0] != '\0') {
3104 /* try to launch network init script */
3105 pid = fork();
3106 if (pid >= 0) {
3107 if (pid == 0) {
3108 parg = args;
3109 *parg++ = (char *)setup_script;
3110 *parg++ = ifname;
3111 *parg++ = NULL;
3112 execv(setup_script, args);
3113 _exit(1);
3115 while (waitpid(pid, &status, 0) != pid);
3116 if (!WIFEXITED(status) ||
3117 WEXITSTATUS(status) != 0) {
3118 fprintf(stderr, "%s: could not launch network script\n",
3119 setup_script);
3120 return -1;
3124 s = net_tap_fd_init(vlan, fd);
3125 if (!s)
3126 return -1;
3127 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3128 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3129 return 0;
3132 #endif /* !_WIN32 */
3134 /* network connection */
3135 typedef struct NetSocketState {
3136 VLANClientState *vc;
3137 int fd;
3138 int state; /* 0 = getting length, 1 = getting data */
3139 int index;
3140 int packet_len;
3141 uint8_t buf[4096];
3142 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3143 } NetSocketState;
3145 typedef struct NetSocketListenState {
3146 VLANState *vlan;
3147 int fd;
3148 } NetSocketListenState;
3150 /* XXX: we consider we can send the whole packet without blocking */
3151 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3153 NetSocketState *s = opaque;
3154 uint32_t len;
3155 len = htonl(size);
3157 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3158 send_all(s->fd, buf, size);
3161 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3163 NetSocketState *s = opaque;
3164 sendto(s->fd, buf, size, 0,
3165 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3168 static void net_socket_send(void *opaque)
3170 NetSocketState *s = opaque;
3171 int l, size, err;
3172 uint8_t buf1[4096];
3173 const uint8_t *buf;
3175 size = recv(s->fd, buf1, sizeof(buf1), 0);
3176 if (size < 0) {
3177 err = socket_error();
3178 if (err != EWOULDBLOCK)
3179 goto eoc;
3180 } else if (size == 0) {
3181 /* end of connection */
3182 eoc:
3183 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3184 closesocket(s->fd);
3185 return;
3187 buf = buf1;
3188 while (size > 0) {
3189 /* reassemble a packet from the network */
3190 switch(s->state) {
3191 case 0:
3192 l = 4 - s->index;
3193 if (l > size)
3194 l = size;
3195 memcpy(s->buf + s->index, buf, l);
3196 buf += l;
3197 size -= l;
3198 s->index += l;
3199 if (s->index == 4) {
3200 /* got length */
3201 s->packet_len = ntohl(*(uint32_t *)s->buf);
3202 s->index = 0;
3203 s->state = 1;
3205 break;
3206 case 1:
3207 l = s->packet_len - s->index;
3208 if (l > size)
3209 l = size;
3210 memcpy(s->buf + s->index, buf, l);
3211 s->index += l;
3212 buf += l;
3213 size -= l;
3214 if (s->index >= s->packet_len) {
3215 qemu_send_packet(s->vc, s->buf, s->packet_len);
3216 s->index = 0;
3217 s->state = 0;
3219 break;
3224 static void net_socket_send_dgram(void *opaque)
3226 NetSocketState *s = opaque;
3227 int size;
3229 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3230 if (size < 0)
3231 return;
3232 if (size == 0) {
3233 /* end of connection */
3234 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3235 return;
3237 qemu_send_packet(s->vc, s->buf, size);
3240 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3242 struct ip_mreq imr;
3243 int fd;
3244 int val, ret;
3245 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3246 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3247 inet_ntoa(mcastaddr->sin_addr),
3248 (int)ntohl(mcastaddr->sin_addr.s_addr));
3249 return -1;
3252 fd = socket(PF_INET, SOCK_DGRAM, 0);
3253 if (fd < 0) {
3254 perror("socket(PF_INET, SOCK_DGRAM)");
3255 return -1;
3258 val = 1;
3259 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3260 (const char *)&val, sizeof(val));
3261 if (ret < 0) {
3262 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3263 goto fail;
3266 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3267 if (ret < 0) {
3268 perror("bind");
3269 goto fail;
3272 /* Add host to multicast group */
3273 imr.imr_multiaddr = mcastaddr->sin_addr;
3274 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3276 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3277 (const char *)&imr, sizeof(struct ip_mreq));
3278 if (ret < 0) {
3279 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3280 goto fail;
3283 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3284 val = 1;
3285 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3286 (const char *)&val, sizeof(val));
3287 if (ret < 0) {
3288 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3289 goto fail;
3292 socket_set_nonblock(fd);
3293 return fd;
3294 fail:
3295 if (fd >= 0)
3296 closesocket(fd);
3297 return -1;
3300 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3301 int is_connected)
3303 struct sockaddr_in saddr;
3304 int newfd;
3305 socklen_t saddr_len;
3306 NetSocketState *s;
3308 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3309 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3310 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3313 if (is_connected) {
3314 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3315 /* must be bound */
3316 if (saddr.sin_addr.s_addr==0) {
3317 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3318 fd);
3319 return NULL;
3321 /* clone dgram socket */
3322 newfd = net_socket_mcast_create(&saddr);
3323 if (newfd < 0) {
3324 /* error already reported by net_socket_mcast_create() */
3325 close(fd);
3326 return NULL;
3328 /* clone newfd to fd, close newfd */
3329 dup2(newfd, fd);
3330 close(newfd);
3332 } else {
3333 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3334 fd, strerror(errno));
3335 return NULL;
3339 s = qemu_mallocz(sizeof(NetSocketState));
3340 if (!s)
3341 return NULL;
3342 s->fd = fd;
3344 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3345 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3347 /* mcast: save bound address as dst */
3348 if (is_connected) s->dgram_dst=saddr;
3350 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3351 "socket: fd=%d (%s mcast=%s:%d)",
3352 fd, is_connected? "cloned" : "",
3353 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3354 return s;
3357 static void net_socket_connect(void *opaque)
3359 NetSocketState *s = opaque;
3360 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3363 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3364 int is_connected)
3366 NetSocketState *s;
3367 s = qemu_mallocz(sizeof(NetSocketState));
3368 if (!s)
3369 return NULL;
3370 s->fd = fd;
3371 s->vc = qemu_new_vlan_client(vlan,
3372 net_socket_receive, NULL, s);
3373 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3374 "socket: fd=%d", fd);
3375 if (is_connected) {
3376 net_socket_connect(s);
3377 } else {
3378 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3380 return s;
3383 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3384 int is_connected)
3386 int so_type=-1, optlen=sizeof(so_type);
3388 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3389 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3390 return NULL;
3392 switch(so_type) {
3393 case SOCK_DGRAM:
3394 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3395 case SOCK_STREAM:
3396 return net_socket_fd_init_stream(vlan, fd, is_connected);
3397 default:
3398 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3399 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3400 return net_socket_fd_init_stream(vlan, fd, is_connected);
3402 return NULL;
3405 static void net_socket_accept(void *opaque)
3407 NetSocketListenState *s = opaque;
3408 NetSocketState *s1;
3409 struct sockaddr_in saddr;
3410 socklen_t len;
3411 int fd;
3413 for(;;) {
3414 len = sizeof(saddr);
3415 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3416 if (fd < 0 && errno != EINTR) {
3417 return;
3418 } else if (fd >= 0) {
3419 break;
3422 s1 = net_socket_fd_init(s->vlan, fd, 1);
3423 if (!s1) {
3424 closesocket(fd);
3425 } else {
3426 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3427 "socket: connection from %s:%d",
3428 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3432 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3434 NetSocketListenState *s;
3435 int fd, val, ret;
3436 struct sockaddr_in saddr;
3438 if (parse_host_port(&saddr, host_str) < 0)
3439 return -1;
3441 s = qemu_mallocz(sizeof(NetSocketListenState));
3442 if (!s)
3443 return -1;
3445 fd = socket(PF_INET, SOCK_STREAM, 0);
3446 if (fd < 0) {
3447 perror("socket");
3448 return -1;
3450 socket_set_nonblock(fd);
3452 /* allow fast reuse */
3453 val = 1;
3454 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3456 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3457 if (ret < 0) {
3458 perror("bind");
3459 return -1;
3461 ret = listen(fd, 0);
3462 if (ret < 0) {
3463 perror("listen");
3464 return -1;
3466 s->vlan = vlan;
3467 s->fd = fd;
3468 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3469 return 0;
3472 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3474 NetSocketState *s;
3475 int fd, connected, ret, err;
3476 struct sockaddr_in saddr;
3478 if (parse_host_port(&saddr, host_str) < 0)
3479 return -1;
3481 fd = socket(PF_INET, SOCK_STREAM, 0);
3482 if (fd < 0) {
3483 perror("socket");
3484 return -1;
3486 socket_set_nonblock(fd);
3488 connected = 0;
3489 for(;;) {
3490 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3491 if (ret < 0) {
3492 err = socket_error();
3493 if (err == EINTR || err == EWOULDBLOCK) {
3494 } else if (err == EINPROGRESS) {
3495 break;
3496 } else {
3497 perror("connect");
3498 closesocket(fd);
3499 return -1;
3501 } else {
3502 connected = 1;
3503 break;
3506 s = net_socket_fd_init(vlan, fd, connected);
3507 if (!s)
3508 return -1;
3509 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3510 "socket: connect to %s:%d",
3511 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3512 return 0;
3515 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3517 NetSocketState *s;
3518 int fd;
3519 struct sockaddr_in saddr;
3521 if (parse_host_port(&saddr, host_str) < 0)
3522 return -1;
3525 fd = net_socket_mcast_create(&saddr);
3526 if (fd < 0)
3527 return -1;
3529 s = net_socket_fd_init(vlan, fd, 0);
3530 if (!s)
3531 return -1;
3533 s->dgram_dst = saddr;
3535 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3536 "socket: mcast=%s:%d",
3537 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3538 return 0;
3542 static int get_param_value(char *buf, int buf_size,
3543 const char *tag, const char *str)
3545 const char *p;
3546 char *q;
3547 char option[128];
3549 p = str;
3550 for(;;) {
3551 q = option;
3552 while (*p != '\0' && *p != '=') {
3553 if ((q - option) < sizeof(option) - 1)
3554 *q++ = *p;
3555 p++;
3557 *q = '\0';
3558 if (*p != '=')
3559 break;
3560 p++;
3561 if (!strcmp(tag, option)) {
3562 q = buf;
3563 while (*p != '\0' && *p != ',') {
3564 if ((q - buf) < buf_size - 1)
3565 *q++ = *p;
3566 p++;
3568 *q = '\0';
3569 return q - buf;
3570 } else {
3571 while (*p != '\0' && *p != ',') {
3572 p++;
3575 if (*p != ',')
3576 break;
3577 p++;
3579 return 0;
3582 int net_client_init(const char *str)
3584 const char *p;
3585 char *q;
3586 char device[64];
3587 char buf[1024];
3588 int vlan_id, ret;
3589 VLANState *vlan;
3591 p = str;
3592 q = device;
3593 while (*p != '\0' && *p != ',') {
3594 if ((q - device) < sizeof(device) - 1)
3595 *q++ = *p;
3596 p++;
3598 *q = '\0';
3599 if (*p == ',')
3600 p++;
3601 vlan_id = 0;
3602 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3603 vlan_id = strtol(buf, NULL, 0);
3605 vlan = qemu_find_vlan(vlan_id);
3606 if (!vlan) {
3607 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3608 return -1;
3610 if (!strcmp(device, "nic")) {
3611 NICInfo *nd;
3612 uint8_t *macaddr;
3614 if (nb_nics >= MAX_NICS) {
3615 fprintf(stderr, "Too Many NICs\n");
3616 return -1;
3618 nd = &nd_table[nb_nics];
3619 macaddr = nd->macaddr;
3620 macaddr[0] = 0x52;
3621 macaddr[1] = 0x54;
3622 macaddr[2] = 0x00;
3623 macaddr[3] = 0x12;
3624 macaddr[4] = 0x34;
3625 macaddr[5] = 0x56 + nb_nics;
3627 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3628 if (parse_macaddr(macaddr, buf) < 0) {
3629 fprintf(stderr, "invalid syntax for ethernet address\n");
3630 return -1;
3633 if (get_param_value(buf, sizeof(buf), "model", p)) {
3634 nd->model = strdup(buf);
3636 nd->vlan = vlan;
3637 nb_nics++;
3638 ret = 0;
3639 } else
3640 if (!strcmp(device, "none")) {
3641 /* does nothing. It is needed to signal that no network cards
3642 are wanted */
3643 ret = 0;
3644 } else
3645 #ifdef CONFIG_SLIRP
3646 if (!strcmp(device, "user")) {
3647 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3648 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3650 ret = net_slirp_init(vlan);
3651 } else
3652 #endif
3653 #ifdef _WIN32
3654 if (!strcmp(device, "tap")) {
3655 char ifname[64];
3656 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3657 fprintf(stderr, "tap: no interface name\n");
3658 return -1;
3660 ret = tap_win32_init(vlan, ifname);
3661 } else
3662 #else
3663 if (!strcmp(device, "tap")) {
3664 char ifname[64];
3665 char setup_script[1024];
3666 int fd;
3667 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3668 fd = strtol(buf, NULL, 0);
3669 ret = -1;
3670 if (net_tap_fd_init(vlan, fd))
3671 ret = 0;
3672 } else {
3673 get_param_value(ifname, sizeof(ifname), "ifname", p);
3674 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3675 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3677 ret = net_tap_init(vlan, ifname, setup_script);
3679 } else
3680 #endif
3681 if (!strcmp(device, "socket")) {
3682 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3683 int fd;
3684 fd = strtol(buf, NULL, 0);
3685 ret = -1;
3686 if (net_socket_fd_init(vlan, fd, 1))
3687 ret = 0;
3688 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3689 ret = net_socket_listen_init(vlan, buf);
3690 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3691 ret = net_socket_connect_init(vlan, buf);
3692 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3693 ret = net_socket_mcast_init(vlan, buf);
3694 } else {
3695 fprintf(stderr, "Unknown socket options: %s\n", p);
3696 return -1;
3698 } else
3700 fprintf(stderr, "Unknown network device: %s\n", device);
3701 return -1;
3703 if (ret < 0) {
3704 fprintf(stderr, "Could not initialize device '%s'\n", device);
3707 return ret;
3710 void do_info_network(void)
3712 VLANState *vlan;
3713 VLANClientState *vc;
3715 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3716 term_printf("VLAN %d devices:\n", vlan->id);
3717 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3718 term_printf(" %s\n", vc->info_str);
3722 /***********************************************************/
3723 /* USB devices */
3725 static USBPort *used_usb_ports;
3726 static USBPort *free_usb_ports;
3728 /* ??? Maybe change this to register a hub to keep track of the topology. */
3729 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3730 usb_attachfn attach)
3732 port->opaque = opaque;
3733 port->index = index;
3734 port->attach = attach;
3735 port->next = free_usb_ports;
3736 free_usb_ports = port;
3739 static int usb_device_add(const char *devname)
3741 const char *p;
3742 USBDevice *dev;
3743 USBPort *port;
3745 if (!free_usb_ports)
3746 return -1;
3748 if (strstart(devname, "host:", &p)) {
3749 dev = usb_host_device_open(p);
3750 } else if (!strcmp(devname, "mouse")) {
3751 dev = usb_mouse_init();
3752 } else if (!strcmp(devname, "tablet")) {
3753 dev = usb_tablet_init();
3754 } else if (strstart(devname, "disk:", &p)) {
3755 dev = usb_msd_init(p);
3756 } else {
3757 return -1;
3759 if (!dev)
3760 return -1;
3762 /* Find a USB port to add the device to. */
3763 port = free_usb_ports;
3764 if (!port->next) {
3765 USBDevice *hub;
3767 /* Create a new hub and chain it on. */
3768 free_usb_ports = NULL;
3769 port->next = used_usb_ports;
3770 used_usb_ports = port;
3772 hub = usb_hub_init(VM_USB_HUB_SIZE);
3773 usb_attach(port, hub);
3774 port = free_usb_ports;
3777 free_usb_ports = port->next;
3778 port->next = used_usb_ports;
3779 used_usb_ports = port;
3780 usb_attach(port, dev);
3781 return 0;
3784 static int usb_device_del(const char *devname)
3786 USBPort *port;
3787 USBPort **lastp;
3788 USBDevice *dev;
3789 int bus_num, addr;
3790 const char *p;
3792 if (!used_usb_ports)
3793 return -1;
3795 p = strchr(devname, '.');
3796 if (!p)
3797 return -1;
3798 bus_num = strtoul(devname, NULL, 0);
3799 addr = strtoul(p + 1, NULL, 0);
3800 if (bus_num != 0)
3801 return -1;
3803 lastp = &used_usb_ports;
3804 port = used_usb_ports;
3805 while (port && port->dev->addr != addr) {
3806 lastp = &port->next;
3807 port = port->next;
3810 if (!port)
3811 return -1;
3813 dev = port->dev;
3814 *lastp = port->next;
3815 usb_attach(port, NULL);
3816 dev->handle_destroy(dev);
3817 port->next = free_usb_ports;
3818 free_usb_ports = port;
3819 return 0;
3822 void do_usb_add(const char *devname)
3824 int ret;
3825 ret = usb_device_add(devname);
3826 if (ret < 0)
3827 term_printf("Could not add USB device '%s'\n", devname);
3830 void do_usb_del(const char *devname)
3832 int ret;
3833 ret = usb_device_del(devname);
3834 if (ret < 0)
3835 term_printf("Could not remove USB device '%s'\n", devname);
3838 void usb_info(void)
3840 USBDevice *dev;
3841 USBPort *port;
3842 const char *speed_str;
3844 if (!usb_enabled) {
3845 term_printf("USB support not enabled\n");
3846 return;
3849 for (port = used_usb_ports; port; port = port->next) {
3850 dev = port->dev;
3851 if (!dev)
3852 continue;
3853 switch(dev->speed) {
3854 case USB_SPEED_LOW:
3855 speed_str = "1.5";
3856 break;
3857 case USB_SPEED_FULL:
3858 speed_str = "12";
3859 break;
3860 case USB_SPEED_HIGH:
3861 speed_str = "480";
3862 break;
3863 default:
3864 speed_str = "?";
3865 break;
3867 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
3868 0, dev->addr, speed_str, dev->devname);
3872 /***********************************************************/
3873 /* pid file */
3875 static char *pid_filename;
3877 /* Remove PID file. Called on normal exit */
3879 static void remove_pidfile(void)
3881 unlink (pid_filename);
3884 static void create_pidfile(const char *filename)
3886 struct stat pidstat;
3887 FILE *f;
3889 /* Try to write our PID to the named file */
3890 if (stat(filename, &pidstat) < 0) {
3891 if (errno == ENOENT) {
3892 if ((f = fopen (filename, "w")) == NULL) {
3893 perror("Opening pidfile");
3894 exit(1);
3896 fprintf(f, "%d\n", getpid());
3897 fclose(f);
3898 pid_filename = qemu_strdup(filename);
3899 if (!pid_filename) {
3900 fprintf(stderr, "Could not save PID filename");
3901 exit(1);
3903 atexit(remove_pidfile);
3905 } else {
3906 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3907 filename);
3908 exit(1);
3912 /***********************************************************/
3913 /* dumb display */
3915 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3919 static void dumb_resize(DisplayState *ds, int w, int h)
3923 static void dumb_refresh(DisplayState *ds)
3925 vga_hw_update();
3928 void dumb_display_init(DisplayState *ds)
3930 ds->data = NULL;
3931 ds->linesize = 0;
3932 ds->depth = 0;
3933 ds->dpy_update = dumb_update;
3934 ds->dpy_resize = dumb_resize;
3935 ds->dpy_refresh = dumb_refresh;
3938 /***********************************************************/
3939 /* I/O handling */
3941 #define MAX_IO_HANDLERS 64
3943 typedef struct IOHandlerRecord {
3944 int fd;
3945 IOCanRWHandler *fd_read_poll;
3946 IOHandler *fd_read;
3947 IOHandler *fd_write;
3948 void *opaque;
3949 /* temporary data */
3950 struct pollfd *ufd;
3951 struct IOHandlerRecord *next;
3952 } IOHandlerRecord;
3954 static IOHandlerRecord *first_io_handler;
3956 /* XXX: fd_read_poll should be suppressed, but an API change is
3957 necessary in the character devices to suppress fd_can_read(). */
3958 int qemu_set_fd_handler2(int fd,
3959 IOCanRWHandler *fd_read_poll,
3960 IOHandler *fd_read,
3961 IOHandler *fd_write,
3962 void *opaque)
3964 IOHandlerRecord **pioh, *ioh;
3966 if (!fd_read && !fd_write) {
3967 pioh = &first_io_handler;
3968 for(;;) {
3969 ioh = *pioh;
3970 if (ioh == NULL)
3971 break;
3972 if (ioh->fd == fd) {
3973 *pioh = ioh->next;
3974 qemu_free(ioh);
3975 break;
3977 pioh = &ioh->next;
3979 } else {
3980 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3981 if (ioh->fd == fd)
3982 goto found;
3984 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3985 if (!ioh)
3986 return -1;
3987 ioh->next = first_io_handler;
3988 first_io_handler = ioh;
3989 found:
3990 ioh->fd = fd;
3991 ioh->fd_read_poll = fd_read_poll;
3992 ioh->fd_read = fd_read;
3993 ioh->fd_write = fd_write;
3994 ioh->opaque = opaque;
3996 return 0;
3999 int qemu_set_fd_handler(int fd,
4000 IOHandler *fd_read,
4001 IOHandler *fd_write,
4002 void *opaque)
4004 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4007 /***********************************************************/
4008 /* Polling handling */
4010 typedef struct PollingEntry {
4011 PollingFunc *func;
4012 void *opaque;
4013 struct PollingEntry *next;
4014 } PollingEntry;
4016 static PollingEntry *first_polling_entry;
4018 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4020 PollingEntry **ppe, *pe;
4021 pe = qemu_mallocz(sizeof(PollingEntry));
4022 if (!pe)
4023 return -1;
4024 pe->func = func;
4025 pe->opaque = opaque;
4026 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4027 *ppe = pe;
4028 return 0;
4031 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4033 PollingEntry **ppe, *pe;
4034 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4035 pe = *ppe;
4036 if (pe->func == func && pe->opaque == opaque) {
4037 *ppe = pe->next;
4038 qemu_free(pe);
4039 break;
4044 #ifdef _WIN32
4045 /***********************************************************/
4046 /* Wait objects support */
4047 typedef struct WaitObjects {
4048 int num;
4049 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4050 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4051 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4052 } WaitObjects;
4054 static WaitObjects wait_objects = {0};
4056 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4058 WaitObjects *w = &wait_objects;
4060 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4061 return -1;
4062 w->events[w->num] = handle;
4063 w->func[w->num] = func;
4064 w->opaque[w->num] = opaque;
4065 w->num++;
4066 return 0;
4069 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4071 int i, found;
4072 WaitObjects *w = &wait_objects;
4074 found = 0;
4075 for (i = 0; i < w->num; i++) {
4076 if (w->events[i] == handle)
4077 found = 1;
4078 if (found) {
4079 w->events[i] = w->events[i + 1];
4080 w->func[i] = w->func[i + 1];
4081 w->opaque[i] = w->opaque[i + 1];
4084 if (found)
4085 w->num--;
4087 #endif
4089 /***********************************************************/
4090 /* savevm/loadvm support */
4092 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4094 fwrite(buf, 1, size, f);
4097 void qemu_put_byte(QEMUFile *f, int v)
4099 fputc(v, f);
4102 void qemu_put_be16(QEMUFile *f, unsigned int v)
4104 qemu_put_byte(f, v >> 8);
4105 qemu_put_byte(f, v);
4108 void qemu_put_be32(QEMUFile *f, unsigned int v)
4110 qemu_put_byte(f, v >> 24);
4111 qemu_put_byte(f, v >> 16);
4112 qemu_put_byte(f, v >> 8);
4113 qemu_put_byte(f, v);
4116 void qemu_put_be64(QEMUFile *f, uint64_t v)
4118 qemu_put_be32(f, v >> 32);
4119 qemu_put_be32(f, v);
4122 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4124 return fread(buf, 1, size, f);
4127 int qemu_get_byte(QEMUFile *f)
4129 int v;
4130 v = fgetc(f);
4131 if (v == EOF)
4132 return 0;
4133 else
4134 return v;
4137 unsigned int qemu_get_be16(QEMUFile *f)
4139 unsigned int v;
4140 v = qemu_get_byte(f) << 8;
4141 v |= qemu_get_byte(f);
4142 return v;
4145 unsigned int qemu_get_be32(QEMUFile *f)
4147 unsigned int v;
4148 v = qemu_get_byte(f) << 24;
4149 v |= qemu_get_byte(f) << 16;
4150 v |= qemu_get_byte(f) << 8;
4151 v |= qemu_get_byte(f);
4152 return v;
4155 uint64_t qemu_get_be64(QEMUFile *f)
4157 uint64_t v;
4158 v = (uint64_t)qemu_get_be32(f) << 32;
4159 v |= qemu_get_be32(f);
4160 return v;
4163 int64_t qemu_ftell(QEMUFile *f)
4165 return ftell(f);
4168 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4170 if (fseek(f, pos, whence) < 0)
4171 return -1;
4172 return ftell(f);
4175 typedef struct SaveStateEntry {
4176 char idstr[256];
4177 int instance_id;
4178 int version_id;
4179 SaveStateHandler *save_state;
4180 LoadStateHandler *load_state;
4181 void *opaque;
4182 struct SaveStateEntry *next;
4183 } SaveStateEntry;
4185 static SaveStateEntry *first_se;
4187 int register_savevm(const char *idstr,
4188 int instance_id,
4189 int version_id,
4190 SaveStateHandler *save_state,
4191 LoadStateHandler *load_state,
4192 void *opaque)
4194 SaveStateEntry *se, **pse;
4196 se = qemu_malloc(sizeof(SaveStateEntry));
4197 if (!se)
4198 return -1;
4199 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4200 se->instance_id = instance_id;
4201 se->version_id = version_id;
4202 se->save_state = save_state;
4203 se->load_state = load_state;
4204 se->opaque = opaque;
4205 se->next = NULL;
4207 /* add at the end of list */
4208 pse = &first_se;
4209 while (*pse != NULL)
4210 pse = &(*pse)->next;
4211 *pse = se;
4212 return 0;
4215 #define QEMU_VM_FILE_MAGIC 0x5145564d
4216 #define QEMU_VM_FILE_VERSION 0x00000001
4218 int qemu_savevm(const char *filename)
4220 SaveStateEntry *se;
4221 QEMUFile *f;
4222 int len, len_pos, cur_pos, saved_vm_running, ret;
4224 saved_vm_running = vm_running;
4225 vm_stop(0);
4227 f = fopen(filename, "wb");
4228 if (!f) {
4229 ret = -1;
4230 goto the_end;
4233 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4234 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4236 for(se = first_se; se != NULL; se = se->next) {
4237 /* ID string */
4238 len = strlen(se->idstr);
4239 qemu_put_byte(f, len);
4240 qemu_put_buffer(f, se->idstr, len);
4242 qemu_put_be32(f, se->instance_id);
4243 qemu_put_be32(f, se->version_id);
4245 /* record size: filled later */
4246 len_pos = ftell(f);
4247 qemu_put_be32(f, 0);
4249 se->save_state(f, se->opaque);
4251 /* fill record size */
4252 cur_pos = ftell(f);
4253 len = ftell(f) - len_pos - 4;
4254 fseek(f, len_pos, SEEK_SET);
4255 qemu_put_be32(f, len);
4256 fseek(f, cur_pos, SEEK_SET);
4259 fclose(f);
4260 ret = 0;
4261 the_end:
4262 if (saved_vm_running)
4263 vm_start();
4264 return ret;
4267 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4269 SaveStateEntry *se;
4271 for(se = first_se; se != NULL; se = se->next) {
4272 if (!strcmp(se->idstr, idstr) &&
4273 instance_id == se->instance_id)
4274 return se;
4276 return NULL;
4279 int qemu_loadvm(const char *filename)
4281 SaveStateEntry *se;
4282 QEMUFile *f;
4283 int len, cur_pos, ret, instance_id, record_len, version_id;
4284 int saved_vm_running;
4285 unsigned int v;
4286 char idstr[256];
4288 saved_vm_running = vm_running;
4289 vm_stop(0);
4291 f = fopen(filename, "rb");
4292 if (!f) {
4293 ret = -1;
4294 goto the_end;
4297 v = qemu_get_be32(f);
4298 if (v != QEMU_VM_FILE_MAGIC)
4299 goto fail;
4300 v = qemu_get_be32(f);
4301 if (v != QEMU_VM_FILE_VERSION) {
4302 fail:
4303 fclose(f);
4304 ret = -1;
4305 goto the_end;
4307 for(;;) {
4308 len = qemu_get_byte(f);
4309 if (feof(f))
4310 break;
4311 qemu_get_buffer(f, idstr, len);
4312 idstr[len] = '\0';
4313 instance_id = qemu_get_be32(f);
4314 version_id = qemu_get_be32(f);
4315 record_len = qemu_get_be32(f);
4316 #if 0
4317 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4318 idstr, instance_id, version_id, record_len);
4319 #endif
4320 cur_pos = ftell(f);
4321 se = find_se(idstr, instance_id);
4322 if (!se) {
4323 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4324 instance_id, idstr);
4325 } else {
4326 ret = se->load_state(f, se->opaque, version_id);
4327 if (ret < 0) {
4328 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4329 instance_id, idstr);
4332 /* always seek to exact end of record */
4333 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4335 fclose(f);
4336 ret = 0;
4337 the_end:
4338 if (saved_vm_running)
4339 vm_start();
4340 return ret;
4343 /***********************************************************/
4344 /* cpu save/restore */
4346 #if defined(TARGET_I386)
4348 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4350 qemu_put_be32(f, dt->selector);
4351 qemu_put_betl(f, dt->base);
4352 qemu_put_be32(f, dt->limit);
4353 qemu_put_be32(f, dt->flags);
4356 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4358 dt->selector = qemu_get_be32(f);
4359 dt->base = qemu_get_betl(f);
4360 dt->limit = qemu_get_be32(f);
4361 dt->flags = qemu_get_be32(f);
4364 void cpu_save(QEMUFile *f, void *opaque)
4366 CPUState *env = opaque;
4367 uint16_t fptag, fpus, fpuc, fpregs_format;
4368 uint32_t hflags;
4369 int i;
4371 for(i = 0; i < CPU_NB_REGS; i++)
4372 qemu_put_betls(f, &env->regs[i]);
4373 qemu_put_betls(f, &env->eip);
4374 qemu_put_betls(f, &env->eflags);
4375 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4376 qemu_put_be32s(f, &hflags);
4378 /* FPU */
4379 fpuc = env->fpuc;
4380 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4381 fptag = 0;
4382 for(i = 0; i < 8; i++) {
4383 fptag |= ((!env->fptags[i]) << i);
4386 qemu_put_be16s(f, &fpuc);
4387 qemu_put_be16s(f, &fpus);
4388 qemu_put_be16s(f, &fptag);
4390 #ifdef USE_X86LDOUBLE
4391 fpregs_format = 0;
4392 #else
4393 fpregs_format = 1;
4394 #endif
4395 qemu_put_be16s(f, &fpregs_format);
4397 for(i = 0; i < 8; i++) {
4398 #ifdef USE_X86LDOUBLE
4400 uint64_t mant;
4401 uint16_t exp;
4402 /* we save the real CPU data (in case of MMX usage only 'mant'
4403 contains the MMX register */
4404 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4405 qemu_put_be64(f, mant);
4406 qemu_put_be16(f, exp);
4408 #else
4409 /* if we use doubles for float emulation, we save the doubles to
4410 avoid losing information in case of MMX usage. It can give
4411 problems if the image is restored on a CPU where long
4412 doubles are used instead. */
4413 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4414 #endif
4417 for(i = 0; i < 6; i++)
4418 cpu_put_seg(f, &env->segs[i]);
4419 cpu_put_seg(f, &env->ldt);
4420 cpu_put_seg(f, &env->tr);
4421 cpu_put_seg(f, &env->gdt);
4422 cpu_put_seg(f, &env->idt);
4424 qemu_put_be32s(f, &env->sysenter_cs);
4425 qemu_put_be32s(f, &env->sysenter_esp);
4426 qemu_put_be32s(f, &env->sysenter_eip);
4428 qemu_put_betls(f, &env->cr[0]);
4429 qemu_put_betls(f, &env->cr[2]);
4430 qemu_put_betls(f, &env->cr[3]);
4431 qemu_put_betls(f, &env->cr[4]);
4433 for(i = 0; i < 8; i++)
4434 qemu_put_betls(f, &env->dr[i]);
4436 /* MMU */
4437 qemu_put_be32s(f, &env->a20_mask);
4439 /* XMM */
4440 qemu_put_be32s(f, &env->mxcsr);
4441 for(i = 0; i < CPU_NB_REGS; i++) {
4442 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4443 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4446 #ifdef TARGET_X86_64
4447 qemu_put_be64s(f, &env->efer);
4448 qemu_put_be64s(f, &env->star);
4449 qemu_put_be64s(f, &env->lstar);
4450 qemu_put_be64s(f, &env->cstar);
4451 qemu_put_be64s(f, &env->fmask);
4452 qemu_put_be64s(f, &env->kernelgsbase);
4453 #endif
4456 #ifdef USE_X86LDOUBLE
4457 /* XXX: add that in a FPU generic layer */
4458 union x86_longdouble {
4459 uint64_t mant;
4460 uint16_t exp;
4463 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4464 #define EXPBIAS1 1023
4465 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4466 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4468 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4470 int e;
4471 /* mantissa */
4472 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4473 /* exponent + sign */
4474 e = EXPD1(temp) - EXPBIAS1 + 16383;
4475 e |= SIGND1(temp) >> 16;
4476 p->exp = e;
4478 #endif
4480 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4482 CPUState *env = opaque;
4483 int i, guess_mmx;
4484 uint32_t hflags;
4485 uint16_t fpus, fpuc, fptag, fpregs_format;
4487 if (version_id != 3)
4488 return -EINVAL;
4489 for(i = 0; i < CPU_NB_REGS; i++)
4490 qemu_get_betls(f, &env->regs[i]);
4491 qemu_get_betls(f, &env->eip);
4492 qemu_get_betls(f, &env->eflags);
4493 qemu_get_be32s(f, &hflags);
4495 qemu_get_be16s(f, &fpuc);
4496 qemu_get_be16s(f, &fpus);
4497 qemu_get_be16s(f, &fptag);
4498 qemu_get_be16s(f, &fpregs_format);
4500 /* NOTE: we cannot always restore the FPU state if the image come
4501 from a host with a different 'USE_X86LDOUBLE' define. We guess
4502 if we are in an MMX state to restore correctly in that case. */
4503 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4504 for(i = 0; i < 8; i++) {
4505 uint64_t mant;
4506 uint16_t exp;
4508 switch(fpregs_format) {
4509 case 0:
4510 mant = qemu_get_be64(f);
4511 exp = qemu_get_be16(f);
4512 #ifdef USE_X86LDOUBLE
4513 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4514 #else
4515 /* difficult case */
4516 if (guess_mmx)
4517 env->fpregs[i].mmx.MMX_Q(0) = mant;
4518 else
4519 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4520 #endif
4521 break;
4522 case 1:
4523 mant = qemu_get_be64(f);
4524 #ifdef USE_X86LDOUBLE
4526 union x86_longdouble *p;
4527 /* difficult case */
4528 p = (void *)&env->fpregs[i];
4529 if (guess_mmx) {
4530 p->mant = mant;
4531 p->exp = 0xffff;
4532 } else {
4533 fp64_to_fp80(p, mant);
4536 #else
4537 env->fpregs[i].mmx.MMX_Q(0) = mant;
4538 #endif
4539 break;
4540 default:
4541 return -EINVAL;
4545 env->fpuc = fpuc;
4546 /* XXX: restore FPU round state */
4547 env->fpstt = (fpus >> 11) & 7;
4548 env->fpus = fpus & ~0x3800;
4549 fptag ^= 0xff;
4550 for(i = 0; i < 8; i++) {
4551 env->fptags[i] = (fptag >> i) & 1;
4554 for(i = 0; i < 6; i++)
4555 cpu_get_seg(f, &env->segs[i]);
4556 cpu_get_seg(f, &env->ldt);
4557 cpu_get_seg(f, &env->tr);
4558 cpu_get_seg(f, &env->gdt);
4559 cpu_get_seg(f, &env->idt);
4561 qemu_get_be32s(f, &env->sysenter_cs);
4562 qemu_get_be32s(f, &env->sysenter_esp);
4563 qemu_get_be32s(f, &env->sysenter_eip);
4565 qemu_get_betls(f, &env->cr[0]);
4566 qemu_get_betls(f, &env->cr[2]);
4567 qemu_get_betls(f, &env->cr[3]);
4568 qemu_get_betls(f, &env->cr[4]);
4570 for(i = 0; i < 8; i++)
4571 qemu_get_betls(f, &env->dr[i]);
4573 /* MMU */
4574 qemu_get_be32s(f, &env->a20_mask);
4576 qemu_get_be32s(f, &env->mxcsr);
4577 for(i = 0; i < CPU_NB_REGS; i++) {
4578 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4579 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4582 #ifdef TARGET_X86_64
4583 qemu_get_be64s(f, &env->efer);
4584 qemu_get_be64s(f, &env->star);
4585 qemu_get_be64s(f, &env->lstar);
4586 qemu_get_be64s(f, &env->cstar);
4587 qemu_get_be64s(f, &env->fmask);
4588 qemu_get_be64s(f, &env->kernelgsbase);
4589 #endif
4591 /* XXX: compute hflags from scratch, except for CPL and IIF */
4592 env->hflags = hflags;
4593 tlb_flush(env, 1);
4594 return 0;
4597 #elif defined(TARGET_PPC)
4598 void cpu_save(QEMUFile *f, void *opaque)
4602 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4604 return 0;
4607 #elif defined(TARGET_MIPS)
4608 void cpu_save(QEMUFile *f, void *opaque)
4612 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4614 return 0;
4617 #elif defined(TARGET_SPARC)
4618 void cpu_save(QEMUFile *f, void *opaque)
4620 CPUState *env = opaque;
4621 int i;
4622 uint32_t tmp;
4624 for(i = 0; i < 8; i++)
4625 qemu_put_betls(f, &env->gregs[i]);
4626 for(i = 0; i < NWINDOWS * 16; i++)
4627 qemu_put_betls(f, &env->regbase[i]);
4629 /* FPU */
4630 for(i = 0; i < TARGET_FPREGS; i++) {
4631 union {
4632 float32 f;
4633 uint32_t i;
4634 } u;
4635 u.f = env->fpr[i];
4636 qemu_put_be32(f, u.i);
4639 qemu_put_betls(f, &env->pc);
4640 qemu_put_betls(f, &env->npc);
4641 qemu_put_betls(f, &env->y);
4642 tmp = GET_PSR(env);
4643 qemu_put_be32(f, tmp);
4644 qemu_put_betls(f, &env->fsr);
4645 qemu_put_betls(f, &env->tbr);
4646 #ifndef TARGET_SPARC64
4647 qemu_put_be32s(f, &env->wim);
4648 /* MMU */
4649 for(i = 0; i < 16; i++)
4650 qemu_put_be32s(f, &env->mmuregs[i]);
4651 #endif
4654 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4656 CPUState *env = opaque;
4657 int i;
4658 uint32_t tmp;
4660 for(i = 0; i < 8; i++)
4661 qemu_get_betls(f, &env->gregs[i]);
4662 for(i = 0; i < NWINDOWS * 16; i++)
4663 qemu_get_betls(f, &env->regbase[i]);
4665 /* FPU */
4666 for(i = 0; i < TARGET_FPREGS; i++) {
4667 union {
4668 float32 f;
4669 uint32_t i;
4670 } u;
4671 u.i = qemu_get_be32(f);
4672 env->fpr[i] = u.f;
4675 qemu_get_betls(f, &env->pc);
4676 qemu_get_betls(f, &env->npc);
4677 qemu_get_betls(f, &env->y);
4678 tmp = qemu_get_be32(f);
4679 env->cwp = 0; /* needed to ensure that the wrapping registers are
4680 correctly updated */
4681 PUT_PSR(env, tmp);
4682 qemu_get_betls(f, &env->fsr);
4683 qemu_get_betls(f, &env->tbr);
4684 #ifndef TARGET_SPARC64
4685 qemu_get_be32s(f, &env->wim);
4686 /* MMU */
4687 for(i = 0; i < 16; i++)
4688 qemu_get_be32s(f, &env->mmuregs[i]);
4689 #endif
4690 tlb_flush(env, 1);
4691 return 0;
4694 #elif defined(TARGET_ARM)
4696 /* ??? Need to implement these. */
4697 void cpu_save(QEMUFile *f, void *opaque)
4701 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4703 return 0;
4706 #else
4708 #warning No CPU save/restore functions
4710 #endif
4712 /***********************************************************/
4713 /* ram save/restore */
4715 /* we just avoid storing empty pages */
4716 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4718 int i, v;
4720 v = buf[0];
4721 for(i = 1; i < len; i++) {
4722 if (buf[i] != v)
4723 goto normal_save;
4725 qemu_put_byte(f, 1);
4726 qemu_put_byte(f, v);
4727 return;
4728 normal_save:
4729 qemu_put_byte(f, 0);
4730 qemu_put_buffer(f, buf, len);
4733 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4735 int v;
4737 v = qemu_get_byte(f);
4738 switch(v) {
4739 case 0:
4740 if (qemu_get_buffer(f, buf, len) != len)
4741 return -EIO;
4742 break;
4743 case 1:
4744 v = qemu_get_byte(f);
4745 memset(buf, v, len);
4746 break;
4747 default:
4748 return -EINVAL;
4750 return 0;
4753 static void ram_save(QEMUFile *f, void *opaque)
4755 int i;
4756 qemu_put_be32(f, phys_ram_size);
4757 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4758 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4762 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4764 int i, ret;
4766 if (version_id != 1)
4767 return -EINVAL;
4768 if (qemu_get_be32(f) != phys_ram_size)
4769 return -EINVAL;
4770 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4771 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4772 if (ret)
4773 return ret;
4775 return 0;
4778 /***********************************************************/
4779 /* machine registration */
4781 QEMUMachine *first_machine = NULL;
4783 int qemu_register_machine(QEMUMachine *m)
4785 QEMUMachine **pm;
4786 pm = &first_machine;
4787 while (*pm != NULL)
4788 pm = &(*pm)->next;
4789 m->next = NULL;
4790 *pm = m;
4791 return 0;
4794 QEMUMachine *find_machine(const char *name)
4796 QEMUMachine *m;
4798 for(m = first_machine; m != NULL; m = m->next) {
4799 if (!strcmp(m->name, name))
4800 return m;
4802 return NULL;
4805 /***********************************************************/
4806 /* main execution loop */
4808 void gui_update(void *opaque)
4810 display_state.dpy_refresh(&display_state);
4811 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4814 struct vm_change_state_entry {
4815 VMChangeStateHandler *cb;
4816 void *opaque;
4817 LIST_ENTRY (vm_change_state_entry) entries;
4820 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4822 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4823 void *opaque)
4825 VMChangeStateEntry *e;
4827 e = qemu_mallocz(sizeof (*e));
4828 if (!e)
4829 return NULL;
4831 e->cb = cb;
4832 e->opaque = opaque;
4833 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4834 return e;
4837 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4839 LIST_REMOVE (e, entries);
4840 qemu_free (e);
4843 static void vm_state_notify(int running)
4845 VMChangeStateEntry *e;
4847 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4848 e->cb(e->opaque, running);
4852 /* XXX: support several handlers */
4853 static VMStopHandler *vm_stop_cb;
4854 static void *vm_stop_opaque;
4856 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4858 vm_stop_cb = cb;
4859 vm_stop_opaque = opaque;
4860 return 0;
4863 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4865 vm_stop_cb = NULL;
4868 void vm_start(void)
4870 if (!vm_running) {
4871 cpu_enable_ticks();
4872 vm_running = 1;
4873 vm_state_notify(1);
4877 void vm_stop(int reason)
4879 if (vm_running) {
4880 cpu_disable_ticks();
4881 vm_running = 0;
4882 if (reason != 0) {
4883 if (vm_stop_cb) {
4884 vm_stop_cb(vm_stop_opaque, reason);
4887 vm_state_notify(0);
4891 /* reset/shutdown handler */
4893 typedef struct QEMUResetEntry {
4894 QEMUResetHandler *func;
4895 void *opaque;
4896 struct QEMUResetEntry *next;
4897 } QEMUResetEntry;
4899 static QEMUResetEntry *first_reset_entry;
4900 static int reset_requested;
4901 static int shutdown_requested;
4902 static int powerdown_requested;
4904 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4906 QEMUResetEntry **pre, *re;
4908 pre = &first_reset_entry;
4909 while (*pre != NULL)
4910 pre = &(*pre)->next;
4911 re = qemu_mallocz(sizeof(QEMUResetEntry));
4912 re->func = func;
4913 re->opaque = opaque;
4914 re->next = NULL;
4915 *pre = re;
4918 void qemu_system_reset(void)
4920 QEMUResetEntry *re;
4922 /* reset all devices */
4923 for(re = first_reset_entry; re != NULL; re = re->next) {
4924 re->func(re->opaque);
4928 void qemu_system_reset_request(void)
4930 reset_requested = 1;
4931 if (cpu_single_env)
4932 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4935 void qemu_system_shutdown_request(void)
4937 shutdown_requested = 1;
4938 if (cpu_single_env)
4939 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4942 void qemu_system_powerdown_request(void)
4944 powerdown_requested = 1;
4945 if (cpu_single_env)
4946 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4949 void main_loop_wait(int timeout)
4951 IOHandlerRecord *ioh, *ioh_next;
4952 fd_set rfds, wfds, xfds;
4953 int ret, nfds;
4954 struct timeval tv;
4955 PollingEntry *pe;
4958 /* XXX: need to suppress polling by better using win32 events */
4959 ret = 0;
4960 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4961 ret |= pe->func(pe->opaque);
4963 #ifdef _WIN32
4964 if (ret == 0 && timeout > 0) {
4965 int err;
4966 WaitObjects *w = &wait_objects;
4968 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
4969 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4970 if (w->func[ret - WAIT_OBJECT_0])
4971 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4972 } else if (ret == WAIT_TIMEOUT) {
4973 } else {
4974 err = GetLastError();
4975 fprintf(stderr, "Wait error %d %d\n", ret, err);
4978 #endif
4979 /* poll any events */
4980 /* XXX: separate device handlers from system ones */
4981 nfds = -1;
4982 FD_ZERO(&rfds);
4983 FD_ZERO(&wfds);
4984 FD_ZERO(&xfds);
4985 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4986 if (ioh->fd_read &&
4987 (!ioh->fd_read_poll ||
4988 ioh->fd_read_poll(ioh->opaque) != 0)) {
4989 FD_SET(ioh->fd, &rfds);
4990 if (ioh->fd > nfds)
4991 nfds = ioh->fd;
4993 if (ioh->fd_write) {
4994 FD_SET(ioh->fd, &wfds);
4995 if (ioh->fd > nfds)
4996 nfds = ioh->fd;
5000 tv.tv_sec = 0;
5001 #ifdef _WIN32
5002 tv.tv_usec = 0;
5003 #else
5004 tv.tv_usec = timeout * 1000;
5005 #endif
5006 #if defined(CONFIG_SLIRP)
5007 if (slirp_inited) {
5008 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5010 #endif
5011 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5012 if (ret > 0) {
5013 /* XXX: better handling of removal */
5014 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5015 ioh_next = ioh->next;
5016 if (FD_ISSET(ioh->fd, &rfds)) {
5017 ioh->fd_read(ioh->opaque);
5019 if (FD_ISSET(ioh->fd, &wfds)) {
5020 ioh->fd_write(ioh->opaque);
5024 #if defined(CONFIG_SLIRP)
5025 if (slirp_inited) {
5026 if (ret < 0) {
5027 FD_ZERO(&rfds);
5028 FD_ZERO(&wfds);
5029 FD_ZERO(&xfds);
5031 slirp_select_poll(&rfds, &wfds, &xfds);
5033 #endif
5034 #ifdef _WIN32
5035 tap_win32_poll();
5036 #endif
5038 if (vm_running) {
5039 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5040 qemu_get_clock(vm_clock));
5041 /* run dma transfers, if any */
5042 DMA_run();
5045 /* real time timers */
5046 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5047 qemu_get_clock(rt_clock));
5050 static CPUState *cur_cpu;
5052 int main_loop(void)
5054 int ret, timeout;
5055 #ifdef CONFIG_PROFILER
5056 int64_t ti;
5057 #endif
5058 CPUState *env;
5060 cur_cpu = first_cpu;
5061 for(;;) {
5062 if (vm_running) {
5064 env = cur_cpu;
5065 for(;;) {
5066 /* get next cpu */
5067 env = env->next_cpu;
5068 if (!env)
5069 env = first_cpu;
5070 #ifdef CONFIG_PROFILER
5071 ti = profile_getclock();
5072 #endif
5073 ret = cpu_exec(env);
5074 #ifdef CONFIG_PROFILER
5075 qemu_time += profile_getclock() - ti;
5076 #endif
5077 if (ret != EXCP_HALTED)
5078 break;
5079 /* all CPUs are halted ? */
5080 if (env == cur_cpu) {
5081 ret = EXCP_HLT;
5082 break;
5085 cur_cpu = env;
5087 if (shutdown_requested) {
5088 ret = EXCP_INTERRUPT;
5089 break;
5091 if (reset_requested) {
5092 reset_requested = 0;
5093 qemu_system_reset();
5094 ret = EXCP_INTERRUPT;
5096 if (powerdown_requested) {
5097 powerdown_requested = 0;
5098 qemu_system_powerdown();
5099 ret = EXCP_INTERRUPT;
5101 if (ret == EXCP_DEBUG) {
5102 vm_stop(EXCP_DEBUG);
5104 /* if hlt instruction, we wait until the next IRQ */
5105 /* XXX: use timeout computed from timers */
5106 if (ret == EXCP_HLT)
5107 timeout = 10;
5108 else
5109 timeout = 0;
5110 } else {
5111 timeout = 10;
5113 #ifdef CONFIG_PROFILER
5114 ti = profile_getclock();
5115 #endif
5116 main_loop_wait(timeout);
5117 #ifdef CONFIG_PROFILER
5118 dev_time += profile_getclock() - ti;
5119 #endif
5121 cpu_disable_ticks();
5122 return ret;
5125 void help(void)
5127 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
5128 "usage: %s [options] [disk_image]\n"
5129 "\n"
5130 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5131 "\n"
5132 "Standard options:\n"
5133 "-M machine select emulated machine (-M ? for list)\n"
5134 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5135 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5136 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5137 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5138 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5139 "-snapshot write to temporary files instead of disk image files\n"
5140 #ifdef TARGET_I386
5141 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5142 #endif
5143 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5144 "-smp n set the number of CPUs to 'n' [default=1]\n"
5145 "-nographic disable graphical output and redirect serial I/Os to console\n"
5146 #ifndef _WIN32
5147 "-k language use keyboard layout (for example \"fr\" for French)\n"
5148 #endif
5149 #ifdef HAS_AUDIO
5150 "-audio-help print list of audio drivers and their options\n"
5151 "-soundhw c1,... enable audio support\n"
5152 " and only specified sound cards (comma separated list)\n"
5153 " use -soundhw ? to get the list of supported cards\n"
5154 " use -soundhw all to enable all of them\n"
5155 #endif
5156 "-localtime set the real time clock to local time [default=utc]\n"
5157 "-full-screen start in full screen\n"
5158 #ifdef TARGET_I386
5159 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5160 #endif
5161 "-usb enable the USB driver (will be the default soon)\n"
5162 "-usbdevice name add the host or guest USB device 'name'\n"
5163 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5164 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5165 #endif
5166 "\n"
5167 "Network options:\n"
5168 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5169 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5170 #ifdef CONFIG_SLIRP
5171 "-net user[,vlan=n][,hostname=host]\n"
5172 " connect the user mode network stack to VLAN 'n' and send\n"
5173 " hostname 'host' to DHCP clients\n"
5174 #endif
5175 #ifdef _WIN32
5176 "-net tap[,vlan=n],ifname=name\n"
5177 " connect the host TAP network interface to VLAN 'n'\n"
5178 #else
5179 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
5180 " connect the host TAP network interface to VLAN 'n' and use\n"
5181 " the network script 'file' (default=%s);\n"
5182 " use 'fd=h' to connect to an already opened TAP interface\n"
5183 #endif
5184 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5185 " connect the vlan 'n' to another VLAN using a socket connection\n"
5186 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5187 " connect the vlan 'n' to multicast maddr and port\n"
5188 "-net none use it alone to have zero network devices; if no -net option\n"
5189 " is provided, the default is '-net nic -net user'\n"
5190 "\n"
5191 #ifdef CONFIG_SLIRP
5192 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5193 #ifndef _WIN32
5194 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5195 #endif
5196 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5197 " redirect TCP or UDP connections from host to guest [-net user]\n"
5198 #endif
5199 "\n"
5200 "Linux boot specific:\n"
5201 "-kernel bzImage use 'bzImage' as kernel image\n"
5202 "-append cmdline use 'cmdline' as kernel command line\n"
5203 "-initrd file use 'file' as initial ram disk\n"
5204 "\n"
5205 "Debug/Expert options:\n"
5206 "-monitor dev redirect the monitor to char device 'dev'\n"
5207 "-serial dev redirect the serial port to char device 'dev'\n"
5208 "-parallel dev redirect the parallel port to char device 'dev'\n"
5209 "-pidfile file Write PID to 'file'\n"
5210 "-S freeze CPU at startup (use 'c' to start execution)\n"
5211 "-s wait gdb connection to port %d\n"
5212 "-p port change gdb connection port\n"
5213 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
5214 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5215 " translation (t=none or lba) (usually qemu can guess them)\n"
5216 "-L path set the directory for the BIOS and VGA BIOS\n"
5217 #ifdef USE_KQEMU
5218 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5219 "-no-kqemu disable KQEMU kernel module usage\n"
5220 #endif
5221 #ifdef USE_CODE_COPY
5222 "-no-code-copy disable code copy acceleration\n"
5223 #endif
5224 #ifdef TARGET_I386
5225 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5226 " (default is CL-GD5446 PCI VGA)\n"
5227 "-no-acpi disable ACPI\n"
5228 #endif
5229 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5230 "-vnc display start a VNC server on display\n"
5231 "\n"
5232 "During emulation, the following keys are useful:\n"
5233 "ctrl-alt-f toggle full screen\n"
5234 "ctrl-alt-n switch to virtual console 'n'\n"
5235 "ctrl-alt toggle mouse and keyboard grab\n"
5236 "\n"
5237 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5239 "qemu",
5240 DEFAULT_RAM_SIZE,
5241 #ifndef _WIN32
5242 DEFAULT_NETWORK_SCRIPT,
5243 #endif
5244 DEFAULT_GDBSTUB_PORT,
5245 "/tmp/qemu.log");
5246 exit(1);
5249 #define HAS_ARG 0x0001
5251 enum {
5252 QEMU_OPTION_h,
5254 QEMU_OPTION_M,
5255 QEMU_OPTION_fda,
5256 QEMU_OPTION_fdb,
5257 QEMU_OPTION_hda,
5258 QEMU_OPTION_hdb,
5259 QEMU_OPTION_hdc,
5260 QEMU_OPTION_hdd,
5261 QEMU_OPTION_cdrom,
5262 QEMU_OPTION_boot,
5263 QEMU_OPTION_snapshot,
5264 #ifdef TARGET_I386
5265 QEMU_OPTION_no_fd_bootchk,
5266 #endif
5267 QEMU_OPTION_m,
5268 QEMU_OPTION_nographic,
5269 #ifdef HAS_AUDIO
5270 QEMU_OPTION_audio_help,
5271 QEMU_OPTION_soundhw,
5272 #endif
5274 QEMU_OPTION_net,
5275 QEMU_OPTION_tftp,
5276 QEMU_OPTION_smb,
5277 QEMU_OPTION_redir,
5279 QEMU_OPTION_kernel,
5280 QEMU_OPTION_append,
5281 QEMU_OPTION_initrd,
5283 QEMU_OPTION_S,
5284 QEMU_OPTION_s,
5285 QEMU_OPTION_p,
5286 QEMU_OPTION_d,
5287 QEMU_OPTION_hdachs,
5288 QEMU_OPTION_L,
5289 QEMU_OPTION_no_code_copy,
5290 QEMU_OPTION_k,
5291 QEMU_OPTION_localtime,
5292 QEMU_OPTION_cirrusvga,
5293 QEMU_OPTION_g,
5294 QEMU_OPTION_std_vga,
5295 QEMU_OPTION_monitor,
5296 QEMU_OPTION_serial,
5297 QEMU_OPTION_parallel,
5298 QEMU_OPTION_loadvm,
5299 QEMU_OPTION_full_screen,
5300 QEMU_OPTION_pidfile,
5301 QEMU_OPTION_no_kqemu,
5302 QEMU_OPTION_kernel_kqemu,
5303 QEMU_OPTION_win2k_hack,
5304 QEMU_OPTION_usb,
5305 QEMU_OPTION_usbdevice,
5306 QEMU_OPTION_smp,
5307 QEMU_OPTION_vnc,
5308 QEMU_OPTION_no_acpi,
5311 typedef struct QEMUOption {
5312 const char *name;
5313 int flags;
5314 int index;
5315 } QEMUOption;
5317 const QEMUOption qemu_options[] = {
5318 { "h", 0, QEMU_OPTION_h },
5320 { "M", HAS_ARG, QEMU_OPTION_M },
5321 { "fda", HAS_ARG, QEMU_OPTION_fda },
5322 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5323 { "hda", HAS_ARG, QEMU_OPTION_hda },
5324 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5325 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5326 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5327 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5328 { "boot", HAS_ARG, QEMU_OPTION_boot },
5329 { "snapshot", 0, QEMU_OPTION_snapshot },
5330 #ifdef TARGET_I386
5331 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5332 #endif
5333 { "m", HAS_ARG, QEMU_OPTION_m },
5334 { "nographic", 0, QEMU_OPTION_nographic },
5335 { "k", HAS_ARG, QEMU_OPTION_k },
5336 #ifdef HAS_AUDIO
5337 { "audio-help", 0, QEMU_OPTION_audio_help },
5338 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5339 #endif
5341 { "net", HAS_ARG, QEMU_OPTION_net},
5342 #ifdef CONFIG_SLIRP
5343 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5344 #ifndef _WIN32
5345 { "smb", HAS_ARG, QEMU_OPTION_smb },
5346 #endif
5347 { "redir", HAS_ARG, QEMU_OPTION_redir },
5348 #endif
5350 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5351 { "append", HAS_ARG, QEMU_OPTION_append },
5352 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5354 { "S", 0, QEMU_OPTION_S },
5355 { "s", 0, QEMU_OPTION_s },
5356 { "p", HAS_ARG, QEMU_OPTION_p },
5357 { "d", HAS_ARG, QEMU_OPTION_d },
5358 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5359 { "L", HAS_ARG, QEMU_OPTION_L },
5360 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
5361 #ifdef USE_KQEMU
5362 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5363 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5364 #endif
5365 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5366 { "g", 1, QEMU_OPTION_g },
5367 #endif
5368 { "localtime", 0, QEMU_OPTION_localtime },
5369 { "std-vga", 0, QEMU_OPTION_std_vga },
5370 { "monitor", 1, QEMU_OPTION_monitor },
5371 { "serial", 1, QEMU_OPTION_serial },
5372 { "parallel", 1, QEMU_OPTION_parallel },
5373 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5374 { "full-screen", 0, QEMU_OPTION_full_screen },
5375 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5376 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5377 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5378 { "smp", HAS_ARG, QEMU_OPTION_smp },
5379 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5381 /* temporary options */
5382 { "usb", 0, QEMU_OPTION_usb },
5383 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
5384 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5385 { NULL },
5388 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5390 /* this stack is only used during signal handling */
5391 #define SIGNAL_STACK_SIZE 32768
5393 static uint8_t *signal_stack;
5395 #endif
5397 /* password input */
5399 static BlockDriverState *get_bdrv(int index)
5401 BlockDriverState *bs;
5403 if (index < 4) {
5404 bs = bs_table[index];
5405 } else if (index < 6) {
5406 bs = fd_table[index - 4];
5407 } else {
5408 bs = NULL;
5410 return bs;
5413 static void read_passwords(void)
5415 BlockDriverState *bs;
5416 int i, j;
5417 char password[256];
5419 for(i = 0; i < 6; i++) {
5420 bs = get_bdrv(i);
5421 if (bs && bdrv_is_encrypted(bs)) {
5422 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5423 for(j = 0; j < 3; j++) {
5424 monitor_readline("Password: ",
5425 1, password, sizeof(password));
5426 if (bdrv_set_key(bs, password) == 0)
5427 break;
5428 term_printf("invalid password\n");
5434 /* XXX: currently we cannot use simultaneously different CPUs */
5435 void register_machines(void)
5437 #if defined(TARGET_I386)
5438 qemu_register_machine(&pc_machine);
5439 qemu_register_machine(&isapc_machine);
5440 #elif defined(TARGET_PPC)
5441 qemu_register_machine(&heathrow_machine);
5442 qemu_register_machine(&core99_machine);
5443 qemu_register_machine(&prep_machine);
5444 #elif defined(TARGET_MIPS)
5445 qemu_register_machine(&mips_machine);
5446 #elif defined(TARGET_SPARC)
5447 #ifdef TARGET_SPARC64
5448 qemu_register_machine(&sun4u_machine);
5449 #else
5450 qemu_register_machine(&sun4m_machine);
5451 #endif
5452 #elif defined(TARGET_ARM)
5453 qemu_register_machine(&integratorcp926_machine);
5454 qemu_register_machine(&integratorcp1026_machine);
5455 qemu_register_machine(&versatilepb_machine);
5456 qemu_register_machine(&versatileab_machine);
5457 #elif defined(TARGET_SH4)
5458 qemu_register_machine(&shix_machine);
5459 #else
5460 #error unsupported CPU
5461 #endif
5464 #ifdef HAS_AUDIO
5465 struct soundhw soundhw[] = {
5466 #ifdef TARGET_I386
5468 "pcspk",
5469 "PC speaker",
5472 { .init_isa = pcspk_audio_init }
5474 #endif
5476 "sb16",
5477 "Creative Sound Blaster 16",
5480 { .init_isa = SB16_init }
5483 #ifdef CONFIG_ADLIB
5485 "adlib",
5486 #ifdef HAS_YMF262
5487 "Yamaha YMF262 (OPL3)",
5488 #else
5489 "Yamaha YM3812 (OPL2)",
5490 #endif
5493 { .init_isa = Adlib_init }
5495 #endif
5497 #ifdef CONFIG_GUS
5499 "gus",
5500 "Gravis Ultrasound GF1",
5503 { .init_isa = GUS_init }
5505 #endif
5508 "es1370",
5509 "ENSONIQ AudioPCI ES1370",
5512 { .init_pci = es1370_init }
5515 { NULL, NULL, 0, 0, { NULL } }
5518 static void select_soundhw (const char *optarg)
5520 struct soundhw *c;
5522 if (*optarg == '?') {
5523 show_valid_cards:
5525 printf ("Valid sound card names (comma separated):\n");
5526 for (c = soundhw; c->name; ++c) {
5527 printf ("%-11s %s\n", c->name, c->descr);
5529 printf ("\n-soundhw all will enable all of the above\n");
5530 exit (*optarg != '?');
5532 else {
5533 size_t l;
5534 const char *p;
5535 char *e;
5536 int bad_card = 0;
5538 if (!strcmp (optarg, "all")) {
5539 for (c = soundhw; c->name; ++c) {
5540 c->enabled = 1;
5542 return;
5545 p = optarg;
5546 while (*p) {
5547 e = strchr (p, ',');
5548 l = !e ? strlen (p) : (size_t) (e - p);
5550 for (c = soundhw; c->name; ++c) {
5551 if (!strncmp (c->name, p, l)) {
5552 c->enabled = 1;
5553 break;
5557 if (!c->name) {
5558 if (l > 80) {
5559 fprintf (stderr,
5560 "Unknown sound card name (too big to show)\n");
5562 else {
5563 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5564 (int) l, p);
5566 bad_card = 1;
5568 p += l + (e != NULL);
5571 if (bad_card)
5572 goto show_valid_cards;
5575 #endif
5577 #ifdef _WIN32
5578 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5580 exit(STATUS_CONTROL_C_EXIT);
5581 return TRUE;
5583 #endif
5585 #define MAX_NET_CLIENTS 32
5587 int main(int argc, char **argv)
5589 #ifdef CONFIG_GDBSTUB
5590 int use_gdbstub, gdbstub_port;
5591 #endif
5592 int i, cdrom_index;
5593 int snapshot, linux_boot;
5594 const char *initrd_filename;
5595 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5596 const char *kernel_filename, *kernel_cmdline;
5597 DisplayState *ds = &display_state;
5598 int cyls, heads, secs, translation;
5599 int start_emulation = 1;
5600 char net_clients[MAX_NET_CLIENTS][256];
5601 int nb_net_clients;
5602 int optind;
5603 const char *r, *optarg;
5604 CharDriverState *monitor_hd;
5605 char monitor_device[128];
5606 char serial_devices[MAX_SERIAL_PORTS][128];
5607 int serial_device_index;
5608 char parallel_devices[MAX_PARALLEL_PORTS][128];
5609 int parallel_device_index;
5610 const char *loadvm = NULL;
5611 QEMUMachine *machine;
5612 char usb_devices[MAX_USB_CMDLINE][128];
5613 int usb_devices_index;
5615 LIST_INIT (&vm_change_state_head);
5616 #ifndef _WIN32
5618 struct sigaction act;
5619 sigfillset(&act.sa_mask);
5620 act.sa_flags = 0;
5621 act.sa_handler = SIG_IGN;
5622 sigaction(SIGPIPE, &act, NULL);
5624 #else
5625 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5626 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5627 QEMU to run on a single CPU */
5629 HANDLE h;
5630 DWORD mask, smask;
5631 int i;
5632 h = GetCurrentProcess();
5633 if (GetProcessAffinityMask(h, &mask, &smask)) {
5634 for(i = 0; i < 32; i++) {
5635 if (mask & (1 << i))
5636 break;
5638 if (i != 32) {
5639 mask = 1 << i;
5640 SetProcessAffinityMask(h, mask);
5644 #endif
5646 register_machines();
5647 machine = first_machine;
5648 initrd_filename = NULL;
5649 for(i = 0; i < MAX_FD; i++)
5650 fd_filename[i] = NULL;
5651 for(i = 0; i < MAX_DISKS; i++)
5652 hd_filename[i] = NULL;
5653 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5654 vga_ram_size = VGA_RAM_SIZE;
5655 bios_size = BIOS_SIZE;
5656 #ifdef CONFIG_GDBSTUB
5657 use_gdbstub = 0;
5658 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5659 #endif
5660 snapshot = 0;
5661 nographic = 0;
5662 kernel_filename = NULL;
5663 kernel_cmdline = "";
5664 #ifdef TARGET_PPC
5665 cdrom_index = 1;
5666 #else
5667 cdrom_index = 2;
5668 #endif
5669 cyls = heads = secs = 0;
5670 translation = BIOS_ATA_TRANSLATION_AUTO;
5671 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5673 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5674 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5675 serial_devices[i][0] = '\0';
5676 serial_device_index = 0;
5678 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5679 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5680 parallel_devices[i][0] = '\0';
5681 parallel_device_index = 0;
5683 usb_devices_index = 0;
5685 nb_net_clients = 0;
5687 nb_nics = 0;
5688 /* default mac address of the first network interface */
5690 optind = 1;
5691 for(;;) {
5692 if (optind >= argc)
5693 break;
5694 r = argv[optind];
5695 if (r[0] != '-') {
5696 hd_filename[0] = argv[optind++];
5697 } else {
5698 const QEMUOption *popt;
5700 optind++;
5701 popt = qemu_options;
5702 for(;;) {
5703 if (!popt->name) {
5704 fprintf(stderr, "%s: invalid option -- '%s'\n",
5705 argv[0], r);
5706 exit(1);
5708 if (!strcmp(popt->name, r + 1))
5709 break;
5710 popt++;
5712 if (popt->flags & HAS_ARG) {
5713 if (optind >= argc) {
5714 fprintf(stderr, "%s: option '%s' requires an argument\n",
5715 argv[0], r);
5716 exit(1);
5718 optarg = argv[optind++];
5719 } else {
5720 optarg = NULL;
5723 switch(popt->index) {
5724 case QEMU_OPTION_M:
5725 machine = find_machine(optarg);
5726 if (!machine) {
5727 QEMUMachine *m;
5728 printf("Supported machines are:\n");
5729 for(m = first_machine; m != NULL; m = m->next) {
5730 printf("%-10s %s%s\n",
5731 m->name, m->desc,
5732 m == first_machine ? " (default)" : "");
5734 exit(1);
5736 break;
5737 case QEMU_OPTION_initrd:
5738 initrd_filename = optarg;
5739 break;
5740 case QEMU_OPTION_hda:
5741 case QEMU_OPTION_hdb:
5742 case QEMU_OPTION_hdc:
5743 case QEMU_OPTION_hdd:
5745 int hd_index;
5746 hd_index = popt->index - QEMU_OPTION_hda;
5747 hd_filename[hd_index] = optarg;
5748 if (hd_index == cdrom_index)
5749 cdrom_index = -1;
5751 break;
5752 case QEMU_OPTION_snapshot:
5753 snapshot = 1;
5754 break;
5755 case QEMU_OPTION_hdachs:
5757 const char *p;
5758 p = optarg;
5759 cyls = strtol(p, (char **)&p, 0);
5760 if (cyls < 1 || cyls > 16383)
5761 goto chs_fail;
5762 if (*p != ',')
5763 goto chs_fail;
5764 p++;
5765 heads = strtol(p, (char **)&p, 0);
5766 if (heads < 1 || heads > 16)
5767 goto chs_fail;
5768 if (*p != ',')
5769 goto chs_fail;
5770 p++;
5771 secs = strtol(p, (char **)&p, 0);
5772 if (secs < 1 || secs > 63)
5773 goto chs_fail;
5774 if (*p == ',') {
5775 p++;
5776 if (!strcmp(p, "none"))
5777 translation = BIOS_ATA_TRANSLATION_NONE;
5778 else if (!strcmp(p, "lba"))
5779 translation = BIOS_ATA_TRANSLATION_LBA;
5780 else if (!strcmp(p, "auto"))
5781 translation = BIOS_ATA_TRANSLATION_AUTO;
5782 else
5783 goto chs_fail;
5784 } else if (*p != '\0') {
5785 chs_fail:
5786 fprintf(stderr, "qemu: invalid physical CHS format\n");
5787 exit(1);
5790 break;
5791 case QEMU_OPTION_nographic:
5792 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5793 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5794 nographic = 1;
5795 break;
5796 case QEMU_OPTION_kernel:
5797 kernel_filename = optarg;
5798 break;
5799 case QEMU_OPTION_append:
5800 kernel_cmdline = optarg;
5801 break;
5802 case QEMU_OPTION_cdrom:
5803 if (cdrom_index >= 0) {
5804 hd_filename[cdrom_index] = optarg;
5806 break;
5807 case QEMU_OPTION_boot:
5808 boot_device = optarg[0];
5809 if (boot_device != 'a' &&
5810 #ifdef TARGET_SPARC
5811 // Network boot
5812 boot_device != 'n' &&
5813 #endif
5814 boot_device != 'c' && boot_device != 'd') {
5815 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5816 exit(1);
5818 break;
5819 case QEMU_OPTION_fda:
5820 fd_filename[0] = optarg;
5821 break;
5822 case QEMU_OPTION_fdb:
5823 fd_filename[1] = optarg;
5824 break;
5825 #ifdef TARGET_I386
5826 case QEMU_OPTION_no_fd_bootchk:
5827 fd_bootchk = 0;
5828 break;
5829 #endif
5830 case QEMU_OPTION_no_code_copy:
5831 code_copy_enabled = 0;
5832 break;
5833 case QEMU_OPTION_net:
5834 if (nb_net_clients >= MAX_NET_CLIENTS) {
5835 fprintf(stderr, "qemu: too many network clients\n");
5836 exit(1);
5838 pstrcpy(net_clients[nb_net_clients],
5839 sizeof(net_clients[0]),
5840 optarg);
5841 nb_net_clients++;
5842 break;
5843 #ifdef CONFIG_SLIRP
5844 case QEMU_OPTION_tftp:
5845 tftp_prefix = optarg;
5846 break;
5847 #ifndef _WIN32
5848 case QEMU_OPTION_smb:
5849 net_slirp_smb(optarg);
5850 break;
5851 #endif
5852 case QEMU_OPTION_redir:
5853 net_slirp_redir(optarg);
5854 break;
5855 #endif
5856 #ifdef HAS_AUDIO
5857 case QEMU_OPTION_audio_help:
5858 AUD_help ();
5859 exit (0);
5860 break;
5861 case QEMU_OPTION_soundhw:
5862 select_soundhw (optarg);
5863 break;
5864 #endif
5865 case QEMU_OPTION_h:
5866 help();
5867 break;
5868 case QEMU_OPTION_m:
5869 ram_size = atoi(optarg) * 1024 * 1024;
5870 if (ram_size <= 0)
5871 help();
5872 if (ram_size > PHYS_RAM_MAX_SIZE) {
5873 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5874 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5875 exit(1);
5877 break;
5878 case QEMU_OPTION_d:
5880 int mask;
5881 CPULogItem *item;
5883 mask = cpu_str_to_log_mask(optarg);
5884 if (!mask) {
5885 printf("Log items (comma separated):\n");
5886 for(item = cpu_log_items; item->mask != 0; item++) {
5887 printf("%-10s %s\n", item->name, item->help);
5889 exit(1);
5891 cpu_set_log(mask);
5893 break;
5894 #ifdef CONFIG_GDBSTUB
5895 case QEMU_OPTION_s:
5896 use_gdbstub = 1;
5897 break;
5898 case QEMU_OPTION_p:
5899 gdbstub_port = atoi(optarg);
5900 break;
5901 #endif
5902 case QEMU_OPTION_L:
5903 bios_dir = optarg;
5904 break;
5905 case QEMU_OPTION_S:
5906 start_emulation = 0;
5907 break;
5908 case QEMU_OPTION_k:
5909 keyboard_layout = optarg;
5910 break;
5911 case QEMU_OPTION_localtime:
5912 rtc_utc = 0;
5913 break;
5914 case QEMU_OPTION_cirrusvga:
5915 cirrus_vga_enabled = 1;
5916 break;
5917 case QEMU_OPTION_std_vga:
5918 cirrus_vga_enabled = 0;
5919 break;
5920 case QEMU_OPTION_g:
5922 const char *p;
5923 int w, h, depth;
5924 p = optarg;
5925 w = strtol(p, (char **)&p, 10);
5926 if (w <= 0) {
5927 graphic_error:
5928 fprintf(stderr, "qemu: invalid resolution or depth\n");
5929 exit(1);
5931 if (*p != 'x')
5932 goto graphic_error;
5933 p++;
5934 h = strtol(p, (char **)&p, 10);
5935 if (h <= 0)
5936 goto graphic_error;
5937 if (*p == 'x') {
5938 p++;
5939 depth = strtol(p, (char **)&p, 10);
5940 if (depth != 8 && depth != 15 && depth != 16 &&
5941 depth != 24 && depth != 32)
5942 goto graphic_error;
5943 } else if (*p == '\0') {
5944 depth = graphic_depth;
5945 } else {
5946 goto graphic_error;
5949 graphic_width = w;
5950 graphic_height = h;
5951 graphic_depth = depth;
5953 break;
5954 case QEMU_OPTION_monitor:
5955 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5956 break;
5957 case QEMU_OPTION_serial:
5958 if (serial_device_index >= MAX_SERIAL_PORTS) {
5959 fprintf(stderr, "qemu: too many serial ports\n");
5960 exit(1);
5962 pstrcpy(serial_devices[serial_device_index],
5963 sizeof(serial_devices[0]), optarg);
5964 serial_device_index++;
5965 break;
5966 case QEMU_OPTION_parallel:
5967 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5968 fprintf(stderr, "qemu: too many parallel ports\n");
5969 exit(1);
5971 pstrcpy(parallel_devices[parallel_device_index],
5972 sizeof(parallel_devices[0]), optarg);
5973 parallel_device_index++;
5974 break;
5975 case QEMU_OPTION_loadvm:
5976 loadvm = optarg;
5977 break;
5978 case QEMU_OPTION_full_screen:
5979 full_screen = 1;
5980 break;
5981 case QEMU_OPTION_pidfile:
5982 create_pidfile(optarg);
5983 break;
5984 #ifdef TARGET_I386
5985 case QEMU_OPTION_win2k_hack:
5986 win2k_install_hack = 1;
5987 break;
5988 #endif
5989 #ifdef USE_KQEMU
5990 case QEMU_OPTION_no_kqemu:
5991 kqemu_allowed = 0;
5992 break;
5993 case QEMU_OPTION_kernel_kqemu:
5994 kqemu_allowed = 2;
5995 break;
5996 #endif
5997 case QEMU_OPTION_usb:
5998 usb_enabled = 1;
5999 break;
6000 case QEMU_OPTION_usbdevice:
6001 usb_enabled = 1;
6002 if (usb_devices_index >= MAX_USB_CMDLINE) {
6003 fprintf(stderr, "Too many USB devices\n");
6004 exit(1);
6006 pstrcpy(usb_devices[usb_devices_index],
6007 sizeof(usb_devices[usb_devices_index]),
6008 optarg);
6009 usb_devices_index++;
6010 break;
6011 case QEMU_OPTION_smp:
6012 smp_cpus = atoi(optarg);
6013 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6014 fprintf(stderr, "Invalid number of CPUs\n");
6015 exit(1);
6017 break;
6018 case QEMU_OPTION_vnc:
6019 vnc_display = atoi(optarg);
6020 if (vnc_display < 0) {
6021 fprintf(stderr, "Invalid VNC display\n");
6022 exit(1);
6024 break;
6025 case QEMU_OPTION_no_acpi:
6026 acpi_enabled = 0;
6027 break;
6032 #ifdef USE_KQEMU
6033 if (smp_cpus > 1)
6034 kqemu_allowed = 0;
6035 #endif
6036 linux_boot = (kernel_filename != NULL);
6038 if (!linux_boot &&
6039 hd_filename[0] == '\0' &&
6040 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6041 fd_filename[0] == '\0')
6042 help();
6044 /* boot to cd by default if no hard disk */
6045 if (hd_filename[0] == '\0' && boot_device == 'c') {
6046 if (fd_filename[0] != '\0')
6047 boot_device = 'a';
6048 else
6049 boot_device = 'd';
6052 setvbuf(stdout, NULL, _IOLBF, 0);
6054 init_timers();
6055 init_timer_alarm();
6057 #ifdef _WIN32
6058 socket_init();
6059 #endif
6061 /* init network clients */
6062 if (nb_net_clients == 0) {
6063 /* if no clients, we use a default config */
6064 pstrcpy(net_clients[0], sizeof(net_clients[0]),
6065 "nic");
6066 pstrcpy(net_clients[1], sizeof(net_clients[0]),
6067 "user");
6068 nb_net_clients = 2;
6071 for(i = 0;i < nb_net_clients; i++) {
6072 if (net_client_init(net_clients[i]) < 0)
6073 exit(1);
6076 /* init the memory */
6077 #if USE_KVM
6078 phys_ram_size = ram_size + vga_ram_size + bios_size + KVM_EXTRA_PAGES * 4096;
6079 kvm_qemu_init();
6080 #else
6081 phys_ram_size = ram_size + vga_ram_size + bios_size;
6082 phys_ram_base = qemu_vmalloc(phys_ram_size);
6083 if (!phys_ram_base) {
6084 fprintf(stderr, "Could not allocate physical memory\n");
6085 exit(1);
6087 #endif
6089 /* we always create the cdrom drive, even if no disk is there */
6090 bdrv_init();
6091 if (cdrom_index >= 0) {
6092 bs_table[cdrom_index] = bdrv_new("cdrom");
6093 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6096 /* open the virtual block devices */
6097 for(i = 0; i < MAX_DISKS; i++) {
6098 if (hd_filename[i]) {
6099 if (!bs_table[i]) {
6100 char buf[64];
6101 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6102 bs_table[i] = bdrv_new(buf);
6104 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
6105 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6106 hd_filename[i]);
6107 exit(1);
6109 if (i == 0 && cyls != 0) {
6110 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6111 bdrv_set_translation_hint(bs_table[i], translation);
6116 /* we always create at least one floppy disk */
6117 fd_table[0] = bdrv_new("fda");
6118 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6120 for(i = 0; i < MAX_FD; i++) {
6121 if (fd_filename[i]) {
6122 if (!fd_table[i]) {
6123 char buf[64];
6124 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6125 fd_table[i] = bdrv_new(buf);
6126 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6128 if (fd_filename[i] != '\0') {
6129 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
6130 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6131 fd_filename[i]);
6132 exit(1);
6138 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
6139 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
6141 init_ioports();
6143 /* terminal init */
6144 if (nographic) {
6145 dumb_display_init(ds);
6146 } else if (vnc_display != -1) {
6147 vnc_display_init(ds, vnc_display);
6148 } else {
6149 #if defined(CONFIG_SDL)
6150 sdl_display_init(ds, full_screen);
6151 #elif defined(CONFIG_COCOA)
6152 cocoa_display_init(ds, full_screen);
6153 #else
6154 dumb_display_init(ds);
6155 #endif
6158 monitor_hd = qemu_chr_open(monitor_device);
6159 if (!monitor_hd) {
6160 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6161 exit(1);
6163 monitor_init(monitor_hd, !nographic);
6165 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6166 if (serial_devices[i][0] != '\0') {
6167 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6168 if (!serial_hds[i]) {
6169 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6170 serial_devices[i]);
6171 exit(1);
6173 if (!strcmp(serial_devices[i], "vc"))
6174 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6178 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6179 if (parallel_devices[i][0] != '\0') {
6180 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6181 if (!parallel_hds[i]) {
6182 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6183 parallel_devices[i]);
6184 exit(1);
6186 if (!strcmp(parallel_devices[i], "vc"))
6187 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6191 machine->init(ram_size, vga_ram_size, boot_device,
6192 ds, fd_filename, snapshot,
6193 kernel_filename, kernel_cmdline, initrd_filename);
6195 /* init USB devices */
6196 if (usb_enabled) {
6197 for(i = 0; i < usb_devices_index; i++) {
6198 if (usb_device_add(usb_devices[i]) < 0) {
6199 fprintf(stderr, "Warning: could not add USB device %s\n",
6200 usb_devices[i]);
6205 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6206 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6208 #ifdef CONFIG_GDBSTUB
6209 if (use_gdbstub) {
6210 if (gdbserver_start(gdbstub_port) < 0) {
6211 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6212 gdbstub_port);
6213 exit(1);
6214 } else {
6215 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6217 } else
6218 #endif
6219 if (loadvm)
6220 qemu_loadvm(loadvm);
6223 /* XXX: simplify init */
6224 read_passwords();
6225 if (start_emulation) {
6226 vm_start();
6229 main_loop();
6230 quit_timers();
6231 return 0;