Flush IO requests before savevm (original patch by Blue Swirl).
[qemu/mini2440.git] / vl.c
blob32c994366cac8227d4349ad99bd9f23476cecc11
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2006 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>
32 #include <zlib.h>
34 #ifndef _WIN32
35 #include <sys/times.h>
36 #include <sys/wait.h>
37 #include <termios.h>
38 #include <sys/poll.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <dirent.h>
44 #include <netdb.h>
45 #ifdef _BSD
46 #include <sys/stat.h>
47 #ifndef __APPLE__
48 #include <libutil.h>
49 #endif
50 #else
51 #ifndef __sun__
52 #include <linux/if.h>
53 #include <linux/if_tun.h>
54 #include <pty.h>
55 #include <malloc.h>
56 #include <linux/rtc.h>
57 #include <linux/ppdev.h>
58 #endif
59 #endif
60 #endif
62 #if defined(CONFIG_SLIRP)
63 #include "libslirp.h"
64 #endif
66 #ifdef _WIN32
67 #include <malloc.h>
68 #include <sys/timeb.h>
69 #include <windows.h>
70 #define getopt_long_only getopt_long
71 #define memalign(align, size) malloc(size)
72 #endif
74 #include "qemu_socket.h"
76 #ifdef CONFIG_SDL
77 #ifdef __APPLE__
78 #include <SDL/SDL.h>
79 #endif
80 #endif /* CONFIG_SDL */
82 #ifdef CONFIG_COCOA
83 #undef main
84 #define main qemu_main
85 #endif /* CONFIG_COCOA */
87 #include "disas.h"
89 #include "exec-all.h"
91 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
93 //#define DEBUG_UNUSED_IOPORT
94 //#define DEBUG_IOPORT
96 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
98 #ifdef TARGET_PPC
99 #define DEFAULT_RAM_SIZE 144
100 #else
101 #define DEFAULT_RAM_SIZE 128
102 #endif
103 /* in ms */
104 #define GUI_REFRESH_INTERVAL 30
106 /* Max number of USB devices that can be specified on the commandline. */
107 #define MAX_USB_CMDLINE 8
109 /* XXX: use a two level table to limit memory usage */
110 #define MAX_IOPORTS 65536
112 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
113 char phys_ram_file[1024];
114 void *ioport_opaque[MAX_IOPORTS];
115 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
116 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
117 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
118 to store the VM snapshots */
119 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
120 /* point to the block driver where the snapshots are managed */
121 BlockDriverState *bs_snapshots;
122 int vga_ram_size;
123 int bios_size;
124 static DisplayState display_state;
125 int nographic;
126 const char* keyboard_layout = NULL;
127 int64_t ticks_per_sec;
128 int boot_device = 'c';
129 int ram_size;
130 int pit_min_timer_count = 0;
131 int nb_nics;
132 NICInfo nd_table[MAX_NICS];
133 QEMUTimer *gui_timer;
134 int vm_running;
135 int rtc_utc = 1;
136 int cirrus_vga_enabled = 1;
137 #ifdef TARGET_SPARC
138 int graphic_width = 1024;
139 int graphic_height = 768;
140 #else
141 int graphic_width = 800;
142 int graphic_height = 600;
143 #endif
144 int graphic_depth = 15;
145 int full_screen = 0;
146 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
147 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
148 #ifdef TARGET_I386
149 int win2k_install_hack = 0;
150 #endif
151 int usb_enabled = 0;
152 static VLANState *first_vlan;
153 int smp_cpus = 1;
154 int vnc_display = -1;
155 #if defined(TARGET_SPARC)
156 #define MAX_CPUS 16
157 #elif defined(TARGET_I386)
158 #define MAX_CPUS 255
159 #else
160 #define MAX_CPUS 1
161 #endif
162 int acpi_enabled = 1;
163 int fd_bootchk = 1;
165 /***********************************************************/
166 /* x86 ISA bus support */
168 target_phys_addr_t isa_mem_base = 0;
169 PicState2 *isa_pic;
171 uint32_t default_ioport_readb(void *opaque, uint32_t address)
173 #ifdef DEBUG_UNUSED_IOPORT
174 fprintf(stderr, "inb: port=0x%04x\n", address);
175 #endif
176 return 0xff;
179 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
181 #ifdef DEBUG_UNUSED_IOPORT
182 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
183 #endif
186 /* default is to make two byte accesses */
187 uint32_t default_ioport_readw(void *opaque, uint32_t address)
189 uint32_t data;
190 data = ioport_read_table[0][address](ioport_opaque[address], address);
191 address = (address + 1) & (MAX_IOPORTS - 1);
192 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
193 return data;
196 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
198 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
199 address = (address + 1) & (MAX_IOPORTS - 1);
200 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
203 uint32_t default_ioport_readl(void *opaque, uint32_t address)
205 #ifdef DEBUG_UNUSED_IOPORT
206 fprintf(stderr, "inl: port=0x%04x\n", address);
207 #endif
208 return 0xffffffff;
211 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
213 #ifdef DEBUG_UNUSED_IOPORT
214 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
215 #endif
218 void init_ioports(void)
220 int i;
222 for(i = 0; i < MAX_IOPORTS; i++) {
223 ioport_read_table[0][i] = default_ioport_readb;
224 ioport_write_table[0][i] = default_ioport_writeb;
225 ioport_read_table[1][i] = default_ioport_readw;
226 ioport_write_table[1][i] = default_ioport_writew;
227 ioport_read_table[2][i] = default_ioport_readl;
228 ioport_write_table[2][i] = default_ioport_writel;
232 /* size is the word size in byte */
233 int register_ioport_read(int start, int length, int size,
234 IOPortReadFunc *func, void *opaque)
236 int i, bsize;
238 if (size == 1) {
239 bsize = 0;
240 } else if (size == 2) {
241 bsize = 1;
242 } else if (size == 4) {
243 bsize = 2;
244 } else {
245 hw_error("register_ioport_read: invalid size");
246 return -1;
248 for(i = start; i < start + length; i += size) {
249 ioport_read_table[bsize][i] = func;
250 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
251 hw_error("register_ioport_read: invalid opaque");
252 ioport_opaque[i] = opaque;
254 return 0;
257 /* size is the word size in byte */
258 int register_ioport_write(int start, int length, int size,
259 IOPortWriteFunc *func, void *opaque)
261 int i, bsize;
263 if (size == 1) {
264 bsize = 0;
265 } else if (size == 2) {
266 bsize = 1;
267 } else if (size == 4) {
268 bsize = 2;
269 } else {
270 hw_error("register_ioport_write: invalid size");
271 return -1;
273 for(i = start; i < start + length; i += size) {
274 ioport_write_table[bsize][i] = func;
275 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
276 hw_error("register_ioport_read: invalid opaque");
277 ioport_opaque[i] = opaque;
279 return 0;
282 void isa_unassign_ioport(int start, int length)
284 int i;
286 for(i = start; i < start + length; i++) {
287 ioport_read_table[0][i] = default_ioport_readb;
288 ioport_read_table[1][i] = default_ioport_readw;
289 ioport_read_table[2][i] = default_ioport_readl;
291 ioport_write_table[0][i] = default_ioport_writeb;
292 ioport_write_table[1][i] = default_ioport_writew;
293 ioport_write_table[2][i] = default_ioport_writel;
297 /***********************************************************/
299 void pstrcpy(char *buf, int buf_size, const char *str)
301 int c;
302 char *q = buf;
304 if (buf_size <= 0)
305 return;
307 for(;;) {
308 c = *str++;
309 if (c == 0 || q >= buf + buf_size - 1)
310 break;
311 *q++ = c;
313 *q = '\0';
316 /* strcat and truncate. */
317 char *pstrcat(char *buf, int buf_size, const char *s)
319 int len;
320 len = strlen(buf);
321 if (len < buf_size)
322 pstrcpy(buf + len, buf_size - len, s);
323 return buf;
326 int strstart(const char *str, const char *val, const char **ptr)
328 const char *p, *q;
329 p = str;
330 q = val;
331 while (*q != '\0') {
332 if (*p != *q)
333 return 0;
334 p++;
335 q++;
337 if (ptr)
338 *ptr = p;
339 return 1;
342 void cpu_outb(CPUState *env, int addr, int val)
344 #ifdef DEBUG_IOPORT
345 if (loglevel & CPU_LOG_IOPORT)
346 fprintf(logfile, "outb: %04x %02x\n", addr, val);
347 #endif
348 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
349 #ifdef USE_KQEMU
350 if (env)
351 env->last_io_time = cpu_get_time_fast();
352 #endif
355 void cpu_outw(CPUState *env, int addr, int val)
357 #ifdef DEBUG_IOPORT
358 if (loglevel & CPU_LOG_IOPORT)
359 fprintf(logfile, "outw: %04x %04x\n", addr, val);
360 #endif
361 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
362 #ifdef USE_KQEMU
363 if (env)
364 env->last_io_time = cpu_get_time_fast();
365 #endif
368 void cpu_outl(CPUState *env, int addr, int val)
370 #ifdef DEBUG_IOPORT
371 if (loglevel & CPU_LOG_IOPORT)
372 fprintf(logfile, "outl: %04x %08x\n", addr, val);
373 #endif
374 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
375 #ifdef USE_KQEMU
376 if (env)
377 env->last_io_time = cpu_get_time_fast();
378 #endif
381 int cpu_inb(CPUState *env, int addr)
383 int val;
384 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
385 #ifdef DEBUG_IOPORT
386 if (loglevel & CPU_LOG_IOPORT)
387 fprintf(logfile, "inb : %04x %02x\n", addr, val);
388 #endif
389 #ifdef USE_KQEMU
390 if (env)
391 env->last_io_time = cpu_get_time_fast();
392 #endif
393 return val;
396 int cpu_inw(CPUState *env, int addr)
398 int val;
399 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
400 #ifdef DEBUG_IOPORT
401 if (loglevel & CPU_LOG_IOPORT)
402 fprintf(logfile, "inw : %04x %04x\n", addr, val);
403 #endif
404 #ifdef USE_KQEMU
405 if (env)
406 env->last_io_time = cpu_get_time_fast();
407 #endif
408 return val;
411 int cpu_inl(CPUState *env, int addr)
413 int val;
414 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
415 #ifdef DEBUG_IOPORT
416 if (loglevel & CPU_LOG_IOPORT)
417 fprintf(logfile, "inl : %04x %08x\n", addr, val);
418 #endif
419 #ifdef USE_KQEMU
420 if (env)
421 env->last_io_time = cpu_get_time_fast();
422 #endif
423 return val;
426 /***********************************************************/
427 void hw_error(const char *fmt, ...)
429 va_list ap;
430 CPUState *env;
432 va_start(ap, fmt);
433 fprintf(stderr, "qemu: hardware error: ");
434 vfprintf(stderr, fmt, ap);
435 fprintf(stderr, "\n");
436 for(env = first_cpu; env != NULL; env = env->next_cpu) {
437 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
438 #ifdef TARGET_I386
439 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
440 #else
441 cpu_dump_state(env, stderr, fprintf, 0);
442 #endif
444 va_end(ap);
445 abort();
448 /***********************************************************/
449 /* keyboard/mouse */
451 static QEMUPutKBDEvent *qemu_put_kbd_event;
452 static void *qemu_put_kbd_event_opaque;
453 static QEMUPutMouseEvent *qemu_put_mouse_event;
454 static void *qemu_put_mouse_event_opaque;
455 static int qemu_put_mouse_event_absolute;
457 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
459 qemu_put_kbd_event_opaque = opaque;
460 qemu_put_kbd_event = func;
463 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
465 qemu_put_mouse_event_opaque = opaque;
466 qemu_put_mouse_event = func;
467 qemu_put_mouse_event_absolute = absolute;
470 void kbd_put_keycode(int keycode)
472 if (qemu_put_kbd_event) {
473 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
477 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
479 if (qemu_put_mouse_event) {
480 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
481 dx, dy, dz, buttons_state);
485 int kbd_mouse_is_absolute(void)
487 return qemu_put_mouse_event_absolute;
490 /* compute with 96 bit intermediate result: (a*b)/c */
491 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
493 union {
494 uint64_t ll;
495 struct {
496 #ifdef WORDS_BIGENDIAN
497 uint32_t high, low;
498 #else
499 uint32_t low, high;
500 #endif
501 } l;
502 } u, res;
503 uint64_t rl, rh;
505 u.ll = a;
506 rl = (uint64_t)u.l.low * (uint64_t)b;
507 rh = (uint64_t)u.l.high * (uint64_t)b;
508 rh += (rl >> 32);
509 res.l.high = rh / c;
510 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
511 return res.ll;
514 /***********************************************************/
515 /* real time host monotonic timer */
517 #define QEMU_TIMER_BASE 1000000000LL
519 #ifdef WIN32
521 static int64_t clock_freq;
523 static void init_get_clock(void)
525 LARGE_INTEGER freq;
526 int ret;
527 ret = QueryPerformanceFrequency(&freq);
528 if (ret == 0) {
529 fprintf(stderr, "Could not calibrate ticks\n");
530 exit(1);
532 clock_freq = freq.QuadPart;
535 static int64_t get_clock(void)
537 LARGE_INTEGER ti;
538 QueryPerformanceCounter(&ti);
539 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
542 #else
544 static int use_rt_clock;
546 static void init_get_clock(void)
548 use_rt_clock = 0;
549 #if defined(__linux__)
551 struct timespec ts;
552 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
553 use_rt_clock = 1;
556 #endif
559 static int64_t get_clock(void)
561 #if defined(__linux__)
562 if (use_rt_clock) {
563 struct timespec ts;
564 clock_gettime(CLOCK_MONOTONIC, &ts);
565 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
566 } else
567 #endif
569 /* XXX: using gettimeofday leads to problems if the date
570 changes, so it should be avoided. */
571 struct timeval tv;
572 gettimeofday(&tv, NULL);
573 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
577 #endif
579 /***********************************************************/
580 /* guest cycle counter */
582 static int64_t cpu_ticks_prev;
583 static int64_t cpu_ticks_offset;
584 static int64_t cpu_clock_offset;
585 static int cpu_ticks_enabled;
587 /* return the host CPU cycle counter and handle stop/restart */
588 int64_t cpu_get_ticks(void)
590 if (!cpu_ticks_enabled) {
591 return cpu_ticks_offset;
592 } else {
593 int64_t ticks;
594 ticks = cpu_get_real_ticks();
595 if (cpu_ticks_prev > ticks) {
596 /* Note: non increasing ticks may happen if the host uses
597 software suspend */
598 cpu_ticks_offset += cpu_ticks_prev - ticks;
600 cpu_ticks_prev = ticks;
601 return ticks + cpu_ticks_offset;
605 /* return the host CPU monotonic timer and handle stop/restart */
606 static int64_t cpu_get_clock(void)
608 int64_t ti;
609 if (!cpu_ticks_enabled) {
610 return cpu_clock_offset;
611 } else {
612 ti = get_clock();
613 return ti + cpu_clock_offset;
617 /* enable cpu_get_ticks() */
618 void cpu_enable_ticks(void)
620 if (!cpu_ticks_enabled) {
621 cpu_ticks_offset -= cpu_get_real_ticks();
622 cpu_clock_offset -= get_clock();
623 cpu_ticks_enabled = 1;
627 /* disable cpu_get_ticks() : the clock is stopped. You must not call
628 cpu_get_ticks() after that. */
629 void cpu_disable_ticks(void)
631 if (cpu_ticks_enabled) {
632 cpu_ticks_offset = cpu_get_ticks();
633 cpu_clock_offset = cpu_get_clock();
634 cpu_ticks_enabled = 0;
638 /***********************************************************/
639 /* timers */
641 #define QEMU_TIMER_REALTIME 0
642 #define QEMU_TIMER_VIRTUAL 1
644 struct QEMUClock {
645 int type;
646 /* XXX: add frequency */
649 struct QEMUTimer {
650 QEMUClock *clock;
651 int64_t expire_time;
652 QEMUTimerCB *cb;
653 void *opaque;
654 struct QEMUTimer *next;
657 QEMUClock *rt_clock;
658 QEMUClock *vm_clock;
660 static QEMUTimer *active_timers[2];
661 #ifdef _WIN32
662 static MMRESULT timerID;
663 static HANDLE host_alarm = NULL;
664 static unsigned int period = 1;
665 #else
666 /* frequency of the times() clock tick */
667 static int timer_freq;
668 #endif
670 QEMUClock *qemu_new_clock(int type)
672 QEMUClock *clock;
673 clock = qemu_mallocz(sizeof(QEMUClock));
674 if (!clock)
675 return NULL;
676 clock->type = type;
677 return clock;
680 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
682 QEMUTimer *ts;
684 ts = qemu_mallocz(sizeof(QEMUTimer));
685 ts->clock = clock;
686 ts->cb = cb;
687 ts->opaque = opaque;
688 return ts;
691 void qemu_free_timer(QEMUTimer *ts)
693 qemu_free(ts);
696 /* stop a timer, but do not dealloc it */
697 void qemu_del_timer(QEMUTimer *ts)
699 QEMUTimer **pt, *t;
701 /* NOTE: this code must be signal safe because
702 qemu_timer_expired() can be called from a signal. */
703 pt = &active_timers[ts->clock->type];
704 for(;;) {
705 t = *pt;
706 if (!t)
707 break;
708 if (t == ts) {
709 *pt = t->next;
710 break;
712 pt = &t->next;
716 /* modify the current timer so that it will be fired when current_time
717 >= expire_time. The corresponding callback will be called. */
718 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
720 QEMUTimer **pt, *t;
722 qemu_del_timer(ts);
724 /* add the timer in the sorted list */
725 /* NOTE: this code must be signal safe because
726 qemu_timer_expired() can be called from a signal. */
727 pt = &active_timers[ts->clock->type];
728 for(;;) {
729 t = *pt;
730 if (!t)
731 break;
732 if (t->expire_time > expire_time)
733 break;
734 pt = &t->next;
736 ts->expire_time = expire_time;
737 ts->next = *pt;
738 *pt = ts;
741 int qemu_timer_pending(QEMUTimer *ts)
743 QEMUTimer *t;
744 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
745 if (t == ts)
746 return 1;
748 return 0;
751 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
753 if (!timer_head)
754 return 0;
755 return (timer_head->expire_time <= current_time);
758 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
760 QEMUTimer *ts;
762 for(;;) {
763 ts = *ptimer_head;
764 if (!ts || ts->expire_time > current_time)
765 break;
766 /* remove timer from the list before calling the callback */
767 *ptimer_head = ts->next;
768 ts->next = NULL;
770 /* run the callback (the timer list can be modified) */
771 ts->cb(ts->opaque);
775 int64_t qemu_get_clock(QEMUClock *clock)
777 switch(clock->type) {
778 case QEMU_TIMER_REALTIME:
779 return get_clock() / 1000000;
780 default:
781 case QEMU_TIMER_VIRTUAL:
782 return cpu_get_clock();
786 static void init_timers(void)
788 init_get_clock();
789 ticks_per_sec = QEMU_TIMER_BASE;
790 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
791 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
794 /* save a timer */
795 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
797 uint64_t expire_time;
799 if (qemu_timer_pending(ts)) {
800 expire_time = ts->expire_time;
801 } else {
802 expire_time = -1;
804 qemu_put_be64(f, expire_time);
807 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
809 uint64_t expire_time;
811 expire_time = qemu_get_be64(f);
812 if (expire_time != -1) {
813 qemu_mod_timer(ts, expire_time);
814 } else {
815 qemu_del_timer(ts);
819 static void timer_save(QEMUFile *f, void *opaque)
821 if (cpu_ticks_enabled) {
822 hw_error("cannot save state if virtual timers are running");
824 qemu_put_be64s(f, &cpu_ticks_offset);
825 qemu_put_be64s(f, &ticks_per_sec);
826 qemu_put_be64s(f, &cpu_clock_offset);
829 static int timer_load(QEMUFile *f, void *opaque, int version_id)
831 if (version_id != 1 && version_id != 2)
832 return -EINVAL;
833 if (cpu_ticks_enabled) {
834 return -EINVAL;
836 qemu_get_be64s(f, &cpu_ticks_offset);
837 qemu_get_be64s(f, &ticks_per_sec);
838 if (version_id == 2) {
839 qemu_get_be64s(f, &cpu_clock_offset);
841 return 0;
844 #ifdef _WIN32
845 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
846 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
847 #else
848 static void host_alarm_handler(int host_signum)
849 #endif
851 #if 0
852 #define DISP_FREQ 1000
854 static int64_t delta_min = INT64_MAX;
855 static int64_t delta_max, delta_cum, last_clock, delta, ti;
856 static int count;
857 ti = qemu_get_clock(vm_clock);
858 if (last_clock != 0) {
859 delta = ti - last_clock;
860 if (delta < delta_min)
861 delta_min = delta;
862 if (delta > delta_max)
863 delta_max = delta;
864 delta_cum += delta;
865 if (++count == DISP_FREQ) {
866 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
867 muldiv64(delta_min, 1000000, ticks_per_sec),
868 muldiv64(delta_max, 1000000, ticks_per_sec),
869 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
870 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
871 count = 0;
872 delta_min = INT64_MAX;
873 delta_max = 0;
874 delta_cum = 0;
877 last_clock = ti;
879 #endif
880 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
881 qemu_get_clock(vm_clock)) ||
882 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
883 qemu_get_clock(rt_clock))) {
884 #ifdef _WIN32
885 SetEvent(host_alarm);
886 #endif
887 CPUState *env = cpu_single_env;
888 if (env) {
889 /* stop the currently executing cpu because a timer occured */
890 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
891 #ifdef USE_KQEMU
892 if (env->kqemu_enabled) {
893 kqemu_cpu_interrupt(env);
895 #endif
900 #ifndef _WIN32
902 #if defined(__linux__)
904 #define RTC_FREQ 1024
906 static int rtc_fd;
908 static int start_rtc_timer(void)
910 rtc_fd = open("/dev/rtc", O_RDONLY);
911 if (rtc_fd < 0)
912 return -1;
913 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
914 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
915 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
916 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
917 goto fail;
919 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
920 fail:
921 close(rtc_fd);
922 return -1;
924 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
925 return 0;
928 #else
930 static int start_rtc_timer(void)
932 return -1;
935 #endif /* !defined(__linux__) */
937 #endif /* !defined(_WIN32) */
939 static void init_timer_alarm(void)
941 #ifdef _WIN32
943 int count=0;
944 TIMECAPS tc;
946 ZeroMemory(&tc, sizeof(TIMECAPS));
947 timeGetDevCaps(&tc, sizeof(TIMECAPS));
948 if (period < tc.wPeriodMin)
949 period = tc.wPeriodMin;
950 timeBeginPeriod(period);
951 timerID = timeSetEvent(1, // interval (ms)
952 period, // resolution
953 host_alarm_handler, // function
954 (DWORD)&count, // user parameter
955 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
956 if( !timerID ) {
957 perror("failed timer alarm");
958 exit(1);
960 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
961 if (!host_alarm) {
962 perror("failed CreateEvent");
963 exit(1);
965 qemu_add_wait_object(host_alarm, NULL, NULL);
967 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
968 #else
970 struct sigaction act;
971 struct itimerval itv;
973 /* get times() syscall frequency */
974 timer_freq = sysconf(_SC_CLK_TCK);
976 /* timer signal */
977 sigfillset(&act.sa_mask);
978 act.sa_flags = 0;
979 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
980 act.sa_flags |= SA_ONSTACK;
981 #endif
982 act.sa_handler = host_alarm_handler;
983 sigaction(SIGALRM, &act, NULL);
985 itv.it_interval.tv_sec = 0;
986 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
987 itv.it_value.tv_sec = 0;
988 itv.it_value.tv_usec = 10 * 1000;
989 setitimer(ITIMER_REAL, &itv, NULL);
990 /* we probe the tick duration of the kernel to inform the user if
991 the emulated kernel requested a too high timer frequency */
992 getitimer(ITIMER_REAL, &itv);
994 #if defined(__linux__)
995 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
996 have timers with 1 ms resolution. The correct solution will
997 be to use the POSIX real time timers available in recent
998 2.6 kernels */
999 if (itv.it_interval.tv_usec > 1000 || 1) {
1000 /* try to use /dev/rtc to have a faster timer */
1001 if (start_rtc_timer() < 0)
1002 goto use_itimer;
1003 /* disable itimer */
1004 itv.it_interval.tv_sec = 0;
1005 itv.it_interval.tv_usec = 0;
1006 itv.it_value.tv_sec = 0;
1007 itv.it_value.tv_usec = 0;
1008 setitimer(ITIMER_REAL, &itv, NULL);
1010 /* use the RTC */
1011 sigaction(SIGIO, &act, NULL);
1012 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1013 fcntl(rtc_fd, F_SETOWN, getpid());
1014 } else
1015 #endif /* defined(__linux__) */
1017 use_itimer:
1018 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1019 PIT_FREQ) / 1000000;
1022 #endif
1025 void quit_timers(void)
1027 #ifdef _WIN32
1028 timeKillEvent(timerID);
1029 timeEndPeriod(period);
1030 if (host_alarm) {
1031 CloseHandle(host_alarm);
1032 host_alarm = NULL;
1034 #endif
1037 /***********************************************************/
1038 /* character device */
1040 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1042 return s->chr_write(s, buf, len);
1045 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1047 if (!s->chr_ioctl)
1048 return -ENOTSUP;
1049 return s->chr_ioctl(s, cmd, arg);
1052 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1054 char buf[4096];
1055 va_list ap;
1056 va_start(ap, fmt);
1057 vsnprintf(buf, sizeof(buf), fmt, ap);
1058 qemu_chr_write(s, buf, strlen(buf));
1059 va_end(ap);
1062 void qemu_chr_send_event(CharDriverState *s, int event)
1064 if (s->chr_send_event)
1065 s->chr_send_event(s, event);
1068 void qemu_chr_add_read_handler(CharDriverState *s,
1069 IOCanRWHandler *fd_can_read,
1070 IOReadHandler *fd_read, void *opaque)
1072 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1075 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1077 s->chr_event = chr_event;
1080 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1082 return len;
1085 static void null_chr_add_read_handler(CharDriverState *chr,
1086 IOCanRWHandler *fd_can_read,
1087 IOReadHandler *fd_read, void *opaque)
1091 CharDriverState *qemu_chr_open_null(void)
1093 CharDriverState *chr;
1095 chr = qemu_mallocz(sizeof(CharDriverState));
1096 if (!chr)
1097 return NULL;
1098 chr->chr_write = null_chr_write;
1099 chr->chr_add_read_handler = null_chr_add_read_handler;
1100 return chr;
1103 #ifdef _WIN32
1105 static void socket_cleanup(void)
1107 WSACleanup();
1110 static int socket_init(void)
1112 WSADATA Data;
1113 int ret, err;
1115 ret = WSAStartup(MAKEWORD(2,2), &Data);
1116 if (ret != 0) {
1117 err = WSAGetLastError();
1118 fprintf(stderr, "WSAStartup: %d\n", err);
1119 return -1;
1121 atexit(socket_cleanup);
1122 return 0;
1125 static int send_all(int fd, const uint8_t *buf, int len1)
1127 int ret, len;
1129 len = len1;
1130 while (len > 0) {
1131 ret = send(fd, buf, len, 0);
1132 if (ret < 0) {
1133 int errno;
1134 errno = WSAGetLastError();
1135 if (errno != WSAEWOULDBLOCK) {
1136 return -1;
1138 } else if (ret == 0) {
1139 break;
1140 } else {
1141 buf += ret;
1142 len -= ret;
1145 return len1 - len;
1148 void socket_set_nonblock(int fd)
1150 unsigned long opt = 1;
1151 ioctlsocket(fd, FIONBIO, &opt);
1154 #else
1156 static int unix_write(int fd, const uint8_t *buf, int len1)
1158 int ret, len;
1160 len = len1;
1161 while (len > 0) {
1162 ret = write(fd, buf, len);
1163 if (ret < 0) {
1164 if (errno != EINTR && errno != EAGAIN)
1165 return -1;
1166 } else if (ret == 0) {
1167 break;
1168 } else {
1169 buf += ret;
1170 len -= ret;
1173 return len1 - len;
1176 static inline int send_all(int fd, const uint8_t *buf, int len1)
1178 return unix_write(fd, buf, len1);
1181 void socket_set_nonblock(int fd)
1183 fcntl(fd, F_SETFL, O_NONBLOCK);
1185 #endif /* !_WIN32 */
1187 #ifndef _WIN32
1189 typedef struct {
1190 int fd_in, fd_out;
1191 IOCanRWHandler *fd_can_read;
1192 IOReadHandler *fd_read;
1193 void *fd_opaque;
1194 int max_size;
1195 } FDCharDriver;
1197 #define STDIO_MAX_CLIENTS 2
1199 static int stdio_nb_clients;
1200 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1202 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1204 FDCharDriver *s = chr->opaque;
1205 return unix_write(s->fd_out, buf, len);
1208 static int fd_chr_read_poll(void *opaque)
1210 CharDriverState *chr = opaque;
1211 FDCharDriver *s = chr->opaque;
1213 s->max_size = s->fd_can_read(s->fd_opaque);
1214 return s->max_size;
1217 static void fd_chr_read(void *opaque)
1219 CharDriverState *chr = opaque;
1220 FDCharDriver *s = chr->opaque;
1221 int size, len;
1222 uint8_t buf[1024];
1224 len = sizeof(buf);
1225 if (len > s->max_size)
1226 len = s->max_size;
1227 if (len == 0)
1228 return;
1229 size = read(s->fd_in, buf, len);
1230 if (size > 0) {
1231 s->fd_read(s->fd_opaque, buf, size);
1235 static void fd_chr_add_read_handler(CharDriverState *chr,
1236 IOCanRWHandler *fd_can_read,
1237 IOReadHandler *fd_read, void *opaque)
1239 FDCharDriver *s = chr->opaque;
1241 if (s->fd_in >= 0) {
1242 s->fd_can_read = fd_can_read;
1243 s->fd_read = fd_read;
1244 s->fd_opaque = opaque;
1245 if (nographic && s->fd_in == 0) {
1246 } else {
1247 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1248 fd_chr_read, NULL, chr);
1253 /* open a character device to a unix fd */
1254 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1256 CharDriverState *chr;
1257 FDCharDriver *s;
1259 chr = qemu_mallocz(sizeof(CharDriverState));
1260 if (!chr)
1261 return NULL;
1262 s = qemu_mallocz(sizeof(FDCharDriver));
1263 if (!s) {
1264 free(chr);
1265 return NULL;
1267 s->fd_in = fd_in;
1268 s->fd_out = fd_out;
1269 chr->opaque = s;
1270 chr->chr_write = fd_chr_write;
1271 chr->chr_add_read_handler = fd_chr_add_read_handler;
1272 return chr;
1275 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1277 int fd_out;
1279 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1280 if (fd_out < 0)
1281 return NULL;
1282 return qemu_chr_open_fd(-1, fd_out);
1285 CharDriverState *qemu_chr_open_pipe(const char *filename)
1287 int fd;
1289 fd = open(filename, O_RDWR | O_BINARY);
1290 if (fd < 0)
1291 return NULL;
1292 return qemu_chr_open_fd(fd, fd);
1296 /* for STDIO, we handle the case where several clients use it
1297 (nographic mode) */
1299 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1301 #define TERM_FIFO_MAX_SIZE 1
1303 static int term_got_escape, client_index;
1304 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1305 static int term_fifo_size;
1306 static int term_timestamps;
1307 static int64_t term_timestamps_start;
1309 void term_print_help(void)
1311 printf("\n"
1312 "C-a h print this help\n"
1313 "C-a x exit emulator\n"
1314 "C-a s save disk data back to file (if -snapshot)\n"
1315 "C-a b send break (magic sysrq)\n"
1316 "C-a t toggle console timestamps\n"
1317 "C-a c switch between console and monitor\n"
1318 "C-a C-a send C-a\n"
1322 /* called when a char is received */
1323 static void stdio_received_byte(int ch)
1325 if (term_got_escape) {
1326 term_got_escape = 0;
1327 switch(ch) {
1328 case 'h':
1329 term_print_help();
1330 break;
1331 case 'x':
1332 exit(0);
1333 break;
1334 case 's':
1336 int i;
1337 for (i = 0; i < MAX_DISKS; i++) {
1338 if (bs_table[i])
1339 bdrv_commit(bs_table[i]);
1342 break;
1343 case 'b':
1344 if (client_index < stdio_nb_clients) {
1345 CharDriverState *chr;
1346 FDCharDriver *s;
1348 chr = stdio_clients[client_index];
1349 s = chr->opaque;
1350 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1352 break;
1353 case 'c':
1354 client_index++;
1355 if (client_index >= stdio_nb_clients)
1356 client_index = 0;
1357 if (client_index == 0) {
1358 /* send a new line in the monitor to get the prompt */
1359 ch = '\r';
1360 goto send_char;
1362 break;
1363 case 't':
1364 term_timestamps = !term_timestamps;
1365 term_timestamps_start = -1;
1366 break;
1367 case TERM_ESCAPE:
1368 goto send_char;
1370 } else if (ch == TERM_ESCAPE) {
1371 term_got_escape = 1;
1372 } else {
1373 send_char:
1374 if (client_index < stdio_nb_clients) {
1375 uint8_t buf[1];
1376 CharDriverState *chr;
1377 FDCharDriver *s;
1379 chr = stdio_clients[client_index];
1380 s = chr->opaque;
1381 if (s->fd_can_read(s->fd_opaque) > 0) {
1382 buf[0] = ch;
1383 s->fd_read(s->fd_opaque, buf, 1);
1384 } else if (term_fifo_size == 0) {
1385 term_fifo[term_fifo_size++] = ch;
1391 static int stdio_read_poll(void *opaque)
1393 CharDriverState *chr;
1394 FDCharDriver *s;
1396 if (client_index < stdio_nb_clients) {
1397 chr = stdio_clients[client_index];
1398 s = chr->opaque;
1399 /* try to flush the queue if needed */
1400 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1401 s->fd_read(s->fd_opaque, term_fifo, 1);
1402 term_fifo_size = 0;
1404 /* see if we can absorb more chars */
1405 if (term_fifo_size == 0)
1406 return 1;
1407 else
1408 return 0;
1409 } else {
1410 return 1;
1414 static void stdio_read(void *opaque)
1416 int size;
1417 uint8_t buf[1];
1419 size = read(0, buf, 1);
1420 if (size > 0)
1421 stdio_received_byte(buf[0]);
1424 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1426 FDCharDriver *s = chr->opaque;
1427 if (!term_timestamps) {
1428 return unix_write(s->fd_out, buf, len);
1429 } else {
1430 int i;
1431 char buf1[64];
1433 for(i = 0; i < len; i++) {
1434 unix_write(s->fd_out, buf + i, 1);
1435 if (buf[i] == '\n') {
1436 int64_t ti;
1437 int secs;
1439 ti = get_clock();
1440 if (term_timestamps_start == -1)
1441 term_timestamps_start = ti;
1442 ti -= term_timestamps_start;
1443 secs = ti / 1000000000;
1444 snprintf(buf1, sizeof(buf1),
1445 "[%02d:%02d:%02d.%03d] ",
1446 secs / 3600,
1447 (secs / 60) % 60,
1448 secs % 60,
1449 (int)((ti / 1000000) % 1000));
1450 unix_write(s->fd_out, buf1, strlen(buf1));
1453 return len;
1457 /* init terminal so that we can grab keys */
1458 static struct termios oldtty;
1459 static int old_fd0_flags;
1461 static void term_exit(void)
1463 tcsetattr (0, TCSANOW, &oldtty);
1464 fcntl(0, F_SETFL, old_fd0_flags);
1467 static void term_init(void)
1469 struct termios tty;
1471 tcgetattr (0, &tty);
1472 oldtty = tty;
1473 old_fd0_flags = fcntl(0, F_GETFL);
1475 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1476 |INLCR|IGNCR|ICRNL|IXON);
1477 tty.c_oflag |= OPOST;
1478 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1479 /* if graphical mode, we allow Ctrl-C handling */
1480 if (nographic)
1481 tty.c_lflag &= ~ISIG;
1482 tty.c_cflag &= ~(CSIZE|PARENB);
1483 tty.c_cflag |= CS8;
1484 tty.c_cc[VMIN] = 1;
1485 tty.c_cc[VTIME] = 0;
1487 tcsetattr (0, TCSANOW, &tty);
1489 atexit(term_exit);
1491 fcntl(0, F_SETFL, O_NONBLOCK);
1494 CharDriverState *qemu_chr_open_stdio(void)
1496 CharDriverState *chr;
1498 if (nographic) {
1499 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1500 return NULL;
1501 chr = qemu_chr_open_fd(0, 1);
1502 chr->chr_write = stdio_write;
1503 if (stdio_nb_clients == 0)
1504 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1505 client_index = stdio_nb_clients;
1506 } else {
1507 if (stdio_nb_clients != 0)
1508 return NULL;
1509 chr = qemu_chr_open_fd(0, 1);
1511 stdio_clients[stdio_nb_clients++] = chr;
1512 if (stdio_nb_clients == 1) {
1513 /* set the terminal in raw mode */
1514 term_init();
1516 return chr;
1519 #if defined(__linux__)
1520 CharDriverState *qemu_chr_open_pty(void)
1522 struct termios tty;
1523 char slave_name[1024];
1524 int master_fd, slave_fd;
1526 /* Not satisfying */
1527 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1528 return NULL;
1531 /* Disabling local echo and line-buffered output */
1532 tcgetattr (master_fd, &tty);
1533 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1534 tty.c_cc[VMIN] = 1;
1535 tty.c_cc[VTIME] = 0;
1536 tcsetattr (master_fd, TCSAFLUSH, &tty);
1538 fprintf(stderr, "char device redirected to %s\n", slave_name);
1539 return qemu_chr_open_fd(master_fd, master_fd);
1542 static void tty_serial_init(int fd, int speed,
1543 int parity, int data_bits, int stop_bits)
1545 struct termios tty;
1546 speed_t spd;
1548 #if 0
1549 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1550 speed, parity, data_bits, stop_bits);
1551 #endif
1552 tcgetattr (fd, &tty);
1554 switch(speed) {
1555 case 50:
1556 spd = B50;
1557 break;
1558 case 75:
1559 spd = B75;
1560 break;
1561 case 300:
1562 spd = B300;
1563 break;
1564 case 600:
1565 spd = B600;
1566 break;
1567 case 1200:
1568 spd = B1200;
1569 break;
1570 case 2400:
1571 spd = B2400;
1572 break;
1573 case 4800:
1574 spd = B4800;
1575 break;
1576 case 9600:
1577 spd = B9600;
1578 break;
1579 case 19200:
1580 spd = B19200;
1581 break;
1582 case 38400:
1583 spd = B38400;
1584 break;
1585 case 57600:
1586 spd = B57600;
1587 break;
1588 default:
1589 case 115200:
1590 spd = B115200;
1591 break;
1594 cfsetispeed(&tty, spd);
1595 cfsetospeed(&tty, spd);
1597 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1598 |INLCR|IGNCR|ICRNL|IXON);
1599 tty.c_oflag |= OPOST;
1600 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1601 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1602 switch(data_bits) {
1603 default:
1604 case 8:
1605 tty.c_cflag |= CS8;
1606 break;
1607 case 7:
1608 tty.c_cflag |= CS7;
1609 break;
1610 case 6:
1611 tty.c_cflag |= CS6;
1612 break;
1613 case 5:
1614 tty.c_cflag |= CS5;
1615 break;
1617 switch(parity) {
1618 default:
1619 case 'N':
1620 break;
1621 case 'E':
1622 tty.c_cflag |= PARENB;
1623 break;
1624 case 'O':
1625 tty.c_cflag |= PARENB | PARODD;
1626 break;
1629 tcsetattr (fd, TCSANOW, &tty);
1632 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1634 FDCharDriver *s = chr->opaque;
1636 switch(cmd) {
1637 case CHR_IOCTL_SERIAL_SET_PARAMS:
1639 QEMUSerialSetParams *ssp = arg;
1640 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1641 ssp->data_bits, ssp->stop_bits);
1643 break;
1644 case CHR_IOCTL_SERIAL_SET_BREAK:
1646 int enable = *(int *)arg;
1647 if (enable)
1648 tcsendbreak(s->fd_in, 1);
1650 break;
1651 default:
1652 return -ENOTSUP;
1654 return 0;
1657 CharDriverState *qemu_chr_open_tty(const char *filename)
1659 CharDriverState *chr;
1660 int fd;
1662 fd = open(filename, O_RDWR | O_NONBLOCK);
1663 if (fd < 0)
1664 return NULL;
1665 fcntl(fd, F_SETFL, O_NONBLOCK);
1666 tty_serial_init(fd, 115200, 'N', 8, 1);
1667 chr = qemu_chr_open_fd(fd, fd);
1668 if (!chr)
1669 return NULL;
1670 chr->chr_ioctl = tty_serial_ioctl;
1671 return chr;
1674 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1676 int fd = (int)chr->opaque;
1677 uint8_t b;
1679 switch(cmd) {
1680 case CHR_IOCTL_PP_READ_DATA:
1681 if (ioctl(fd, PPRDATA, &b) < 0)
1682 return -ENOTSUP;
1683 *(uint8_t *)arg = b;
1684 break;
1685 case CHR_IOCTL_PP_WRITE_DATA:
1686 b = *(uint8_t *)arg;
1687 if (ioctl(fd, PPWDATA, &b) < 0)
1688 return -ENOTSUP;
1689 break;
1690 case CHR_IOCTL_PP_READ_CONTROL:
1691 if (ioctl(fd, PPRCONTROL, &b) < 0)
1692 return -ENOTSUP;
1693 *(uint8_t *)arg = b;
1694 break;
1695 case CHR_IOCTL_PP_WRITE_CONTROL:
1696 b = *(uint8_t *)arg;
1697 if (ioctl(fd, PPWCONTROL, &b) < 0)
1698 return -ENOTSUP;
1699 break;
1700 case CHR_IOCTL_PP_READ_STATUS:
1701 if (ioctl(fd, PPRSTATUS, &b) < 0)
1702 return -ENOTSUP;
1703 *(uint8_t *)arg = b;
1704 break;
1705 default:
1706 return -ENOTSUP;
1708 return 0;
1711 CharDriverState *qemu_chr_open_pp(const char *filename)
1713 CharDriverState *chr;
1714 int fd;
1716 fd = open(filename, O_RDWR);
1717 if (fd < 0)
1718 return NULL;
1720 if (ioctl(fd, PPCLAIM) < 0) {
1721 close(fd);
1722 return NULL;
1725 chr = qemu_mallocz(sizeof(CharDriverState));
1726 if (!chr) {
1727 close(fd);
1728 return NULL;
1730 chr->opaque = (void *)fd;
1731 chr->chr_write = null_chr_write;
1732 chr->chr_add_read_handler = null_chr_add_read_handler;
1733 chr->chr_ioctl = pp_ioctl;
1734 return chr;
1737 #else
1738 CharDriverState *qemu_chr_open_pty(void)
1740 return NULL;
1742 #endif
1744 #endif /* !defined(_WIN32) */
1746 #ifdef _WIN32
1747 typedef struct {
1748 IOCanRWHandler *fd_can_read;
1749 IOReadHandler *fd_read;
1750 void *win_opaque;
1751 int max_size;
1752 HANDLE hcom, hrecv, hsend;
1753 OVERLAPPED orecv, osend;
1754 BOOL fpipe;
1755 DWORD len;
1756 } WinCharState;
1758 #define NSENDBUF 2048
1759 #define NRECVBUF 2048
1760 #define MAXCONNECT 1
1761 #define NTIMEOUT 5000
1763 static int win_chr_poll(void *opaque);
1764 static int win_chr_pipe_poll(void *opaque);
1766 static void win_chr_close2(WinCharState *s)
1768 if (s->hsend) {
1769 CloseHandle(s->hsend);
1770 s->hsend = NULL;
1772 if (s->hrecv) {
1773 CloseHandle(s->hrecv);
1774 s->hrecv = NULL;
1776 if (s->hcom) {
1777 CloseHandle(s->hcom);
1778 s->hcom = NULL;
1780 if (s->fpipe)
1781 qemu_del_polling_cb(win_chr_pipe_poll, s);
1782 else
1783 qemu_del_polling_cb(win_chr_poll, s);
1786 static void win_chr_close(CharDriverState *chr)
1788 WinCharState *s = chr->opaque;
1789 win_chr_close2(s);
1792 static int win_chr_init(WinCharState *s, const char *filename)
1794 COMMCONFIG comcfg;
1795 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1796 COMSTAT comstat;
1797 DWORD size;
1798 DWORD err;
1800 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1801 if (!s->hsend) {
1802 fprintf(stderr, "Failed CreateEvent\n");
1803 goto fail;
1805 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1806 if (!s->hrecv) {
1807 fprintf(stderr, "Failed CreateEvent\n");
1808 goto fail;
1811 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1812 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1813 if (s->hcom == INVALID_HANDLE_VALUE) {
1814 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1815 s->hcom = NULL;
1816 goto fail;
1819 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1820 fprintf(stderr, "Failed SetupComm\n");
1821 goto fail;
1824 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1825 size = sizeof(COMMCONFIG);
1826 GetDefaultCommConfig(filename, &comcfg, &size);
1827 comcfg.dcb.DCBlength = sizeof(DCB);
1828 CommConfigDialog(filename, NULL, &comcfg);
1830 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1831 fprintf(stderr, "Failed SetCommState\n");
1832 goto fail;
1835 if (!SetCommMask(s->hcom, EV_ERR)) {
1836 fprintf(stderr, "Failed SetCommMask\n");
1837 goto fail;
1840 cto.ReadIntervalTimeout = MAXDWORD;
1841 if (!SetCommTimeouts(s->hcom, &cto)) {
1842 fprintf(stderr, "Failed SetCommTimeouts\n");
1843 goto fail;
1846 if (!ClearCommError(s->hcom, &err, &comstat)) {
1847 fprintf(stderr, "Failed ClearCommError\n");
1848 goto fail;
1850 qemu_add_polling_cb(win_chr_poll, s);
1851 return 0;
1853 fail:
1854 win_chr_close2(s);
1855 return -1;
1858 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1860 WinCharState *s = chr->opaque;
1861 DWORD len, ret, size, err;
1863 len = len1;
1864 ZeroMemory(&s->osend, sizeof(s->osend));
1865 s->osend.hEvent = s->hsend;
1866 while (len > 0) {
1867 if (s->hsend)
1868 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1869 else
1870 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1871 if (!ret) {
1872 err = GetLastError();
1873 if (err == ERROR_IO_PENDING) {
1874 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1875 if (ret) {
1876 buf += size;
1877 len -= size;
1878 } else {
1879 break;
1881 } else {
1882 break;
1884 } else {
1885 buf += size;
1886 len -= size;
1889 return len1 - len;
1892 static int win_chr_read_poll(WinCharState *s)
1894 s->max_size = s->fd_can_read(s->win_opaque);
1895 return s->max_size;
1898 static void win_chr_readfile(WinCharState *s)
1900 int ret, err;
1901 uint8_t buf[1024];
1902 DWORD size;
1904 ZeroMemory(&s->orecv, sizeof(s->orecv));
1905 s->orecv.hEvent = s->hrecv;
1906 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1907 if (!ret) {
1908 err = GetLastError();
1909 if (err == ERROR_IO_PENDING) {
1910 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1914 if (size > 0) {
1915 s->fd_read(s->win_opaque, buf, size);
1919 static void win_chr_read(WinCharState *s)
1921 if (s->len > s->max_size)
1922 s->len = s->max_size;
1923 if (s->len == 0)
1924 return;
1926 win_chr_readfile(s);
1929 static int win_chr_poll(void *opaque)
1931 WinCharState *s = opaque;
1932 COMSTAT status;
1933 DWORD comerr;
1935 ClearCommError(s->hcom, &comerr, &status);
1936 if (status.cbInQue > 0) {
1937 s->len = status.cbInQue;
1938 win_chr_read_poll(s);
1939 win_chr_read(s);
1940 return 1;
1942 return 0;
1945 static void win_chr_add_read_handler(CharDriverState *chr,
1946 IOCanRWHandler *fd_can_read,
1947 IOReadHandler *fd_read, void *opaque)
1949 WinCharState *s = chr->opaque;
1951 s->fd_can_read = fd_can_read;
1952 s->fd_read = fd_read;
1953 s->win_opaque = opaque;
1956 CharDriverState *qemu_chr_open_win(const char *filename)
1958 CharDriverState *chr;
1959 WinCharState *s;
1961 chr = qemu_mallocz(sizeof(CharDriverState));
1962 if (!chr)
1963 return NULL;
1964 s = qemu_mallocz(sizeof(WinCharState));
1965 if (!s) {
1966 free(chr);
1967 return NULL;
1969 chr->opaque = s;
1970 chr->chr_write = win_chr_write;
1971 chr->chr_add_read_handler = win_chr_add_read_handler;
1972 chr->chr_close = win_chr_close;
1974 if (win_chr_init(s, filename) < 0) {
1975 free(s);
1976 free(chr);
1977 return NULL;
1979 return chr;
1982 static int win_chr_pipe_poll(void *opaque)
1984 WinCharState *s = opaque;
1985 DWORD size;
1987 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1988 if (size > 0) {
1989 s->len = size;
1990 win_chr_read_poll(s);
1991 win_chr_read(s);
1992 return 1;
1994 return 0;
1997 static int win_chr_pipe_init(WinCharState *s, const char *filename)
1999 OVERLAPPED ov;
2000 int ret;
2001 DWORD size;
2002 char openname[256];
2004 s->fpipe = TRUE;
2006 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2007 if (!s->hsend) {
2008 fprintf(stderr, "Failed CreateEvent\n");
2009 goto fail;
2011 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2012 if (!s->hrecv) {
2013 fprintf(stderr, "Failed CreateEvent\n");
2014 goto fail;
2017 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2018 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2019 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2020 PIPE_WAIT,
2021 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2022 if (s->hcom == INVALID_HANDLE_VALUE) {
2023 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2024 s->hcom = NULL;
2025 goto fail;
2028 ZeroMemory(&ov, sizeof(ov));
2029 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2030 ret = ConnectNamedPipe(s->hcom, &ov);
2031 if (ret) {
2032 fprintf(stderr, "Failed ConnectNamedPipe\n");
2033 goto fail;
2036 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2037 if (!ret) {
2038 fprintf(stderr, "Failed GetOverlappedResult\n");
2039 if (ov.hEvent) {
2040 CloseHandle(ov.hEvent);
2041 ov.hEvent = NULL;
2043 goto fail;
2046 if (ov.hEvent) {
2047 CloseHandle(ov.hEvent);
2048 ov.hEvent = NULL;
2050 qemu_add_polling_cb(win_chr_pipe_poll, s);
2051 return 0;
2053 fail:
2054 win_chr_close2(s);
2055 return -1;
2059 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2061 CharDriverState *chr;
2062 WinCharState *s;
2064 chr = qemu_mallocz(sizeof(CharDriverState));
2065 if (!chr)
2066 return NULL;
2067 s = qemu_mallocz(sizeof(WinCharState));
2068 if (!s) {
2069 free(chr);
2070 return NULL;
2072 chr->opaque = s;
2073 chr->chr_write = win_chr_write;
2074 chr->chr_add_read_handler = win_chr_add_read_handler;
2075 chr->chr_close = win_chr_close;
2077 if (win_chr_pipe_init(s, filename) < 0) {
2078 free(s);
2079 free(chr);
2080 return NULL;
2082 return chr;
2085 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2087 CharDriverState *chr;
2088 WinCharState *s;
2090 chr = qemu_mallocz(sizeof(CharDriverState));
2091 if (!chr)
2092 return NULL;
2093 s = qemu_mallocz(sizeof(WinCharState));
2094 if (!s) {
2095 free(chr);
2096 return NULL;
2098 s->hcom = fd_out;
2099 chr->opaque = s;
2100 chr->chr_write = win_chr_write;
2101 chr->chr_add_read_handler = win_chr_add_read_handler;
2102 return chr;
2105 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2107 HANDLE fd_out;
2109 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2110 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2111 if (fd_out == INVALID_HANDLE_VALUE)
2112 return NULL;
2114 return qemu_chr_open_win_file(fd_out);
2116 #endif
2118 /***********************************************************/
2119 /* UDP Net console */
2121 typedef struct {
2122 IOCanRWHandler *fd_can_read;
2123 IOReadHandler *fd_read;
2124 void *fd_opaque;
2125 int fd;
2126 struct sockaddr_in daddr;
2127 char buf[1024];
2128 int bufcnt;
2129 int bufptr;
2130 int max_size;
2131 } NetCharDriver;
2133 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2135 NetCharDriver *s = chr->opaque;
2137 return sendto(s->fd, buf, len, 0,
2138 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2141 static int udp_chr_read_poll(void *opaque)
2143 CharDriverState *chr = opaque;
2144 NetCharDriver *s = chr->opaque;
2146 s->max_size = s->fd_can_read(s->fd_opaque);
2148 /* If there were any stray characters in the queue process them
2149 * first
2151 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2152 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2153 s->bufptr++;
2154 s->max_size = s->fd_can_read(s->fd_opaque);
2156 return s->max_size;
2159 static void udp_chr_read(void *opaque)
2161 CharDriverState *chr = opaque;
2162 NetCharDriver *s = chr->opaque;
2164 if (s->max_size == 0)
2165 return;
2166 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2167 s->bufptr = s->bufcnt;
2168 if (s->bufcnt <= 0)
2169 return;
2171 s->bufptr = 0;
2172 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2173 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2174 s->bufptr++;
2175 s->max_size = s->fd_can_read(s->fd_opaque);
2179 static void udp_chr_add_read_handler(CharDriverState *chr,
2180 IOCanRWHandler *fd_can_read,
2181 IOReadHandler *fd_read, void *opaque)
2183 NetCharDriver *s = chr->opaque;
2185 if (s->fd >= 0) {
2186 s->fd_can_read = fd_can_read;
2187 s->fd_read = fd_read;
2188 s->fd_opaque = opaque;
2189 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2190 udp_chr_read, NULL, chr);
2194 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2195 int parse_host_src_port(struct sockaddr_in *haddr,
2196 struct sockaddr_in *saddr,
2197 const char *str);
2199 CharDriverState *qemu_chr_open_udp(const char *def)
2201 CharDriverState *chr = NULL;
2202 NetCharDriver *s = NULL;
2203 int fd = -1;
2204 struct sockaddr_in saddr;
2206 chr = qemu_mallocz(sizeof(CharDriverState));
2207 if (!chr)
2208 goto return_err;
2209 s = qemu_mallocz(sizeof(NetCharDriver));
2210 if (!s)
2211 goto return_err;
2213 fd = socket(PF_INET, SOCK_DGRAM, 0);
2214 if (fd < 0) {
2215 perror("socket(PF_INET, SOCK_DGRAM)");
2216 goto return_err;
2219 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2220 printf("Could not parse: %s\n", def);
2221 goto return_err;
2224 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2226 perror("bind");
2227 goto return_err;
2230 s->fd = fd;
2231 s->bufcnt = 0;
2232 s->bufptr = 0;
2233 chr->opaque = s;
2234 chr->chr_write = udp_chr_write;
2235 chr->chr_add_read_handler = udp_chr_add_read_handler;
2236 return chr;
2238 return_err:
2239 if (chr)
2240 free(chr);
2241 if (s)
2242 free(s);
2243 if (fd >= 0)
2244 closesocket(fd);
2245 return NULL;
2248 /***********************************************************/
2249 /* TCP Net console */
2251 typedef struct {
2252 IOCanRWHandler *fd_can_read;
2253 IOReadHandler *fd_read;
2254 void *fd_opaque;
2255 int fd, listen_fd;
2256 int connected;
2257 int max_size;
2258 int do_telnetopt;
2259 } TCPCharDriver;
2261 static void tcp_chr_accept(void *opaque);
2263 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2265 TCPCharDriver *s = chr->opaque;
2266 if (s->connected) {
2267 return send_all(s->fd, buf, len);
2268 } else {
2269 /* XXX: indicate an error ? */
2270 return len;
2274 static int tcp_chr_read_poll(void *opaque)
2276 CharDriverState *chr = opaque;
2277 TCPCharDriver *s = chr->opaque;
2278 if (!s->connected)
2279 return 0;
2280 s->max_size = s->fd_can_read(s->fd_opaque);
2281 return s->max_size;
2284 #define IAC 255
2285 #define IAC_BREAK 243
2286 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2287 TCPCharDriver *s,
2288 char *buf, int *size)
2290 /* Handle any telnet client's basic IAC options to satisfy char by
2291 * char mode with no echo. All IAC options will be removed from
2292 * the buf and the do_telnetopt variable will be used to track the
2293 * state of the width of the IAC information.
2295 * IAC commands come in sets of 3 bytes with the exception of the
2296 * "IAC BREAK" command and the double IAC.
2299 int i;
2300 int j = 0;
2302 for (i = 0; i < *size; i++) {
2303 if (s->do_telnetopt > 1) {
2304 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2305 /* Double IAC means send an IAC */
2306 if (j != i)
2307 buf[j] = buf[i];
2308 j++;
2309 s->do_telnetopt = 1;
2310 } else {
2311 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2312 /* Handle IAC break commands by sending a serial break */
2313 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2314 s->do_telnetopt++;
2316 s->do_telnetopt++;
2318 if (s->do_telnetopt >= 4) {
2319 s->do_telnetopt = 1;
2321 } else {
2322 if ((unsigned char)buf[i] == IAC) {
2323 s->do_telnetopt = 2;
2324 } else {
2325 if (j != i)
2326 buf[j] = buf[i];
2327 j++;
2331 *size = j;
2334 static void tcp_chr_read(void *opaque)
2336 CharDriverState *chr = opaque;
2337 TCPCharDriver *s = chr->opaque;
2338 uint8_t buf[1024];
2339 int len, size;
2341 if (!s->connected || s->max_size <= 0)
2342 return;
2343 len = sizeof(buf);
2344 if (len > s->max_size)
2345 len = s->max_size;
2346 size = recv(s->fd, buf, len, 0);
2347 if (size == 0) {
2348 /* connection closed */
2349 s->connected = 0;
2350 if (s->listen_fd >= 0) {
2351 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2353 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2354 closesocket(s->fd);
2355 s->fd = -1;
2356 } else if (size > 0) {
2357 if (s->do_telnetopt)
2358 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2359 if (size > 0)
2360 s->fd_read(s->fd_opaque, buf, size);
2364 static void tcp_chr_add_read_handler(CharDriverState *chr,
2365 IOCanRWHandler *fd_can_read,
2366 IOReadHandler *fd_read, void *opaque)
2368 TCPCharDriver *s = chr->opaque;
2370 s->fd_can_read = fd_can_read;
2371 s->fd_read = fd_read;
2372 s->fd_opaque = opaque;
2375 static void tcp_chr_connect(void *opaque)
2377 CharDriverState *chr = opaque;
2378 TCPCharDriver *s = chr->opaque;
2380 s->connected = 1;
2381 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2382 tcp_chr_read, NULL, chr);
2385 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2386 static void tcp_chr_telnet_init(int fd)
2388 char buf[3];
2389 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2390 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2391 send(fd, (char *)buf, 3, 0);
2392 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2393 send(fd, (char *)buf, 3, 0);
2394 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2395 send(fd, (char *)buf, 3, 0);
2396 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2397 send(fd, (char *)buf, 3, 0);
2400 static void tcp_chr_accept(void *opaque)
2402 CharDriverState *chr = opaque;
2403 TCPCharDriver *s = chr->opaque;
2404 struct sockaddr_in saddr;
2405 socklen_t len;
2406 int fd;
2408 for(;;) {
2409 len = sizeof(saddr);
2410 fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2411 if (fd < 0 && errno != EINTR) {
2412 return;
2413 } else if (fd >= 0) {
2414 if (s->do_telnetopt)
2415 tcp_chr_telnet_init(fd);
2416 break;
2419 socket_set_nonblock(fd);
2420 s->fd = fd;
2421 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2422 tcp_chr_connect(chr);
2425 static void tcp_chr_close(CharDriverState *chr)
2427 TCPCharDriver *s = chr->opaque;
2428 if (s->fd >= 0)
2429 closesocket(s->fd);
2430 if (s->listen_fd >= 0)
2431 closesocket(s->listen_fd);
2432 qemu_free(s);
2435 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2436 int is_telnet)
2438 CharDriverState *chr = NULL;
2439 TCPCharDriver *s = NULL;
2440 int fd = -1, ret, err, val;
2441 int is_listen = 0;
2442 int is_waitconnect = 1;
2443 const char *ptr;
2444 struct sockaddr_in saddr;
2446 if (parse_host_port(&saddr, host_str) < 0)
2447 goto fail;
2449 ptr = host_str;
2450 while((ptr = strchr(ptr,','))) {
2451 ptr++;
2452 if (!strncmp(ptr,"server",6)) {
2453 is_listen = 1;
2454 } else if (!strncmp(ptr,"nowait",6)) {
2455 is_waitconnect = 0;
2456 } else {
2457 printf("Unknown option: %s\n", ptr);
2458 goto fail;
2461 if (!is_listen)
2462 is_waitconnect = 0;
2464 chr = qemu_mallocz(sizeof(CharDriverState));
2465 if (!chr)
2466 goto fail;
2467 s = qemu_mallocz(sizeof(TCPCharDriver));
2468 if (!s)
2469 goto fail;
2471 fd = socket(PF_INET, SOCK_STREAM, 0);
2472 if (fd < 0)
2473 goto fail;
2475 if (!is_waitconnect)
2476 socket_set_nonblock(fd);
2478 s->connected = 0;
2479 s->fd = -1;
2480 s->listen_fd = -1;
2481 if (is_listen) {
2482 /* allow fast reuse */
2483 val = 1;
2484 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2486 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2487 if (ret < 0)
2488 goto fail;
2489 ret = listen(fd, 0);
2490 if (ret < 0)
2491 goto fail;
2492 s->listen_fd = fd;
2493 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2494 if (is_telnet)
2495 s->do_telnetopt = 1;
2496 } else {
2497 for(;;) {
2498 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2499 if (ret < 0) {
2500 err = socket_error();
2501 if (err == EINTR || err == EWOULDBLOCK) {
2502 } else if (err == EINPROGRESS) {
2503 break;
2504 } else {
2505 goto fail;
2507 } else {
2508 s->connected = 1;
2509 break;
2512 s->fd = fd;
2513 if (s->connected)
2514 tcp_chr_connect(chr);
2515 else
2516 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2519 chr->opaque = s;
2520 chr->chr_write = tcp_chr_write;
2521 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2522 chr->chr_close = tcp_chr_close;
2523 if (is_listen && is_waitconnect) {
2524 printf("QEMU waiting for connection on: %s\n", host_str);
2525 tcp_chr_accept(chr);
2526 socket_set_nonblock(s->listen_fd);
2529 return chr;
2530 fail:
2531 if (fd >= 0)
2532 closesocket(fd);
2533 qemu_free(s);
2534 qemu_free(chr);
2535 return NULL;
2538 CharDriverState *qemu_chr_open(const char *filename)
2540 const char *p;
2542 if (!strcmp(filename, "vc")) {
2543 return text_console_init(&display_state);
2544 } else if (!strcmp(filename, "null")) {
2545 return qemu_chr_open_null();
2546 } else
2547 if (strstart(filename, "tcp:", &p)) {
2548 return qemu_chr_open_tcp(p, 0);
2549 } else
2550 if (strstart(filename, "telnet:", &p)) {
2551 return qemu_chr_open_tcp(p, 1);
2552 } else
2553 if (strstart(filename, "udp:", &p)) {
2554 return qemu_chr_open_udp(p);
2555 } else
2556 #ifndef _WIN32
2557 if (strstart(filename, "file:", &p)) {
2558 return qemu_chr_open_file_out(p);
2559 } else if (strstart(filename, "pipe:", &p)) {
2560 return qemu_chr_open_pipe(p);
2561 } else if (!strcmp(filename, "pty")) {
2562 return qemu_chr_open_pty();
2563 } else if (!strcmp(filename, "stdio")) {
2564 return qemu_chr_open_stdio();
2565 } else
2566 #endif
2567 #if defined(__linux__)
2568 if (strstart(filename, "/dev/parport", NULL)) {
2569 return qemu_chr_open_pp(filename);
2570 } else
2571 if (strstart(filename, "/dev/", NULL)) {
2572 return qemu_chr_open_tty(filename);
2573 } else
2574 #endif
2575 #ifdef _WIN32
2576 if (strstart(filename, "COM", NULL)) {
2577 return qemu_chr_open_win(filename);
2578 } else
2579 if (strstart(filename, "pipe:", &p)) {
2580 return qemu_chr_open_win_pipe(p);
2581 } else
2582 if (strstart(filename, "file:", &p)) {
2583 return qemu_chr_open_win_file_out(p);
2585 #endif
2587 return NULL;
2591 void qemu_chr_close(CharDriverState *chr)
2593 if (chr->chr_close)
2594 chr->chr_close(chr);
2597 /***********************************************************/
2598 /* network device redirectors */
2600 void hex_dump(FILE *f, const uint8_t *buf, int size)
2602 int len, i, j, c;
2604 for(i=0;i<size;i+=16) {
2605 len = size - i;
2606 if (len > 16)
2607 len = 16;
2608 fprintf(f, "%08x ", i);
2609 for(j=0;j<16;j++) {
2610 if (j < len)
2611 fprintf(f, " %02x", buf[i+j]);
2612 else
2613 fprintf(f, " ");
2615 fprintf(f, " ");
2616 for(j=0;j<len;j++) {
2617 c = buf[i+j];
2618 if (c < ' ' || c > '~')
2619 c = '.';
2620 fprintf(f, "%c", c);
2622 fprintf(f, "\n");
2626 static int parse_macaddr(uint8_t *macaddr, const char *p)
2628 int i;
2629 for(i = 0; i < 6; i++) {
2630 macaddr[i] = strtol(p, (char **)&p, 16);
2631 if (i == 5) {
2632 if (*p != '\0')
2633 return -1;
2634 } else {
2635 if (*p != ':')
2636 return -1;
2637 p++;
2640 return 0;
2643 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2645 const char *p, *p1;
2646 int len;
2647 p = *pp;
2648 p1 = strchr(p, sep);
2649 if (!p1)
2650 return -1;
2651 len = p1 - p;
2652 p1++;
2653 if (buf_size > 0) {
2654 if (len > buf_size - 1)
2655 len = buf_size - 1;
2656 memcpy(buf, p, len);
2657 buf[len] = '\0';
2659 *pp = p1;
2660 return 0;
2663 int parse_host_src_port(struct sockaddr_in *haddr,
2664 struct sockaddr_in *saddr,
2665 const char *input_str)
2667 char *str = strdup(input_str);
2668 char *host_str = str;
2669 char *src_str;
2670 char *ptr;
2673 * Chop off any extra arguments at the end of the string which
2674 * would start with a comma, then fill in the src port information
2675 * if it was provided else use the "any address" and "any port".
2677 if ((ptr = strchr(str,',')))
2678 *ptr = '\0';
2680 if ((src_str = strchr(input_str,'@'))) {
2681 *src_str = '\0';
2682 src_str++;
2685 if (parse_host_port(haddr, host_str) < 0)
2686 goto fail;
2688 if (!src_str || *src_str == '\0')
2689 src_str = ":0";
2691 if (parse_host_port(saddr, src_str) < 0)
2692 goto fail;
2694 free(str);
2695 return(0);
2697 fail:
2698 free(str);
2699 return -1;
2702 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2704 char buf[512];
2705 struct hostent *he;
2706 const char *p, *r;
2707 int port;
2709 p = str;
2710 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2711 return -1;
2712 saddr->sin_family = AF_INET;
2713 if (buf[0] == '\0') {
2714 saddr->sin_addr.s_addr = 0;
2715 } else {
2716 if (isdigit(buf[0])) {
2717 if (!inet_aton(buf, &saddr->sin_addr))
2718 return -1;
2719 } else {
2720 if ((he = gethostbyname(buf)) == NULL)
2721 return - 1;
2722 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2725 port = strtol(p, (char **)&r, 0);
2726 if (r == p)
2727 return -1;
2728 saddr->sin_port = htons(port);
2729 return 0;
2732 /* find or alloc a new VLAN */
2733 VLANState *qemu_find_vlan(int id)
2735 VLANState **pvlan, *vlan;
2736 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2737 if (vlan->id == id)
2738 return vlan;
2740 vlan = qemu_mallocz(sizeof(VLANState));
2741 if (!vlan)
2742 return NULL;
2743 vlan->id = id;
2744 vlan->next = NULL;
2745 pvlan = &first_vlan;
2746 while (*pvlan != NULL)
2747 pvlan = &(*pvlan)->next;
2748 *pvlan = vlan;
2749 return vlan;
2752 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2753 IOReadHandler *fd_read,
2754 IOCanRWHandler *fd_can_read,
2755 void *opaque)
2757 VLANClientState *vc, **pvc;
2758 vc = qemu_mallocz(sizeof(VLANClientState));
2759 if (!vc)
2760 return NULL;
2761 vc->fd_read = fd_read;
2762 vc->fd_can_read = fd_can_read;
2763 vc->opaque = opaque;
2764 vc->vlan = vlan;
2766 vc->next = NULL;
2767 pvc = &vlan->first_client;
2768 while (*pvc != NULL)
2769 pvc = &(*pvc)->next;
2770 *pvc = vc;
2771 return vc;
2774 int qemu_can_send_packet(VLANClientState *vc1)
2776 VLANState *vlan = vc1->vlan;
2777 VLANClientState *vc;
2779 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2780 if (vc != vc1) {
2781 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2782 return 0;
2785 return 1;
2788 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2790 VLANState *vlan = vc1->vlan;
2791 VLANClientState *vc;
2793 #if 0
2794 printf("vlan %d send:\n", vlan->id);
2795 hex_dump(stdout, buf, size);
2796 #endif
2797 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2798 if (vc != vc1) {
2799 vc->fd_read(vc->opaque, buf, size);
2804 #if defined(CONFIG_SLIRP)
2806 /* slirp network adapter */
2808 static int slirp_inited;
2809 static VLANClientState *slirp_vc;
2811 int slirp_can_output(void)
2813 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2816 void slirp_output(const uint8_t *pkt, int pkt_len)
2818 #if 0
2819 printf("slirp output:\n");
2820 hex_dump(stdout, pkt, pkt_len);
2821 #endif
2822 if (!slirp_vc)
2823 return;
2824 qemu_send_packet(slirp_vc, pkt, pkt_len);
2827 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2829 #if 0
2830 printf("slirp input:\n");
2831 hex_dump(stdout, buf, size);
2832 #endif
2833 slirp_input(buf, size);
2836 static int net_slirp_init(VLANState *vlan)
2838 if (!slirp_inited) {
2839 slirp_inited = 1;
2840 slirp_init();
2842 slirp_vc = qemu_new_vlan_client(vlan,
2843 slirp_receive, NULL, NULL);
2844 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2845 return 0;
2848 static void net_slirp_redir(const char *redir_str)
2850 int is_udp;
2851 char buf[256], *r;
2852 const char *p;
2853 struct in_addr guest_addr;
2854 int host_port, guest_port;
2856 if (!slirp_inited) {
2857 slirp_inited = 1;
2858 slirp_init();
2861 p = redir_str;
2862 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2863 goto fail;
2864 if (!strcmp(buf, "tcp")) {
2865 is_udp = 0;
2866 } else if (!strcmp(buf, "udp")) {
2867 is_udp = 1;
2868 } else {
2869 goto fail;
2872 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2873 goto fail;
2874 host_port = strtol(buf, &r, 0);
2875 if (r == buf)
2876 goto fail;
2878 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2879 goto fail;
2880 if (buf[0] == '\0') {
2881 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2883 if (!inet_aton(buf, &guest_addr))
2884 goto fail;
2886 guest_port = strtol(p, &r, 0);
2887 if (r == p)
2888 goto fail;
2890 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2891 fprintf(stderr, "qemu: could not set up redirection\n");
2892 exit(1);
2894 return;
2895 fail:
2896 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2897 exit(1);
2900 #ifndef _WIN32
2902 char smb_dir[1024];
2904 static void smb_exit(void)
2906 DIR *d;
2907 struct dirent *de;
2908 char filename[1024];
2910 /* erase all the files in the directory */
2911 d = opendir(smb_dir);
2912 for(;;) {
2913 de = readdir(d);
2914 if (!de)
2915 break;
2916 if (strcmp(de->d_name, ".") != 0 &&
2917 strcmp(de->d_name, "..") != 0) {
2918 snprintf(filename, sizeof(filename), "%s/%s",
2919 smb_dir, de->d_name);
2920 unlink(filename);
2923 closedir(d);
2924 rmdir(smb_dir);
2927 /* automatic user mode samba server configuration */
2928 void net_slirp_smb(const char *exported_dir)
2930 char smb_conf[1024];
2931 char smb_cmdline[1024];
2932 FILE *f;
2934 if (!slirp_inited) {
2935 slirp_inited = 1;
2936 slirp_init();
2939 /* XXX: better tmp dir construction */
2940 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2941 if (mkdir(smb_dir, 0700) < 0) {
2942 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2943 exit(1);
2945 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2947 f = fopen(smb_conf, "w");
2948 if (!f) {
2949 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2950 exit(1);
2952 fprintf(f,
2953 "[global]\n"
2954 "private dir=%s\n"
2955 "smb ports=0\n"
2956 "socket address=127.0.0.1\n"
2957 "pid directory=%s\n"
2958 "lock directory=%s\n"
2959 "log file=%s/log.smbd\n"
2960 "smb passwd file=%s/smbpasswd\n"
2961 "security = share\n"
2962 "[qemu]\n"
2963 "path=%s\n"
2964 "read only=no\n"
2965 "guest ok=yes\n",
2966 smb_dir,
2967 smb_dir,
2968 smb_dir,
2969 smb_dir,
2970 smb_dir,
2971 exported_dir
2973 fclose(f);
2974 atexit(smb_exit);
2976 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2977 smb_conf);
2979 slirp_add_exec(0, smb_cmdline, 4, 139);
2982 #endif /* !defined(_WIN32) */
2984 #endif /* CONFIG_SLIRP */
2986 #if !defined(_WIN32)
2988 typedef struct TAPState {
2989 VLANClientState *vc;
2990 int fd;
2991 } TAPState;
2993 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2995 TAPState *s = opaque;
2996 int ret;
2997 for(;;) {
2998 ret = write(s->fd, buf, size);
2999 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3000 } else {
3001 break;
3006 static void tap_send(void *opaque)
3008 TAPState *s = opaque;
3009 uint8_t buf[4096];
3010 int size;
3012 size = read(s->fd, buf, sizeof(buf));
3013 if (size > 0) {
3014 qemu_send_packet(s->vc, buf, size);
3018 /* fd support */
3020 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3022 TAPState *s;
3024 s = qemu_mallocz(sizeof(TAPState));
3025 if (!s)
3026 return NULL;
3027 s->fd = fd;
3028 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3029 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3030 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3031 return s;
3034 #ifdef _BSD
3035 static int tap_open(char *ifname, int ifname_size)
3037 int fd;
3038 char *dev;
3039 struct stat s;
3041 fd = open("/dev/tap", O_RDWR);
3042 if (fd < 0) {
3043 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3044 return -1;
3047 fstat(fd, &s);
3048 dev = devname(s.st_rdev, S_IFCHR);
3049 pstrcpy(ifname, ifname_size, dev);
3051 fcntl(fd, F_SETFL, O_NONBLOCK);
3052 return fd;
3054 #elif defined(__sun__)
3055 static int tap_open(char *ifname, int ifname_size)
3057 fprintf(stderr, "warning: tap_open not yet implemented\n");
3058 return -1;
3060 #else
3061 static int tap_open(char *ifname, int ifname_size)
3063 struct ifreq ifr;
3064 int fd, ret;
3066 fd = open("/dev/net/tun", O_RDWR);
3067 if (fd < 0) {
3068 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3069 return -1;
3071 memset(&ifr, 0, sizeof(ifr));
3072 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3073 if (ifname[0] != '\0')
3074 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3075 else
3076 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3077 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3078 if (ret != 0) {
3079 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3080 close(fd);
3081 return -1;
3083 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3084 fcntl(fd, F_SETFL, O_NONBLOCK);
3085 return fd;
3087 #endif
3089 static int net_tap_init(VLANState *vlan, const char *ifname1,
3090 const char *setup_script)
3092 TAPState *s;
3093 int pid, status, fd;
3094 char *args[3];
3095 char **parg;
3096 char ifname[128];
3098 if (ifname1 != NULL)
3099 pstrcpy(ifname, sizeof(ifname), ifname1);
3100 else
3101 ifname[0] = '\0';
3102 fd = tap_open(ifname, sizeof(ifname));
3103 if (fd < 0)
3104 return -1;
3106 if (!setup_script)
3107 setup_script = "";
3108 if (setup_script[0] != '\0') {
3109 /* try to launch network init script */
3110 pid = fork();
3111 if (pid >= 0) {
3112 if (pid == 0) {
3113 parg = args;
3114 *parg++ = (char *)setup_script;
3115 *parg++ = ifname;
3116 *parg++ = NULL;
3117 execv(setup_script, args);
3118 _exit(1);
3120 while (waitpid(pid, &status, 0) != pid);
3121 if (!WIFEXITED(status) ||
3122 WEXITSTATUS(status) != 0) {
3123 fprintf(stderr, "%s: could not launch network script\n",
3124 setup_script);
3125 return -1;
3129 s = net_tap_fd_init(vlan, fd);
3130 if (!s)
3131 return -1;
3132 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3133 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3134 return 0;
3137 #endif /* !_WIN32 */
3139 /* network connection */
3140 typedef struct NetSocketState {
3141 VLANClientState *vc;
3142 int fd;
3143 int state; /* 0 = getting length, 1 = getting data */
3144 int index;
3145 int packet_len;
3146 uint8_t buf[4096];
3147 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3148 } NetSocketState;
3150 typedef struct NetSocketListenState {
3151 VLANState *vlan;
3152 int fd;
3153 } NetSocketListenState;
3155 /* XXX: we consider we can send the whole packet without blocking */
3156 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3158 NetSocketState *s = opaque;
3159 uint32_t len;
3160 len = htonl(size);
3162 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3163 send_all(s->fd, buf, size);
3166 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3168 NetSocketState *s = opaque;
3169 sendto(s->fd, buf, size, 0,
3170 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3173 static void net_socket_send(void *opaque)
3175 NetSocketState *s = opaque;
3176 int l, size, err;
3177 uint8_t buf1[4096];
3178 const uint8_t *buf;
3180 size = recv(s->fd, buf1, sizeof(buf1), 0);
3181 if (size < 0) {
3182 err = socket_error();
3183 if (err != EWOULDBLOCK)
3184 goto eoc;
3185 } else if (size == 0) {
3186 /* end of connection */
3187 eoc:
3188 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3189 closesocket(s->fd);
3190 return;
3192 buf = buf1;
3193 while (size > 0) {
3194 /* reassemble a packet from the network */
3195 switch(s->state) {
3196 case 0:
3197 l = 4 - s->index;
3198 if (l > size)
3199 l = size;
3200 memcpy(s->buf + s->index, buf, l);
3201 buf += l;
3202 size -= l;
3203 s->index += l;
3204 if (s->index == 4) {
3205 /* got length */
3206 s->packet_len = ntohl(*(uint32_t *)s->buf);
3207 s->index = 0;
3208 s->state = 1;
3210 break;
3211 case 1:
3212 l = s->packet_len - s->index;
3213 if (l > size)
3214 l = size;
3215 memcpy(s->buf + s->index, buf, l);
3216 s->index += l;
3217 buf += l;
3218 size -= l;
3219 if (s->index >= s->packet_len) {
3220 qemu_send_packet(s->vc, s->buf, s->packet_len);
3221 s->index = 0;
3222 s->state = 0;
3224 break;
3229 static void net_socket_send_dgram(void *opaque)
3231 NetSocketState *s = opaque;
3232 int size;
3234 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3235 if (size < 0)
3236 return;
3237 if (size == 0) {
3238 /* end of connection */
3239 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3240 return;
3242 qemu_send_packet(s->vc, s->buf, size);
3245 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3247 struct ip_mreq imr;
3248 int fd;
3249 int val, ret;
3250 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3251 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3252 inet_ntoa(mcastaddr->sin_addr),
3253 (int)ntohl(mcastaddr->sin_addr.s_addr));
3254 return -1;
3257 fd = socket(PF_INET, SOCK_DGRAM, 0);
3258 if (fd < 0) {
3259 perror("socket(PF_INET, SOCK_DGRAM)");
3260 return -1;
3263 val = 1;
3264 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3265 (const char *)&val, sizeof(val));
3266 if (ret < 0) {
3267 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3268 goto fail;
3271 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3272 if (ret < 0) {
3273 perror("bind");
3274 goto fail;
3277 /* Add host to multicast group */
3278 imr.imr_multiaddr = mcastaddr->sin_addr;
3279 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3281 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3282 (const char *)&imr, sizeof(struct ip_mreq));
3283 if (ret < 0) {
3284 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3285 goto fail;
3288 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3289 val = 1;
3290 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3291 (const char *)&val, sizeof(val));
3292 if (ret < 0) {
3293 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3294 goto fail;
3297 socket_set_nonblock(fd);
3298 return fd;
3299 fail:
3300 if (fd >= 0)
3301 closesocket(fd);
3302 return -1;
3305 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3306 int is_connected)
3308 struct sockaddr_in saddr;
3309 int newfd;
3310 socklen_t saddr_len;
3311 NetSocketState *s;
3313 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3314 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3315 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3318 if (is_connected) {
3319 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3320 /* must be bound */
3321 if (saddr.sin_addr.s_addr==0) {
3322 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3323 fd);
3324 return NULL;
3326 /* clone dgram socket */
3327 newfd = net_socket_mcast_create(&saddr);
3328 if (newfd < 0) {
3329 /* error already reported by net_socket_mcast_create() */
3330 close(fd);
3331 return NULL;
3333 /* clone newfd to fd, close newfd */
3334 dup2(newfd, fd);
3335 close(newfd);
3337 } else {
3338 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3339 fd, strerror(errno));
3340 return NULL;
3344 s = qemu_mallocz(sizeof(NetSocketState));
3345 if (!s)
3346 return NULL;
3347 s->fd = fd;
3349 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3350 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3352 /* mcast: save bound address as dst */
3353 if (is_connected) s->dgram_dst=saddr;
3355 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3356 "socket: fd=%d (%s mcast=%s:%d)",
3357 fd, is_connected? "cloned" : "",
3358 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3359 return s;
3362 static void net_socket_connect(void *opaque)
3364 NetSocketState *s = opaque;
3365 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3368 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3369 int is_connected)
3371 NetSocketState *s;
3372 s = qemu_mallocz(sizeof(NetSocketState));
3373 if (!s)
3374 return NULL;
3375 s->fd = fd;
3376 s->vc = qemu_new_vlan_client(vlan,
3377 net_socket_receive, NULL, s);
3378 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3379 "socket: fd=%d", fd);
3380 if (is_connected) {
3381 net_socket_connect(s);
3382 } else {
3383 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3385 return s;
3388 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3389 int is_connected)
3391 int so_type=-1, optlen=sizeof(so_type);
3393 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3394 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3395 return NULL;
3397 switch(so_type) {
3398 case SOCK_DGRAM:
3399 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3400 case SOCK_STREAM:
3401 return net_socket_fd_init_stream(vlan, fd, is_connected);
3402 default:
3403 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3404 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3405 return net_socket_fd_init_stream(vlan, fd, is_connected);
3407 return NULL;
3410 static void net_socket_accept(void *opaque)
3412 NetSocketListenState *s = opaque;
3413 NetSocketState *s1;
3414 struct sockaddr_in saddr;
3415 socklen_t len;
3416 int fd;
3418 for(;;) {
3419 len = sizeof(saddr);
3420 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3421 if (fd < 0 && errno != EINTR) {
3422 return;
3423 } else if (fd >= 0) {
3424 break;
3427 s1 = net_socket_fd_init(s->vlan, fd, 1);
3428 if (!s1) {
3429 closesocket(fd);
3430 } else {
3431 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3432 "socket: connection from %s:%d",
3433 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3437 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3439 NetSocketListenState *s;
3440 int fd, val, ret;
3441 struct sockaddr_in saddr;
3443 if (parse_host_port(&saddr, host_str) < 0)
3444 return -1;
3446 s = qemu_mallocz(sizeof(NetSocketListenState));
3447 if (!s)
3448 return -1;
3450 fd = socket(PF_INET, SOCK_STREAM, 0);
3451 if (fd < 0) {
3452 perror("socket");
3453 return -1;
3455 socket_set_nonblock(fd);
3457 /* allow fast reuse */
3458 val = 1;
3459 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3461 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3462 if (ret < 0) {
3463 perror("bind");
3464 return -1;
3466 ret = listen(fd, 0);
3467 if (ret < 0) {
3468 perror("listen");
3469 return -1;
3471 s->vlan = vlan;
3472 s->fd = fd;
3473 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3474 return 0;
3477 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3479 NetSocketState *s;
3480 int fd, connected, ret, err;
3481 struct sockaddr_in saddr;
3483 if (parse_host_port(&saddr, host_str) < 0)
3484 return -1;
3486 fd = socket(PF_INET, SOCK_STREAM, 0);
3487 if (fd < 0) {
3488 perror("socket");
3489 return -1;
3491 socket_set_nonblock(fd);
3493 connected = 0;
3494 for(;;) {
3495 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3496 if (ret < 0) {
3497 err = socket_error();
3498 if (err == EINTR || err == EWOULDBLOCK) {
3499 } else if (err == EINPROGRESS) {
3500 break;
3501 } else {
3502 perror("connect");
3503 closesocket(fd);
3504 return -1;
3506 } else {
3507 connected = 1;
3508 break;
3511 s = net_socket_fd_init(vlan, fd, connected);
3512 if (!s)
3513 return -1;
3514 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3515 "socket: connect to %s:%d",
3516 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3517 return 0;
3520 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3522 NetSocketState *s;
3523 int fd;
3524 struct sockaddr_in saddr;
3526 if (parse_host_port(&saddr, host_str) < 0)
3527 return -1;
3530 fd = net_socket_mcast_create(&saddr);
3531 if (fd < 0)
3532 return -1;
3534 s = net_socket_fd_init(vlan, fd, 0);
3535 if (!s)
3536 return -1;
3538 s->dgram_dst = saddr;
3540 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3541 "socket: mcast=%s:%d",
3542 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3543 return 0;
3547 static int get_param_value(char *buf, int buf_size,
3548 const char *tag, const char *str)
3550 const char *p;
3551 char *q;
3552 char option[128];
3554 p = str;
3555 for(;;) {
3556 q = option;
3557 while (*p != '\0' && *p != '=') {
3558 if ((q - option) < sizeof(option) - 1)
3559 *q++ = *p;
3560 p++;
3562 *q = '\0';
3563 if (*p != '=')
3564 break;
3565 p++;
3566 if (!strcmp(tag, option)) {
3567 q = buf;
3568 while (*p != '\0' && *p != ',') {
3569 if ((q - buf) < buf_size - 1)
3570 *q++ = *p;
3571 p++;
3573 *q = '\0';
3574 return q - buf;
3575 } else {
3576 while (*p != '\0' && *p != ',') {
3577 p++;
3580 if (*p != ',')
3581 break;
3582 p++;
3584 return 0;
3587 int net_client_init(const char *str)
3589 const char *p;
3590 char *q;
3591 char device[64];
3592 char buf[1024];
3593 int vlan_id, ret;
3594 VLANState *vlan;
3596 p = str;
3597 q = device;
3598 while (*p != '\0' && *p != ',') {
3599 if ((q - device) < sizeof(device) - 1)
3600 *q++ = *p;
3601 p++;
3603 *q = '\0';
3604 if (*p == ',')
3605 p++;
3606 vlan_id = 0;
3607 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3608 vlan_id = strtol(buf, NULL, 0);
3610 vlan = qemu_find_vlan(vlan_id);
3611 if (!vlan) {
3612 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3613 return -1;
3615 if (!strcmp(device, "nic")) {
3616 NICInfo *nd;
3617 uint8_t *macaddr;
3619 if (nb_nics >= MAX_NICS) {
3620 fprintf(stderr, "Too Many NICs\n");
3621 return -1;
3623 nd = &nd_table[nb_nics];
3624 macaddr = nd->macaddr;
3625 macaddr[0] = 0x52;
3626 macaddr[1] = 0x54;
3627 macaddr[2] = 0x00;
3628 macaddr[3] = 0x12;
3629 macaddr[4] = 0x34;
3630 macaddr[5] = 0x56 + nb_nics;
3632 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3633 if (parse_macaddr(macaddr, buf) < 0) {
3634 fprintf(stderr, "invalid syntax for ethernet address\n");
3635 return -1;
3638 if (get_param_value(buf, sizeof(buf), "model", p)) {
3639 nd->model = strdup(buf);
3641 nd->vlan = vlan;
3642 nb_nics++;
3643 ret = 0;
3644 } else
3645 if (!strcmp(device, "none")) {
3646 /* does nothing. It is needed to signal that no network cards
3647 are wanted */
3648 ret = 0;
3649 } else
3650 #ifdef CONFIG_SLIRP
3651 if (!strcmp(device, "user")) {
3652 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3653 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3655 ret = net_slirp_init(vlan);
3656 } else
3657 #endif
3658 #ifdef _WIN32
3659 if (!strcmp(device, "tap")) {
3660 char ifname[64];
3661 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3662 fprintf(stderr, "tap: no interface name\n");
3663 return -1;
3665 ret = tap_win32_init(vlan, ifname);
3666 } else
3667 #else
3668 if (!strcmp(device, "tap")) {
3669 char ifname[64];
3670 char setup_script[1024];
3671 int fd;
3672 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3673 fd = strtol(buf, NULL, 0);
3674 ret = -1;
3675 if (net_tap_fd_init(vlan, fd))
3676 ret = 0;
3677 } else {
3678 get_param_value(ifname, sizeof(ifname), "ifname", p);
3679 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3680 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3682 ret = net_tap_init(vlan, ifname, setup_script);
3684 } else
3685 #endif
3686 if (!strcmp(device, "socket")) {
3687 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3688 int fd;
3689 fd = strtol(buf, NULL, 0);
3690 ret = -1;
3691 if (net_socket_fd_init(vlan, fd, 1))
3692 ret = 0;
3693 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3694 ret = net_socket_listen_init(vlan, buf);
3695 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3696 ret = net_socket_connect_init(vlan, buf);
3697 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3698 ret = net_socket_mcast_init(vlan, buf);
3699 } else {
3700 fprintf(stderr, "Unknown socket options: %s\n", p);
3701 return -1;
3703 } else
3705 fprintf(stderr, "Unknown network device: %s\n", device);
3706 return -1;
3708 if (ret < 0) {
3709 fprintf(stderr, "Could not initialize device '%s'\n", device);
3712 return ret;
3715 void do_info_network(void)
3717 VLANState *vlan;
3718 VLANClientState *vc;
3720 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3721 term_printf("VLAN %d devices:\n", vlan->id);
3722 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3723 term_printf(" %s\n", vc->info_str);
3727 /***********************************************************/
3728 /* USB devices */
3730 static USBPort *used_usb_ports;
3731 static USBPort *free_usb_ports;
3733 /* ??? Maybe change this to register a hub to keep track of the topology. */
3734 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3735 usb_attachfn attach)
3737 port->opaque = opaque;
3738 port->index = index;
3739 port->attach = attach;
3740 port->next = free_usb_ports;
3741 free_usb_ports = port;
3744 static int usb_device_add(const char *devname)
3746 const char *p;
3747 USBDevice *dev;
3748 USBPort *port;
3750 if (!free_usb_ports)
3751 return -1;
3753 if (strstart(devname, "host:", &p)) {
3754 dev = usb_host_device_open(p);
3755 } else if (!strcmp(devname, "mouse")) {
3756 dev = usb_mouse_init();
3757 } else if (!strcmp(devname, "tablet")) {
3758 dev = usb_tablet_init();
3759 } else if (strstart(devname, "disk:", &p)) {
3760 dev = usb_msd_init(p);
3761 } else {
3762 return -1;
3764 if (!dev)
3765 return -1;
3767 /* Find a USB port to add the device to. */
3768 port = free_usb_ports;
3769 if (!port->next) {
3770 USBDevice *hub;
3772 /* Create a new hub and chain it on. */
3773 free_usb_ports = NULL;
3774 port->next = used_usb_ports;
3775 used_usb_ports = port;
3777 hub = usb_hub_init(VM_USB_HUB_SIZE);
3778 usb_attach(port, hub);
3779 port = free_usb_ports;
3782 free_usb_ports = port->next;
3783 port->next = used_usb_ports;
3784 used_usb_ports = port;
3785 usb_attach(port, dev);
3786 return 0;
3789 static int usb_device_del(const char *devname)
3791 USBPort *port;
3792 USBPort **lastp;
3793 USBDevice *dev;
3794 int bus_num, addr;
3795 const char *p;
3797 if (!used_usb_ports)
3798 return -1;
3800 p = strchr(devname, '.');
3801 if (!p)
3802 return -1;
3803 bus_num = strtoul(devname, NULL, 0);
3804 addr = strtoul(p + 1, NULL, 0);
3805 if (bus_num != 0)
3806 return -1;
3808 lastp = &used_usb_ports;
3809 port = used_usb_ports;
3810 while (port && port->dev->addr != addr) {
3811 lastp = &port->next;
3812 port = port->next;
3815 if (!port)
3816 return -1;
3818 dev = port->dev;
3819 *lastp = port->next;
3820 usb_attach(port, NULL);
3821 dev->handle_destroy(dev);
3822 port->next = free_usb_ports;
3823 free_usb_ports = port;
3824 return 0;
3827 void do_usb_add(const char *devname)
3829 int ret;
3830 ret = usb_device_add(devname);
3831 if (ret < 0)
3832 term_printf("Could not add USB device '%s'\n", devname);
3835 void do_usb_del(const char *devname)
3837 int ret;
3838 ret = usb_device_del(devname);
3839 if (ret < 0)
3840 term_printf("Could not remove USB device '%s'\n", devname);
3843 void usb_info(void)
3845 USBDevice *dev;
3846 USBPort *port;
3847 const char *speed_str;
3849 if (!usb_enabled) {
3850 term_printf("USB support not enabled\n");
3851 return;
3854 for (port = used_usb_ports; port; port = port->next) {
3855 dev = port->dev;
3856 if (!dev)
3857 continue;
3858 switch(dev->speed) {
3859 case USB_SPEED_LOW:
3860 speed_str = "1.5";
3861 break;
3862 case USB_SPEED_FULL:
3863 speed_str = "12";
3864 break;
3865 case USB_SPEED_HIGH:
3866 speed_str = "480";
3867 break;
3868 default:
3869 speed_str = "?";
3870 break;
3872 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
3873 0, dev->addr, speed_str, dev->devname);
3877 /***********************************************************/
3878 /* pid file */
3880 static char *pid_filename;
3882 /* Remove PID file. Called on normal exit */
3884 static void remove_pidfile(void)
3886 unlink (pid_filename);
3889 static void create_pidfile(const char *filename)
3891 struct stat pidstat;
3892 FILE *f;
3894 /* Try to write our PID to the named file */
3895 if (stat(filename, &pidstat) < 0) {
3896 if (errno == ENOENT) {
3897 if ((f = fopen (filename, "w")) == NULL) {
3898 perror("Opening pidfile");
3899 exit(1);
3901 fprintf(f, "%d\n", getpid());
3902 fclose(f);
3903 pid_filename = qemu_strdup(filename);
3904 if (!pid_filename) {
3905 fprintf(stderr, "Could not save PID filename");
3906 exit(1);
3908 atexit(remove_pidfile);
3910 } else {
3911 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3912 filename);
3913 exit(1);
3917 /***********************************************************/
3918 /* dumb display */
3920 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3924 static void dumb_resize(DisplayState *ds, int w, int h)
3928 static void dumb_refresh(DisplayState *ds)
3930 vga_hw_update();
3933 void dumb_display_init(DisplayState *ds)
3935 ds->data = NULL;
3936 ds->linesize = 0;
3937 ds->depth = 0;
3938 ds->dpy_update = dumb_update;
3939 ds->dpy_resize = dumb_resize;
3940 ds->dpy_refresh = dumb_refresh;
3943 /***********************************************************/
3944 /* I/O handling */
3946 #define MAX_IO_HANDLERS 64
3948 typedef struct IOHandlerRecord {
3949 int fd;
3950 IOCanRWHandler *fd_read_poll;
3951 IOHandler *fd_read;
3952 IOHandler *fd_write;
3953 void *opaque;
3954 /* temporary data */
3955 struct pollfd *ufd;
3956 struct IOHandlerRecord *next;
3957 } IOHandlerRecord;
3959 static IOHandlerRecord *first_io_handler;
3961 /* XXX: fd_read_poll should be suppressed, but an API change is
3962 necessary in the character devices to suppress fd_can_read(). */
3963 int qemu_set_fd_handler2(int fd,
3964 IOCanRWHandler *fd_read_poll,
3965 IOHandler *fd_read,
3966 IOHandler *fd_write,
3967 void *opaque)
3969 IOHandlerRecord **pioh, *ioh;
3971 if (!fd_read && !fd_write) {
3972 pioh = &first_io_handler;
3973 for(;;) {
3974 ioh = *pioh;
3975 if (ioh == NULL)
3976 break;
3977 if (ioh->fd == fd) {
3978 *pioh = ioh->next;
3979 qemu_free(ioh);
3980 break;
3982 pioh = &ioh->next;
3984 } else {
3985 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3986 if (ioh->fd == fd)
3987 goto found;
3989 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3990 if (!ioh)
3991 return -1;
3992 ioh->next = first_io_handler;
3993 first_io_handler = ioh;
3994 found:
3995 ioh->fd = fd;
3996 ioh->fd_read_poll = fd_read_poll;
3997 ioh->fd_read = fd_read;
3998 ioh->fd_write = fd_write;
3999 ioh->opaque = opaque;
4001 return 0;
4004 int qemu_set_fd_handler(int fd,
4005 IOHandler *fd_read,
4006 IOHandler *fd_write,
4007 void *opaque)
4009 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4012 /***********************************************************/
4013 /* Polling handling */
4015 typedef struct PollingEntry {
4016 PollingFunc *func;
4017 void *opaque;
4018 struct PollingEntry *next;
4019 } PollingEntry;
4021 static PollingEntry *first_polling_entry;
4023 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4025 PollingEntry **ppe, *pe;
4026 pe = qemu_mallocz(sizeof(PollingEntry));
4027 if (!pe)
4028 return -1;
4029 pe->func = func;
4030 pe->opaque = opaque;
4031 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4032 *ppe = pe;
4033 return 0;
4036 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4038 PollingEntry **ppe, *pe;
4039 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4040 pe = *ppe;
4041 if (pe->func == func && pe->opaque == opaque) {
4042 *ppe = pe->next;
4043 qemu_free(pe);
4044 break;
4049 #ifdef _WIN32
4050 /***********************************************************/
4051 /* Wait objects support */
4052 typedef struct WaitObjects {
4053 int num;
4054 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4055 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4056 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4057 } WaitObjects;
4059 static WaitObjects wait_objects = {0};
4061 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4063 WaitObjects *w = &wait_objects;
4065 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4066 return -1;
4067 w->events[w->num] = handle;
4068 w->func[w->num] = func;
4069 w->opaque[w->num] = opaque;
4070 w->num++;
4071 return 0;
4074 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4076 int i, found;
4077 WaitObjects *w = &wait_objects;
4079 found = 0;
4080 for (i = 0; i < w->num; i++) {
4081 if (w->events[i] == handle)
4082 found = 1;
4083 if (found) {
4084 w->events[i] = w->events[i + 1];
4085 w->func[i] = w->func[i + 1];
4086 w->opaque[i] = w->opaque[i + 1];
4089 if (found)
4090 w->num--;
4092 #endif
4094 /***********************************************************/
4095 /* savevm/loadvm support */
4097 #define IO_BUF_SIZE 32768
4099 struct QEMUFile {
4100 FILE *outfile;
4101 BlockDriverState *bs;
4102 int is_file;
4103 int is_writable;
4104 int64_t base_offset;
4105 int64_t buf_offset; /* start of buffer when writing, end of buffer
4106 when reading */
4107 int buf_index;
4108 int buf_size; /* 0 when writing */
4109 uint8_t buf[IO_BUF_SIZE];
4112 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4114 QEMUFile *f;
4116 f = qemu_mallocz(sizeof(QEMUFile));
4117 if (!f)
4118 return NULL;
4119 if (!strcmp(mode, "wb")) {
4120 f->is_writable = 1;
4121 } else if (!strcmp(mode, "rb")) {
4122 f->is_writable = 0;
4123 } else {
4124 goto fail;
4126 f->outfile = fopen(filename, mode);
4127 if (!f->outfile)
4128 goto fail;
4129 f->is_file = 1;
4130 return f;
4131 fail:
4132 if (f->outfile)
4133 fclose(f->outfile);
4134 qemu_free(f);
4135 return NULL;
4138 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4140 QEMUFile *f;
4142 f = qemu_mallocz(sizeof(QEMUFile));
4143 if (!f)
4144 return NULL;
4145 f->is_file = 0;
4146 f->bs = bs;
4147 f->is_writable = is_writable;
4148 f->base_offset = offset;
4149 return f;
4152 void qemu_fflush(QEMUFile *f)
4154 if (!f->is_writable)
4155 return;
4156 if (f->buf_index > 0) {
4157 if (f->is_file) {
4158 fseek(f->outfile, f->buf_offset, SEEK_SET);
4159 fwrite(f->buf, 1, f->buf_index, f->outfile);
4160 } else {
4161 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4162 f->buf, f->buf_index);
4164 f->buf_offset += f->buf_index;
4165 f->buf_index = 0;
4169 static void qemu_fill_buffer(QEMUFile *f)
4171 int len;
4173 if (f->is_writable)
4174 return;
4175 if (f->is_file) {
4176 fseek(f->outfile, f->buf_offset, SEEK_SET);
4177 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4178 if (len < 0)
4179 len = 0;
4180 } else {
4181 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4182 f->buf, IO_BUF_SIZE);
4183 if (len < 0)
4184 len = 0;
4186 f->buf_index = 0;
4187 f->buf_size = len;
4188 f->buf_offset += len;
4191 void qemu_fclose(QEMUFile *f)
4193 if (f->is_writable)
4194 qemu_fflush(f);
4195 if (f->is_file) {
4196 fclose(f->outfile);
4198 qemu_free(f);
4201 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4203 int l;
4204 while (size > 0) {
4205 l = IO_BUF_SIZE - f->buf_index;
4206 if (l > size)
4207 l = size;
4208 memcpy(f->buf + f->buf_index, buf, l);
4209 f->buf_index += l;
4210 buf += l;
4211 size -= l;
4212 if (f->buf_index >= IO_BUF_SIZE)
4213 qemu_fflush(f);
4217 void qemu_put_byte(QEMUFile *f, int v)
4219 f->buf[f->buf_index++] = v;
4220 if (f->buf_index >= IO_BUF_SIZE)
4221 qemu_fflush(f);
4224 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4226 int size, l;
4228 size = size1;
4229 while (size > 0) {
4230 l = f->buf_size - f->buf_index;
4231 if (l == 0) {
4232 qemu_fill_buffer(f);
4233 l = f->buf_size - f->buf_index;
4234 if (l == 0)
4235 break;
4237 if (l > size)
4238 l = size;
4239 memcpy(buf, f->buf + f->buf_index, l);
4240 f->buf_index += l;
4241 buf += l;
4242 size -= l;
4244 return size1 - size;
4247 int qemu_get_byte(QEMUFile *f)
4249 if (f->buf_index >= f->buf_size) {
4250 qemu_fill_buffer(f);
4251 if (f->buf_index >= f->buf_size)
4252 return 0;
4254 return f->buf[f->buf_index++];
4257 int64_t qemu_ftell(QEMUFile *f)
4259 return f->buf_offset - f->buf_size + f->buf_index;
4262 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4264 if (whence == SEEK_SET) {
4265 /* nothing to do */
4266 } else if (whence == SEEK_CUR) {
4267 pos += qemu_ftell(f);
4268 } else {
4269 /* SEEK_END not supported */
4270 return -1;
4272 if (f->is_writable) {
4273 qemu_fflush(f);
4274 f->buf_offset = pos;
4275 } else {
4276 f->buf_offset = pos;
4277 f->buf_index = 0;
4278 f->buf_size = 0;
4280 return pos;
4283 void qemu_put_be16(QEMUFile *f, unsigned int v)
4285 qemu_put_byte(f, v >> 8);
4286 qemu_put_byte(f, v);
4289 void qemu_put_be32(QEMUFile *f, unsigned int v)
4291 qemu_put_byte(f, v >> 24);
4292 qemu_put_byte(f, v >> 16);
4293 qemu_put_byte(f, v >> 8);
4294 qemu_put_byte(f, v);
4297 void qemu_put_be64(QEMUFile *f, uint64_t v)
4299 qemu_put_be32(f, v >> 32);
4300 qemu_put_be32(f, v);
4303 unsigned int qemu_get_be16(QEMUFile *f)
4305 unsigned int v;
4306 v = qemu_get_byte(f) << 8;
4307 v |= qemu_get_byte(f);
4308 return v;
4311 unsigned int qemu_get_be32(QEMUFile *f)
4313 unsigned int v;
4314 v = qemu_get_byte(f) << 24;
4315 v |= qemu_get_byte(f) << 16;
4316 v |= qemu_get_byte(f) << 8;
4317 v |= qemu_get_byte(f);
4318 return v;
4321 uint64_t qemu_get_be64(QEMUFile *f)
4323 uint64_t v;
4324 v = (uint64_t)qemu_get_be32(f) << 32;
4325 v |= qemu_get_be32(f);
4326 return v;
4329 typedef struct SaveStateEntry {
4330 char idstr[256];
4331 int instance_id;
4332 int version_id;
4333 SaveStateHandler *save_state;
4334 LoadStateHandler *load_state;
4335 void *opaque;
4336 struct SaveStateEntry *next;
4337 } SaveStateEntry;
4339 static SaveStateEntry *first_se;
4341 int register_savevm(const char *idstr,
4342 int instance_id,
4343 int version_id,
4344 SaveStateHandler *save_state,
4345 LoadStateHandler *load_state,
4346 void *opaque)
4348 SaveStateEntry *se, **pse;
4350 se = qemu_malloc(sizeof(SaveStateEntry));
4351 if (!se)
4352 return -1;
4353 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4354 se->instance_id = instance_id;
4355 se->version_id = version_id;
4356 se->save_state = save_state;
4357 se->load_state = load_state;
4358 se->opaque = opaque;
4359 se->next = NULL;
4361 /* add at the end of list */
4362 pse = &first_se;
4363 while (*pse != NULL)
4364 pse = &(*pse)->next;
4365 *pse = se;
4366 return 0;
4369 #define QEMU_VM_FILE_MAGIC 0x5145564d
4370 #define QEMU_VM_FILE_VERSION 0x00000002
4372 int qemu_savevm_state(QEMUFile *f)
4374 SaveStateEntry *se;
4375 int len, ret;
4376 int64_t cur_pos, len_pos, total_len_pos;
4378 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4379 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4380 total_len_pos = qemu_ftell(f);
4381 qemu_put_be64(f, 0); /* total size */
4383 for(se = first_se; se != NULL; se = se->next) {
4384 /* ID string */
4385 len = strlen(se->idstr);
4386 qemu_put_byte(f, len);
4387 qemu_put_buffer(f, se->idstr, len);
4389 qemu_put_be32(f, se->instance_id);
4390 qemu_put_be32(f, se->version_id);
4392 /* record size: filled later */
4393 len_pos = qemu_ftell(f);
4394 qemu_put_be32(f, 0);
4396 se->save_state(f, se->opaque);
4398 /* fill record size */
4399 cur_pos = qemu_ftell(f);
4400 len = cur_pos - len_pos - 4;
4401 qemu_fseek(f, len_pos, SEEK_SET);
4402 qemu_put_be32(f, len);
4403 qemu_fseek(f, cur_pos, SEEK_SET);
4405 cur_pos = qemu_ftell(f);
4406 qemu_fseek(f, total_len_pos, SEEK_SET);
4407 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4408 qemu_fseek(f, cur_pos, SEEK_SET);
4410 ret = 0;
4411 return ret;
4414 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4416 SaveStateEntry *se;
4418 for(se = first_se; se != NULL; se = se->next) {
4419 if (!strcmp(se->idstr, idstr) &&
4420 instance_id == se->instance_id)
4421 return se;
4423 return NULL;
4426 int qemu_loadvm_state(QEMUFile *f)
4428 SaveStateEntry *se;
4429 int len, ret, instance_id, record_len, version_id;
4430 int64_t total_len, end_pos, cur_pos;
4431 unsigned int v;
4432 char idstr[256];
4434 v = qemu_get_be32(f);
4435 if (v != QEMU_VM_FILE_MAGIC)
4436 goto fail;
4437 v = qemu_get_be32(f);
4438 if (v != QEMU_VM_FILE_VERSION) {
4439 fail:
4440 ret = -1;
4441 goto the_end;
4443 total_len = qemu_get_be64(f);
4444 end_pos = total_len + qemu_ftell(f);
4445 for(;;) {
4446 if (qemu_ftell(f) >= end_pos)
4447 break;
4448 len = qemu_get_byte(f);
4449 qemu_get_buffer(f, idstr, len);
4450 idstr[len] = '\0';
4451 instance_id = qemu_get_be32(f);
4452 version_id = qemu_get_be32(f);
4453 record_len = qemu_get_be32(f);
4454 #if 0
4455 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4456 idstr, instance_id, version_id, record_len);
4457 #endif
4458 cur_pos = qemu_ftell(f);
4459 se = find_se(idstr, instance_id);
4460 if (!se) {
4461 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4462 instance_id, idstr);
4463 } else {
4464 ret = se->load_state(f, se->opaque, version_id);
4465 if (ret < 0) {
4466 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4467 instance_id, idstr);
4470 /* always seek to exact end of record */
4471 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4473 ret = 0;
4474 the_end:
4475 return ret;
4478 /* device can contain snapshots */
4479 static int bdrv_can_snapshot(BlockDriverState *bs)
4481 return (bs &&
4482 !bdrv_is_removable(bs) &&
4483 !bdrv_is_read_only(bs));
4486 /* device must be snapshots in order to have a reliable snapshot */
4487 static int bdrv_has_snapshot(BlockDriverState *bs)
4489 return (bs &&
4490 !bdrv_is_removable(bs) &&
4491 !bdrv_is_read_only(bs));
4494 static BlockDriverState *get_bs_snapshots(void)
4496 BlockDriverState *bs;
4497 int i;
4499 if (bs_snapshots)
4500 return bs_snapshots;
4501 for(i = 0; i <= MAX_DISKS; i++) {
4502 bs = bs_table[i];
4503 if (bdrv_can_snapshot(bs))
4504 goto ok;
4506 return NULL;
4508 bs_snapshots = bs;
4509 return bs;
4512 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4513 const char *name)
4515 QEMUSnapshotInfo *sn_tab, *sn;
4516 int nb_sns, i, ret;
4518 ret = -ENOENT;
4519 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4520 if (nb_sns < 0)
4521 return ret;
4522 for(i = 0; i < nb_sns; i++) {
4523 sn = &sn_tab[i];
4524 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4525 *sn_info = *sn;
4526 ret = 0;
4527 break;
4530 qemu_free(sn_tab);
4531 return ret;
4534 void do_savevm(const char *name)
4536 BlockDriverState *bs, *bs1;
4537 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4538 int must_delete, ret, i;
4539 BlockDriverInfo bdi1, *bdi = &bdi1;
4540 QEMUFile *f;
4541 int saved_vm_running;
4542 #ifdef _WIN32
4543 struct _timeb tb;
4544 #else
4545 struct timeval tv;
4546 #endif
4548 bs = get_bs_snapshots();
4549 if (!bs) {
4550 term_printf("No block device can accept snapshots\n");
4551 return;
4554 /* ??? Should this occur after vm_stop? */
4555 qemu_aio_flush();
4557 saved_vm_running = vm_running;
4558 vm_stop(0);
4560 must_delete = 0;
4561 if (name) {
4562 ret = bdrv_snapshot_find(bs, old_sn, name);
4563 if (ret >= 0) {
4564 must_delete = 1;
4567 memset(sn, 0, sizeof(*sn));
4568 if (must_delete) {
4569 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4570 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4571 } else {
4572 if (name)
4573 pstrcpy(sn->name, sizeof(sn->name), name);
4576 /* fill auxiliary fields */
4577 #ifdef _WIN32
4578 _ftime(&tb);
4579 sn->date_sec = tb.time;
4580 sn->date_nsec = tb.millitm * 1000000;
4581 #else
4582 gettimeofday(&tv, NULL);
4583 sn->date_sec = tv.tv_sec;
4584 sn->date_nsec = tv.tv_usec * 1000;
4585 #endif
4586 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4588 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4589 term_printf("Device %s does not support VM state snapshots\n",
4590 bdrv_get_device_name(bs));
4591 goto the_end;
4594 /* save the VM state */
4595 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4596 if (!f) {
4597 term_printf("Could not open VM state file\n");
4598 goto the_end;
4600 ret = qemu_savevm_state(f);
4601 sn->vm_state_size = qemu_ftell(f);
4602 qemu_fclose(f);
4603 if (ret < 0) {
4604 term_printf("Error %d while writing VM\n", ret);
4605 goto the_end;
4608 /* create the snapshots */
4610 for(i = 0; i < MAX_DISKS; i++) {
4611 bs1 = bs_table[i];
4612 if (bdrv_has_snapshot(bs1)) {
4613 if (must_delete) {
4614 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
4615 if (ret < 0) {
4616 term_printf("Error while deleting snapshot on '%s'\n",
4617 bdrv_get_device_name(bs1));
4620 ret = bdrv_snapshot_create(bs1, sn);
4621 if (ret < 0) {
4622 term_printf("Error while creating snapshot on '%s'\n",
4623 bdrv_get_device_name(bs1));
4628 the_end:
4629 if (saved_vm_running)
4630 vm_start();
4633 void do_loadvm(const char *name)
4635 BlockDriverState *bs, *bs1;
4636 BlockDriverInfo bdi1, *bdi = &bdi1;
4637 QEMUFile *f;
4638 int i, ret;
4639 int saved_vm_running;
4641 bs = get_bs_snapshots();
4642 if (!bs) {
4643 term_printf("No block device supports snapshots\n");
4644 return;
4647 /* Flush all IO requests so they don't interfere with the new state. */
4648 qemu_aio_flush();
4650 saved_vm_running = vm_running;
4651 vm_stop(0);
4653 for(i = 0; i <= MAX_DISKS; i++) {
4654 bs1 = bs_table[i];
4655 if (bdrv_has_snapshot(bs1)) {
4656 ret = bdrv_snapshot_goto(bs1, name);
4657 if (ret < 0) {
4658 if (bs != bs1)
4659 term_printf("Warning: ");
4660 switch(ret) {
4661 case -ENOTSUP:
4662 term_printf("Snapshots not supported on device '%s'\n",
4663 bdrv_get_device_name(bs1));
4664 break;
4665 case -ENOENT:
4666 term_printf("Could not find snapshot '%s' on device '%s'\n",
4667 name, bdrv_get_device_name(bs1));
4668 break;
4669 default:
4670 term_printf("Error %d while activating snapshot on '%s'\n",
4671 ret, bdrv_get_device_name(bs1));
4672 break;
4674 /* fatal on snapshot block device */
4675 if (bs == bs1)
4676 goto the_end;
4681 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4682 term_printf("Device %s does not support VM state snapshots\n",
4683 bdrv_get_device_name(bs));
4684 return;
4687 /* restore the VM state */
4688 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
4689 if (!f) {
4690 term_printf("Could not open VM state file\n");
4691 goto the_end;
4693 ret = qemu_loadvm_state(f);
4694 qemu_fclose(f);
4695 if (ret < 0) {
4696 term_printf("Error %d while loading VM state\n", ret);
4698 the_end:
4699 if (saved_vm_running)
4700 vm_start();
4703 void do_delvm(const char *name)
4705 BlockDriverState *bs, *bs1;
4706 int i, ret;
4708 bs = get_bs_snapshots();
4709 if (!bs) {
4710 term_printf("No block device supports snapshots\n");
4711 return;
4714 for(i = 0; i <= MAX_DISKS; i++) {
4715 bs1 = bs_table[i];
4716 if (bdrv_has_snapshot(bs1)) {
4717 ret = bdrv_snapshot_delete(bs1, name);
4718 if (ret < 0) {
4719 if (ret == -ENOTSUP)
4720 term_printf("Snapshots not supported on device '%s'\n",
4721 bdrv_get_device_name(bs1));
4722 else
4723 term_printf("Error %d while deleting snapshot on '%s'\n",
4724 ret, bdrv_get_device_name(bs1));
4730 void do_info_snapshots(void)
4732 BlockDriverState *bs, *bs1;
4733 QEMUSnapshotInfo *sn_tab, *sn;
4734 int nb_sns, i;
4735 char buf[256];
4737 bs = get_bs_snapshots();
4738 if (!bs) {
4739 term_printf("No available block device supports snapshots\n");
4740 return;
4742 term_printf("Snapshot devices:");
4743 for(i = 0; i <= MAX_DISKS; i++) {
4744 bs1 = bs_table[i];
4745 if (bdrv_has_snapshot(bs1)) {
4746 if (bs == bs1)
4747 term_printf(" %s", bdrv_get_device_name(bs1));
4750 term_printf("\n");
4752 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4753 if (nb_sns < 0) {
4754 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
4755 return;
4757 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
4758 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
4759 for(i = 0; i < nb_sns; i++) {
4760 sn = &sn_tab[i];
4761 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
4763 qemu_free(sn_tab);
4766 /***********************************************************/
4767 /* cpu save/restore */
4769 #if defined(TARGET_I386)
4771 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4773 qemu_put_be32(f, dt->selector);
4774 qemu_put_betl(f, dt->base);
4775 qemu_put_be32(f, dt->limit);
4776 qemu_put_be32(f, dt->flags);
4779 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4781 dt->selector = qemu_get_be32(f);
4782 dt->base = qemu_get_betl(f);
4783 dt->limit = qemu_get_be32(f);
4784 dt->flags = qemu_get_be32(f);
4787 void cpu_save(QEMUFile *f, void *opaque)
4789 CPUState *env = opaque;
4790 uint16_t fptag, fpus, fpuc, fpregs_format;
4791 uint32_t hflags;
4792 int i;
4794 for(i = 0; i < CPU_NB_REGS; i++)
4795 qemu_put_betls(f, &env->regs[i]);
4796 qemu_put_betls(f, &env->eip);
4797 qemu_put_betls(f, &env->eflags);
4798 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4799 qemu_put_be32s(f, &hflags);
4801 /* FPU */
4802 fpuc = env->fpuc;
4803 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4804 fptag = 0;
4805 for(i = 0; i < 8; i++) {
4806 fptag |= ((!env->fptags[i]) << i);
4809 qemu_put_be16s(f, &fpuc);
4810 qemu_put_be16s(f, &fpus);
4811 qemu_put_be16s(f, &fptag);
4813 #ifdef USE_X86LDOUBLE
4814 fpregs_format = 0;
4815 #else
4816 fpregs_format = 1;
4817 #endif
4818 qemu_put_be16s(f, &fpregs_format);
4820 for(i = 0; i < 8; i++) {
4821 #ifdef USE_X86LDOUBLE
4823 uint64_t mant;
4824 uint16_t exp;
4825 /* we save the real CPU data (in case of MMX usage only 'mant'
4826 contains the MMX register */
4827 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4828 qemu_put_be64(f, mant);
4829 qemu_put_be16(f, exp);
4831 #else
4832 /* if we use doubles for float emulation, we save the doubles to
4833 avoid losing information in case of MMX usage. It can give
4834 problems if the image is restored on a CPU where long
4835 doubles are used instead. */
4836 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4837 #endif
4840 for(i = 0; i < 6; i++)
4841 cpu_put_seg(f, &env->segs[i]);
4842 cpu_put_seg(f, &env->ldt);
4843 cpu_put_seg(f, &env->tr);
4844 cpu_put_seg(f, &env->gdt);
4845 cpu_put_seg(f, &env->idt);
4847 qemu_put_be32s(f, &env->sysenter_cs);
4848 qemu_put_be32s(f, &env->sysenter_esp);
4849 qemu_put_be32s(f, &env->sysenter_eip);
4851 qemu_put_betls(f, &env->cr[0]);
4852 qemu_put_betls(f, &env->cr[2]);
4853 qemu_put_betls(f, &env->cr[3]);
4854 qemu_put_betls(f, &env->cr[4]);
4856 for(i = 0; i < 8; i++)
4857 qemu_put_betls(f, &env->dr[i]);
4859 /* MMU */
4860 qemu_put_be32s(f, &env->a20_mask);
4862 /* XMM */
4863 qemu_put_be32s(f, &env->mxcsr);
4864 for(i = 0; i < CPU_NB_REGS; i++) {
4865 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4866 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4869 #ifdef TARGET_X86_64
4870 qemu_put_be64s(f, &env->efer);
4871 qemu_put_be64s(f, &env->star);
4872 qemu_put_be64s(f, &env->lstar);
4873 qemu_put_be64s(f, &env->cstar);
4874 qemu_put_be64s(f, &env->fmask);
4875 qemu_put_be64s(f, &env->kernelgsbase);
4876 #endif
4879 #ifdef USE_X86LDOUBLE
4880 /* XXX: add that in a FPU generic layer */
4881 union x86_longdouble {
4882 uint64_t mant;
4883 uint16_t exp;
4886 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4887 #define EXPBIAS1 1023
4888 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4889 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4891 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4893 int e;
4894 /* mantissa */
4895 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4896 /* exponent + sign */
4897 e = EXPD1(temp) - EXPBIAS1 + 16383;
4898 e |= SIGND1(temp) >> 16;
4899 p->exp = e;
4901 #endif
4903 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4905 CPUState *env = opaque;
4906 int i, guess_mmx;
4907 uint32_t hflags;
4908 uint16_t fpus, fpuc, fptag, fpregs_format;
4910 if (version_id != 3)
4911 return -EINVAL;
4912 for(i = 0; i < CPU_NB_REGS; i++)
4913 qemu_get_betls(f, &env->regs[i]);
4914 qemu_get_betls(f, &env->eip);
4915 qemu_get_betls(f, &env->eflags);
4916 qemu_get_be32s(f, &hflags);
4918 qemu_get_be16s(f, &fpuc);
4919 qemu_get_be16s(f, &fpus);
4920 qemu_get_be16s(f, &fptag);
4921 qemu_get_be16s(f, &fpregs_format);
4923 /* NOTE: we cannot always restore the FPU state if the image come
4924 from a host with a different 'USE_X86LDOUBLE' define. We guess
4925 if we are in an MMX state to restore correctly in that case. */
4926 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4927 for(i = 0; i < 8; i++) {
4928 uint64_t mant;
4929 uint16_t exp;
4931 switch(fpregs_format) {
4932 case 0:
4933 mant = qemu_get_be64(f);
4934 exp = qemu_get_be16(f);
4935 #ifdef USE_X86LDOUBLE
4936 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4937 #else
4938 /* difficult case */
4939 if (guess_mmx)
4940 env->fpregs[i].mmx.MMX_Q(0) = mant;
4941 else
4942 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4943 #endif
4944 break;
4945 case 1:
4946 mant = qemu_get_be64(f);
4947 #ifdef USE_X86LDOUBLE
4949 union x86_longdouble *p;
4950 /* difficult case */
4951 p = (void *)&env->fpregs[i];
4952 if (guess_mmx) {
4953 p->mant = mant;
4954 p->exp = 0xffff;
4955 } else {
4956 fp64_to_fp80(p, mant);
4959 #else
4960 env->fpregs[i].mmx.MMX_Q(0) = mant;
4961 #endif
4962 break;
4963 default:
4964 return -EINVAL;
4968 env->fpuc = fpuc;
4969 /* XXX: restore FPU round state */
4970 env->fpstt = (fpus >> 11) & 7;
4971 env->fpus = fpus & ~0x3800;
4972 fptag ^= 0xff;
4973 for(i = 0; i < 8; i++) {
4974 env->fptags[i] = (fptag >> i) & 1;
4977 for(i = 0; i < 6; i++)
4978 cpu_get_seg(f, &env->segs[i]);
4979 cpu_get_seg(f, &env->ldt);
4980 cpu_get_seg(f, &env->tr);
4981 cpu_get_seg(f, &env->gdt);
4982 cpu_get_seg(f, &env->idt);
4984 qemu_get_be32s(f, &env->sysenter_cs);
4985 qemu_get_be32s(f, &env->sysenter_esp);
4986 qemu_get_be32s(f, &env->sysenter_eip);
4988 qemu_get_betls(f, &env->cr[0]);
4989 qemu_get_betls(f, &env->cr[2]);
4990 qemu_get_betls(f, &env->cr[3]);
4991 qemu_get_betls(f, &env->cr[4]);
4993 for(i = 0; i < 8; i++)
4994 qemu_get_betls(f, &env->dr[i]);
4996 /* MMU */
4997 qemu_get_be32s(f, &env->a20_mask);
4999 qemu_get_be32s(f, &env->mxcsr);
5000 for(i = 0; i < CPU_NB_REGS; i++) {
5001 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5002 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5005 #ifdef TARGET_X86_64
5006 qemu_get_be64s(f, &env->efer);
5007 qemu_get_be64s(f, &env->star);
5008 qemu_get_be64s(f, &env->lstar);
5009 qemu_get_be64s(f, &env->cstar);
5010 qemu_get_be64s(f, &env->fmask);
5011 qemu_get_be64s(f, &env->kernelgsbase);
5012 #endif
5014 /* XXX: compute hflags from scratch, except for CPL and IIF */
5015 env->hflags = hflags;
5016 tlb_flush(env, 1);
5017 return 0;
5020 #elif defined(TARGET_PPC)
5021 void cpu_save(QEMUFile *f, void *opaque)
5025 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5027 return 0;
5030 #elif defined(TARGET_MIPS)
5031 void cpu_save(QEMUFile *f, void *opaque)
5035 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5037 return 0;
5040 #elif defined(TARGET_SPARC)
5041 void cpu_save(QEMUFile *f, void *opaque)
5043 CPUState *env = opaque;
5044 int i;
5045 uint32_t tmp;
5047 for(i = 0; i < 8; i++)
5048 qemu_put_betls(f, &env->gregs[i]);
5049 for(i = 0; i < NWINDOWS * 16; i++)
5050 qemu_put_betls(f, &env->regbase[i]);
5052 /* FPU */
5053 for(i = 0; i < TARGET_FPREGS; i++) {
5054 union {
5055 float32 f;
5056 uint32_t i;
5057 } u;
5058 u.f = env->fpr[i];
5059 qemu_put_be32(f, u.i);
5062 qemu_put_betls(f, &env->pc);
5063 qemu_put_betls(f, &env->npc);
5064 qemu_put_betls(f, &env->y);
5065 tmp = GET_PSR(env);
5066 qemu_put_be32(f, tmp);
5067 qemu_put_betls(f, &env->fsr);
5068 qemu_put_betls(f, &env->tbr);
5069 #ifndef TARGET_SPARC64
5070 qemu_put_be32s(f, &env->wim);
5071 /* MMU */
5072 for(i = 0; i < 16; i++)
5073 qemu_put_be32s(f, &env->mmuregs[i]);
5074 #endif
5077 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5079 CPUState *env = opaque;
5080 int i;
5081 uint32_t tmp;
5083 for(i = 0; i < 8; i++)
5084 qemu_get_betls(f, &env->gregs[i]);
5085 for(i = 0; i < NWINDOWS * 16; i++)
5086 qemu_get_betls(f, &env->regbase[i]);
5088 /* FPU */
5089 for(i = 0; i < TARGET_FPREGS; i++) {
5090 union {
5091 float32 f;
5092 uint32_t i;
5093 } u;
5094 u.i = qemu_get_be32(f);
5095 env->fpr[i] = u.f;
5098 qemu_get_betls(f, &env->pc);
5099 qemu_get_betls(f, &env->npc);
5100 qemu_get_betls(f, &env->y);
5101 tmp = qemu_get_be32(f);
5102 env->cwp = 0; /* needed to ensure that the wrapping registers are
5103 correctly updated */
5104 PUT_PSR(env, tmp);
5105 qemu_get_betls(f, &env->fsr);
5106 qemu_get_betls(f, &env->tbr);
5107 #ifndef TARGET_SPARC64
5108 qemu_get_be32s(f, &env->wim);
5109 /* MMU */
5110 for(i = 0; i < 16; i++)
5111 qemu_get_be32s(f, &env->mmuregs[i]);
5112 #endif
5113 tlb_flush(env, 1);
5114 return 0;
5117 #elif defined(TARGET_ARM)
5119 /* ??? Need to implement these. */
5120 void cpu_save(QEMUFile *f, void *opaque)
5124 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5126 return 0;
5129 #else
5131 #warning No CPU save/restore functions
5133 #endif
5135 /***********************************************************/
5136 /* ram save/restore */
5138 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5140 int v;
5142 v = qemu_get_byte(f);
5143 switch(v) {
5144 case 0:
5145 if (qemu_get_buffer(f, buf, len) != len)
5146 return -EIO;
5147 break;
5148 case 1:
5149 v = qemu_get_byte(f);
5150 memset(buf, v, len);
5151 break;
5152 default:
5153 return -EINVAL;
5155 return 0;
5158 static int ram_load_v1(QEMUFile *f, void *opaque)
5160 int i, ret;
5162 if (qemu_get_be32(f) != phys_ram_size)
5163 return -EINVAL;
5164 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5165 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5166 if (ret)
5167 return ret;
5169 return 0;
5172 #define BDRV_HASH_BLOCK_SIZE 1024
5173 #define IOBUF_SIZE 4096
5174 #define RAM_CBLOCK_MAGIC 0xfabe
5176 typedef struct RamCompressState {
5177 z_stream zstream;
5178 QEMUFile *f;
5179 uint8_t buf[IOBUF_SIZE];
5180 } RamCompressState;
5182 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5184 int ret;
5185 memset(s, 0, sizeof(*s));
5186 s->f = f;
5187 ret = deflateInit2(&s->zstream, 1,
5188 Z_DEFLATED, 15,
5189 9, Z_DEFAULT_STRATEGY);
5190 if (ret != Z_OK)
5191 return -1;
5192 s->zstream.avail_out = IOBUF_SIZE;
5193 s->zstream.next_out = s->buf;
5194 return 0;
5197 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5199 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5200 qemu_put_be16(s->f, len);
5201 qemu_put_buffer(s->f, buf, len);
5204 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5206 int ret;
5208 s->zstream.avail_in = len;
5209 s->zstream.next_in = (uint8_t *)buf;
5210 while (s->zstream.avail_in > 0) {
5211 ret = deflate(&s->zstream, Z_NO_FLUSH);
5212 if (ret != Z_OK)
5213 return -1;
5214 if (s->zstream.avail_out == 0) {
5215 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5216 s->zstream.avail_out = IOBUF_SIZE;
5217 s->zstream.next_out = s->buf;
5220 return 0;
5223 static void ram_compress_close(RamCompressState *s)
5225 int len, ret;
5227 /* compress last bytes */
5228 for(;;) {
5229 ret = deflate(&s->zstream, Z_FINISH);
5230 if (ret == Z_OK || ret == Z_STREAM_END) {
5231 len = IOBUF_SIZE - s->zstream.avail_out;
5232 if (len > 0) {
5233 ram_put_cblock(s, s->buf, len);
5235 s->zstream.avail_out = IOBUF_SIZE;
5236 s->zstream.next_out = s->buf;
5237 if (ret == Z_STREAM_END)
5238 break;
5239 } else {
5240 goto fail;
5243 fail:
5244 deflateEnd(&s->zstream);
5247 typedef struct RamDecompressState {
5248 z_stream zstream;
5249 QEMUFile *f;
5250 uint8_t buf[IOBUF_SIZE];
5251 } RamDecompressState;
5253 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5255 int ret;
5256 memset(s, 0, sizeof(*s));
5257 s->f = f;
5258 ret = inflateInit(&s->zstream);
5259 if (ret != Z_OK)
5260 return -1;
5261 return 0;
5264 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5266 int ret, clen;
5268 s->zstream.avail_out = len;
5269 s->zstream.next_out = buf;
5270 while (s->zstream.avail_out > 0) {
5271 if (s->zstream.avail_in == 0) {
5272 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5273 return -1;
5274 clen = qemu_get_be16(s->f);
5275 if (clen > IOBUF_SIZE)
5276 return -1;
5277 qemu_get_buffer(s->f, s->buf, clen);
5278 s->zstream.avail_in = clen;
5279 s->zstream.next_in = s->buf;
5281 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5282 if (ret != Z_OK && ret != Z_STREAM_END) {
5283 return -1;
5286 return 0;
5289 static void ram_decompress_close(RamDecompressState *s)
5291 inflateEnd(&s->zstream);
5294 static void ram_save(QEMUFile *f, void *opaque)
5296 int i;
5297 RamCompressState s1, *s = &s1;
5298 uint8_t buf[10];
5300 qemu_put_be32(f, phys_ram_size);
5301 if (ram_compress_open(s, f) < 0)
5302 return;
5303 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5304 #if 0
5305 if (tight_savevm_enabled) {
5306 int64_t sector_num;
5307 int j;
5309 /* find if the memory block is available on a virtual
5310 block device */
5311 sector_num = -1;
5312 for(j = 0; j < MAX_DISKS; j++) {
5313 if (bs_table[j]) {
5314 sector_num = bdrv_hash_find(bs_table[j],
5315 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5316 if (sector_num >= 0)
5317 break;
5320 if (j == MAX_DISKS)
5321 goto normal_compress;
5322 buf[0] = 1;
5323 buf[1] = j;
5324 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5325 ram_compress_buf(s, buf, 10);
5326 } else
5327 #endif
5329 // normal_compress:
5330 buf[0] = 0;
5331 ram_compress_buf(s, buf, 1);
5332 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5335 ram_compress_close(s);
5338 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5340 RamDecompressState s1, *s = &s1;
5341 uint8_t buf[10];
5342 int i;
5344 if (version_id == 1)
5345 return ram_load_v1(f, opaque);
5346 if (version_id != 2)
5347 return -EINVAL;
5348 if (qemu_get_be32(f) != phys_ram_size)
5349 return -EINVAL;
5350 if (ram_decompress_open(s, f) < 0)
5351 return -EINVAL;
5352 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5353 if (ram_decompress_buf(s, buf, 1) < 0) {
5354 fprintf(stderr, "Error while reading ram block header\n");
5355 goto error;
5357 if (buf[0] == 0) {
5358 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5359 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5360 goto error;
5362 } else
5363 #if 0
5364 if (buf[0] == 1) {
5365 int bs_index;
5366 int64_t sector_num;
5368 ram_decompress_buf(s, buf + 1, 9);
5369 bs_index = buf[1];
5370 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5371 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5372 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5373 goto error;
5375 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5376 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5377 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5378 bs_index, sector_num);
5379 goto error;
5381 } else
5382 #endif
5384 error:
5385 printf("Error block header\n");
5386 return -EINVAL;
5389 ram_decompress_close(s);
5390 return 0;
5393 /***********************************************************/
5394 /* bottom halves (can be seen as timers which expire ASAP) */
5396 struct QEMUBH {
5397 QEMUBHFunc *cb;
5398 void *opaque;
5399 int scheduled;
5400 QEMUBH *next;
5403 static QEMUBH *first_bh = NULL;
5405 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5407 QEMUBH *bh;
5408 bh = qemu_mallocz(sizeof(QEMUBH));
5409 if (!bh)
5410 return NULL;
5411 bh->cb = cb;
5412 bh->opaque = opaque;
5413 return bh;
5416 int qemu_bh_poll(void)
5418 QEMUBH *bh, **pbh;
5419 int ret;
5421 ret = 0;
5422 for(;;) {
5423 pbh = &first_bh;
5424 bh = *pbh;
5425 if (!bh)
5426 break;
5427 ret = 1;
5428 *pbh = bh->next;
5429 bh->scheduled = 0;
5430 bh->cb(bh->opaque);
5432 return ret;
5435 void qemu_bh_schedule(QEMUBH *bh)
5437 CPUState *env = cpu_single_env;
5438 if (bh->scheduled)
5439 return;
5440 bh->scheduled = 1;
5441 bh->next = first_bh;
5442 first_bh = bh;
5444 /* stop the currently executing CPU to execute the BH ASAP */
5445 if (env) {
5446 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5450 void qemu_bh_cancel(QEMUBH *bh)
5452 QEMUBH **pbh;
5453 if (bh->scheduled) {
5454 pbh = &first_bh;
5455 while (*pbh != bh)
5456 pbh = &(*pbh)->next;
5457 *pbh = bh->next;
5458 bh->scheduled = 0;
5462 void qemu_bh_delete(QEMUBH *bh)
5464 qemu_bh_cancel(bh);
5465 qemu_free(bh);
5468 /***********************************************************/
5469 /* machine registration */
5471 QEMUMachine *first_machine = NULL;
5473 int qemu_register_machine(QEMUMachine *m)
5475 QEMUMachine **pm;
5476 pm = &first_machine;
5477 while (*pm != NULL)
5478 pm = &(*pm)->next;
5479 m->next = NULL;
5480 *pm = m;
5481 return 0;
5484 QEMUMachine *find_machine(const char *name)
5486 QEMUMachine *m;
5488 for(m = first_machine; m != NULL; m = m->next) {
5489 if (!strcmp(m->name, name))
5490 return m;
5492 return NULL;
5495 /***********************************************************/
5496 /* main execution loop */
5498 void gui_update(void *opaque)
5500 display_state.dpy_refresh(&display_state);
5501 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5504 struct vm_change_state_entry {
5505 VMChangeStateHandler *cb;
5506 void *opaque;
5507 LIST_ENTRY (vm_change_state_entry) entries;
5510 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5512 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5513 void *opaque)
5515 VMChangeStateEntry *e;
5517 e = qemu_mallocz(sizeof (*e));
5518 if (!e)
5519 return NULL;
5521 e->cb = cb;
5522 e->opaque = opaque;
5523 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5524 return e;
5527 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5529 LIST_REMOVE (e, entries);
5530 qemu_free (e);
5533 static void vm_state_notify(int running)
5535 VMChangeStateEntry *e;
5537 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5538 e->cb(e->opaque, running);
5542 /* XXX: support several handlers */
5543 static VMStopHandler *vm_stop_cb;
5544 static void *vm_stop_opaque;
5546 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5548 vm_stop_cb = cb;
5549 vm_stop_opaque = opaque;
5550 return 0;
5553 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5555 vm_stop_cb = NULL;
5558 void vm_start(void)
5560 if (!vm_running) {
5561 cpu_enable_ticks();
5562 vm_running = 1;
5563 vm_state_notify(1);
5567 void vm_stop(int reason)
5569 if (vm_running) {
5570 cpu_disable_ticks();
5571 vm_running = 0;
5572 if (reason != 0) {
5573 if (vm_stop_cb) {
5574 vm_stop_cb(vm_stop_opaque, reason);
5577 vm_state_notify(0);
5581 /* reset/shutdown handler */
5583 typedef struct QEMUResetEntry {
5584 QEMUResetHandler *func;
5585 void *opaque;
5586 struct QEMUResetEntry *next;
5587 } QEMUResetEntry;
5589 static QEMUResetEntry *first_reset_entry;
5590 static int reset_requested;
5591 static int shutdown_requested;
5592 static int powerdown_requested;
5594 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5596 QEMUResetEntry **pre, *re;
5598 pre = &first_reset_entry;
5599 while (*pre != NULL)
5600 pre = &(*pre)->next;
5601 re = qemu_mallocz(sizeof(QEMUResetEntry));
5602 re->func = func;
5603 re->opaque = opaque;
5604 re->next = NULL;
5605 *pre = re;
5608 void qemu_system_reset(void)
5610 QEMUResetEntry *re;
5612 /* reset all devices */
5613 for(re = first_reset_entry; re != NULL; re = re->next) {
5614 re->func(re->opaque);
5618 void qemu_system_reset_request(void)
5620 reset_requested = 1;
5621 if (cpu_single_env)
5622 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5625 void qemu_system_shutdown_request(void)
5627 shutdown_requested = 1;
5628 if (cpu_single_env)
5629 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5632 void qemu_system_powerdown_request(void)
5634 powerdown_requested = 1;
5635 if (cpu_single_env)
5636 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5639 void main_loop_wait(int timeout)
5641 IOHandlerRecord *ioh, *ioh_next;
5642 fd_set rfds, wfds, xfds;
5643 int ret, nfds;
5644 struct timeval tv;
5645 PollingEntry *pe;
5648 /* XXX: need to suppress polling by better using win32 events */
5649 ret = 0;
5650 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5651 ret |= pe->func(pe->opaque);
5653 #ifdef _WIN32
5654 if (ret == 0 && timeout > 0) {
5655 int err;
5656 WaitObjects *w = &wait_objects;
5658 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5659 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5660 if (w->func[ret - WAIT_OBJECT_0])
5661 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5662 } else if (ret == WAIT_TIMEOUT) {
5663 } else {
5664 err = GetLastError();
5665 fprintf(stderr, "Wait error %d %d\n", ret, err);
5668 #endif
5669 /* poll any events */
5670 /* XXX: separate device handlers from system ones */
5671 nfds = -1;
5672 FD_ZERO(&rfds);
5673 FD_ZERO(&wfds);
5674 FD_ZERO(&xfds);
5675 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5676 if (ioh->fd_read &&
5677 (!ioh->fd_read_poll ||
5678 ioh->fd_read_poll(ioh->opaque) != 0)) {
5679 FD_SET(ioh->fd, &rfds);
5680 if (ioh->fd > nfds)
5681 nfds = ioh->fd;
5683 if (ioh->fd_write) {
5684 FD_SET(ioh->fd, &wfds);
5685 if (ioh->fd > nfds)
5686 nfds = ioh->fd;
5690 tv.tv_sec = 0;
5691 #ifdef _WIN32
5692 tv.tv_usec = 0;
5693 #else
5694 tv.tv_usec = timeout * 1000;
5695 #endif
5696 #if defined(CONFIG_SLIRP)
5697 if (slirp_inited) {
5698 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5700 #endif
5701 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5702 if (ret > 0) {
5703 /* XXX: better handling of removal */
5704 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5705 ioh_next = ioh->next;
5706 if (FD_ISSET(ioh->fd, &rfds)) {
5707 ioh->fd_read(ioh->opaque);
5709 if (FD_ISSET(ioh->fd, &wfds)) {
5710 ioh->fd_write(ioh->opaque);
5714 #if defined(CONFIG_SLIRP)
5715 if (slirp_inited) {
5716 if (ret < 0) {
5717 FD_ZERO(&rfds);
5718 FD_ZERO(&wfds);
5719 FD_ZERO(&xfds);
5721 slirp_select_poll(&rfds, &wfds, &xfds);
5723 #endif
5724 qemu_aio_poll();
5725 qemu_bh_poll();
5727 if (vm_running) {
5728 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5729 qemu_get_clock(vm_clock));
5730 /* run dma transfers, if any */
5731 DMA_run();
5734 /* real time timers */
5735 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5736 qemu_get_clock(rt_clock));
5739 static CPUState *cur_cpu;
5741 int main_loop(void)
5743 int ret, timeout;
5744 #ifdef CONFIG_PROFILER
5745 int64_t ti;
5746 #endif
5747 CPUState *env;
5749 cur_cpu = first_cpu;
5750 for(;;) {
5751 if (vm_running) {
5753 env = cur_cpu;
5754 for(;;) {
5755 /* get next cpu */
5756 env = env->next_cpu;
5757 if (!env)
5758 env = first_cpu;
5759 #ifdef CONFIG_PROFILER
5760 ti = profile_getclock();
5761 #endif
5762 ret = cpu_exec(env);
5763 #ifdef CONFIG_PROFILER
5764 qemu_time += profile_getclock() - ti;
5765 #endif
5766 if (ret != EXCP_HALTED)
5767 break;
5768 /* all CPUs are halted ? */
5769 if (env == cur_cpu) {
5770 ret = EXCP_HLT;
5771 break;
5774 cur_cpu = env;
5776 if (shutdown_requested) {
5777 ret = EXCP_INTERRUPT;
5778 break;
5780 if (reset_requested) {
5781 reset_requested = 0;
5782 qemu_system_reset();
5783 ret = EXCP_INTERRUPT;
5785 if (powerdown_requested) {
5786 powerdown_requested = 0;
5787 qemu_system_powerdown();
5788 ret = EXCP_INTERRUPT;
5790 if (ret == EXCP_DEBUG) {
5791 vm_stop(EXCP_DEBUG);
5793 /* if hlt instruction, we wait until the next IRQ */
5794 /* XXX: use timeout computed from timers */
5795 if (ret == EXCP_HLT)
5796 timeout = 10;
5797 else
5798 timeout = 0;
5799 } else {
5800 timeout = 10;
5802 #ifdef CONFIG_PROFILER
5803 ti = profile_getclock();
5804 #endif
5805 main_loop_wait(timeout);
5806 #ifdef CONFIG_PROFILER
5807 dev_time += profile_getclock() - ti;
5808 #endif
5810 cpu_disable_ticks();
5811 return ret;
5814 void help(void)
5816 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2006 Fabrice Bellard\n"
5817 "usage: %s [options] [disk_image]\n"
5818 "\n"
5819 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5820 "\n"
5821 "Standard options:\n"
5822 "-M machine select emulated machine (-M ? for list)\n"
5823 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5824 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5825 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5826 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5827 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5828 "-snapshot write to temporary files instead of disk image files\n"
5829 #ifdef TARGET_I386
5830 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5831 #endif
5832 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5833 "-smp n set the number of CPUs to 'n' [default=1]\n"
5834 "-nographic disable graphical output and redirect serial I/Os to console\n"
5835 #ifndef _WIN32
5836 "-k language use keyboard layout (for example \"fr\" for French)\n"
5837 #endif
5838 #ifdef HAS_AUDIO
5839 "-audio-help print list of audio drivers and their options\n"
5840 "-soundhw c1,... enable audio support\n"
5841 " and only specified sound cards (comma separated list)\n"
5842 " use -soundhw ? to get the list of supported cards\n"
5843 " use -soundhw all to enable all of them\n"
5844 #endif
5845 "-localtime set the real time clock to local time [default=utc]\n"
5846 "-full-screen start in full screen\n"
5847 #ifdef TARGET_I386
5848 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5849 #endif
5850 "-usb enable the USB driver (will be the default soon)\n"
5851 "-usbdevice name add the host or guest USB device 'name'\n"
5852 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5853 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5854 #endif
5855 "\n"
5856 "Network options:\n"
5857 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5858 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5859 #ifdef CONFIG_SLIRP
5860 "-net user[,vlan=n][,hostname=host]\n"
5861 " connect the user mode network stack to VLAN 'n' and send\n"
5862 " hostname 'host' to DHCP clients\n"
5863 #endif
5864 #ifdef _WIN32
5865 "-net tap[,vlan=n],ifname=name\n"
5866 " connect the host TAP network interface to VLAN 'n'\n"
5867 #else
5868 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
5869 " connect the host TAP network interface to VLAN 'n' and use\n"
5870 " the network script 'file' (default=%s);\n"
5871 " use 'fd=h' to connect to an already opened TAP interface\n"
5872 #endif
5873 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5874 " connect the vlan 'n' to another VLAN using a socket connection\n"
5875 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5876 " connect the vlan 'n' to multicast maddr and port\n"
5877 "-net none use it alone to have zero network devices; if no -net option\n"
5878 " is provided, the default is '-net nic -net user'\n"
5879 "\n"
5880 #ifdef CONFIG_SLIRP
5881 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5882 #ifndef _WIN32
5883 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5884 #endif
5885 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5886 " redirect TCP or UDP connections from host to guest [-net user]\n"
5887 #endif
5888 "\n"
5889 "Linux boot specific:\n"
5890 "-kernel bzImage use 'bzImage' as kernel image\n"
5891 "-append cmdline use 'cmdline' as kernel command line\n"
5892 "-initrd file use 'file' as initial ram disk\n"
5893 "\n"
5894 "Debug/Expert options:\n"
5895 "-monitor dev redirect the monitor to char device 'dev'\n"
5896 "-serial dev redirect the serial port to char device 'dev'\n"
5897 "-parallel dev redirect the parallel port to char device 'dev'\n"
5898 "-pidfile file Write PID to 'file'\n"
5899 "-S freeze CPU at startup (use 'c' to start execution)\n"
5900 "-s wait gdb connection to port %d\n"
5901 "-p port change gdb connection port\n"
5902 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
5903 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5904 " translation (t=none or lba) (usually qemu can guess them)\n"
5905 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
5906 #ifdef USE_KQEMU
5907 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5908 "-no-kqemu disable KQEMU kernel module usage\n"
5909 #endif
5910 #ifdef USE_CODE_COPY
5911 "-no-code-copy disable code copy acceleration\n"
5912 #endif
5913 #ifdef TARGET_I386
5914 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5915 " (default is CL-GD5446 PCI VGA)\n"
5916 "-no-acpi disable ACPI\n"
5917 #endif
5918 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5919 "-vnc display start a VNC server on display\n"
5920 "\n"
5921 "During emulation, the following keys are useful:\n"
5922 "ctrl-alt-f toggle full screen\n"
5923 "ctrl-alt-n switch to virtual console 'n'\n"
5924 "ctrl-alt toggle mouse and keyboard grab\n"
5925 "\n"
5926 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5928 "qemu",
5929 DEFAULT_RAM_SIZE,
5930 #ifndef _WIN32
5931 DEFAULT_NETWORK_SCRIPT,
5932 #endif
5933 DEFAULT_GDBSTUB_PORT,
5934 "/tmp/qemu.log");
5935 exit(1);
5938 #define HAS_ARG 0x0001
5940 enum {
5941 QEMU_OPTION_h,
5943 QEMU_OPTION_M,
5944 QEMU_OPTION_fda,
5945 QEMU_OPTION_fdb,
5946 QEMU_OPTION_hda,
5947 QEMU_OPTION_hdb,
5948 QEMU_OPTION_hdc,
5949 QEMU_OPTION_hdd,
5950 QEMU_OPTION_cdrom,
5951 QEMU_OPTION_boot,
5952 QEMU_OPTION_snapshot,
5953 #ifdef TARGET_I386
5954 QEMU_OPTION_no_fd_bootchk,
5955 #endif
5956 QEMU_OPTION_m,
5957 QEMU_OPTION_nographic,
5958 #ifdef HAS_AUDIO
5959 QEMU_OPTION_audio_help,
5960 QEMU_OPTION_soundhw,
5961 #endif
5963 QEMU_OPTION_net,
5964 QEMU_OPTION_tftp,
5965 QEMU_OPTION_smb,
5966 QEMU_OPTION_redir,
5968 QEMU_OPTION_kernel,
5969 QEMU_OPTION_append,
5970 QEMU_OPTION_initrd,
5972 QEMU_OPTION_S,
5973 QEMU_OPTION_s,
5974 QEMU_OPTION_p,
5975 QEMU_OPTION_d,
5976 QEMU_OPTION_hdachs,
5977 QEMU_OPTION_L,
5978 QEMU_OPTION_no_code_copy,
5979 QEMU_OPTION_k,
5980 QEMU_OPTION_localtime,
5981 QEMU_OPTION_cirrusvga,
5982 QEMU_OPTION_g,
5983 QEMU_OPTION_std_vga,
5984 QEMU_OPTION_monitor,
5985 QEMU_OPTION_serial,
5986 QEMU_OPTION_parallel,
5987 QEMU_OPTION_loadvm,
5988 QEMU_OPTION_full_screen,
5989 QEMU_OPTION_pidfile,
5990 QEMU_OPTION_no_kqemu,
5991 QEMU_OPTION_kernel_kqemu,
5992 QEMU_OPTION_win2k_hack,
5993 QEMU_OPTION_usb,
5994 QEMU_OPTION_usbdevice,
5995 QEMU_OPTION_smp,
5996 QEMU_OPTION_vnc,
5997 QEMU_OPTION_no_acpi,
6000 typedef struct QEMUOption {
6001 const char *name;
6002 int flags;
6003 int index;
6004 } QEMUOption;
6006 const QEMUOption qemu_options[] = {
6007 { "h", 0, QEMU_OPTION_h },
6009 { "M", HAS_ARG, QEMU_OPTION_M },
6010 { "fda", HAS_ARG, QEMU_OPTION_fda },
6011 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6012 { "hda", HAS_ARG, QEMU_OPTION_hda },
6013 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6014 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6015 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6016 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6017 { "boot", HAS_ARG, QEMU_OPTION_boot },
6018 { "snapshot", 0, QEMU_OPTION_snapshot },
6019 #ifdef TARGET_I386
6020 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6021 #endif
6022 { "m", HAS_ARG, QEMU_OPTION_m },
6023 { "nographic", 0, QEMU_OPTION_nographic },
6024 { "k", HAS_ARG, QEMU_OPTION_k },
6025 #ifdef HAS_AUDIO
6026 { "audio-help", 0, QEMU_OPTION_audio_help },
6027 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6028 #endif
6030 { "net", HAS_ARG, QEMU_OPTION_net},
6031 #ifdef CONFIG_SLIRP
6032 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6033 #ifndef _WIN32
6034 { "smb", HAS_ARG, QEMU_OPTION_smb },
6035 #endif
6036 { "redir", HAS_ARG, QEMU_OPTION_redir },
6037 #endif
6039 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6040 { "append", HAS_ARG, QEMU_OPTION_append },
6041 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6043 { "S", 0, QEMU_OPTION_S },
6044 { "s", 0, QEMU_OPTION_s },
6045 { "p", HAS_ARG, QEMU_OPTION_p },
6046 { "d", HAS_ARG, QEMU_OPTION_d },
6047 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6048 { "L", HAS_ARG, QEMU_OPTION_L },
6049 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6050 #ifdef USE_KQEMU
6051 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6052 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6053 #endif
6054 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6055 { "g", 1, QEMU_OPTION_g },
6056 #endif
6057 { "localtime", 0, QEMU_OPTION_localtime },
6058 { "std-vga", 0, QEMU_OPTION_std_vga },
6059 { "monitor", 1, QEMU_OPTION_monitor },
6060 { "serial", 1, QEMU_OPTION_serial },
6061 { "parallel", 1, QEMU_OPTION_parallel },
6062 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6063 { "full-screen", 0, QEMU_OPTION_full_screen },
6064 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6065 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6066 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6067 { "smp", HAS_ARG, QEMU_OPTION_smp },
6068 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6070 /* temporary options */
6071 { "usb", 0, QEMU_OPTION_usb },
6072 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6073 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6074 { NULL },
6077 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6079 /* this stack is only used during signal handling */
6080 #define SIGNAL_STACK_SIZE 32768
6082 static uint8_t *signal_stack;
6084 #endif
6086 /* password input */
6088 static BlockDriverState *get_bdrv(int index)
6090 BlockDriverState *bs;
6092 if (index < 4) {
6093 bs = bs_table[index];
6094 } else if (index < 6) {
6095 bs = fd_table[index - 4];
6096 } else {
6097 bs = NULL;
6099 return bs;
6102 static void read_passwords(void)
6104 BlockDriverState *bs;
6105 int i, j;
6106 char password[256];
6108 for(i = 0; i < 6; i++) {
6109 bs = get_bdrv(i);
6110 if (bs && bdrv_is_encrypted(bs)) {
6111 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6112 for(j = 0; j < 3; j++) {
6113 monitor_readline("Password: ",
6114 1, password, sizeof(password));
6115 if (bdrv_set_key(bs, password) == 0)
6116 break;
6117 term_printf("invalid password\n");
6123 /* XXX: currently we cannot use simultaneously different CPUs */
6124 void register_machines(void)
6126 #if defined(TARGET_I386)
6127 qemu_register_machine(&pc_machine);
6128 qemu_register_machine(&isapc_machine);
6129 #elif defined(TARGET_PPC)
6130 qemu_register_machine(&heathrow_machine);
6131 qemu_register_machine(&core99_machine);
6132 qemu_register_machine(&prep_machine);
6133 #elif defined(TARGET_MIPS)
6134 qemu_register_machine(&mips_machine);
6135 #elif defined(TARGET_SPARC)
6136 #ifdef TARGET_SPARC64
6137 qemu_register_machine(&sun4u_machine);
6138 #else
6139 qemu_register_machine(&sun4m_machine);
6140 #endif
6141 #elif defined(TARGET_ARM)
6142 qemu_register_machine(&integratorcp926_machine);
6143 qemu_register_machine(&integratorcp1026_machine);
6144 qemu_register_machine(&versatilepb_machine);
6145 qemu_register_machine(&versatileab_machine);
6146 #elif defined(TARGET_SH4)
6147 qemu_register_machine(&shix_machine);
6148 #else
6149 #error unsupported CPU
6150 #endif
6153 #ifdef HAS_AUDIO
6154 struct soundhw soundhw[] = {
6155 #ifdef TARGET_I386
6157 "pcspk",
6158 "PC speaker",
6161 { .init_isa = pcspk_audio_init }
6163 #endif
6165 "sb16",
6166 "Creative Sound Blaster 16",
6169 { .init_isa = SB16_init }
6172 #ifdef CONFIG_ADLIB
6174 "adlib",
6175 #ifdef HAS_YMF262
6176 "Yamaha YMF262 (OPL3)",
6177 #else
6178 "Yamaha YM3812 (OPL2)",
6179 #endif
6182 { .init_isa = Adlib_init }
6184 #endif
6186 #ifdef CONFIG_GUS
6188 "gus",
6189 "Gravis Ultrasound GF1",
6192 { .init_isa = GUS_init }
6194 #endif
6197 "es1370",
6198 "ENSONIQ AudioPCI ES1370",
6201 { .init_pci = es1370_init }
6204 { NULL, NULL, 0, 0, { NULL } }
6207 static void select_soundhw (const char *optarg)
6209 struct soundhw *c;
6211 if (*optarg == '?') {
6212 show_valid_cards:
6214 printf ("Valid sound card names (comma separated):\n");
6215 for (c = soundhw; c->name; ++c) {
6216 printf ("%-11s %s\n", c->name, c->descr);
6218 printf ("\n-soundhw all will enable all of the above\n");
6219 exit (*optarg != '?');
6221 else {
6222 size_t l;
6223 const char *p;
6224 char *e;
6225 int bad_card = 0;
6227 if (!strcmp (optarg, "all")) {
6228 for (c = soundhw; c->name; ++c) {
6229 c->enabled = 1;
6231 return;
6234 p = optarg;
6235 while (*p) {
6236 e = strchr (p, ',');
6237 l = !e ? strlen (p) : (size_t) (e - p);
6239 for (c = soundhw; c->name; ++c) {
6240 if (!strncmp (c->name, p, l)) {
6241 c->enabled = 1;
6242 break;
6246 if (!c->name) {
6247 if (l > 80) {
6248 fprintf (stderr,
6249 "Unknown sound card name (too big to show)\n");
6251 else {
6252 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6253 (int) l, p);
6255 bad_card = 1;
6257 p += l + (e != NULL);
6260 if (bad_card)
6261 goto show_valid_cards;
6264 #endif
6266 #ifdef _WIN32
6267 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6269 exit(STATUS_CONTROL_C_EXIT);
6270 return TRUE;
6272 #endif
6274 #define MAX_NET_CLIENTS 32
6276 int main(int argc, char **argv)
6278 #ifdef CONFIG_GDBSTUB
6279 int use_gdbstub, gdbstub_port;
6280 #endif
6281 int i, cdrom_index;
6282 int snapshot, linux_boot;
6283 const char *initrd_filename;
6284 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6285 const char *kernel_filename, *kernel_cmdline;
6286 DisplayState *ds = &display_state;
6287 int cyls, heads, secs, translation;
6288 int start_emulation = 1;
6289 char net_clients[MAX_NET_CLIENTS][256];
6290 int nb_net_clients;
6291 int optind;
6292 const char *r, *optarg;
6293 CharDriverState *monitor_hd;
6294 char monitor_device[128];
6295 char serial_devices[MAX_SERIAL_PORTS][128];
6296 int serial_device_index;
6297 char parallel_devices[MAX_PARALLEL_PORTS][128];
6298 int parallel_device_index;
6299 const char *loadvm = NULL;
6300 QEMUMachine *machine;
6301 char usb_devices[MAX_USB_CMDLINE][128];
6302 int usb_devices_index;
6304 LIST_INIT (&vm_change_state_head);
6305 #ifndef _WIN32
6307 struct sigaction act;
6308 sigfillset(&act.sa_mask);
6309 act.sa_flags = 0;
6310 act.sa_handler = SIG_IGN;
6311 sigaction(SIGPIPE, &act, NULL);
6313 #else
6314 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6315 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6316 QEMU to run on a single CPU */
6318 HANDLE h;
6319 DWORD mask, smask;
6320 int i;
6321 h = GetCurrentProcess();
6322 if (GetProcessAffinityMask(h, &mask, &smask)) {
6323 for(i = 0; i < 32; i++) {
6324 if (mask & (1 << i))
6325 break;
6327 if (i != 32) {
6328 mask = 1 << i;
6329 SetProcessAffinityMask(h, mask);
6333 #endif
6335 register_machines();
6336 machine = first_machine;
6337 initrd_filename = NULL;
6338 for(i = 0; i < MAX_FD; i++)
6339 fd_filename[i] = NULL;
6340 for(i = 0; i < MAX_DISKS; i++)
6341 hd_filename[i] = NULL;
6342 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6343 vga_ram_size = VGA_RAM_SIZE;
6344 bios_size = BIOS_SIZE;
6345 #ifdef CONFIG_GDBSTUB
6346 use_gdbstub = 0;
6347 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6348 #endif
6349 snapshot = 0;
6350 nographic = 0;
6351 kernel_filename = NULL;
6352 kernel_cmdline = "";
6353 #ifdef TARGET_PPC
6354 cdrom_index = 1;
6355 #else
6356 cdrom_index = 2;
6357 #endif
6358 cyls = heads = secs = 0;
6359 translation = BIOS_ATA_TRANSLATION_AUTO;
6360 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6362 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6363 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6364 serial_devices[i][0] = '\0';
6365 serial_device_index = 0;
6367 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6368 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6369 parallel_devices[i][0] = '\0';
6370 parallel_device_index = 0;
6372 usb_devices_index = 0;
6374 nb_net_clients = 0;
6376 nb_nics = 0;
6377 /* default mac address of the first network interface */
6379 optind = 1;
6380 for(;;) {
6381 if (optind >= argc)
6382 break;
6383 r = argv[optind];
6384 if (r[0] != '-') {
6385 hd_filename[0] = argv[optind++];
6386 } else {
6387 const QEMUOption *popt;
6389 optind++;
6390 popt = qemu_options;
6391 for(;;) {
6392 if (!popt->name) {
6393 fprintf(stderr, "%s: invalid option -- '%s'\n",
6394 argv[0], r);
6395 exit(1);
6397 if (!strcmp(popt->name, r + 1))
6398 break;
6399 popt++;
6401 if (popt->flags & HAS_ARG) {
6402 if (optind >= argc) {
6403 fprintf(stderr, "%s: option '%s' requires an argument\n",
6404 argv[0], r);
6405 exit(1);
6407 optarg = argv[optind++];
6408 } else {
6409 optarg = NULL;
6412 switch(popt->index) {
6413 case QEMU_OPTION_M:
6414 machine = find_machine(optarg);
6415 if (!machine) {
6416 QEMUMachine *m;
6417 printf("Supported machines are:\n");
6418 for(m = first_machine; m != NULL; m = m->next) {
6419 printf("%-10s %s%s\n",
6420 m->name, m->desc,
6421 m == first_machine ? " (default)" : "");
6423 exit(1);
6425 break;
6426 case QEMU_OPTION_initrd:
6427 initrd_filename = optarg;
6428 break;
6429 case QEMU_OPTION_hda:
6430 case QEMU_OPTION_hdb:
6431 case QEMU_OPTION_hdc:
6432 case QEMU_OPTION_hdd:
6434 int hd_index;
6435 hd_index = popt->index - QEMU_OPTION_hda;
6436 hd_filename[hd_index] = optarg;
6437 if (hd_index == cdrom_index)
6438 cdrom_index = -1;
6440 break;
6441 case QEMU_OPTION_snapshot:
6442 snapshot = 1;
6443 break;
6444 case QEMU_OPTION_hdachs:
6446 const char *p;
6447 p = optarg;
6448 cyls = strtol(p, (char **)&p, 0);
6449 if (cyls < 1 || cyls > 16383)
6450 goto chs_fail;
6451 if (*p != ',')
6452 goto chs_fail;
6453 p++;
6454 heads = strtol(p, (char **)&p, 0);
6455 if (heads < 1 || heads > 16)
6456 goto chs_fail;
6457 if (*p != ',')
6458 goto chs_fail;
6459 p++;
6460 secs = strtol(p, (char **)&p, 0);
6461 if (secs < 1 || secs > 63)
6462 goto chs_fail;
6463 if (*p == ',') {
6464 p++;
6465 if (!strcmp(p, "none"))
6466 translation = BIOS_ATA_TRANSLATION_NONE;
6467 else if (!strcmp(p, "lba"))
6468 translation = BIOS_ATA_TRANSLATION_LBA;
6469 else if (!strcmp(p, "auto"))
6470 translation = BIOS_ATA_TRANSLATION_AUTO;
6471 else
6472 goto chs_fail;
6473 } else if (*p != '\0') {
6474 chs_fail:
6475 fprintf(stderr, "qemu: invalid physical CHS format\n");
6476 exit(1);
6479 break;
6480 case QEMU_OPTION_nographic:
6481 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
6482 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
6483 nographic = 1;
6484 break;
6485 case QEMU_OPTION_kernel:
6486 kernel_filename = optarg;
6487 break;
6488 case QEMU_OPTION_append:
6489 kernel_cmdline = optarg;
6490 break;
6491 case QEMU_OPTION_cdrom:
6492 if (cdrom_index >= 0) {
6493 hd_filename[cdrom_index] = optarg;
6495 break;
6496 case QEMU_OPTION_boot:
6497 boot_device = optarg[0];
6498 if (boot_device != 'a' &&
6499 #ifdef TARGET_SPARC
6500 // Network boot
6501 boot_device != 'n' &&
6502 #endif
6503 boot_device != 'c' && boot_device != 'd') {
6504 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
6505 exit(1);
6507 break;
6508 case QEMU_OPTION_fda:
6509 fd_filename[0] = optarg;
6510 break;
6511 case QEMU_OPTION_fdb:
6512 fd_filename[1] = optarg;
6513 break;
6514 #ifdef TARGET_I386
6515 case QEMU_OPTION_no_fd_bootchk:
6516 fd_bootchk = 0;
6517 break;
6518 #endif
6519 case QEMU_OPTION_no_code_copy:
6520 code_copy_enabled = 0;
6521 break;
6522 case QEMU_OPTION_net:
6523 if (nb_net_clients >= MAX_NET_CLIENTS) {
6524 fprintf(stderr, "qemu: too many network clients\n");
6525 exit(1);
6527 pstrcpy(net_clients[nb_net_clients],
6528 sizeof(net_clients[0]),
6529 optarg);
6530 nb_net_clients++;
6531 break;
6532 #ifdef CONFIG_SLIRP
6533 case QEMU_OPTION_tftp:
6534 tftp_prefix = optarg;
6535 break;
6536 #ifndef _WIN32
6537 case QEMU_OPTION_smb:
6538 net_slirp_smb(optarg);
6539 break;
6540 #endif
6541 case QEMU_OPTION_redir:
6542 net_slirp_redir(optarg);
6543 break;
6544 #endif
6545 #ifdef HAS_AUDIO
6546 case QEMU_OPTION_audio_help:
6547 AUD_help ();
6548 exit (0);
6549 break;
6550 case QEMU_OPTION_soundhw:
6551 select_soundhw (optarg);
6552 break;
6553 #endif
6554 case QEMU_OPTION_h:
6555 help();
6556 break;
6557 case QEMU_OPTION_m:
6558 ram_size = atoi(optarg) * 1024 * 1024;
6559 if (ram_size <= 0)
6560 help();
6561 if (ram_size > PHYS_RAM_MAX_SIZE) {
6562 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6563 PHYS_RAM_MAX_SIZE / (1024 * 1024));
6564 exit(1);
6566 break;
6567 case QEMU_OPTION_d:
6569 int mask;
6570 CPULogItem *item;
6572 mask = cpu_str_to_log_mask(optarg);
6573 if (!mask) {
6574 printf("Log items (comma separated):\n");
6575 for(item = cpu_log_items; item->mask != 0; item++) {
6576 printf("%-10s %s\n", item->name, item->help);
6578 exit(1);
6580 cpu_set_log(mask);
6582 break;
6583 #ifdef CONFIG_GDBSTUB
6584 case QEMU_OPTION_s:
6585 use_gdbstub = 1;
6586 break;
6587 case QEMU_OPTION_p:
6588 gdbstub_port = atoi(optarg);
6589 break;
6590 #endif
6591 case QEMU_OPTION_L:
6592 bios_dir = optarg;
6593 break;
6594 case QEMU_OPTION_S:
6595 start_emulation = 0;
6596 break;
6597 case QEMU_OPTION_k:
6598 keyboard_layout = optarg;
6599 break;
6600 case QEMU_OPTION_localtime:
6601 rtc_utc = 0;
6602 break;
6603 case QEMU_OPTION_cirrusvga:
6604 cirrus_vga_enabled = 1;
6605 break;
6606 case QEMU_OPTION_std_vga:
6607 cirrus_vga_enabled = 0;
6608 break;
6609 case QEMU_OPTION_g:
6611 const char *p;
6612 int w, h, depth;
6613 p = optarg;
6614 w = strtol(p, (char **)&p, 10);
6615 if (w <= 0) {
6616 graphic_error:
6617 fprintf(stderr, "qemu: invalid resolution or depth\n");
6618 exit(1);
6620 if (*p != 'x')
6621 goto graphic_error;
6622 p++;
6623 h = strtol(p, (char **)&p, 10);
6624 if (h <= 0)
6625 goto graphic_error;
6626 if (*p == 'x') {
6627 p++;
6628 depth = strtol(p, (char **)&p, 10);
6629 if (depth != 8 && depth != 15 && depth != 16 &&
6630 depth != 24 && depth != 32)
6631 goto graphic_error;
6632 } else if (*p == '\0') {
6633 depth = graphic_depth;
6634 } else {
6635 goto graphic_error;
6638 graphic_width = w;
6639 graphic_height = h;
6640 graphic_depth = depth;
6642 break;
6643 case QEMU_OPTION_monitor:
6644 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6645 break;
6646 case QEMU_OPTION_serial:
6647 if (serial_device_index >= MAX_SERIAL_PORTS) {
6648 fprintf(stderr, "qemu: too many serial ports\n");
6649 exit(1);
6651 pstrcpy(serial_devices[serial_device_index],
6652 sizeof(serial_devices[0]), optarg);
6653 serial_device_index++;
6654 break;
6655 case QEMU_OPTION_parallel:
6656 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6657 fprintf(stderr, "qemu: too many parallel ports\n");
6658 exit(1);
6660 pstrcpy(parallel_devices[parallel_device_index],
6661 sizeof(parallel_devices[0]), optarg);
6662 parallel_device_index++;
6663 break;
6664 case QEMU_OPTION_loadvm:
6665 loadvm = optarg;
6666 break;
6667 case QEMU_OPTION_full_screen:
6668 full_screen = 1;
6669 break;
6670 case QEMU_OPTION_pidfile:
6671 create_pidfile(optarg);
6672 break;
6673 #ifdef TARGET_I386
6674 case QEMU_OPTION_win2k_hack:
6675 win2k_install_hack = 1;
6676 break;
6677 #endif
6678 #ifdef USE_KQEMU
6679 case QEMU_OPTION_no_kqemu:
6680 kqemu_allowed = 0;
6681 break;
6682 case QEMU_OPTION_kernel_kqemu:
6683 kqemu_allowed = 2;
6684 break;
6685 #endif
6686 case QEMU_OPTION_usb:
6687 usb_enabled = 1;
6688 break;
6689 case QEMU_OPTION_usbdevice:
6690 usb_enabled = 1;
6691 if (usb_devices_index >= MAX_USB_CMDLINE) {
6692 fprintf(stderr, "Too many USB devices\n");
6693 exit(1);
6695 pstrcpy(usb_devices[usb_devices_index],
6696 sizeof(usb_devices[usb_devices_index]),
6697 optarg);
6698 usb_devices_index++;
6699 break;
6700 case QEMU_OPTION_smp:
6701 smp_cpus = atoi(optarg);
6702 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6703 fprintf(stderr, "Invalid number of CPUs\n");
6704 exit(1);
6706 break;
6707 case QEMU_OPTION_vnc:
6708 vnc_display = atoi(optarg);
6709 if (vnc_display < 0) {
6710 fprintf(stderr, "Invalid VNC display\n");
6711 exit(1);
6713 break;
6714 case QEMU_OPTION_no_acpi:
6715 acpi_enabled = 0;
6716 break;
6721 #ifdef USE_KQEMU
6722 if (smp_cpus > 1)
6723 kqemu_allowed = 0;
6724 #endif
6725 linux_boot = (kernel_filename != NULL);
6727 if (!linux_boot &&
6728 hd_filename[0] == '\0' &&
6729 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6730 fd_filename[0] == '\0')
6731 help();
6733 /* boot to cd by default if no hard disk */
6734 if (hd_filename[0] == '\0' && boot_device == 'c') {
6735 if (fd_filename[0] != '\0')
6736 boot_device = 'a';
6737 else
6738 boot_device = 'd';
6741 setvbuf(stdout, NULL, _IOLBF, 0);
6743 init_timers();
6744 init_timer_alarm();
6745 qemu_aio_init();
6747 #ifdef _WIN32
6748 socket_init();
6749 #endif
6751 /* init network clients */
6752 if (nb_net_clients == 0) {
6753 /* if no clients, we use a default config */
6754 pstrcpy(net_clients[0], sizeof(net_clients[0]),
6755 "nic");
6756 pstrcpy(net_clients[1], sizeof(net_clients[0]),
6757 "user");
6758 nb_net_clients = 2;
6761 for(i = 0;i < nb_net_clients; i++) {
6762 if (net_client_init(net_clients[i]) < 0)
6763 exit(1);
6766 /* init the memory */
6767 phys_ram_size = ram_size + vga_ram_size + bios_size;
6769 phys_ram_base = qemu_vmalloc(phys_ram_size);
6770 if (!phys_ram_base) {
6771 fprintf(stderr, "Could not allocate physical memory\n");
6772 exit(1);
6775 /* we always create the cdrom drive, even if no disk is there */
6776 bdrv_init();
6777 if (cdrom_index >= 0) {
6778 bs_table[cdrom_index] = bdrv_new("cdrom");
6779 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6782 /* open the virtual block devices */
6783 for(i = 0; i < MAX_DISKS; i++) {
6784 if (hd_filename[i]) {
6785 if (!bs_table[i]) {
6786 char buf[64];
6787 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6788 bs_table[i] = bdrv_new(buf);
6790 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
6791 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6792 hd_filename[i]);
6793 exit(1);
6795 if (i == 0 && cyls != 0) {
6796 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6797 bdrv_set_translation_hint(bs_table[i], translation);
6802 /* we always create at least one floppy disk */
6803 fd_table[0] = bdrv_new("fda");
6804 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6806 for(i = 0; i < MAX_FD; i++) {
6807 if (fd_filename[i]) {
6808 if (!fd_table[i]) {
6809 char buf[64];
6810 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6811 fd_table[i] = bdrv_new(buf);
6812 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6814 if (fd_filename[i] != '\0') {
6815 if (bdrv_open(fd_table[i], fd_filename[i],
6816 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
6817 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6818 fd_filename[i]);
6819 exit(1);
6825 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6826 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
6828 init_ioports();
6830 /* terminal init */
6831 if (nographic) {
6832 dumb_display_init(ds);
6833 } else if (vnc_display != -1) {
6834 vnc_display_init(ds, vnc_display);
6835 } else {
6836 #if defined(CONFIG_SDL)
6837 sdl_display_init(ds, full_screen);
6838 #elif defined(CONFIG_COCOA)
6839 cocoa_display_init(ds, full_screen);
6840 #else
6841 dumb_display_init(ds);
6842 #endif
6845 monitor_hd = qemu_chr_open(monitor_device);
6846 if (!monitor_hd) {
6847 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6848 exit(1);
6850 monitor_init(monitor_hd, !nographic);
6852 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6853 if (serial_devices[i][0] != '\0') {
6854 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6855 if (!serial_hds[i]) {
6856 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6857 serial_devices[i]);
6858 exit(1);
6860 if (!strcmp(serial_devices[i], "vc"))
6861 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6865 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6866 if (parallel_devices[i][0] != '\0') {
6867 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6868 if (!parallel_hds[i]) {
6869 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6870 parallel_devices[i]);
6871 exit(1);
6873 if (!strcmp(parallel_devices[i], "vc"))
6874 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6878 machine->init(ram_size, vga_ram_size, boot_device,
6879 ds, fd_filename, snapshot,
6880 kernel_filename, kernel_cmdline, initrd_filename);
6882 /* init USB devices */
6883 if (usb_enabled) {
6884 for(i = 0; i < usb_devices_index; i++) {
6885 if (usb_device_add(usb_devices[i]) < 0) {
6886 fprintf(stderr, "Warning: could not add USB device %s\n",
6887 usb_devices[i]);
6892 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6893 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6895 #ifdef CONFIG_GDBSTUB
6896 if (use_gdbstub) {
6897 if (gdbserver_start(gdbstub_port) < 0) {
6898 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6899 gdbstub_port);
6900 exit(1);
6901 } else {
6902 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6904 } else
6905 #endif
6906 if (loadvm)
6907 do_loadvm(loadvm);
6910 /* XXX: simplify init */
6911 read_passwords();
6912 if (start_emulation) {
6913 vm_start();
6916 main_loop();
6917 quit_timers();
6918 return 0;