Add missing ARM syscall numbers.
[qemu/mini2440.git] / vl.c
blob447da38a949d44469105cbd44ee67f83f581170d
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;
164 int no_reboot = 0;
166 /***********************************************************/
167 /* x86 ISA bus support */
169 target_phys_addr_t isa_mem_base = 0;
170 PicState2 *isa_pic;
172 uint32_t default_ioport_readb(void *opaque, uint32_t address)
174 #ifdef DEBUG_UNUSED_IOPORT
175 fprintf(stderr, "inb: port=0x%04x\n", address);
176 #endif
177 return 0xff;
180 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
182 #ifdef DEBUG_UNUSED_IOPORT
183 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
184 #endif
187 /* default is to make two byte accesses */
188 uint32_t default_ioport_readw(void *opaque, uint32_t address)
190 uint32_t data;
191 data = ioport_read_table[0][address](ioport_opaque[address], address);
192 address = (address + 1) & (MAX_IOPORTS - 1);
193 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
194 return data;
197 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
199 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
200 address = (address + 1) & (MAX_IOPORTS - 1);
201 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
204 uint32_t default_ioport_readl(void *opaque, uint32_t address)
206 #ifdef DEBUG_UNUSED_IOPORT
207 fprintf(stderr, "inl: port=0x%04x\n", address);
208 #endif
209 return 0xffffffff;
212 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
214 #ifdef DEBUG_UNUSED_IOPORT
215 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
216 #endif
219 void init_ioports(void)
221 int i;
223 for(i = 0; i < MAX_IOPORTS; i++) {
224 ioport_read_table[0][i] = default_ioport_readb;
225 ioport_write_table[0][i] = default_ioport_writeb;
226 ioport_read_table[1][i] = default_ioport_readw;
227 ioport_write_table[1][i] = default_ioport_writew;
228 ioport_read_table[2][i] = default_ioport_readl;
229 ioport_write_table[2][i] = default_ioport_writel;
233 /* size is the word size in byte */
234 int register_ioport_read(int start, int length, int size,
235 IOPortReadFunc *func, void *opaque)
237 int i, bsize;
239 if (size == 1) {
240 bsize = 0;
241 } else if (size == 2) {
242 bsize = 1;
243 } else if (size == 4) {
244 bsize = 2;
245 } else {
246 hw_error("register_ioport_read: invalid size");
247 return -1;
249 for(i = start; i < start + length; i += size) {
250 ioport_read_table[bsize][i] = func;
251 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
252 hw_error("register_ioport_read: invalid opaque");
253 ioport_opaque[i] = opaque;
255 return 0;
258 /* size is the word size in byte */
259 int register_ioport_write(int start, int length, int size,
260 IOPortWriteFunc *func, void *opaque)
262 int i, bsize;
264 if (size == 1) {
265 bsize = 0;
266 } else if (size == 2) {
267 bsize = 1;
268 } else if (size == 4) {
269 bsize = 2;
270 } else {
271 hw_error("register_ioport_write: invalid size");
272 return -1;
274 for(i = start; i < start + length; i += size) {
275 ioport_write_table[bsize][i] = func;
276 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
277 hw_error("register_ioport_read: invalid opaque");
278 ioport_opaque[i] = opaque;
280 return 0;
283 void isa_unassign_ioport(int start, int length)
285 int i;
287 for(i = start; i < start + length; i++) {
288 ioport_read_table[0][i] = default_ioport_readb;
289 ioport_read_table[1][i] = default_ioport_readw;
290 ioport_read_table[2][i] = default_ioport_readl;
292 ioport_write_table[0][i] = default_ioport_writeb;
293 ioport_write_table[1][i] = default_ioport_writew;
294 ioport_write_table[2][i] = default_ioport_writel;
298 /***********************************************************/
300 void pstrcpy(char *buf, int buf_size, const char *str)
302 int c;
303 char *q = buf;
305 if (buf_size <= 0)
306 return;
308 for(;;) {
309 c = *str++;
310 if (c == 0 || q >= buf + buf_size - 1)
311 break;
312 *q++ = c;
314 *q = '\0';
317 /* strcat and truncate. */
318 char *pstrcat(char *buf, int buf_size, const char *s)
320 int len;
321 len = strlen(buf);
322 if (len < buf_size)
323 pstrcpy(buf + len, buf_size - len, s);
324 return buf;
327 int strstart(const char *str, const char *val, const char **ptr)
329 const char *p, *q;
330 p = str;
331 q = val;
332 while (*q != '\0') {
333 if (*p != *q)
334 return 0;
335 p++;
336 q++;
338 if (ptr)
339 *ptr = p;
340 return 1;
343 void cpu_outb(CPUState *env, int addr, int val)
345 #ifdef DEBUG_IOPORT
346 if (loglevel & CPU_LOG_IOPORT)
347 fprintf(logfile, "outb: %04x %02x\n", addr, val);
348 #endif
349 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
350 #ifdef USE_KQEMU
351 if (env)
352 env->last_io_time = cpu_get_time_fast();
353 #endif
356 void cpu_outw(CPUState *env, int addr, int val)
358 #ifdef DEBUG_IOPORT
359 if (loglevel & CPU_LOG_IOPORT)
360 fprintf(logfile, "outw: %04x %04x\n", addr, val);
361 #endif
362 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
363 #ifdef USE_KQEMU
364 if (env)
365 env->last_io_time = cpu_get_time_fast();
366 #endif
369 void cpu_outl(CPUState *env, int addr, int val)
371 #ifdef DEBUG_IOPORT
372 if (loglevel & CPU_LOG_IOPORT)
373 fprintf(logfile, "outl: %04x %08x\n", addr, val);
374 #endif
375 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
376 #ifdef USE_KQEMU
377 if (env)
378 env->last_io_time = cpu_get_time_fast();
379 #endif
382 int cpu_inb(CPUState *env, int addr)
384 int val;
385 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
386 #ifdef DEBUG_IOPORT
387 if (loglevel & CPU_LOG_IOPORT)
388 fprintf(logfile, "inb : %04x %02x\n", addr, val);
389 #endif
390 #ifdef USE_KQEMU
391 if (env)
392 env->last_io_time = cpu_get_time_fast();
393 #endif
394 return val;
397 int cpu_inw(CPUState *env, int addr)
399 int val;
400 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
401 #ifdef DEBUG_IOPORT
402 if (loglevel & CPU_LOG_IOPORT)
403 fprintf(logfile, "inw : %04x %04x\n", addr, val);
404 #endif
405 #ifdef USE_KQEMU
406 if (env)
407 env->last_io_time = cpu_get_time_fast();
408 #endif
409 return val;
412 int cpu_inl(CPUState *env, int addr)
414 int val;
415 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
416 #ifdef DEBUG_IOPORT
417 if (loglevel & CPU_LOG_IOPORT)
418 fprintf(logfile, "inl : %04x %08x\n", addr, val);
419 #endif
420 #ifdef USE_KQEMU
421 if (env)
422 env->last_io_time = cpu_get_time_fast();
423 #endif
424 return val;
427 /***********************************************************/
428 void hw_error(const char *fmt, ...)
430 va_list ap;
431 CPUState *env;
433 va_start(ap, fmt);
434 fprintf(stderr, "qemu: hardware error: ");
435 vfprintf(stderr, fmt, ap);
436 fprintf(stderr, "\n");
437 for(env = first_cpu; env != NULL; env = env->next_cpu) {
438 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
439 #ifdef TARGET_I386
440 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
441 #else
442 cpu_dump_state(env, stderr, fprintf, 0);
443 #endif
445 va_end(ap);
446 abort();
449 /***********************************************************/
450 /* keyboard/mouse */
452 static QEMUPutKBDEvent *qemu_put_kbd_event;
453 static void *qemu_put_kbd_event_opaque;
454 static QEMUPutMouseEvent *qemu_put_mouse_event;
455 static void *qemu_put_mouse_event_opaque;
456 static int qemu_put_mouse_event_absolute;
458 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
460 qemu_put_kbd_event_opaque = opaque;
461 qemu_put_kbd_event = func;
464 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
466 qemu_put_mouse_event_opaque = opaque;
467 qemu_put_mouse_event = func;
468 qemu_put_mouse_event_absolute = absolute;
471 void kbd_put_keycode(int keycode)
473 if (qemu_put_kbd_event) {
474 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
478 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
480 if (qemu_put_mouse_event) {
481 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
482 dx, dy, dz, buttons_state);
486 int kbd_mouse_is_absolute(void)
488 return qemu_put_mouse_event_absolute;
491 /* compute with 96 bit intermediate result: (a*b)/c */
492 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
494 union {
495 uint64_t ll;
496 struct {
497 #ifdef WORDS_BIGENDIAN
498 uint32_t high, low;
499 #else
500 uint32_t low, high;
501 #endif
502 } l;
503 } u, res;
504 uint64_t rl, rh;
506 u.ll = a;
507 rl = (uint64_t)u.l.low * (uint64_t)b;
508 rh = (uint64_t)u.l.high * (uint64_t)b;
509 rh += (rl >> 32);
510 res.l.high = rh / c;
511 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
512 return res.ll;
515 /***********************************************************/
516 /* real time host monotonic timer */
518 #define QEMU_TIMER_BASE 1000000000LL
520 #ifdef WIN32
522 static int64_t clock_freq;
524 static void init_get_clock(void)
526 LARGE_INTEGER freq;
527 int ret;
528 ret = QueryPerformanceFrequency(&freq);
529 if (ret == 0) {
530 fprintf(stderr, "Could not calibrate ticks\n");
531 exit(1);
533 clock_freq = freq.QuadPart;
536 static int64_t get_clock(void)
538 LARGE_INTEGER ti;
539 QueryPerformanceCounter(&ti);
540 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
543 #else
545 static int use_rt_clock;
547 static void init_get_clock(void)
549 use_rt_clock = 0;
550 #if defined(__linux__)
552 struct timespec ts;
553 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
554 use_rt_clock = 1;
557 #endif
560 static int64_t get_clock(void)
562 #if defined(__linux__)
563 if (use_rt_clock) {
564 struct timespec ts;
565 clock_gettime(CLOCK_MONOTONIC, &ts);
566 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
567 } else
568 #endif
570 /* XXX: using gettimeofday leads to problems if the date
571 changes, so it should be avoided. */
572 struct timeval tv;
573 gettimeofday(&tv, NULL);
574 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
578 #endif
580 /***********************************************************/
581 /* guest cycle counter */
583 static int64_t cpu_ticks_prev;
584 static int64_t cpu_ticks_offset;
585 static int64_t cpu_clock_offset;
586 static int cpu_ticks_enabled;
588 /* return the host CPU cycle counter and handle stop/restart */
589 int64_t cpu_get_ticks(void)
591 if (!cpu_ticks_enabled) {
592 return cpu_ticks_offset;
593 } else {
594 int64_t ticks;
595 ticks = cpu_get_real_ticks();
596 if (cpu_ticks_prev > ticks) {
597 /* Note: non increasing ticks may happen if the host uses
598 software suspend */
599 cpu_ticks_offset += cpu_ticks_prev - ticks;
601 cpu_ticks_prev = ticks;
602 return ticks + cpu_ticks_offset;
606 /* return the host CPU monotonic timer and handle stop/restart */
607 static int64_t cpu_get_clock(void)
609 int64_t ti;
610 if (!cpu_ticks_enabled) {
611 return cpu_clock_offset;
612 } else {
613 ti = get_clock();
614 return ti + cpu_clock_offset;
618 /* enable cpu_get_ticks() */
619 void cpu_enable_ticks(void)
621 if (!cpu_ticks_enabled) {
622 cpu_ticks_offset -= cpu_get_real_ticks();
623 cpu_clock_offset -= get_clock();
624 cpu_ticks_enabled = 1;
628 /* disable cpu_get_ticks() : the clock is stopped. You must not call
629 cpu_get_ticks() after that. */
630 void cpu_disable_ticks(void)
632 if (cpu_ticks_enabled) {
633 cpu_ticks_offset = cpu_get_ticks();
634 cpu_clock_offset = cpu_get_clock();
635 cpu_ticks_enabled = 0;
639 /***********************************************************/
640 /* timers */
642 #define QEMU_TIMER_REALTIME 0
643 #define QEMU_TIMER_VIRTUAL 1
645 struct QEMUClock {
646 int type;
647 /* XXX: add frequency */
650 struct QEMUTimer {
651 QEMUClock *clock;
652 int64_t expire_time;
653 QEMUTimerCB *cb;
654 void *opaque;
655 struct QEMUTimer *next;
658 QEMUClock *rt_clock;
659 QEMUClock *vm_clock;
661 static QEMUTimer *active_timers[2];
662 #ifdef _WIN32
663 static MMRESULT timerID;
664 static HANDLE host_alarm = NULL;
665 static unsigned int period = 1;
666 #else
667 /* frequency of the times() clock tick */
668 static int timer_freq;
669 #endif
671 QEMUClock *qemu_new_clock(int type)
673 QEMUClock *clock;
674 clock = qemu_mallocz(sizeof(QEMUClock));
675 if (!clock)
676 return NULL;
677 clock->type = type;
678 return clock;
681 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
683 QEMUTimer *ts;
685 ts = qemu_mallocz(sizeof(QEMUTimer));
686 ts->clock = clock;
687 ts->cb = cb;
688 ts->opaque = opaque;
689 return ts;
692 void qemu_free_timer(QEMUTimer *ts)
694 qemu_free(ts);
697 /* stop a timer, but do not dealloc it */
698 void qemu_del_timer(QEMUTimer *ts)
700 QEMUTimer **pt, *t;
702 /* NOTE: this code must be signal safe because
703 qemu_timer_expired() can be called from a signal. */
704 pt = &active_timers[ts->clock->type];
705 for(;;) {
706 t = *pt;
707 if (!t)
708 break;
709 if (t == ts) {
710 *pt = t->next;
711 break;
713 pt = &t->next;
717 /* modify the current timer so that it will be fired when current_time
718 >= expire_time. The corresponding callback will be called. */
719 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
721 QEMUTimer **pt, *t;
723 qemu_del_timer(ts);
725 /* add the timer in the sorted list */
726 /* NOTE: this code must be signal safe because
727 qemu_timer_expired() can be called from a signal. */
728 pt = &active_timers[ts->clock->type];
729 for(;;) {
730 t = *pt;
731 if (!t)
732 break;
733 if (t->expire_time > expire_time)
734 break;
735 pt = &t->next;
737 ts->expire_time = expire_time;
738 ts->next = *pt;
739 *pt = ts;
742 int qemu_timer_pending(QEMUTimer *ts)
744 QEMUTimer *t;
745 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
746 if (t == ts)
747 return 1;
749 return 0;
752 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
754 if (!timer_head)
755 return 0;
756 return (timer_head->expire_time <= current_time);
759 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
761 QEMUTimer *ts;
763 for(;;) {
764 ts = *ptimer_head;
765 if (!ts || ts->expire_time > current_time)
766 break;
767 /* remove timer from the list before calling the callback */
768 *ptimer_head = ts->next;
769 ts->next = NULL;
771 /* run the callback (the timer list can be modified) */
772 ts->cb(ts->opaque);
776 int64_t qemu_get_clock(QEMUClock *clock)
778 switch(clock->type) {
779 case QEMU_TIMER_REALTIME:
780 return get_clock() / 1000000;
781 default:
782 case QEMU_TIMER_VIRTUAL:
783 return cpu_get_clock();
787 static void init_timers(void)
789 init_get_clock();
790 ticks_per_sec = QEMU_TIMER_BASE;
791 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
792 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
795 /* save a timer */
796 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
798 uint64_t expire_time;
800 if (qemu_timer_pending(ts)) {
801 expire_time = ts->expire_time;
802 } else {
803 expire_time = -1;
805 qemu_put_be64(f, expire_time);
808 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
810 uint64_t expire_time;
812 expire_time = qemu_get_be64(f);
813 if (expire_time != -1) {
814 qemu_mod_timer(ts, expire_time);
815 } else {
816 qemu_del_timer(ts);
820 static void timer_save(QEMUFile *f, void *opaque)
822 if (cpu_ticks_enabled) {
823 hw_error("cannot save state if virtual timers are running");
825 qemu_put_be64s(f, &cpu_ticks_offset);
826 qemu_put_be64s(f, &ticks_per_sec);
827 qemu_put_be64s(f, &cpu_clock_offset);
830 static int timer_load(QEMUFile *f, void *opaque, int version_id)
832 if (version_id != 1 && version_id != 2)
833 return -EINVAL;
834 if (cpu_ticks_enabled) {
835 return -EINVAL;
837 qemu_get_be64s(f, &cpu_ticks_offset);
838 qemu_get_be64s(f, &ticks_per_sec);
839 if (version_id == 2) {
840 qemu_get_be64s(f, &cpu_clock_offset);
842 return 0;
845 #ifdef _WIN32
846 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
847 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
848 #else
849 static void host_alarm_handler(int host_signum)
850 #endif
852 #if 0
853 #define DISP_FREQ 1000
855 static int64_t delta_min = INT64_MAX;
856 static int64_t delta_max, delta_cum, last_clock, delta, ti;
857 static int count;
858 ti = qemu_get_clock(vm_clock);
859 if (last_clock != 0) {
860 delta = ti - last_clock;
861 if (delta < delta_min)
862 delta_min = delta;
863 if (delta > delta_max)
864 delta_max = delta;
865 delta_cum += delta;
866 if (++count == DISP_FREQ) {
867 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
868 muldiv64(delta_min, 1000000, ticks_per_sec),
869 muldiv64(delta_max, 1000000, ticks_per_sec),
870 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
871 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
872 count = 0;
873 delta_min = INT64_MAX;
874 delta_max = 0;
875 delta_cum = 0;
878 last_clock = ti;
880 #endif
881 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
882 qemu_get_clock(vm_clock)) ||
883 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
884 qemu_get_clock(rt_clock))) {
885 #ifdef _WIN32
886 SetEvent(host_alarm);
887 #endif
888 CPUState *env = cpu_single_env;
889 if (env) {
890 /* stop the currently executing cpu because a timer occured */
891 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
892 #ifdef USE_KQEMU
893 if (env->kqemu_enabled) {
894 kqemu_cpu_interrupt(env);
896 #endif
901 #ifndef _WIN32
903 #if defined(__linux__)
905 #define RTC_FREQ 1024
907 static int rtc_fd;
909 static int start_rtc_timer(void)
911 rtc_fd = open("/dev/rtc", O_RDONLY);
912 if (rtc_fd < 0)
913 return -1;
914 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
915 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
916 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
917 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
918 goto fail;
920 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
921 fail:
922 close(rtc_fd);
923 return -1;
925 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
926 return 0;
929 #else
931 static int start_rtc_timer(void)
933 return -1;
936 #endif /* !defined(__linux__) */
938 #endif /* !defined(_WIN32) */
940 static void init_timer_alarm(void)
942 #ifdef _WIN32
944 int count=0;
945 TIMECAPS tc;
947 ZeroMemory(&tc, sizeof(TIMECAPS));
948 timeGetDevCaps(&tc, sizeof(TIMECAPS));
949 if (period < tc.wPeriodMin)
950 period = tc.wPeriodMin;
951 timeBeginPeriod(period);
952 timerID = timeSetEvent(1, // interval (ms)
953 period, // resolution
954 host_alarm_handler, // function
955 (DWORD)&count, // user parameter
956 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
957 if( !timerID ) {
958 perror("failed timer alarm");
959 exit(1);
961 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
962 if (!host_alarm) {
963 perror("failed CreateEvent");
964 exit(1);
966 qemu_add_wait_object(host_alarm, NULL, NULL);
968 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
969 #else
971 struct sigaction act;
972 struct itimerval itv;
974 /* get times() syscall frequency */
975 timer_freq = sysconf(_SC_CLK_TCK);
977 /* timer signal */
978 sigfillset(&act.sa_mask);
979 act.sa_flags = 0;
980 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
981 act.sa_flags |= SA_ONSTACK;
982 #endif
983 act.sa_handler = host_alarm_handler;
984 sigaction(SIGALRM, &act, NULL);
986 itv.it_interval.tv_sec = 0;
987 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
988 itv.it_value.tv_sec = 0;
989 itv.it_value.tv_usec = 10 * 1000;
990 setitimer(ITIMER_REAL, &itv, NULL);
991 /* we probe the tick duration of the kernel to inform the user if
992 the emulated kernel requested a too high timer frequency */
993 getitimer(ITIMER_REAL, &itv);
995 #if defined(__linux__)
996 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
997 have timers with 1 ms resolution. The correct solution will
998 be to use the POSIX real time timers available in recent
999 2.6 kernels */
1000 if (itv.it_interval.tv_usec > 1000 || 1) {
1001 /* try to use /dev/rtc to have a faster timer */
1002 if (start_rtc_timer() < 0)
1003 goto use_itimer;
1004 /* disable itimer */
1005 itv.it_interval.tv_sec = 0;
1006 itv.it_interval.tv_usec = 0;
1007 itv.it_value.tv_sec = 0;
1008 itv.it_value.tv_usec = 0;
1009 setitimer(ITIMER_REAL, &itv, NULL);
1011 /* use the RTC */
1012 sigaction(SIGIO, &act, NULL);
1013 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1014 fcntl(rtc_fd, F_SETOWN, getpid());
1015 } else
1016 #endif /* defined(__linux__) */
1018 use_itimer:
1019 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1020 PIT_FREQ) / 1000000;
1023 #endif
1026 void quit_timers(void)
1028 #ifdef _WIN32
1029 timeKillEvent(timerID);
1030 timeEndPeriod(period);
1031 if (host_alarm) {
1032 CloseHandle(host_alarm);
1033 host_alarm = NULL;
1035 #endif
1038 /***********************************************************/
1039 /* character device */
1041 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1043 return s->chr_write(s, buf, len);
1046 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1048 if (!s->chr_ioctl)
1049 return -ENOTSUP;
1050 return s->chr_ioctl(s, cmd, arg);
1053 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1055 char buf[4096];
1056 va_list ap;
1057 va_start(ap, fmt);
1058 vsnprintf(buf, sizeof(buf), fmt, ap);
1059 qemu_chr_write(s, buf, strlen(buf));
1060 va_end(ap);
1063 void qemu_chr_send_event(CharDriverState *s, int event)
1065 if (s->chr_send_event)
1066 s->chr_send_event(s, event);
1069 void qemu_chr_add_read_handler(CharDriverState *s,
1070 IOCanRWHandler *fd_can_read,
1071 IOReadHandler *fd_read, void *opaque)
1073 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1076 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1078 s->chr_event = chr_event;
1081 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1083 return len;
1086 static void null_chr_add_read_handler(CharDriverState *chr,
1087 IOCanRWHandler *fd_can_read,
1088 IOReadHandler *fd_read, void *opaque)
1092 CharDriverState *qemu_chr_open_null(void)
1094 CharDriverState *chr;
1096 chr = qemu_mallocz(sizeof(CharDriverState));
1097 if (!chr)
1098 return NULL;
1099 chr->chr_write = null_chr_write;
1100 chr->chr_add_read_handler = null_chr_add_read_handler;
1101 return chr;
1104 #ifdef _WIN32
1106 static void socket_cleanup(void)
1108 WSACleanup();
1111 static int socket_init(void)
1113 WSADATA Data;
1114 int ret, err;
1116 ret = WSAStartup(MAKEWORD(2,2), &Data);
1117 if (ret != 0) {
1118 err = WSAGetLastError();
1119 fprintf(stderr, "WSAStartup: %d\n", err);
1120 return -1;
1122 atexit(socket_cleanup);
1123 return 0;
1126 static int send_all(int fd, const uint8_t *buf, int len1)
1128 int ret, len;
1130 len = len1;
1131 while (len > 0) {
1132 ret = send(fd, buf, len, 0);
1133 if (ret < 0) {
1134 int errno;
1135 errno = WSAGetLastError();
1136 if (errno != WSAEWOULDBLOCK) {
1137 return -1;
1139 } else if (ret == 0) {
1140 break;
1141 } else {
1142 buf += ret;
1143 len -= ret;
1146 return len1 - len;
1149 void socket_set_nonblock(int fd)
1151 unsigned long opt = 1;
1152 ioctlsocket(fd, FIONBIO, &opt);
1155 #else
1157 static int unix_write(int fd, const uint8_t *buf, int len1)
1159 int ret, len;
1161 len = len1;
1162 while (len > 0) {
1163 ret = write(fd, buf, len);
1164 if (ret < 0) {
1165 if (errno != EINTR && errno != EAGAIN)
1166 return -1;
1167 } else if (ret == 0) {
1168 break;
1169 } else {
1170 buf += ret;
1171 len -= ret;
1174 return len1 - len;
1177 static inline int send_all(int fd, const uint8_t *buf, int len1)
1179 return unix_write(fd, buf, len1);
1182 void socket_set_nonblock(int fd)
1184 fcntl(fd, F_SETFL, O_NONBLOCK);
1186 #endif /* !_WIN32 */
1188 #ifndef _WIN32
1190 typedef struct {
1191 int fd_in, fd_out;
1192 IOCanRWHandler *fd_can_read;
1193 IOReadHandler *fd_read;
1194 void *fd_opaque;
1195 int max_size;
1196 } FDCharDriver;
1198 #define STDIO_MAX_CLIENTS 2
1200 static int stdio_nb_clients;
1201 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1203 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1205 FDCharDriver *s = chr->opaque;
1206 return unix_write(s->fd_out, buf, len);
1209 static int fd_chr_read_poll(void *opaque)
1211 CharDriverState *chr = opaque;
1212 FDCharDriver *s = chr->opaque;
1214 s->max_size = s->fd_can_read(s->fd_opaque);
1215 return s->max_size;
1218 static void fd_chr_read(void *opaque)
1220 CharDriverState *chr = opaque;
1221 FDCharDriver *s = chr->opaque;
1222 int size, len;
1223 uint8_t buf[1024];
1225 len = sizeof(buf);
1226 if (len > s->max_size)
1227 len = s->max_size;
1228 if (len == 0)
1229 return;
1230 size = read(s->fd_in, buf, len);
1231 if (size == 0) {
1232 /* FD has been closed. Remove it from the active list. */
1233 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1234 return;
1236 if (size > 0) {
1237 s->fd_read(s->fd_opaque, buf, size);
1241 static void fd_chr_add_read_handler(CharDriverState *chr,
1242 IOCanRWHandler *fd_can_read,
1243 IOReadHandler *fd_read, void *opaque)
1245 FDCharDriver *s = chr->opaque;
1247 if (s->fd_in >= 0) {
1248 s->fd_can_read = fd_can_read;
1249 s->fd_read = fd_read;
1250 s->fd_opaque = opaque;
1251 if (nographic && s->fd_in == 0) {
1252 } else {
1253 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1254 fd_chr_read, NULL, chr);
1259 /* open a character device to a unix fd */
1260 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1262 CharDriverState *chr;
1263 FDCharDriver *s;
1265 chr = qemu_mallocz(sizeof(CharDriverState));
1266 if (!chr)
1267 return NULL;
1268 s = qemu_mallocz(sizeof(FDCharDriver));
1269 if (!s) {
1270 free(chr);
1271 return NULL;
1273 s->fd_in = fd_in;
1274 s->fd_out = fd_out;
1275 chr->opaque = s;
1276 chr->chr_write = fd_chr_write;
1277 chr->chr_add_read_handler = fd_chr_add_read_handler;
1278 return chr;
1281 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1283 int fd_out;
1285 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1286 if (fd_out < 0)
1287 return NULL;
1288 return qemu_chr_open_fd(-1, fd_out);
1291 CharDriverState *qemu_chr_open_pipe(const char *filename)
1293 int fd;
1295 fd = open(filename, O_RDWR | O_BINARY);
1296 if (fd < 0)
1297 return NULL;
1298 return qemu_chr_open_fd(fd, fd);
1302 /* for STDIO, we handle the case where several clients use it
1303 (nographic mode) */
1305 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1307 #define TERM_FIFO_MAX_SIZE 1
1309 static int term_got_escape, client_index;
1310 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1311 static int term_fifo_size;
1312 static int term_timestamps;
1313 static int64_t term_timestamps_start;
1315 void term_print_help(void)
1317 printf("\n"
1318 "C-a h print this help\n"
1319 "C-a x exit emulator\n"
1320 "C-a s save disk data back to file (if -snapshot)\n"
1321 "C-a b send break (magic sysrq)\n"
1322 "C-a t toggle console timestamps\n"
1323 "C-a c switch between console and monitor\n"
1324 "C-a C-a send C-a\n"
1328 /* called when a char is received */
1329 static void stdio_received_byte(int ch)
1331 if (term_got_escape) {
1332 term_got_escape = 0;
1333 switch(ch) {
1334 case 'h':
1335 term_print_help();
1336 break;
1337 case 'x':
1338 exit(0);
1339 break;
1340 case 's':
1342 int i;
1343 for (i = 0; i < MAX_DISKS; i++) {
1344 if (bs_table[i])
1345 bdrv_commit(bs_table[i]);
1348 break;
1349 case 'b':
1350 if (client_index < stdio_nb_clients) {
1351 CharDriverState *chr;
1352 FDCharDriver *s;
1354 chr = stdio_clients[client_index];
1355 s = chr->opaque;
1356 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1358 break;
1359 case 'c':
1360 client_index++;
1361 if (client_index >= stdio_nb_clients)
1362 client_index = 0;
1363 if (client_index == 0) {
1364 /* send a new line in the monitor to get the prompt */
1365 ch = '\r';
1366 goto send_char;
1368 break;
1369 case 't':
1370 term_timestamps = !term_timestamps;
1371 term_timestamps_start = -1;
1372 break;
1373 case TERM_ESCAPE:
1374 goto send_char;
1376 } else if (ch == TERM_ESCAPE) {
1377 term_got_escape = 1;
1378 } else {
1379 send_char:
1380 if (client_index < stdio_nb_clients) {
1381 uint8_t buf[1];
1382 CharDriverState *chr;
1383 FDCharDriver *s;
1385 chr = stdio_clients[client_index];
1386 s = chr->opaque;
1387 if (s->fd_can_read(s->fd_opaque) > 0) {
1388 buf[0] = ch;
1389 s->fd_read(s->fd_opaque, buf, 1);
1390 } else if (term_fifo_size == 0) {
1391 term_fifo[term_fifo_size++] = ch;
1397 static int stdio_read_poll(void *opaque)
1399 CharDriverState *chr;
1400 FDCharDriver *s;
1402 if (client_index < stdio_nb_clients) {
1403 chr = stdio_clients[client_index];
1404 s = chr->opaque;
1405 /* try to flush the queue if needed */
1406 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1407 s->fd_read(s->fd_opaque, term_fifo, 1);
1408 term_fifo_size = 0;
1410 /* see if we can absorb more chars */
1411 if (term_fifo_size == 0)
1412 return 1;
1413 else
1414 return 0;
1415 } else {
1416 return 1;
1420 static void stdio_read(void *opaque)
1422 int size;
1423 uint8_t buf[1];
1425 size = read(0, buf, 1);
1426 if (size == 0) {
1427 /* stdin has been closed. Remove it from the active list. */
1428 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1429 return;
1431 if (size > 0)
1432 stdio_received_byte(buf[0]);
1435 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1437 FDCharDriver *s = chr->opaque;
1438 if (!term_timestamps) {
1439 return unix_write(s->fd_out, buf, len);
1440 } else {
1441 int i;
1442 char buf1[64];
1444 for(i = 0; i < len; i++) {
1445 unix_write(s->fd_out, buf + i, 1);
1446 if (buf[i] == '\n') {
1447 int64_t ti;
1448 int secs;
1450 ti = get_clock();
1451 if (term_timestamps_start == -1)
1452 term_timestamps_start = ti;
1453 ti -= term_timestamps_start;
1454 secs = ti / 1000000000;
1455 snprintf(buf1, sizeof(buf1),
1456 "[%02d:%02d:%02d.%03d] ",
1457 secs / 3600,
1458 (secs / 60) % 60,
1459 secs % 60,
1460 (int)((ti / 1000000) % 1000));
1461 unix_write(s->fd_out, buf1, strlen(buf1));
1464 return len;
1468 /* init terminal so that we can grab keys */
1469 static struct termios oldtty;
1470 static int old_fd0_flags;
1472 static void term_exit(void)
1474 tcsetattr (0, TCSANOW, &oldtty);
1475 fcntl(0, F_SETFL, old_fd0_flags);
1478 static void term_init(void)
1480 struct termios tty;
1482 tcgetattr (0, &tty);
1483 oldtty = tty;
1484 old_fd0_flags = fcntl(0, F_GETFL);
1486 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1487 |INLCR|IGNCR|ICRNL|IXON);
1488 tty.c_oflag |= OPOST;
1489 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1490 /* if graphical mode, we allow Ctrl-C handling */
1491 if (nographic)
1492 tty.c_lflag &= ~ISIG;
1493 tty.c_cflag &= ~(CSIZE|PARENB);
1494 tty.c_cflag |= CS8;
1495 tty.c_cc[VMIN] = 1;
1496 tty.c_cc[VTIME] = 0;
1498 tcsetattr (0, TCSANOW, &tty);
1500 atexit(term_exit);
1502 fcntl(0, F_SETFL, O_NONBLOCK);
1505 CharDriverState *qemu_chr_open_stdio(void)
1507 CharDriverState *chr;
1509 if (nographic) {
1510 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1511 return NULL;
1512 chr = qemu_chr_open_fd(0, 1);
1513 chr->chr_write = stdio_write;
1514 if (stdio_nb_clients == 0)
1515 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1516 client_index = stdio_nb_clients;
1517 } else {
1518 if (stdio_nb_clients != 0)
1519 return NULL;
1520 chr = qemu_chr_open_fd(0, 1);
1522 stdio_clients[stdio_nb_clients++] = chr;
1523 if (stdio_nb_clients == 1) {
1524 /* set the terminal in raw mode */
1525 term_init();
1527 return chr;
1530 #if defined(__linux__)
1531 CharDriverState *qemu_chr_open_pty(void)
1533 struct termios tty;
1534 char slave_name[1024];
1535 int master_fd, slave_fd;
1537 /* Not satisfying */
1538 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1539 return NULL;
1542 /* Disabling local echo and line-buffered output */
1543 tcgetattr (master_fd, &tty);
1544 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1545 tty.c_cc[VMIN] = 1;
1546 tty.c_cc[VTIME] = 0;
1547 tcsetattr (master_fd, TCSAFLUSH, &tty);
1549 fprintf(stderr, "char device redirected to %s\n", slave_name);
1550 return qemu_chr_open_fd(master_fd, master_fd);
1553 static void tty_serial_init(int fd, int speed,
1554 int parity, int data_bits, int stop_bits)
1556 struct termios tty;
1557 speed_t spd;
1559 #if 0
1560 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1561 speed, parity, data_bits, stop_bits);
1562 #endif
1563 tcgetattr (fd, &tty);
1565 switch(speed) {
1566 case 50:
1567 spd = B50;
1568 break;
1569 case 75:
1570 spd = B75;
1571 break;
1572 case 300:
1573 spd = B300;
1574 break;
1575 case 600:
1576 spd = B600;
1577 break;
1578 case 1200:
1579 spd = B1200;
1580 break;
1581 case 2400:
1582 spd = B2400;
1583 break;
1584 case 4800:
1585 spd = B4800;
1586 break;
1587 case 9600:
1588 spd = B9600;
1589 break;
1590 case 19200:
1591 spd = B19200;
1592 break;
1593 case 38400:
1594 spd = B38400;
1595 break;
1596 case 57600:
1597 spd = B57600;
1598 break;
1599 default:
1600 case 115200:
1601 spd = B115200;
1602 break;
1605 cfsetispeed(&tty, spd);
1606 cfsetospeed(&tty, spd);
1608 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1609 |INLCR|IGNCR|ICRNL|IXON);
1610 tty.c_oflag |= OPOST;
1611 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1612 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1613 switch(data_bits) {
1614 default:
1615 case 8:
1616 tty.c_cflag |= CS8;
1617 break;
1618 case 7:
1619 tty.c_cflag |= CS7;
1620 break;
1621 case 6:
1622 tty.c_cflag |= CS6;
1623 break;
1624 case 5:
1625 tty.c_cflag |= CS5;
1626 break;
1628 switch(parity) {
1629 default:
1630 case 'N':
1631 break;
1632 case 'E':
1633 tty.c_cflag |= PARENB;
1634 break;
1635 case 'O':
1636 tty.c_cflag |= PARENB | PARODD;
1637 break;
1639 if (stop_bits == 2)
1640 tty.c_cflag |= CSTOPB;
1642 tcsetattr (fd, TCSANOW, &tty);
1645 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1647 FDCharDriver *s = chr->opaque;
1649 switch(cmd) {
1650 case CHR_IOCTL_SERIAL_SET_PARAMS:
1652 QEMUSerialSetParams *ssp = arg;
1653 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1654 ssp->data_bits, ssp->stop_bits);
1656 break;
1657 case CHR_IOCTL_SERIAL_SET_BREAK:
1659 int enable = *(int *)arg;
1660 if (enable)
1661 tcsendbreak(s->fd_in, 1);
1663 break;
1664 default:
1665 return -ENOTSUP;
1667 return 0;
1670 CharDriverState *qemu_chr_open_tty(const char *filename)
1672 CharDriverState *chr;
1673 int fd;
1675 fd = open(filename, O_RDWR | O_NONBLOCK);
1676 if (fd < 0)
1677 return NULL;
1678 fcntl(fd, F_SETFL, O_NONBLOCK);
1679 tty_serial_init(fd, 115200, 'N', 8, 1);
1680 chr = qemu_chr_open_fd(fd, fd);
1681 if (!chr)
1682 return NULL;
1683 chr->chr_ioctl = tty_serial_ioctl;
1684 return chr;
1687 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1689 int fd = (int)chr->opaque;
1690 uint8_t b;
1692 switch(cmd) {
1693 case CHR_IOCTL_PP_READ_DATA:
1694 if (ioctl(fd, PPRDATA, &b) < 0)
1695 return -ENOTSUP;
1696 *(uint8_t *)arg = b;
1697 break;
1698 case CHR_IOCTL_PP_WRITE_DATA:
1699 b = *(uint8_t *)arg;
1700 if (ioctl(fd, PPWDATA, &b) < 0)
1701 return -ENOTSUP;
1702 break;
1703 case CHR_IOCTL_PP_READ_CONTROL:
1704 if (ioctl(fd, PPRCONTROL, &b) < 0)
1705 return -ENOTSUP;
1706 *(uint8_t *)arg = b;
1707 break;
1708 case CHR_IOCTL_PP_WRITE_CONTROL:
1709 b = *(uint8_t *)arg;
1710 if (ioctl(fd, PPWCONTROL, &b) < 0)
1711 return -ENOTSUP;
1712 break;
1713 case CHR_IOCTL_PP_READ_STATUS:
1714 if (ioctl(fd, PPRSTATUS, &b) < 0)
1715 return -ENOTSUP;
1716 *(uint8_t *)arg = b;
1717 break;
1718 default:
1719 return -ENOTSUP;
1721 return 0;
1724 CharDriverState *qemu_chr_open_pp(const char *filename)
1726 CharDriverState *chr;
1727 int fd;
1729 fd = open(filename, O_RDWR);
1730 if (fd < 0)
1731 return NULL;
1733 if (ioctl(fd, PPCLAIM) < 0) {
1734 close(fd);
1735 return NULL;
1738 chr = qemu_mallocz(sizeof(CharDriverState));
1739 if (!chr) {
1740 close(fd);
1741 return NULL;
1743 chr->opaque = (void *)fd;
1744 chr->chr_write = null_chr_write;
1745 chr->chr_add_read_handler = null_chr_add_read_handler;
1746 chr->chr_ioctl = pp_ioctl;
1747 return chr;
1750 #else
1751 CharDriverState *qemu_chr_open_pty(void)
1753 return NULL;
1755 #endif
1757 #endif /* !defined(_WIN32) */
1759 #ifdef _WIN32
1760 typedef struct {
1761 IOCanRWHandler *fd_can_read;
1762 IOReadHandler *fd_read;
1763 void *win_opaque;
1764 int max_size;
1765 HANDLE hcom, hrecv, hsend;
1766 OVERLAPPED orecv, osend;
1767 BOOL fpipe;
1768 DWORD len;
1769 } WinCharState;
1771 #define NSENDBUF 2048
1772 #define NRECVBUF 2048
1773 #define MAXCONNECT 1
1774 #define NTIMEOUT 5000
1776 static int win_chr_poll(void *opaque);
1777 static int win_chr_pipe_poll(void *opaque);
1779 static void win_chr_close2(WinCharState *s)
1781 if (s->hsend) {
1782 CloseHandle(s->hsend);
1783 s->hsend = NULL;
1785 if (s->hrecv) {
1786 CloseHandle(s->hrecv);
1787 s->hrecv = NULL;
1789 if (s->hcom) {
1790 CloseHandle(s->hcom);
1791 s->hcom = NULL;
1793 if (s->fpipe)
1794 qemu_del_polling_cb(win_chr_pipe_poll, s);
1795 else
1796 qemu_del_polling_cb(win_chr_poll, s);
1799 static void win_chr_close(CharDriverState *chr)
1801 WinCharState *s = chr->opaque;
1802 win_chr_close2(s);
1805 static int win_chr_init(WinCharState *s, const char *filename)
1807 COMMCONFIG comcfg;
1808 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1809 COMSTAT comstat;
1810 DWORD size;
1811 DWORD err;
1813 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1814 if (!s->hsend) {
1815 fprintf(stderr, "Failed CreateEvent\n");
1816 goto fail;
1818 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1819 if (!s->hrecv) {
1820 fprintf(stderr, "Failed CreateEvent\n");
1821 goto fail;
1824 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1825 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1826 if (s->hcom == INVALID_HANDLE_VALUE) {
1827 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1828 s->hcom = NULL;
1829 goto fail;
1832 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1833 fprintf(stderr, "Failed SetupComm\n");
1834 goto fail;
1837 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1838 size = sizeof(COMMCONFIG);
1839 GetDefaultCommConfig(filename, &comcfg, &size);
1840 comcfg.dcb.DCBlength = sizeof(DCB);
1841 CommConfigDialog(filename, NULL, &comcfg);
1843 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1844 fprintf(stderr, "Failed SetCommState\n");
1845 goto fail;
1848 if (!SetCommMask(s->hcom, EV_ERR)) {
1849 fprintf(stderr, "Failed SetCommMask\n");
1850 goto fail;
1853 cto.ReadIntervalTimeout = MAXDWORD;
1854 if (!SetCommTimeouts(s->hcom, &cto)) {
1855 fprintf(stderr, "Failed SetCommTimeouts\n");
1856 goto fail;
1859 if (!ClearCommError(s->hcom, &err, &comstat)) {
1860 fprintf(stderr, "Failed ClearCommError\n");
1861 goto fail;
1863 qemu_add_polling_cb(win_chr_poll, s);
1864 return 0;
1866 fail:
1867 win_chr_close2(s);
1868 return -1;
1871 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1873 WinCharState *s = chr->opaque;
1874 DWORD len, ret, size, err;
1876 len = len1;
1877 ZeroMemory(&s->osend, sizeof(s->osend));
1878 s->osend.hEvent = s->hsend;
1879 while (len > 0) {
1880 if (s->hsend)
1881 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1882 else
1883 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1884 if (!ret) {
1885 err = GetLastError();
1886 if (err == ERROR_IO_PENDING) {
1887 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1888 if (ret) {
1889 buf += size;
1890 len -= size;
1891 } else {
1892 break;
1894 } else {
1895 break;
1897 } else {
1898 buf += size;
1899 len -= size;
1902 return len1 - len;
1905 static int win_chr_read_poll(WinCharState *s)
1907 s->max_size = s->fd_can_read(s->win_opaque);
1908 return s->max_size;
1911 static void win_chr_readfile(WinCharState *s)
1913 int ret, err;
1914 uint8_t buf[1024];
1915 DWORD size;
1917 ZeroMemory(&s->orecv, sizeof(s->orecv));
1918 s->orecv.hEvent = s->hrecv;
1919 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1920 if (!ret) {
1921 err = GetLastError();
1922 if (err == ERROR_IO_PENDING) {
1923 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1927 if (size > 0) {
1928 s->fd_read(s->win_opaque, buf, size);
1932 static void win_chr_read(WinCharState *s)
1934 if (s->len > s->max_size)
1935 s->len = s->max_size;
1936 if (s->len == 0)
1937 return;
1939 win_chr_readfile(s);
1942 static int win_chr_poll(void *opaque)
1944 WinCharState *s = opaque;
1945 COMSTAT status;
1946 DWORD comerr;
1948 ClearCommError(s->hcom, &comerr, &status);
1949 if (status.cbInQue > 0) {
1950 s->len = status.cbInQue;
1951 win_chr_read_poll(s);
1952 win_chr_read(s);
1953 return 1;
1955 return 0;
1958 static void win_chr_add_read_handler(CharDriverState *chr,
1959 IOCanRWHandler *fd_can_read,
1960 IOReadHandler *fd_read, void *opaque)
1962 WinCharState *s = chr->opaque;
1964 s->fd_can_read = fd_can_read;
1965 s->fd_read = fd_read;
1966 s->win_opaque = opaque;
1969 CharDriverState *qemu_chr_open_win(const char *filename)
1971 CharDriverState *chr;
1972 WinCharState *s;
1974 chr = qemu_mallocz(sizeof(CharDriverState));
1975 if (!chr)
1976 return NULL;
1977 s = qemu_mallocz(sizeof(WinCharState));
1978 if (!s) {
1979 free(chr);
1980 return NULL;
1982 chr->opaque = s;
1983 chr->chr_write = win_chr_write;
1984 chr->chr_add_read_handler = win_chr_add_read_handler;
1985 chr->chr_close = win_chr_close;
1987 if (win_chr_init(s, filename) < 0) {
1988 free(s);
1989 free(chr);
1990 return NULL;
1992 return chr;
1995 static int win_chr_pipe_poll(void *opaque)
1997 WinCharState *s = opaque;
1998 DWORD size;
2000 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2001 if (size > 0) {
2002 s->len = size;
2003 win_chr_read_poll(s);
2004 win_chr_read(s);
2005 return 1;
2007 return 0;
2010 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2012 OVERLAPPED ov;
2013 int ret;
2014 DWORD size;
2015 char openname[256];
2017 s->fpipe = TRUE;
2019 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2020 if (!s->hsend) {
2021 fprintf(stderr, "Failed CreateEvent\n");
2022 goto fail;
2024 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2025 if (!s->hrecv) {
2026 fprintf(stderr, "Failed CreateEvent\n");
2027 goto fail;
2030 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2031 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2032 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2033 PIPE_WAIT,
2034 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2035 if (s->hcom == INVALID_HANDLE_VALUE) {
2036 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2037 s->hcom = NULL;
2038 goto fail;
2041 ZeroMemory(&ov, sizeof(ov));
2042 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2043 ret = ConnectNamedPipe(s->hcom, &ov);
2044 if (ret) {
2045 fprintf(stderr, "Failed ConnectNamedPipe\n");
2046 goto fail;
2049 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2050 if (!ret) {
2051 fprintf(stderr, "Failed GetOverlappedResult\n");
2052 if (ov.hEvent) {
2053 CloseHandle(ov.hEvent);
2054 ov.hEvent = NULL;
2056 goto fail;
2059 if (ov.hEvent) {
2060 CloseHandle(ov.hEvent);
2061 ov.hEvent = NULL;
2063 qemu_add_polling_cb(win_chr_pipe_poll, s);
2064 return 0;
2066 fail:
2067 win_chr_close2(s);
2068 return -1;
2072 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2074 CharDriverState *chr;
2075 WinCharState *s;
2077 chr = qemu_mallocz(sizeof(CharDriverState));
2078 if (!chr)
2079 return NULL;
2080 s = qemu_mallocz(sizeof(WinCharState));
2081 if (!s) {
2082 free(chr);
2083 return NULL;
2085 chr->opaque = s;
2086 chr->chr_write = win_chr_write;
2087 chr->chr_add_read_handler = win_chr_add_read_handler;
2088 chr->chr_close = win_chr_close;
2090 if (win_chr_pipe_init(s, filename) < 0) {
2091 free(s);
2092 free(chr);
2093 return NULL;
2095 return chr;
2098 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2100 CharDriverState *chr;
2101 WinCharState *s;
2103 chr = qemu_mallocz(sizeof(CharDriverState));
2104 if (!chr)
2105 return NULL;
2106 s = qemu_mallocz(sizeof(WinCharState));
2107 if (!s) {
2108 free(chr);
2109 return NULL;
2111 s->hcom = fd_out;
2112 chr->opaque = s;
2113 chr->chr_write = win_chr_write;
2114 chr->chr_add_read_handler = win_chr_add_read_handler;
2115 return chr;
2118 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2120 HANDLE fd_out;
2122 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2123 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2124 if (fd_out == INVALID_HANDLE_VALUE)
2125 return NULL;
2127 return qemu_chr_open_win_file(fd_out);
2129 #endif
2131 /***********************************************************/
2132 /* UDP Net console */
2134 typedef struct {
2135 IOCanRWHandler *fd_can_read;
2136 IOReadHandler *fd_read;
2137 void *fd_opaque;
2138 int fd;
2139 struct sockaddr_in daddr;
2140 char buf[1024];
2141 int bufcnt;
2142 int bufptr;
2143 int max_size;
2144 } NetCharDriver;
2146 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2148 NetCharDriver *s = chr->opaque;
2150 return sendto(s->fd, buf, len, 0,
2151 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2154 static int udp_chr_read_poll(void *opaque)
2156 CharDriverState *chr = opaque;
2157 NetCharDriver *s = chr->opaque;
2159 s->max_size = s->fd_can_read(s->fd_opaque);
2161 /* If there were any stray characters in the queue process them
2162 * first
2164 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2165 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2166 s->bufptr++;
2167 s->max_size = s->fd_can_read(s->fd_opaque);
2169 return s->max_size;
2172 static void udp_chr_read(void *opaque)
2174 CharDriverState *chr = opaque;
2175 NetCharDriver *s = chr->opaque;
2177 if (s->max_size == 0)
2178 return;
2179 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2180 s->bufptr = s->bufcnt;
2181 if (s->bufcnt <= 0)
2182 return;
2184 s->bufptr = 0;
2185 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2186 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2187 s->bufptr++;
2188 s->max_size = s->fd_can_read(s->fd_opaque);
2192 static void udp_chr_add_read_handler(CharDriverState *chr,
2193 IOCanRWHandler *fd_can_read,
2194 IOReadHandler *fd_read, void *opaque)
2196 NetCharDriver *s = chr->opaque;
2198 if (s->fd >= 0) {
2199 s->fd_can_read = fd_can_read;
2200 s->fd_read = fd_read;
2201 s->fd_opaque = opaque;
2202 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2203 udp_chr_read, NULL, chr);
2207 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2208 int parse_host_src_port(struct sockaddr_in *haddr,
2209 struct sockaddr_in *saddr,
2210 const char *str);
2212 CharDriverState *qemu_chr_open_udp(const char *def)
2214 CharDriverState *chr = NULL;
2215 NetCharDriver *s = NULL;
2216 int fd = -1;
2217 struct sockaddr_in saddr;
2219 chr = qemu_mallocz(sizeof(CharDriverState));
2220 if (!chr)
2221 goto return_err;
2222 s = qemu_mallocz(sizeof(NetCharDriver));
2223 if (!s)
2224 goto return_err;
2226 fd = socket(PF_INET, SOCK_DGRAM, 0);
2227 if (fd < 0) {
2228 perror("socket(PF_INET, SOCK_DGRAM)");
2229 goto return_err;
2232 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2233 printf("Could not parse: %s\n", def);
2234 goto return_err;
2237 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2239 perror("bind");
2240 goto return_err;
2243 s->fd = fd;
2244 s->bufcnt = 0;
2245 s->bufptr = 0;
2246 chr->opaque = s;
2247 chr->chr_write = udp_chr_write;
2248 chr->chr_add_read_handler = udp_chr_add_read_handler;
2249 return chr;
2251 return_err:
2252 if (chr)
2253 free(chr);
2254 if (s)
2255 free(s);
2256 if (fd >= 0)
2257 closesocket(fd);
2258 return NULL;
2261 /***********************************************************/
2262 /* TCP Net console */
2264 typedef struct {
2265 IOCanRWHandler *fd_can_read;
2266 IOReadHandler *fd_read;
2267 void *fd_opaque;
2268 int fd, listen_fd;
2269 int connected;
2270 int max_size;
2271 int do_telnetopt;
2272 } TCPCharDriver;
2274 static void tcp_chr_accept(void *opaque);
2276 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2278 TCPCharDriver *s = chr->opaque;
2279 if (s->connected) {
2280 return send_all(s->fd, buf, len);
2281 } else {
2282 /* XXX: indicate an error ? */
2283 return len;
2287 static int tcp_chr_read_poll(void *opaque)
2289 CharDriverState *chr = opaque;
2290 TCPCharDriver *s = chr->opaque;
2291 if (!s->connected)
2292 return 0;
2293 s->max_size = s->fd_can_read(s->fd_opaque);
2294 return s->max_size;
2297 #define IAC 255
2298 #define IAC_BREAK 243
2299 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2300 TCPCharDriver *s,
2301 char *buf, int *size)
2303 /* Handle any telnet client's basic IAC options to satisfy char by
2304 * char mode with no echo. All IAC options will be removed from
2305 * the buf and the do_telnetopt variable will be used to track the
2306 * state of the width of the IAC information.
2308 * IAC commands come in sets of 3 bytes with the exception of the
2309 * "IAC BREAK" command and the double IAC.
2312 int i;
2313 int j = 0;
2315 for (i = 0; i < *size; i++) {
2316 if (s->do_telnetopt > 1) {
2317 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2318 /* Double IAC means send an IAC */
2319 if (j != i)
2320 buf[j] = buf[i];
2321 j++;
2322 s->do_telnetopt = 1;
2323 } else {
2324 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2325 /* Handle IAC break commands by sending a serial break */
2326 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2327 s->do_telnetopt++;
2329 s->do_telnetopt++;
2331 if (s->do_telnetopt >= 4) {
2332 s->do_telnetopt = 1;
2334 } else {
2335 if ((unsigned char)buf[i] == IAC) {
2336 s->do_telnetopt = 2;
2337 } else {
2338 if (j != i)
2339 buf[j] = buf[i];
2340 j++;
2344 *size = j;
2347 static void tcp_chr_read(void *opaque)
2349 CharDriverState *chr = opaque;
2350 TCPCharDriver *s = chr->opaque;
2351 uint8_t buf[1024];
2352 int len, size;
2354 if (!s->connected || s->max_size <= 0)
2355 return;
2356 len = sizeof(buf);
2357 if (len > s->max_size)
2358 len = s->max_size;
2359 size = recv(s->fd, buf, len, 0);
2360 if (size == 0) {
2361 /* connection closed */
2362 s->connected = 0;
2363 if (s->listen_fd >= 0) {
2364 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2366 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2367 closesocket(s->fd);
2368 s->fd = -1;
2369 } else if (size > 0) {
2370 if (s->do_telnetopt)
2371 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2372 if (size > 0)
2373 s->fd_read(s->fd_opaque, buf, size);
2377 static void tcp_chr_add_read_handler(CharDriverState *chr,
2378 IOCanRWHandler *fd_can_read,
2379 IOReadHandler *fd_read, void *opaque)
2381 TCPCharDriver *s = chr->opaque;
2383 s->fd_can_read = fd_can_read;
2384 s->fd_read = fd_read;
2385 s->fd_opaque = opaque;
2388 static void tcp_chr_connect(void *opaque)
2390 CharDriverState *chr = opaque;
2391 TCPCharDriver *s = chr->opaque;
2393 s->connected = 1;
2394 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2395 tcp_chr_read, NULL, chr);
2398 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2399 static void tcp_chr_telnet_init(int fd)
2401 char buf[3];
2402 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2403 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2404 send(fd, (char *)buf, 3, 0);
2405 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2406 send(fd, (char *)buf, 3, 0);
2407 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2408 send(fd, (char *)buf, 3, 0);
2409 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2410 send(fd, (char *)buf, 3, 0);
2413 static void tcp_chr_accept(void *opaque)
2415 CharDriverState *chr = opaque;
2416 TCPCharDriver *s = chr->opaque;
2417 struct sockaddr_in saddr;
2418 socklen_t len;
2419 int fd;
2421 for(;;) {
2422 len = sizeof(saddr);
2423 fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2424 if (fd < 0 && errno != EINTR) {
2425 return;
2426 } else if (fd >= 0) {
2427 if (s->do_telnetopt)
2428 tcp_chr_telnet_init(fd);
2429 break;
2432 socket_set_nonblock(fd);
2433 s->fd = fd;
2434 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2435 tcp_chr_connect(chr);
2438 static void tcp_chr_close(CharDriverState *chr)
2440 TCPCharDriver *s = chr->opaque;
2441 if (s->fd >= 0)
2442 closesocket(s->fd);
2443 if (s->listen_fd >= 0)
2444 closesocket(s->listen_fd);
2445 qemu_free(s);
2448 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2449 int is_telnet)
2451 CharDriverState *chr = NULL;
2452 TCPCharDriver *s = NULL;
2453 int fd = -1, ret, err, val;
2454 int is_listen = 0;
2455 int is_waitconnect = 1;
2456 const char *ptr;
2457 struct sockaddr_in saddr;
2459 if (parse_host_port(&saddr, host_str) < 0)
2460 goto fail;
2462 ptr = host_str;
2463 while((ptr = strchr(ptr,','))) {
2464 ptr++;
2465 if (!strncmp(ptr,"server",6)) {
2466 is_listen = 1;
2467 } else if (!strncmp(ptr,"nowait",6)) {
2468 is_waitconnect = 0;
2469 } else {
2470 printf("Unknown option: %s\n", ptr);
2471 goto fail;
2474 if (!is_listen)
2475 is_waitconnect = 0;
2477 chr = qemu_mallocz(sizeof(CharDriverState));
2478 if (!chr)
2479 goto fail;
2480 s = qemu_mallocz(sizeof(TCPCharDriver));
2481 if (!s)
2482 goto fail;
2484 fd = socket(PF_INET, SOCK_STREAM, 0);
2485 if (fd < 0)
2486 goto fail;
2488 if (!is_waitconnect)
2489 socket_set_nonblock(fd);
2491 s->connected = 0;
2492 s->fd = -1;
2493 s->listen_fd = -1;
2494 if (is_listen) {
2495 /* allow fast reuse */
2496 val = 1;
2497 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2499 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2500 if (ret < 0)
2501 goto fail;
2502 ret = listen(fd, 0);
2503 if (ret < 0)
2504 goto fail;
2505 s->listen_fd = fd;
2506 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2507 if (is_telnet)
2508 s->do_telnetopt = 1;
2509 } else {
2510 for(;;) {
2511 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2512 if (ret < 0) {
2513 err = socket_error();
2514 if (err == EINTR || err == EWOULDBLOCK) {
2515 } else if (err == EINPROGRESS) {
2516 break;
2517 } else {
2518 goto fail;
2520 } else {
2521 s->connected = 1;
2522 break;
2525 s->fd = fd;
2526 if (s->connected)
2527 tcp_chr_connect(chr);
2528 else
2529 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2532 chr->opaque = s;
2533 chr->chr_write = tcp_chr_write;
2534 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2535 chr->chr_close = tcp_chr_close;
2536 if (is_listen && is_waitconnect) {
2537 printf("QEMU waiting for connection on: %s\n", host_str);
2538 tcp_chr_accept(chr);
2539 socket_set_nonblock(s->listen_fd);
2542 return chr;
2543 fail:
2544 if (fd >= 0)
2545 closesocket(fd);
2546 qemu_free(s);
2547 qemu_free(chr);
2548 return NULL;
2551 CharDriverState *qemu_chr_open(const char *filename)
2553 const char *p;
2555 if (!strcmp(filename, "vc")) {
2556 return text_console_init(&display_state);
2557 } else if (!strcmp(filename, "null")) {
2558 return qemu_chr_open_null();
2559 } else
2560 if (strstart(filename, "tcp:", &p)) {
2561 return qemu_chr_open_tcp(p, 0);
2562 } else
2563 if (strstart(filename, "telnet:", &p)) {
2564 return qemu_chr_open_tcp(p, 1);
2565 } else
2566 if (strstart(filename, "udp:", &p)) {
2567 return qemu_chr_open_udp(p);
2568 } else
2569 #ifndef _WIN32
2570 if (strstart(filename, "file:", &p)) {
2571 return qemu_chr_open_file_out(p);
2572 } else if (strstart(filename, "pipe:", &p)) {
2573 return qemu_chr_open_pipe(p);
2574 } else if (!strcmp(filename, "pty")) {
2575 return qemu_chr_open_pty();
2576 } else if (!strcmp(filename, "stdio")) {
2577 return qemu_chr_open_stdio();
2578 } else
2579 #endif
2580 #if defined(__linux__)
2581 if (strstart(filename, "/dev/parport", NULL)) {
2582 return qemu_chr_open_pp(filename);
2583 } else
2584 if (strstart(filename, "/dev/", NULL)) {
2585 return qemu_chr_open_tty(filename);
2586 } else
2587 #endif
2588 #ifdef _WIN32
2589 if (strstart(filename, "COM", NULL)) {
2590 return qemu_chr_open_win(filename);
2591 } else
2592 if (strstart(filename, "pipe:", &p)) {
2593 return qemu_chr_open_win_pipe(p);
2594 } else
2595 if (strstart(filename, "file:", &p)) {
2596 return qemu_chr_open_win_file_out(p);
2598 #endif
2600 return NULL;
2604 void qemu_chr_close(CharDriverState *chr)
2606 if (chr->chr_close)
2607 chr->chr_close(chr);
2610 /***********************************************************/
2611 /* network device redirectors */
2613 void hex_dump(FILE *f, const uint8_t *buf, int size)
2615 int len, i, j, c;
2617 for(i=0;i<size;i+=16) {
2618 len = size - i;
2619 if (len > 16)
2620 len = 16;
2621 fprintf(f, "%08x ", i);
2622 for(j=0;j<16;j++) {
2623 if (j < len)
2624 fprintf(f, " %02x", buf[i+j]);
2625 else
2626 fprintf(f, " ");
2628 fprintf(f, " ");
2629 for(j=0;j<len;j++) {
2630 c = buf[i+j];
2631 if (c < ' ' || c > '~')
2632 c = '.';
2633 fprintf(f, "%c", c);
2635 fprintf(f, "\n");
2639 static int parse_macaddr(uint8_t *macaddr, const char *p)
2641 int i;
2642 for(i = 0; i < 6; i++) {
2643 macaddr[i] = strtol(p, (char **)&p, 16);
2644 if (i == 5) {
2645 if (*p != '\0')
2646 return -1;
2647 } else {
2648 if (*p != ':')
2649 return -1;
2650 p++;
2653 return 0;
2656 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2658 const char *p, *p1;
2659 int len;
2660 p = *pp;
2661 p1 = strchr(p, sep);
2662 if (!p1)
2663 return -1;
2664 len = p1 - p;
2665 p1++;
2666 if (buf_size > 0) {
2667 if (len > buf_size - 1)
2668 len = buf_size - 1;
2669 memcpy(buf, p, len);
2670 buf[len] = '\0';
2672 *pp = p1;
2673 return 0;
2676 int parse_host_src_port(struct sockaddr_in *haddr,
2677 struct sockaddr_in *saddr,
2678 const char *input_str)
2680 char *str = strdup(input_str);
2681 char *host_str = str;
2682 char *src_str;
2683 char *ptr;
2686 * Chop off any extra arguments at the end of the string which
2687 * would start with a comma, then fill in the src port information
2688 * if it was provided else use the "any address" and "any port".
2690 if ((ptr = strchr(str,',')))
2691 *ptr = '\0';
2693 if ((src_str = strchr(input_str,'@'))) {
2694 *src_str = '\0';
2695 src_str++;
2698 if (parse_host_port(haddr, host_str) < 0)
2699 goto fail;
2701 if (!src_str || *src_str == '\0')
2702 src_str = ":0";
2704 if (parse_host_port(saddr, src_str) < 0)
2705 goto fail;
2707 free(str);
2708 return(0);
2710 fail:
2711 free(str);
2712 return -1;
2715 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2717 char buf[512];
2718 struct hostent *he;
2719 const char *p, *r;
2720 int port;
2722 p = str;
2723 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2724 return -1;
2725 saddr->sin_family = AF_INET;
2726 if (buf[0] == '\0') {
2727 saddr->sin_addr.s_addr = 0;
2728 } else {
2729 if (isdigit(buf[0])) {
2730 if (!inet_aton(buf, &saddr->sin_addr))
2731 return -1;
2732 } else {
2733 if ((he = gethostbyname(buf)) == NULL)
2734 return - 1;
2735 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2738 port = strtol(p, (char **)&r, 0);
2739 if (r == p)
2740 return -1;
2741 saddr->sin_port = htons(port);
2742 return 0;
2745 /* find or alloc a new VLAN */
2746 VLANState *qemu_find_vlan(int id)
2748 VLANState **pvlan, *vlan;
2749 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2750 if (vlan->id == id)
2751 return vlan;
2753 vlan = qemu_mallocz(sizeof(VLANState));
2754 if (!vlan)
2755 return NULL;
2756 vlan->id = id;
2757 vlan->next = NULL;
2758 pvlan = &first_vlan;
2759 while (*pvlan != NULL)
2760 pvlan = &(*pvlan)->next;
2761 *pvlan = vlan;
2762 return vlan;
2765 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2766 IOReadHandler *fd_read,
2767 IOCanRWHandler *fd_can_read,
2768 void *opaque)
2770 VLANClientState *vc, **pvc;
2771 vc = qemu_mallocz(sizeof(VLANClientState));
2772 if (!vc)
2773 return NULL;
2774 vc->fd_read = fd_read;
2775 vc->fd_can_read = fd_can_read;
2776 vc->opaque = opaque;
2777 vc->vlan = vlan;
2779 vc->next = NULL;
2780 pvc = &vlan->first_client;
2781 while (*pvc != NULL)
2782 pvc = &(*pvc)->next;
2783 *pvc = vc;
2784 return vc;
2787 int qemu_can_send_packet(VLANClientState *vc1)
2789 VLANState *vlan = vc1->vlan;
2790 VLANClientState *vc;
2792 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2793 if (vc != vc1) {
2794 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2795 return 0;
2798 return 1;
2801 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2803 VLANState *vlan = vc1->vlan;
2804 VLANClientState *vc;
2806 #if 0
2807 printf("vlan %d send:\n", vlan->id);
2808 hex_dump(stdout, buf, size);
2809 #endif
2810 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2811 if (vc != vc1) {
2812 vc->fd_read(vc->opaque, buf, size);
2817 #if defined(CONFIG_SLIRP)
2819 /* slirp network adapter */
2821 static int slirp_inited;
2822 static VLANClientState *slirp_vc;
2824 int slirp_can_output(void)
2826 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2829 void slirp_output(const uint8_t *pkt, int pkt_len)
2831 #if 0
2832 printf("slirp output:\n");
2833 hex_dump(stdout, pkt, pkt_len);
2834 #endif
2835 if (!slirp_vc)
2836 return;
2837 qemu_send_packet(slirp_vc, pkt, pkt_len);
2840 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2842 #if 0
2843 printf("slirp input:\n");
2844 hex_dump(stdout, buf, size);
2845 #endif
2846 slirp_input(buf, size);
2849 static int net_slirp_init(VLANState *vlan)
2851 if (!slirp_inited) {
2852 slirp_inited = 1;
2853 slirp_init();
2855 slirp_vc = qemu_new_vlan_client(vlan,
2856 slirp_receive, NULL, NULL);
2857 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2858 return 0;
2861 static void net_slirp_redir(const char *redir_str)
2863 int is_udp;
2864 char buf[256], *r;
2865 const char *p;
2866 struct in_addr guest_addr;
2867 int host_port, guest_port;
2869 if (!slirp_inited) {
2870 slirp_inited = 1;
2871 slirp_init();
2874 p = redir_str;
2875 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2876 goto fail;
2877 if (!strcmp(buf, "tcp")) {
2878 is_udp = 0;
2879 } else if (!strcmp(buf, "udp")) {
2880 is_udp = 1;
2881 } else {
2882 goto fail;
2885 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2886 goto fail;
2887 host_port = strtol(buf, &r, 0);
2888 if (r == buf)
2889 goto fail;
2891 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2892 goto fail;
2893 if (buf[0] == '\0') {
2894 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2896 if (!inet_aton(buf, &guest_addr))
2897 goto fail;
2899 guest_port = strtol(p, &r, 0);
2900 if (r == p)
2901 goto fail;
2903 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2904 fprintf(stderr, "qemu: could not set up redirection\n");
2905 exit(1);
2907 return;
2908 fail:
2909 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2910 exit(1);
2913 #ifndef _WIN32
2915 char smb_dir[1024];
2917 static void smb_exit(void)
2919 DIR *d;
2920 struct dirent *de;
2921 char filename[1024];
2923 /* erase all the files in the directory */
2924 d = opendir(smb_dir);
2925 for(;;) {
2926 de = readdir(d);
2927 if (!de)
2928 break;
2929 if (strcmp(de->d_name, ".") != 0 &&
2930 strcmp(de->d_name, "..") != 0) {
2931 snprintf(filename, sizeof(filename), "%s/%s",
2932 smb_dir, de->d_name);
2933 unlink(filename);
2936 closedir(d);
2937 rmdir(smb_dir);
2940 /* automatic user mode samba server configuration */
2941 void net_slirp_smb(const char *exported_dir)
2943 char smb_conf[1024];
2944 char smb_cmdline[1024];
2945 FILE *f;
2947 if (!slirp_inited) {
2948 slirp_inited = 1;
2949 slirp_init();
2952 /* XXX: better tmp dir construction */
2953 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2954 if (mkdir(smb_dir, 0700) < 0) {
2955 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2956 exit(1);
2958 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2960 f = fopen(smb_conf, "w");
2961 if (!f) {
2962 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2963 exit(1);
2965 fprintf(f,
2966 "[global]\n"
2967 "private dir=%s\n"
2968 "smb ports=0\n"
2969 "socket address=127.0.0.1\n"
2970 "pid directory=%s\n"
2971 "lock directory=%s\n"
2972 "log file=%s/log.smbd\n"
2973 "smb passwd file=%s/smbpasswd\n"
2974 "security = share\n"
2975 "[qemu]\n"
2976 "path=%s\n"
2977 "read only=no\n"
2978 "guest ok=yes\n",
2979 smb_dir,
2980 smb_dir,
2981 smb_dir,
2982 smb_dir,
2983 smb_dir,
2984 exported_dir
2986 fclose(f);
2987 atexit(smb_exit);
2989 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2990 smb_conf);
2992 slirp_add_exec(0, smb_cmdline, 4, 139);
2995 #endif /* !defined(_WIN32) */
2997 #endif /* CONFIG_SLIRP */
2999 #if !defined(_WIN32)
3001 typedef struct TAPState {
3002 VLANClientState *vc;
3003 int fd;
3004 } TAPState;
3006 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3008 TAPState *s = opaque;
3009 int ret;
3010 for(;;) {
3011 ret = write(s->fd, buf, size);
3012 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3013 } else {
3014 break;
3019 static void tap_send(void *opaque)
3021 TAPState *s = opaque;
3022 uint8_t buf[4096];
3023 int size;
3025 size = read(s->fd, buf, sizeof(buf));
3026 if (size > 0) {
3027 qemu_send_packet(s->vc, buf, size);
3031 /* fd support */
3033 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3035 TAPState *s;
3037 s = qemu_mallocz(sizeof(TAPState));
3038 if (!s)
3039 return NULL;
3040 s->fd = fd;
3041 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3042 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3043 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3044 return s;
3047 #ifdef _BSD
3048 static int tap_open(char *ifname, int ifname_size)
3050 int fd;
3051 char *dev;
3052 struct stat s;
3054 fd = open("/dev/tap", O_RDWR);
3055 if (fd < 0) {
3056 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3057 return -1;
3060 fstat(fd, &s);
3061 dev = devname(s.st_rdev, S_IFCHR);
3062 pstrcpy(ifname, ifname_size, dev);
3064 fcntl(fd, F_SETFL, O_NONBLOCK);
3065 return fd;
3067 #elif defined(__sun__)
3068 static int tap_open(char *ifname, int ifname_size)
3070 fprintf(stderr, "warning: tap_open not yet implemented\n");
3071 return -1;
3073 #else
3074 static int tap_open(char *ifname, int ifname_size)
3076 struct ifreq ifr;
3077 int fd, ret;
3079 fd = open("/dev/net/tun", O_RDWR);
3080 if (fd < 0) {
3081 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3082 return -1;
3084 memset(&ifr, 0, sizeof(ifr));
3085 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3086 if (ifname[0] != '\0')
3087 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3088 else
3089 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3090 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3091 if (ret != 0) {
3092 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3093 close(fd);
3094 return -1;
3096 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3097 fcntl(fd, F_SETFL, O_NONBLOCK);
3098 return fd;
3100 #endif
3102 static int net_tap_init(VLANState *vlan, const char *ifname1,
3103 const char *setup_script)
3105 TAPState *s;
3106 int pid, status, fd;
3107 char *args[3];
3108 char **parg;
3109 char ifname[128];
3111 if (ifname1 != NULL)
3112 pstrcpy(ifname, sizeof(ifname), ifname1);
3113 else
3114 ifname[0] = '\0';
3115 fd = tap_open(ifname, sizeof(ifname));
3116 if (fd < 0)
3117 return -1;
3119 if (!setup_script)
3120 setup_script = "";
3121 if (setup_script[0] != '\0') {
3122 /* try to launch network init script */
3123 pid = fork();
3124 if (pid >= 0) {
3125 if (pid == 0) {
3126 parg = args;
3127 *parg++ = (char *)setup_script;
3128 *parg++ = ifname;
3129 *parg++ = NULL;
3130 execv(setup_script, args);
3131 _exit(1);
3133 while (waitpid(pid, &status, 0) != pid);
3134 if (!WIFEXITED(status) ||
3135 WEXITSTATUS(status) != 0) {
3136 fprintf(stderr, "%s: could not launch network script\n",
3137 setup_script);
3138 return -1;
3142 s = net_tap_fd_init(vlan, fd);
3143 if (!s)
3144 return -1;
3145 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3146 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3147 return 0;
3150 #endif /* !_WIN32 */
3152 /* network connection */
3153 typedef struct NetSocketState {
3154 VLANClientState *vc;
3155 int fd;
3156 int state; /* 0 = getting length, 1 = getting data */
3157 int index;
3158 int packet_len;
3159 uint8_t buf[4096];
3160 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3161 } NetSocketState;
3163 typedef struct NetSocketListenState {
3164 VLANState *vlan;
3165 int fd;
3166 } NetSocketListenState;
3168 /* XXX: we consider we can send the whole packet without blocking */
3169 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3171 NetSocketState *s = opaque;
3172 uint32_t len;
3173 len = htonl(size);
3175 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3176 send_all(s->fd, buf, size);
3179 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3181 NetSocketState *s = opaque;
3182 sendto(s->fd, buf, size, 0,
3183 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3186 static void net_socket_send(void *opaque)
3188 NetSocketState *s = opaque;
3189 int l, size, err;
3190 uint8_t buf1[4096];
3191 const uint8_t *buf;
3193 size = recv(s->fd, buf1, sizeof(buf1), 0);
3194 if (size < 0) {
3195 err = socket_error();
3196 if (err != EWOULDBLOCK)
3197 goto eoc;
3198 } else if (size == 0) {
3199 /* end of connection */
3200 eoc:
3201 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3202 closesocket(s->fd);
3203 return;
3205 buf = buf1;
3206 while (size > 0) {
3207 /* reassemble a packet from the network */
3208 switch(s->state) {
3209 case 0:
3210 l = 4 - s->index;
3211 if (l > size)
3212 l = size;
3213 memcpy(s->buf + s->index, buf, l);
3214 buf += l;
3215 size -= l;
3216 s->index += l;
3217 if (s->index == 4) {
3218 /* got length */
3219 s->packet_len = ntohl(*(uint32_t *)s->buf);
3220 s->index = 0;
3221 s->state = 1;
3223 break;
3224 case 1:
3225 l = s->packet_len - s->index;
3226 if (l > size)
3227 l = size;
3228 memcpy(s->buf + s->index, buf, l);
3229 s->index += l;
3230 buf += l;
3231 size -= l;
3232 if (s->index >= s->packet_len) {
3233 qemu_send_packet(s->vc, s->buf, s->packet_len);
3234 s->index = 0;
3235 s->state = 0;
3237 break;
3242 static void net_socket_send_dgram(void *opaque)
3244 NetSocketState *s = opaque;
3245 int size;
3247 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3248 if (size < 0)
3249 return;
3250 if (size == 0) {
3251 /* end of connection */
3252 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3253 return;
3255 qemu_send_packet(s->vc, s->buf, size);
3258 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3260 struct ip_mreq imr;
3261 int fd;
3262 int val, ret;
3263 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3264 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3265 inet_ntoa(mcastaddr->sin_addr),
3266 (int)ntohl(mcastaddr->sin_addr.s_addr));
3267 return -1;
3270 fd = socket(PF_INET, SOCK_DGRAM, 0);
3271 if (fd < 0) {
3272 perror("socket(PF_INET, SOCK_DGRAM)");
3273 return -1;
3276 val = 1;
3277 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3278 (const char *)&val, sizeof(val));
3279 if (ret < 0) {
3280 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3281 goto fail;
3284 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3285 if (ret < 0) {
3286 perror("bind");
3287 goto fail;
3290 /* Add host to multicast group */
3291 imr.imr_multiaddr = mcastaddr->sin_addr;
3292 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3294 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3295 (const char *)&imr, sizeof(struct ip_mreq));
3296 if (ret < 0) {
3297 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3298 goto fail;
3301 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3302 val = 1;
3303 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3304 (const char *)&val, sizeof(val));
3305 if (ret < 0) {
3306 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3307 goto fail;
3310 socket_set_nonblock(fd);
3311 return fd;
3312 fail:
3313 if (fd >= 0)
3314 closesocket(fd);
3315 return -1;
3318 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3319 int is_connected)
3321 struct sockaddr_in saddr;
3322 int newfd;
3323 socklen_t saddr_len;
3324 NetSocketState *s;
3326 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3327 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3328 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3331 if (is_connected) {
3332 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3333 /* must be bound */
3334 if (saddr.sin_addr.s_addr==0) {
3335 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3336 fd);
3337 return NULL;
3339 /* clone dgram socket */
3340 newfd = net_socket_mcast_create(&saddr);
3341 if (newfd < 0) {
3342 /* error already reported by net_socket_mcast_create() */
3343 close(fd);
3344 return NULL;
3346 /* clone newfd to fd, close newfd */
3347 dup2(newfd, fd);
3348 close(newfd);
3350 } else {
3351 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3352 fd, strerror(errno));
3353 return NULL;
3357 s = qemu_mallocz(sizeof(NetSocketState));
3358 if (!s)
3359 return NULL;
3360 s->fd = fd;
3362 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3363 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3365 /* mcast: save bound address as dst */
3366 if (is_connected) s->dgram_dst=saddr;
3368 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3369 "socket: fd=%d (%s mcast=%s:%d)",
3370 fd, is_connected? "cloned" : "",
3371 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3372 return s;
3375 static void net_socket_connect(void *opaque)
3377 NetSocketState *s = opaque;
3378 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3381 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3382 int is_connected)
3384 NetSocketState *s;
3385 s = qemu_mallocz(sizeof(NetSocketState));
3386 if (!s)
3387 return NULL;
3388 s->fd = fd;
3389 s->vc = qemu_new_vlan_client(vlan,
3390 net_socket_receive, NULL, s);
3391 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3392 "socket: fd=%d", fd);
3393 if (is_connected) {
3394 net_socket_connect(s);
3395 } else {
3396 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3398 return s;
3401 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3402 int is_connected)
3404 int so_type=-1, optlen=sizeof(so_type);
3406 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3407 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3408 return NULL;
3410 switch(so_type) {
3411 case SOCK_DGRAM:
3412 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3413 case SOCK_STREAM:
3414 return net_socket_fd_init_stream(vlan, fd, is_connected);
3415 default:
3416 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3417 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3418 return net_socket_fd_init_stream(vlan, fd, is_connected);
3420 return NULL;
3423 static void net_socket_accept(void *opaque)
3425 NetSocketListenState *s = opaque;
3426 NetSocketState *s1;
3427 struct sockaddr_in saddr;
3428 socklen_t len;
3429 int fd;
3431 for(;;) {
3432 len = sizeof(saddr);
3433 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3434 if (fd < 0 && errno != EINTR) {
3435 return;
3436 } else if (fd >= 0) {
3437 break;
3440 s1 = net_socket_fd_init(s->vlan, fd, 1);
3441 if (!s1) {
3442 closesocket(fd);
3443 } else {
3444 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3445 "socket: connection from %s:%d",
3446 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3450 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3452 NetSocketListenState *s;
3453 int fd, val, ret;
3454 struct sockaddr_in saddr;
3456 if (parse_host_port(&saddr, host_str) < 0)
3457 return -1;
3459 s = qemu_mallocz(sizeof(NetSocketListenState));
3460 if (!s)
3461 return -1;
3463 fd = socket(PF_INET, SOCK_STREAM, 0);
3464 if (fd < 0) {
3465 perror("socket");
3466 return -1;
3468 socket_set_nonblock(fd);
3470 /* allow fast reuse */
3471 val = 1;
3472 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3474 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3475 if (ret < 0) {
3476 perror("bind");
3477 return -1;
3479 ret = listen(fd, 0);
3480 if (ret < 0) {
3481 perror("listen");
3482 return -1;
3484 s->vlan = vlan;
3485 s->fd = fd;
3486 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3487 return 0;
3490 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3492 NetSocketState *s;
3493 int fd, connected, ret, err;
3494 struct sockaddr_in saddr;
3496 if (parse_host_port(&saddr, host_str) < 0)
3497 return -1;
3499 fd = socket(PF_INET, SOCK_STREAM, 0);
3500 if (fd < 0) {
3501 perror("socket");
3502 return -1;
3504 socket_set_nonblock(fd);
3506 connected = 0;
3507 for(;;) {
3508 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3509 if (ret < 0) {
3510 err = socket_error();
3511 if (err == EINTR || err == EWOULDBLOCK) {
3512 } else if (err == EINPROGRESS) {
3513 break;
3514 } else {
3515 perror("connect");
3516 closesocket(fd);
3517 return -1;
3519 } else {
3520 connected = 1;
3521 break;
3524 s = net_socket_fd_init(vlan, fd, connected);
3525 if (!s)
3526 return -1;
3527 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3528 "socket: connect to %s:%d",
3529 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3530 return 0;
3533 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3535 NetSocketState *s;
3536 int fd;
3537 struct sockaddr_in saddr;
3539 if (parse_host_port(&saddr, host_str) < 0)
3540 return -1;
3543 fd = net_socket_mcast_create(&saddr);
3544 if (fd < 0)
3545 return -1;
3547 s = net_socket_fd_init(vlan, fd, 0);
3548 if (!s)
3549 return -1;
3551 s->dgram_dst = saddr;
3553 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3554 "socket: mcast=%s:%d",
3555 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3556 return 0;
3560 static int get_param_value(char *buf, int buf_size,
3561 const char *tag, const char *str)
3563 const char *p;
3564 char *q;
3565 char option[128];
3567 p = str;
3568 for(;;) {
3569 q = option;
3570 while (*p != '\0' && *p != '=') {
3571 if ((q - option) < sizeof(option) - 1)
3572 *q++ = *p;
3573 p++;
3575 *q = '\0';
3576 if (*p != '=')
3577 break;
3578 p++;
3579 if (!strcmp(tag, option)) {
3580 q = buf;
3581 while (*p != '\0' && *p != ',') {
3582 if ((q - buf) < buf_size - 1)
3583 *q++ = *p;
3584 p++;
3586 *q = '\0';
3587 return q - buf;
3588 } else {
3589 while (*p != '\0' && *p != ',') {
3590 p++;
3593 if (*p != ',')
3594 break;
3595 p++;
3597 return 0;
3600 int net_client_init(const char *str)
3602 const char *p;
3603 char *q;
3604 char device[64];
3605 char buf[1024];
3606 int vlan_id, ret;
3607 VLANState *vlan;
3609 p = str;
3610 q = device;
3611 while (*p != '\0' && *p != ',') {
3612 if ((q - device) < sizeof(device) - 1)
3613 *q++ = *p;
3614 p++;
3616 *q = '\0';
3617 if (*p == ',')
3618 p++;
3619 vlan_id = 0;
3620 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3621 vlan_id = strtol(buf, NULL, 0);
3623 vlan = qemu_find_vlan(vlan_id);
3624 if (!vlan) {
3625 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3626 return -1;
3628 if (!strcmp(device, "nic")) {
3629 NICInfo *nd;
3630 uint8_t *macaddr;
3632 if (nb_nics >= MAX_NICS) {
3633 fprintf(stderr, "Too Many NICs\n");
3634 return -1;
3636 nd = &nd_table[nb_nics];
3637 macaddr = nd->macaddr;
3638 macaddr[0] = 0x52;
3639 macaddr[1] = 0x54;
3640 macaddr[2] = 0x00;
3641 macaddr[3] = 0x12;
3642 macaddr[4] = 0x34;
3643 macaddr[5] = 0x56 + nb_nics;
3645 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3646 if (parse_macaddr(macaddr, buf) < 0) {
3647 fprintf(stderr, "invalid syntax for ethernet address\n");
3648 return -1;
3651 if (get_param_value(buf, sizeof(buf), "model", p)) {
3652 nd->model = strdup(buf);
3654 nd->vlan = vlan;
3655 nb_nics++;
3656 ret = 0;
3657 } else
3658 if (!strcmp(device, "none")) {
3659 /* does nothing. It is needed to signal that no network cards
3660 are wanted */
3661 ret = 0;
3662 } else
3663 #ifdef CONFIG_SLIRP
3664 if (!strcmp(device, "user")) {
3665 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3666 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3668 ret = net_slirp_init(vlan);
3669 } else
3670 #endif
3671 #ifdef _WIN32
3672 if (!strcmp(device, "tap")) {
3673 char ifname[64];
3674 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3675 fprintf(stderr, "tap: no interface name\n");
3676 return -1;
3678 ret = tap_win32_init(vlan, ifname);
3679 } else
3680 #else
3681 if (!strcmp(device, "tap")) {
3682 char ifname[64];
3683 char setup_script[1024];
3684 int fd;
3685 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3686 fd = strtol(buf, NULL, 0);
3687 ret = -1;
3688 if (net_tap_fd_init(vlan, fd))
3689 ret = 0;
3690 } else {
3691 get_param_value(ifname, sizeof(ifname), "ifname", p);
3692 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3693 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3695 ret = net_tap_init(vlan, ifname, setup_script);
3697 } else
3698 #endif
3699 if (!strcmp(device, "socket")) {
3700 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3701 int fd;
3702 fd = strtol(buf, NULL, 0);
3703 ret = -1;
3704 if (net_socket_fd_init(vlan, fd, 1))
3705 ret = 0;
3706 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3707 ret = net_socket_listen_init(vlan, buf);
3708 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3709 ret = net_socket_connect_init(vlan, buf);
3710 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3711 ret = net_socket_mcast_init(vlan, buf);
3712 } else {
3713 fprintf(stderr, "Unknown socket options: %s\n", p);
3714 return -1;
3716 } else
3718 fprintf(stderr, "Unknown network device: %s\n", device);
3719 return -1;
3721 if (ret < 0) {
3722 fprintf(stderr, "Could not initialize device '%s'\n", device);
3725 return ret;
3728 void do_info_network(void)
3730 VLANState *vlan;
3731 VLANClientState *vc;
3733 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3734 term_printf("VLAN %d devices:\n", vlan->id);
3735 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3736 term_printf(" %s\n", vc->info_str);
3740 /***********************************************************/
3741 /* USB devices */
3743 static USBPort *used_usb_ports;
3744 static USBPort *free_usb_ports;
3746 /* ??? Maybe change this to register a hub to keep track of the topology. */
3747 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3748 usb_attachfn attach)
3750 port->opaque = opaque;
3751 port->index = index;
3752 port->attach = attach;
3753 port->next = free_usb_ports;
3754 free_usb_ports = port;
3757 static int usb_device_add(const char *devname)
3759 const char *p;
3760 USBDevice *dev;
3761 USBPort *port;
3763 if (!free_usb_ports)
3764 return -1;
3766 if (strstart(devname, "host:", &p)) {
3767 dev = usb_host_device_open(p);
3768 } else if (!strcmp(devname, "mouse")) {
3769 dev = usb_mouse_init();
3770 } else if (!strcmp(devname, "tablet")) {
3771 dev = usb_tablet_init();
3772 } else if (strstart(devname, "disk:", &p)) {
3773 dev = usb_msd_init(p);
3774 } else {
3775 return -1;
3777 if (!dev)
3778 return -1;
3780 /* Find a USB port to add the device to. */
3781 port = free_usb_ports;
3782 if (!port->next) {
3783 USBDevice *hub;
3785 /* Create a new hub and chain it on. */
3786 free_usb_ports = NULL;
3787 port->next = used_usb_ports;
3788 used_usb_ports = port;
3790 hub = usb_hub_init(VM_USB_HUB_SIZE);
3791 usb_attach(port, hub);
3792 port = free_usb_ports;
3795 free_usb_ports = port->next;
3796 port->next = used_usb_ports;
3797 used_usb_ports = port;
3798 usb_attach(port, dev);
3799 return 0;
3802 static int usb_device_del(const char *devname)
3804 USBPort *port;
3805 USBPort **lastp;
3806 USBDevice *dev;
3807 int bus_num, addr;
3808 const char *p;
3810 if (!used_usb_ports)
3811 return -1;
3813 p = strchr(devname, '.');
3814 if (!p)
3815 return -1;
3816 bus_num = strtoul(devname, NULL, 0);
3817 addr = strtoul(p + 1, NULL, 0);
3818 if (bus_num != 0)
3819 return -1;
3821 lastp = &used_usb_ports;
3822 port = used_usb_ports;
3823 while (port && port->dev->addr != addr) {
3824 lastp = &port->next;
3825 port = port->next;
3828 if (!port)
3829 return -1;
3831 dev = port->dev;
3832 *lastp = port->next;
3833 usb_attach(port, NULL);
3834 dev->handle_destroy(dev);
3835 port->next = free_usb_ports;
3836 free_usb_ports = port;
3837 return 0;
3840 void do_usb_add(const char *devname)
3842 int ret;
3843 ret = usb_device_add(devname);
3844 if (ret < 0)
3845 term_printf("Could not add USB device '%s'\n", devname);
3848 void do_usb_del(const char *devname)
3850 int ret;
3851 ret = usb_device_del(devname);
3852 if (ret < 0)
3853 term_printf("Could not remove USB device '%s'\n", devname);
3856 void usb_info(void)
3858 USBDevice *dev;
3859 USBPort *port;
3860 const char *speed_str;
3862 if (!usb_enabled) {
3863 term_printf("USB support not enabled\n");
3864 return;
3867 for (port = used_usb_ports; port; port = port->next) {
3868 dev = port->dev;
3869 if (!dev)
3870 continue;
3871 switch(dev->speed) {
3872 case USB_SPEED_LOW:
3873 speed_str = "1.5";
3874 break;
3875 case USB_SPEED_FULL:
3876 speed_str = "12";
3877 break;
3878 case USB_SPEED_HIGH:
3879 speed_str = "480";
3880 break;
3881 default:
3882 speed_str = "?";
3883 break;
3885 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
3886 0, dev->addr, speed_str, dev->devname);
3890 /***********************************************************/
3891 /* pid file */
3893 static char *pid_filename;
3895 /* Remove PID file. Called on normal exit */
3897 static void remove_pidfile(void)
3899 unlink (pid_filename);
3902 static void create_pidfile(const char *filename)
3904 struct stat pidstat;
3905 FILE *f;
3907 /* Try to write our PID to the named file */
3908 if (stat(filename, &pidstat) < 0) {
3909 if (errno == ENOENT) {
3910 if ((f = fopen (filename, "w")) == NULL) {
3911 perror("Opening pidfile");
3912 exit(1);
3914 fprintf(f, "%d\n", getpid());
3915 fclose(f);
3916 pid_filename = qemu_strdup(filename);
3917 if (!pid_filename) {
3918 fprintf(stderr, "Could not save PID filename");
3919 exit(1);
3921 atexit(remove_pidfile);
3923 } else {
3924 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3925 filename);
3926 exit(1);
3930 /***********************************************************/
3931 /* dumb display */
3933 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3937 static void dumb_resize(DisplayState *ds, int w, int h)
3941 static void dumb_refresh(DisplayState *ds)
3943 vga_hw_update();
3946 void dumb_display_init(DisplayState *ds)
3948 ds->data = NULL;
3949 ds->linesize = 0;
3950 ds->depth = 0;
3951 ds->dpy_update = dumb_update;
3952 ds->dpy_resize = dumb_resize;
3953 ds->dpy_refresh = dumb_refresh;
3956 /***********************************************************/
3957 /* I/O handling */
3959 #define MAX_IO_HANDLERS 64
3961 typedef struct IOHandlerRecord {
3962 int fd;
3963 IOCanRWHandler *fd_read_poll;
3964 IOHandler *fd_read;
3965 IOHandler *fd_write;
3966 void *opaque;
3967 /* temporary data */
3968 struct pollfd *ufd;
3969 struct IOHandlerRecord *next;
3970 } IOHandlerRecord;
3972 static IOHandlerRecord *first_io_handler;
3974 /* XXX: fd_read_poll should be suppressed, but an API change is
3975 necessary in the character devices to suppress fd_can_read(). */
3976 int qemu_set_fd_handler2(int fd,
3977 IOCanRWHandler *fd_read_poll,
3978 IOHandler *fd_read,
3979 IOHandler *fd_write,
3980 void *opaque)
3982 IOHandlerRecord **pioh, *ioh;
3984 if (!fd_read && !fd_write) {
3985 pioh = &first_io_handler;
3986 for(;;) {
3987 ioh = *pioh;
3988 if (ioh == NULL)
3989 break;
3990 if (ioh->fd == fd) {
3991 *pioh = ioh->next;
3992 qemu_free(ioh);
3993 break;
3995 pioh = &ioh->next;
3997 } else {
3998 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3999 if (ioh->fd == fd)
4000 goto found;
4002 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4003 if (!ioh)
4004 return -1;
4005 ioh->next = first_io_handler;
4006 first_io_handler = ioh;
4007 found:
4008 ioh->fd = fd;
4009 ioh->fd_read_poll = fd_read_poll;
4010 ioh->fd_read = fd_read;
4011 ioh->fd_write = fd_write;
4012 ioh->opaque = opaque;
4014 return 0;
4017 int qemu_set_fd_handler(int fd,
4018 IOHandler *fd_read,
4019 IOHandler *fd_write,
4020 void *opaque)
4022 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4025 /***********************************************************/
4026 /* Polling handling */
4028 typedef struct PollingEntry {
4029 PollingFunc *func;
4030 void *opaque;
4031 struct PollingEntry *next;
4032 } PollingEntry;
4034 static PollingEntry *first_polling_entry;
4036 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4038 PollingEntry **ppe, *pe;
4039 pe = qemu_mallocz(sizeof(PollingEntry));
4040 if (!pe)
4041 return -1;
4042 pe->func = func;
4043 pe->opaque = opaque;
4044 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4045 *ppe = pe;
4046 return 0;
4049 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4051 PollingEntry **ppe, *pe;
4052 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4053 pe = *ppe;
4054 if (pe->func == func && pe->opaque == opaque) {
4055 *ppe = pe->next;
4056 qemu_free(pe);
4057 break;
4062 #ifdef _WIN32
4063 /***********************************************************/
4064 /* Wait objects support */
4065 typedef struct WaitObjects {
4066 int num;
4067 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4068 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4069 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4070 } WaitObjects;
4072 static WaitObjects wait_objects = {0};
4074 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4076 WaitObjects *w = &wait_objects;
4078 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4079 return -1;
4080 w->events[w->num] = handle;
4081 w->func[w->num] = func;
4082 w->opaque[w->num] = opaque;
4083 w->num++;
4084 return 0;
4087 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4089 int i, found;
4090 WaitObjects *w = &wait_objects;
4092 found = 0;
4093 for (i = 0; i < w->num; i++) {
4094 if (w->events[i] == handle)
4095 found = 1;
4096 if (found) {
4097 w->events[i] = w->events[i + 1];
4098 w->func[i] = w->func[i + 1];
4099 w->opaque[i] = w->opaque[i + 1];
4102 if (found)
4103 w->num--;
4105 #endif
4107 /***********************************************************/
4108 /* savevm/loadvm support */
4110 #define IO_BUF_SIZE 32768
4112 struct QEMUFile {
4113 FILE *outfile;
4114 BlockDriverState *bs;
4115 int is_file;
4116 int is_writable;
4117 int64_t base_offset;
4118 int64_t buf_offset; /* start of buffer when writing, end of buffer
4119 when reading */
4120 int buf_index;
4121 int buf_size; /* 0 when writing */
4122 uint8_t buf[IO_BUF_SIZE];
4125 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4127 QEMUFile *f;
4129 f = qemu_mallocz(sizeof(QEMUFile));
4130 if (!f)
4131 return NULL;
4132 if (!strcmp(mode, "wb")) {
4133 f->is_writable = 1;
4134 } else if (!strcmp(mode, "rb")) {
4135 f->is_writable = 0;
4136 } else {
4137 goto fail;
4139 f->outfile = fopen(filename, mode);
4140 if (!f->outfile)
4141 goto fail;
4142 f->is_file = 1;
4143 return f;
4144 fail:
4145 if (f->outfile)
4146 fclose(f->outfile);
4147 qemu_free(f);
4148 return NULL;
4151 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4153 QEMUFile *f;
4155 f = qemu_mallocz(sizeof(QEMUFile));
4156 if (!f)
4157 return NULL;
4158 f->is_file = 0;
4159 f->bs = bs;
4160 f->is_writable = is_writable;
4161 f->base_offset = offset;
4162 return f;
4165 void qemu_fflush(QEMUFile *f)
4167 if (!f->is_writable)
4168 return;
4169 if (f->buf_index > 0) {
4170 if (f->is_file) {
4171 fseek(f->outfile, f->buf_offset, SEEK_SET);
4172 fwrite(f->buf, 1, f->buf_index, f->outfile);
4173 } else {
4174 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4175 f->buf, f->buf_index);
4177 f->buf_offset += f->buf_index;
4178 f->buf_index = 0;
4182 static void qemu_fill_buffer(QEMUFile *f)
4184 int len;
4186 if (f->is_writable)
4187 return;
4188 if (f->is_file) {
4189 fseek(f->outfile, f->buf_offset, SEEK_SET);
4190 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4191 if (len < 0)
4192 len = 0;
4193 } else {
4194 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4195 f->buf, IO_BUF_SIZE);
4196 if (len < 0)
4197 len = 0;
4199 f->buf_index = 0;
4200 f->buf_size = len;
4201 f->buf_offset += len;
4204 void qemu_fclose(QEMUFile *f)
4206 if (f->is_writable)
4207 qemu_fflush(f);
4208 if (f->is_file) {
4209 fclose(f->outfile);
4211 qemu_free(f);
4214 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4216 int l;
4217 while (size > 0) {
4218 l = IO_BUF_SIZE - f->buf_index;
4219 if (l > size)
4220 l = size;
4221 memcpy(f->buf + f->buf_index, buf, l);
4222 f->buf_index += l;
4223 buf += l;
4224 size -= l;
4225 if (f->buf_index >= IO_BUF_SIZE)
4226 qemu_fflush(f);
4230 void qemu_put_byte(QEMUFile *f, int v)
4232 f->buf[f->buf_index++] = v;
4233 if (f->buf_index >= IO_BUF_SIZE)
4234 qemu_fflush(f);
4237 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4239 int size, l;
4241 size = size1;
4242 while (size > 0) {
4243 l = f->buf_size - f->buf_index;
4244 if (l == 0) {
4245 qemu_fill_buffer(f);
4246 l = f->buf_size - f->buf_index;
4247 if (l == 0)
4248 break;
4250 if (l > size)
4251 l = size;
4252 memcpy(buf, f->buf + f->buf_index, l);
4253 f->buf_index += l;
4254 buf += l;
4255 size -= l;
4257 return size1 - size;
4260 int qemu_get_byte(QEMUFile *f)
4262 if (f->buf_index >= f->buf_size) {
4263 qemu_fill_buffer(f);
4264 if (f->buf_index >= f->buf_size)
4265 return 0;
4267 return f->buf[f->buf_index++];
4270 int64_t qemu_ftell(QEMUFile *f)
4272 return f->buf_offset - f->buf_size + f->buf_index;
4275 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4277 if (whence == SEEK_SET) {
4278 /* nothing to do */
4279 } else if (whence == SEEK_CUR) {
4280 pos += qemu_ftell(f);
4281 } else {
4282 /* SEEK_END not supported */
4283 return -1;
4285 if (f->is_writable) {
4286 qemu_fflush(f);
4287 f->buf_offset = pos;
4288 } else {
4289 f->buf_offset = pos;
4290 f->buf_index = 0;
4291 f->buf_size = 0;
4293 return pos;
4296 void qemu_put_be16(QEMUFile *f, unsigned int v)
4298 qemu_put_byte(f, v >> 8);
4299 qemu_put_byte(f, v);
4302 void qemu_put_be32(QEMUFile *f, unsigned int v)
4304 qemu_put_byte(f, v >> 24);
4305 qemu_put_byte(f, v >> 16);
4306 qemu_put_byte(f, v >> 8);
4307 qemu_put_byte(f, v);
4310 void qemu_put_be64(QEMUFile *f, uint64_t v)
4312 qemu_put_be32(f, v >> 32);
4313 qemu_put_be32(f, v);
4316 unsigned int qemu_get_be16(QEMUFile *f)
4318 unsigned int v;
4319 v = qemu_get_byte(f) << 8;
4320 v |= qemu_get_byte(f);
4321 return v;
4324 unsigned int qemu_get_be32(QEMUFile *f)
4326 unsigned int v;
4327 v = qemu_get_byte(f) << 24;
4328 v |= qemu_get_byte(f) << 16;
4329 v |= qemu_get_byte(f) << 8;
4330 v |= qemu_get_byte(f);
4331 return v;
4334 uint64_t qemu_get_be64(QEMUFile *f)
4336 uint64_t v;
4337 v = (uint64_t)qemu_get_be32(f) << 32;
4338 v |= qemu_get_be32(f);
4339 return v;
4342 typedef struct SaveStateEntry {
4343 char idstr[256];
4344 int instance_id;
4345 int version_id;
4346 SaveStateHandler *save_state;
4347 LoadStateHandler *load_state;
4348 void *opaque;
4349 struct SaveStateEntry *next;
4350 } SaveStateEntry;
4352 static SaveStateEntry *first_se;
4354 int register_savevm(const char *idstr,
4355 int instance_id,
4356 int version_id,
4357 SaveStateHandler *save_state,
4358 LoadStateHandler *load_state,
4359 void *opaque)
4361 SaveStateEntry *se, **pse;
4363 se = qemu_malloc(sizeof(SaveStateEntry));
4364 if (!se)
4365 return -1;
4366 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4367 se->instance_id = instance_id;
4368 se->version_id = version_id;
4369 se->save_state = save_state;
4370 se->load_state = load_state;
4371 se->opaque = opaque;
4372 se->next = NULL;
4374 /* add at the end of list */
4375 pse = &first_se;
4376 while (*pse != NULL)
4377 pse = &(*pse)->next;
4378 *pse = se;
4379 return 0;
4382 #define QEMU_VM_FILE_MAGIC 0x5145564d
4383 #define QEMU_VM_FILE_VERSION 0x00000002
4385 int qemu_savevm_state(QEMUFile *f)
4387 SaveStateEntry *se;
4388 int len, ret;
4389 int64_t cur_pos, len_pos, total_len_pos;
4391 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4392 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4393 total_len_pos = qemu_ftell(f);
4394 qemu_put_be64(f, 0); /* total size */
4396 for(se = first_se; se != NULL; se = se->next) {
4397 /* ID string */
4398 len = strlen(se->idstr);
4399 qemu_put_byte(f, len);
4400 qemu_put_buffer(f, se->idstr, len);
4402 qemu_put_be32(f, se->instance_id);
4403 qemu_put_be32(f, se->version_id);
4405 /* record size: filled later */
4406 len_pos = qemu_ftell(f);
4407 qemu_put_be32(f, 0);
4409 se->save_state(f, se->opaque);
4411 /* fill record size */
4412 cur_pos = qemu_ftell(f);
4413 len = cur_pos - len_pos - 4;
4414 qemu_fseek(f, len_pos, SEEK_SET);
4415 qemu_put_be32(f, len);
4416 qemu_fseek(f, cur_pos, SEEK_SET);
4418 cur_pos = qemu_ftell(f);
4419 qemu_fseek(f, total_len_pos, SEEK_SET);
4420 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4421 qemu_fseek(f, cur_pos, SEEK_SET);
4423 ret = 0;
4424 return ret;
4427 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4429 SaveStateEntry *se;
4431 for(se = first_se; se != NULL; se = se->next) {
4432 if (!strcmp(se->idstr, idstr) &&
4433 instance_id == se->instance_id)
4434 return se;
4436 return NULL;
4439 int qemu_loadvm_state(QEMUFile *f)
4441 SaveStateEntry *se;
4442 int len, ret, instance_id, record_len, version_id;
4443 int64_t total_len, end_pos, cur_pos;
4444 unsigned int v;
4445 char idstr[256];
4447 v = qemu_get_be32(f);
4448 if (v != QEMU_VM_FILE_MAGIC)
4449 goto fail;
4450 v = qemu_get_be32(f);
4451 if (v != QEMU_VM_FILE_VERSION) {
4452 fail:
4453 ret = -1;
4454 goto the_end;
4456 total_len = qemu_get_be64(f);
4457 end_pos = total_len + qemu_ftell(f);
4458 for(;;) {
4459 if (qemu_ftell(f) >= end_pos)
4460 break;
4461 len = qemu_get_byte(f);
4462 qemu_get_buffer(f, idstr, len);
4463 idstr[len] = '\0';
4464 instance_id = qemu_get_be32(f);
4465 version_id = qemu_get_be32(f);
4466 record_len = qemu_get_be32(f);
4467 #if 0
4468 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4469 idstr, instance_id, version_id, record_len);
4470 #endif
4471 cur_pos = qemu_ftell(f);
4472 se = find_se(idstr, instance_id);
4473 if (!se) {
4474 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4475 instance_id, idstr);
4476 } else {
4477 ret = se->load_state(f, se->opaque, version_id);
4478 if (ret < 0) {
4479 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4480 instance_id, idstr);
4483 /* always seek to exact end of record */
4484 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4486 ret = 0;
4487 the_end:
4488 return ret;
4491 /* device can contain snapshots */
4492 static int bdrv_can_snapshot(BlockDriverState *bs)
4494 return (bs &&
4495 !bdrv_is_removable(bs) &&
4496 !bdrv_is_read_only(bs));
4499 /* device must be snapshots in order to have a reliable snapshot */
4500 static int bdrv_has_snapshot(BlockDriverState *bs)
4502 return (bs &&
4503 !bdrv_is_removable(bs) &&
4504 !bdrv_is_read_only(bs));
4507 static BlockDriverState *get_bs_snapshots(void)
4509 BlockDriverState *bs;
4510 int i;
4512 if (bs_snapshots)
4513 return bs_snapshots;
4514 for(i = 0; i <= MAX_DISKS; i++) {
4515 bs = bs_table[i];
4516 if (bdrv_can_snapshot(bs))
4517 goto ok;
4519 return NULL;
4521 bs_snapshots = bs;
4522 return bs;
4525 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4526 const char *name)
4528 QEMUSnapshotInfo *sn_tab, *sn;
4529 int nb_sns, i, ret;
4531 ret = -ENOENT;
4532 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4533 if (nb_sns < 0)
4534 return ret;
4535 for(i = 0; i < nb_sns; i++) {
4536 sn = &sn_tab[i];
4537 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4538 *sn_info = *sn;
4539 ret = 0;
4540 break;
4543 qemu_free(sn_tab);
4544 return ret;
4547 void do_savevm(const char *name)
4549 BlockDriverState *bs, *bs1;
4550 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4551 int must_delete, ret, i;
4552 BlockDriverInfo bdi1, *bdi = &bdi1;
4553 QEMUFile *f;
4554 int saved_vm_running;
4555 #ifdef _WIN32
4556 struct _timeb tb;
4557 #else
4558 struct timeval tv;
4559 #endif
4561 bs = get_bs_snapshots();
4562 if (!bs) {
4563 term_printf("No block device can accept snapshots\n");
4564 return;
4567 /* ??? Should this occur after vm_stop? */
4568 qemu_aio_flush();
4570 saved_vm_running = vm_running;
4571 vm_stop(0);
4573 must_delete = 0;
4574 if (name) {
4575 ret = bdrv_snapshot_find(bs, old_sn, name);
4576 if (ret >= 0) {
4577 must_delete = 1;
4580 memset(sn, 0, sizeof(*sn));
4581 if (must_delete) {
4582 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4583 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4584 } else {
4585 if (name)
4586 pstrcpy(sn->name, sizeof(sn->name), name);
4589 /* fill auxiliary fields */
4590 #ifdef _WIN32
4591 _ftime(&tb);
4592 sn->date_sec = tb.time;
4593 sn->date_nsec = tb.millitm * 1000000;
4594 #else
4595 gettimeofday(&tv, NULL);
4596 sn->date_sec = tv.tv_sec;
4597 sn->date_nsec = tv.tv_usec * 1000;
4598 #endif
4599 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4601 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4602 term_printf("Device %s does not support VM state snapshots\n",
4603 bdrv_get_device_name(bs));
4604 goto the_end;
4607 /* save the VM state */
4608 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4609 if (!f) {
4610 term_printf("Could not open VM state file\n");
4611 goto the_end;
4613 ret = qemu_savevm_state(f);
4614 sn->vm_state_size = qemu_ftell(f);
4615 qemu_fclose(f);
4616 if (ret < 0) {
4617 term_printf("Error %d while writing VM\n", ret);
4618 goto the_end;
4621 /* create the snapshots */
4623 for(i = 0; i < MAX_DISKS; i++) {
4624 bs1 = bs_table[i];
4625 if (bdrv_has_snapshot(bs1)) {
4626 if (must_delete) {
4627 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
4628 if (ret < 0) {
4629 term_printf("Error while deleting snapshot on '%s'\n",
4630 bdrv_get_device_name(bs1));
4633 ret = bdrv_snapshot_create(bs1, sn);
4634 if (ret < 0) {
4635 term_printf("Error while creating snapshot on '%s'\n",
4636 bdrv_get_device_name(bs1));
4641 the_end:
4642 if (saved_vm_running)
4643 vm_start();
4646 void do_loadvm(const char *name)
4648 BlockDriverState *bs, *bs1;
4649 BlockDriverInfo bdi1, *bdi = &bdi1;
4650 QEMUFile *f;
4651 int i, ret;
4652 int saved_vm_running;
4654 bs = get_bs_snapshots();
4655 if (!bs) {
4656 term_printf("No block device supports snapshots\n");
4657 return;
4660 /* Flush all IO requests so they don't interfere with the new state. */
4661 qemu_aio_flush();
4663 saved_vm_running = vm_running;
4664 vm_stop(0);
4666 for(i = 0; i <= MAX_DISKS; i++) {
4667 bs1 = bs_table[i];
4668 if (bdrv_has_snapshot(bs1)) {
4669 ret = bdrv_snapshot_goto(bs1, name);
4670 if (ret < 0) {
4671 if (bs != bs1)
4672 term_printf("Warning: ");
4673 switch(ret) {
4674 case -ENOTSUP:
4675 term_printf("Snapshots not supported on device '%s'\n",
4676 bdrv_get_device_name(bs1));
4677 break;
4678 case -ENOENT:
4679 term_printf("Could not find snapshot '%s' on device '%s'\n",
4680 name, bdrv_get_device_name(bs1));
4681 break;
4682 default:
4683 term_printf("Error %d while activating snapshot on '%s'\n",
4684 ret, bdrv_get_device_name(bs1));
4685 break;
4687 /* fatal on snapshot block device */
4688 if (bs == bs1)
4689 goto the_end;
4694 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4695 term_printf("Device %s does not support VM state snapshots\n",
4696 bdrv_get_device_name(bs));
4697 return;
4700 /* restore the VM state */
4701 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
4702 if (!f) {
4703 term_printf("Could not open VM state file\n");
4704 goto the_end;
4706 ret = qemu_loadvm_state(f);
4707 qemu_fclose(f);
4708 if (ret < 0) {
4709 term_printf("Error %d while loading VM state\n", ret);
4711 the_end:
4712 if (saved_vm_running)
4713 vm_start();
4716 void do_delvm(const char *name)
4718 BlockDriverState *bs, *bs1;
4719 int i, ret;
4721 bs = get_bs_snapshots();
4722 if (!bs) {
4723 term_printf("No block device supports snapshots\n");
4724 return;
4727 for(i = 0; i <= MAX_DISKS; i++) {
4728 bs1 = bs_table[i];
4729 if (bdrv_has_snapshot(bs1)) {
4730 ret = bdrv_snapshot_delete(bs1, name);
4731 if (ret < 0) {
4732 if (ret == -ENOTSUP)
4733 term_printf("Snapshots not supported on device '%s'\n",
4734 bdrv_get_device_name(bs1));
4735 else
4736 term_printf("Error %d while deleting snapshot on '%s'\n",
4737 ret, bdrv_get_device_name(bs1));
4743 void do_info_snapshots(void)
4745 BlockDriverState *bs, *bs1;
4746 QEMUSnapshotInfo *sn_tab, *sn;
4747 int nb_sns, i;
4748 char buf[256];
4750 bs = get_bs_snapshots();
4751 if (!bs) {
4752 term_printf("No available block device supports snapshots\n");
4753 return;
4755 term_printf("Snapshot devices:");
4756 for(i = 0; i <= MAX_DISKS; i++) {
4757 bs1 = bs_table[i];
4758 if (bdrv_has_snapshot(bs1)) {
4759 if (bs == bs1)
4760 term_printf(" %s", bdrv_get_device_name(bs1));
4763 term_printf("\n");
4765 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4766 if (nb_sns < 0) {
4767 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
4768 return;
4770 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
4771 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
4772 for(i = 0; i < nb_sns; i++) {
4773 sn = &sn_tab[i];
4774 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
4776 qemu_free(sn_tab);
4779 /***********************************************************/
4780 /* cpu save/restore */
4782 #if defined(TARGET_I386)
4784 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4786 qemu_put_be32(f, dt->selector);
4787 qemu_put_betl(f, dt->base);
4788 qemu_put_be32(f, dt->limit);
4789 qemu_put_be32(f, dt->flags);
4792 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4794 dt->selector = qemu_get_be32(f);
4795 dt->base = qemu_get_betl(f);
4796 dt->limit = qemu_get_be32(f);
4797 dt->flags = qemu_get_be32(f);
4800 void cpu_save(QEMUFile *f, void *opaque)
4802 CPUState *env = opaque;
4803 uint16_t fptag, fpus, fpuc, fpregs_format;
4804 uint32_t hflags;
4805 int i;
4807 for(i = 0; i < CPU_NB_REGS; i++)
4808 qemu_put_betls(f, &env->regs[i]);
4809 qemu_put_betls(f, &env->eip);
4810 qemu_put_betls(f, &env->eflags);
4811 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4812 qemu_put_be32s(f, &hflags);
4814 /* FPU */
4815 fpuc = env->fpuc;
4816 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4817 fptag = 0;
4818 for(i = 0; i < 8; i++) {
4819 fptag |= ((!env->fptags[i]) << i);
4822 qemu_put_be16s(f, &fpuc);
4823 qemu_put_be16s(f, &fpus);
4824 qemu_put_be16s(f, &fptag);
4826 #ifdef USE_X86LDOUBLE
4827 fpregs_format = 0;
4828 #else
4829 fpregs_format = 1;
4830 #endif
4831 qemu_put_be16s(f, &fpregs_format);
4833 for(i = 0; i < 8; i++) {
4834 #ifdef USE_X86LDOUBLE
4836 uint64_t mant;
4837 uint16_t exp;
4838 /* we save the real CPU data (in case of MMX usage only 'mant'
4839 contains the MMX register */
4840 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4841 qemu_put_be64(f, mant);
4842 qemu_put_be16(f, exp);
4844 #else
4845 /* if we use doubles for float emulation, we save the doubles to
4846 avoid losing information in case of MMX usage. It can give
4847 problems if the image is restored on a CPU where long
4848 doubles are used instead. */
4849 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4850 #endif
4853 for(i = 0; i < 6; i++)
4854 cpu_put_seg(f, &env->segs[i]);
4855 cpu_put_seg(f, &env->ldt);
4856 cpu_put_seg(f, &env->tr);
4857 cpu_put_seg(f, &env->gdt);
4858 cpu_put_seg(f, &env->idt);
4860 qemu_put_be32s(f, &env->sysenter_cs);
4861 qemu_put_be32s(f, &env->sysenter_esp);
4862 qemu_put_be32s(f, &env->sysenter_eip);
4864 qemu_put_betls(f, &env->cr[0]);
4865 qemu_put_betls(f, &env->cr[2]);
4866 qemu_put_betls(f, &env->cr[3]);
4867 qemu_put_betls(f, &env->cr[4]);
4869 for(i = 0; i < 8; i++)
4870 qemu_put_betls(f, &env->dr[i]);
4872 /* MMU */
4873 qemu_put_be32s(f, &env->a20_mask);
4875 /* XMM */
4876 qemu_put_be32s(f, &env->mxcsr);
4877 for(i = 0; i < CPU_NB_REGS; i++) {
4878 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4879 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4882 #ifdef TARGET_X86_64
4883 qemu_put_be64s(f, &env->efer);
4884 qemu_put_be64s(f, &env->star);
4885 qemu_put_be64s(f, &env->lstar);
4886 qemu_put_be64s(f, &env->cstar);
4887 qemu_put_be64s(f, &env->fmask);
4888 qemu_put_be64s(f, &env->kernelgsbase);
4889 #endif
4890 qemu_put_be32s(f, &env->smbase);
4893 #ifdef USE_X86LDOUBLE
4894 /* XXX: add that in a FPU generic layer */
4895 union x86_longdouble {
4896 uint64_t mant;
4897 uint16_t exp;
4900 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4901 #define EXPBIAS1 1023
4902 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4903 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4905 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4907 int e;
4908 /* mantissa */
4909 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4910 /* exponent + sign */
4911 e = EXPD1(temp) - EXPBIAS1 + 16383;
4912 e |= SIGND1(temp) >> 16;
4913 p->exp = e;
4915 #endif
4917 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4919 CPUState *env = opaque;
4920 int i, guess_mmx;
4921 uint32_t hflags;
4922 uint16_t fpus, fpuc, fptag, fpregs_format;
4924 if (version_id != 3 && version_id != 4)
4925 return -EINVAL;
4926 for(i = 0; i < CPU_NB_REGS; i++)
4927 qemu_get_betls(f, &env->regs[i]);
4928 qemu_get_betls(f, &env->eip);
4929 qemu_get_betls(f, &env->eflags);
4930 qemu_get_be32s(f, &hflags);
4932 qemu_get_be16s(f, &fpuc);
4933 qemu_get_be16s(f, &fpus);
4934 qemu_get_be16s(f, &fptag);
4935 qemu_get_be16s(f, &fpregs_format);
4937 /* NOTE: we cannot always restore the FPU state if the image come
4938 from a host with a different 'USE_X86LDOUBLE' define. We guess
4939 if we are in an MMX state to restore correctly in that case. */
4940 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4941 for(i = 0; i < 8; i++) {
4942 uint64_t mant;
4943 uint16_t exp;
4945 switch(fpregs_format) {
4946 case 0:
4947 mant = qemu_get_be64(f);
4948 exp = qemu_get_be16(f);
4949 #ifdef USE_X86LDOUBLE
4950 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4951 #else
4952 /* difficult case */
4953 if (guess_mmx)
4954 env->fpregs[i].mmx.MMX_Q(0) = mant;
4955 else
4956 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4957 #endif
4958 break;
4959 case 1:
4960 mant = qemu_get_be64(f);
4961 #ifdef USE_X86LDOUBLE
4963 union x86_longdouble *p;
4964 /* difficult case */
4965 p = (void *)&env->fpregs[i];
4966 if (guess_mmx) {
4967 p->mant = mant;
4968 p->exp = 0xffff;
4969 } else {
4970 fp64_to_fp80(p, mant);
4973 #else
4974 env->fpregs[i].mmx.MMX_Q(0) = mant;
4975 #endif
4976 break;
4977 default:
4978 return -EINVAL;
4982 env->fpuc = fpuc;
4983 /* XXX: restore FPU round state */
4984 env->fpstt = (fpus >> 11) & 7;
4985 env->fpus = fpus & ~0x3800;
4986 fptag ^= 0xff;
4987 for(i = 0; i < 8; i++) {
4988 env->fptags[i] = (fptag >> i) & 1;
4991 for(i = 0; i < 6; i++)
4992 cpu_get_seg(f, &env->segs[i]);
4993 cpu_get_seg(f, &env->ldt);
4994 cpu_get_seg(f, &env->tr);
4995 cpu_get_seg(f, &env->gdt);
4996 cpu_get_seg(f, &env->idt);
4998 qemu_get_be32s(f, &env->sysenter_cs);
4999 qemu_get_be32s(f, &env->sysenter_esp);
5000 qemu_get_be32s(f, &env->sysenter_eip);
5002 qemu_get_betls(f, &env->cr[0]);
5003 qemu_get_betls(f, &env->cr[2]);
5004 qemu_get_betls(f, &env->cr[3]);
5005 qemu_get_betls(f, &env->cr[4]);
5007 for(i = 0; i < 8; i++)
5008 qemu_get_betls(f, &env->dr[i]);
5010 /* MMU */
5011 qemu_get_be32s(f, &env->a20_mask);
5013 qemu_get_be32s(f, &env->mxcsr);
5014 for(i = 0; i < CPU_NB_REGS; i++) {
5015 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5016 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5019 #ifdef TARGET_X86_64
5020 qemu_get_be64s(f, &env->efer);
5021 qemu_get_be64s(f, &env->star);
5022 qemu_get_be64s(f, &env->lstar);
5023 qemu_get_be64s(f, &env->cstar);
5024 qemu_get_be64s(f, &env->fmask);
5025 qemu_get_be64s(f, &env->kernelgsbase);
5026 #endif
5027 if (version_id >= 4)
5028 qemu_get_be32s(f, &env->smbase);
5030 /* XXX: compute hflags from scratch, except for CPL and IIF */
5031 env->hflags = hflags;
5032 tlb_flush(env, 1);
5033 return 0;
5036 #elif defined(TARGET_PPC)
5037 void cpu_save(QEMUFile *f, void *opaque)
5041 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5043 return 0;
5046 #elif defined(TARGET_MIPS)
5047 void cpu_save(QEMUFile *f, void *opaque)
5051 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5053 return 0;
5056 #elif defined(TARGET_SPARC)
5057 void cpu_save(QEMUFile *f, void *opaque)
5059 CPUState *env = opaque;
5060 int i;
5061 uint32_t tmp;
5063 for(i = 0; i < 8; i++)
5064 qemu_put_betls(f, &env->gregs[i]);
5065 for(i = 0; i < NWINDOWS * 16; i++)
5066 qemu_put_betls(f, &env->regbase[i]);
5068 /* FPU */
5069 for(i = 0; i < TARGET_FPREGS; i++) {
5070 union {
5071 float32 f;
5072 uint32_t i;
5073 } u;
5074 u.f = env->fpr[i];
5075 qemu_put_be32(f, u.i);
5078 qemu_put_betls(f, &env->pc);
5079 qemu_put_betls(f, &env->npc);
5080 qemu_put_betls(f, &env->y);
5081 tmp = GET_PSR(env);
5082 qemu_put_be32(f, tmp);
5083 qemu_put_betls(f, &env->fsr);
5084 qemu_put_betls(f, &env->tbr);
5085 #ifndef TARGET_SPARC64
5086 qemu_put_be32s(f, &env->wim);
5087 /* MMU */
5088 for(i = 0; i < 16; i++)
5089 qemu_put_be32s(f, &env->mmuregs[i]);
5090 #endif
5093 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5095 CPUState *env = opaque;
5096 int i;
5097 uint32_t tmp;
5099 for(i = 0; i < 8; i++)
5100 qemu_get_betls(f, &env->gregs[i]);
5101 for(i = 0; i < NWINDOWS * 16; i++)
5102 qemu_get_betls(f, &env->regbase[i]);
5104 /* FPU */
5105 for(i = 0; i < TARGET_FPREGS; i++) {
5106 union {
5107 float32 f;
5108 uint32_t i;
5109 } u;
5110 u.i = qemu_get_be32(f);
5111 env->fpr[i] = u.f;
5114 qemu_get_betls(f, &env->pc);
5115 qemu_get_betls(f, &env->npc);
5116 qemu_get_betls(f, &env->y);
5117 tmp = qemu_get_be32(f);
5118 env->cwp = 0; /* needed to ensure that the wrapping registers are
5119 correctly updated */
5120 PUT_PSR(env, tmp);
5121 qemu_get_betls(f, &env->fsr);
5122 qemu_get_betls(f, &env->tbr);
5123 #ifndef TARGET_SPARC64
5124 qemu_get_be32s(f, &env->wim);
5125 /* MMU */
5126 for(i = 0; i < 16; i++)
5127 qemu_get_be32s(f, &env->mmuregs[i]);
5128 #endif
5129 tlb_flush(env, 1);
5130 return 0;
5133 #elif defined(TARGET_ARM)
5135 /* ??? Need to implement these. */
5136 void cpu_save(QEMUFile *f, void *opaque)
5140 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5142 return 0;
5145 #else
5147 #warning No CPU save/restore functions
5149 #endif
5151 /***********************************************************/
5152 /* ram save/restore */
5154 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5156 int v;
5158 v = qemu_get_byte(f);
5159 switch(v) {
5160 case 0:
5161 if (qemu_get_buffer(f, buf, len) != len)
5162 return -EIO;
5163 break;
5164 case 1:
5165 v = qemu_get_byte(f);
5166 memset(buf, v, len);
5167 break;
5168 default:
5169 return -EINVAL;
5171 return 0;
5174 static int ram_load_v1(QEMUFile *f, void *opaque)
5176 int i, ret;
5178 if (qemu_get_be32(f) != phys_ram_size)
5179 return -EINVAL;
5180 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5181 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5182 if (ret)
5183 return ret;
5185 return 0;
5188 #define BDRV_HASH_BLOCK_SIZE 1024
5189 #define IOBUF_SIZE 4096
5190 #define RAM_CBLOCK_MAGIC 0xfabe
5192 typedef struct RamCompressState {
5193 z_stream zstream;
5194 QEMUFile *f;
5195 uint8_t buf[IOBUF_SIZE];
5196 } RamCompressState;
5198 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5200 int ret;
5201 memset(s, 0, sizeof(*s));
5202 s->f = f;
5203 ret = deflateInit2(&s->zstream, 1,
5204 Z_DEFLATED, 15,
5205 9, Z_DEFAULT_STRATEGY);
5206 if (ret != Z_OK)
5207 return -1;
5208 s->zstream.avail_out = IOBUF_SIZE;
5209 s->zstream.next_out = s->buf;
5210 return 0;
5213 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5215 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5216 qemu_put_be16(s->f, len);
5217 qemu_put_buffer(s->f, buf, len);
5220 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5222 int ret;
5224 s->zstream.avail_in = len;
5225 s->zstream.next_in = (uint8_t *)buf;
5226 while (s->zstream.avail_in > 0) {
5227 ret = deflate(&s->zstream, Z_NO_FLUSH);
5228 if (ret != Z_OK)
5229 return -1;
5230 if (s->zstream.avail_out == 0) {
5231 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5232 s->zstream.avail_out = IOBUF_SIZE;
5233 s->zstream.next_out = s->buf;
5236 return 0;
5239 static void ram_compress_close(RamCompressState *s)
5241 int len, ret;
5243 /* compress last bytes */
5244 for(;;) {
5245 ret = deflate(&s->zstream, Z_FINISH);
5246 if (ret == Z_OK || ret == Z_STREAM_END) {
5247 len = IOBUF_SIZE - s->zstream.avail_out;
5248 if (len > 0) {
5249 ram_put_cblock(s, s->buf, len);
5251 s->zstream.avail_out = IOBUF_SIZE;
5252 s->zstream.next_out = s->buf;
5253 if (ret == Z_STREAM_END)
5254 break;
5255 } else {
5256 goto fail;
5259 fail:
5260 deflateEnd(&s->zstream);
5263 typedef struct RamDecompressState {
5264 z_stream zstream;
5265 QEMUFile *f;
5266 uint8_t buf[IOBUF_SIZE];
5267 } RamDecompressState;
5269 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5271 int ret;
5272 memset(s, 0, sizeof(*s));
5273 s->f = f;
5274 ret = inflateInit(&s->zstream);
5275 if (ret != Z_OK)
5276 return -1;
5277 return 0;
5280 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5282 int ret, clen;
5284 s->zstream.avail_out = len;
5285 s->zstream.next_out = buf;
5286 while (s->zstream.avail_out > 0) {
5287 if (s->zstream.avail_in == 0) {
5288 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5289 return -1;
5290 clen = qemu_get_be16(s->f);
5291 if (clen > IOBUF_SIZE)
5292 return -1;
5293 qemu_get_buffer(s->f, s->buf, clen);
5294 s->zstream.avail_in = clen;
5295 s->zstream.next_in = s->buf;
5297 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5298 if (ret != Z_OK && ret != Z_STREAM_END) {
5299 return -1;
5302 return 0;
5305 static void ram_decompress_close(RamDecompressState *s)
5307 inflateEnd(&s->zstream);
5310 static void ram_save(QEMUFile *f, void *opaque)
5312 int i;
5313 RamCompressState s1, *s = &s1;
5314 uint8_t buf[10];
5316 qemu_put_be32(f, phys_ram_size);
5317 if (ram_compress_open(s, f) < 0)
5318 return;
5319 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5320 #if 0
5321 if (tight_savevm_enabled) {
5322 int64_t sector_num;
5323 int j;
5325 /* find if the memory block is available on a virtual
5326 block device */
5327 sector_num = -1;
5328 for(j = 0; j < MAX_DISKS; j++) {
5329 if (bs_table[j]) {
5330 sector_num = bdrv_hash_find(bs_table[j],
5331 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5332 if (sector_num >= 0)
5333 break;
5336 if (j == MAX_DISKS)
5337 goto normal_compress;
5338 buf[0] = 1;
5339 buf[1] = j;
5340 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5341 ram_compress_buf(s, buf, 10);
5342 } else
5343 #endif
5345 // normal_compress:
5346 buf[0] = 0;
5347 ram_compress_buf(s, buf, 1);
5348 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5351 ram_compress_close(s);
5354 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5356 RamDecompressState s1, *s = &s1;
5357 uint8_t buf[10];
5358 int i;
5360 if (version_id == 1)
5361 return ram_load_v1(f, opaque);
5362 if (version_id != 2)
5363 return -EINVAL;
5364 if (qemu_get_be32(f) != phys_ram_size)
5365 return -EINVAL;
5366 if (ram_decompress_open(s, f) < 0)
5367 return -EINVAL;
5368 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5369 if (ram_decompress_buf(s, buf, 1) < 0) {
5370 fprintf(stderr, "Error while reading ram block header\n");
5371 goto error;
5373 if (buf[0] == 0) {
5374 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5375 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5376 goto error;
5378 } else
5379 #if 0
5380 if (buf[0] == 1) {
5381 int bs_index;
5382 int64_t sector_num;
5384 ram_decompress_buf(s, buf + 1, 9);
5385 bs_index = buf[1];
5386 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5387 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5388 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5389 goto error;
5391 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5392 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5393 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5394 bs_index, sector_num);
5395 goto error;
5397 } else
5398 #endif
5400 error:
5401 printf("Error block header\n");
5402 return -EINVAL;
5405 ram_decompress_close(s);
5406 return 0;
5409 /***********************************************************/
5410 /* bottom halves (can be seen as timers which expire ASAP) */
5412 struct QEMUBH {
5413 QEMUBHFunc *cb;
5414 void *opaque;
5415 int scheduled;
5416 QEMUBH *next;
5419 static QEMUBH *first_bh = NULL;
5421 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5423 QEMUBH *bh;
5424 bh = qemu_mallocz(sizeof(QEMUBH));
5425 if (!bh)
5426 return NULL;
5427 bh->cb = cb;
5428 bh->opaque = opaque;
5429 return bh;
5432 int qemu_bh_poll(void)
5434 QEMUBH *bh, **pbh;
5435 int ret;
5437 ret = 0;
5438 for(;;) {
5439 pbh = &first_bh;
5440 bh = *pbh;
5441 if (!bh)
5442 break;
5443 ret = 1;
5444 *pbh = bh->next;
5445 bh->scheduled = 0;
5446 bh->cb(bh->opaque);
5448 return ret;
5451 void qemu_bh_schedule(QEMUBH *bh)
5453 CPUState *env = cpu_single_env;
5454 if (bh->scheduled)
5455 return;
5456 bh->scheduled = 1;
5457 bh->next = first_bh;
5458 first_bh = bh;
5460 /* stop the currently executing CPU to execute the BH ASAP */
5461 if (env) {
5462 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5466 void qemu_bh_cancel(QEMUBH *bh)
5468 QEMUBH **pbh;
5469 if (bh->scheduled) {
5470 pbh = &first_bh;
5471 while (*pbh != bh)
5472 pbh = &(*pbh)->next;
5473 *pbh = bh->next;
5474 bh->scheduled = 0;
5478 void qemu_bh_delete(QEMUBH *bh)
5480 qemu_bh_cancel(bh);
5481 qemu_free(bh);
5484 /***********************************************************/
5485 /* machine registration */
5487 QEMUMachine *first_machine = NULL;
5489 int qemu_register_machine(QEMUMachine *m)
5491 QEMUMachine **pm;
5492 pm = &first_machine;
5493 while (*pm != NULL)
5494 pm = &(*pm)->next;
5495 m->next = NULL;
5496 *pm = m;
5497 return 0;
5500 QEMUMachine *find_machine(const char *name)
5502 QEMUMachine *m;
5504 for(m = first_machine; m != NULL; m = m->next) {
5505 if (!strcmp(m->name, name))
5506 return m;
5508 return NULL;
5511 /***********************************************************/
5512 /* main execution loop */
5514 void gui_update(void *opaque)
5516 display_state.dpy_refresh(&display_state);
5517 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5520 struct vm_change_state_entry {
5521 VMChangeStateHandler *cb;
5522 void *opaque;
5523 LIST_ENTRY (vm_change_state_entry) entries;
5526 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5528 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5529 void *opaque)
5531 VMChangeStateEntry *e;
5533 e = qemu_mallocz(sizeof (*e));
5534 if (!e)
5535 return NULL;
5537 e->cb = cb;
5538 e->opaque = opaque;
5539 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5540 return e;
5543 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5545 LIST_REMOVE (e, entries);
5546 qemu_free (e);
5549 static void vm_state_notify(int running)
5551 VMChangeStateEntry *e;
5553 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5554 e->cb(e->opaque, running);
5558 /* XXX: support several handlers */
5559 static VMStopHandler *vm_stop_cb;
5560 static void *vm_stop_opaque;
5562 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5564 vm_stop_cb = cb;
5565 vm_stop_opaque = opaque;
5566 return 0;
5569 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5571 vm_stop_cb = NULL;
5574 void vm_start(void)
5576 if (!vm_running) {
5577 cpu_enable_ticks();
5578 vm_running = 1;
5579 vm_state_notify(1);
5583 void vm_stop(int reason)
5585 if (vm_running) {
5586 cpu_disable_ticks();
5587 vm_running = 0;
5588 if (reason != 0) {
5589 if (vm_stop_cb) {
5590 vm_stop_cb(vm_stop_opaque, reason);
5593 vm_state_notify(0);
5597 /* reset/shutdown handler */
5599 typedef struct QEMUResetEntry {
5600 QEMUResetHandler *func;
5601 void *opaque;
5602 struct QEMUResetEntry *next;
5603 } QEMUResetEntry;
5605 static QEMUResetEntry *first_reset_entry;
5606 static int reset_requested;
5607 static int shutdown_requested;
5608 static int powerdown_requested;
5610 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5612 QEMUResetEntry **pre, *re;
5614 pre = &first_reset_entry;
5615 while (*pre != NULL)
5616 pre = &(*pre)->next;
5617 re = qemu_mallocz(sizeof(QEMUResetEntry));
5618 re->func = func;
5619 re->opaque = opaque;
5620 re->next = NULL;
5621 *pre = re;
5624 void qemu_system_reset(void)
5626 QEMUResetEntry *re;
5628 /* reset all devices */
5629 for(re = first_reset_entry; re != NULL; re = re->next) {
5630 re->func(re->opaque);
5634 void qemu_system_reset_request(void)
5636 if (no_reboot) {
5637 shutdown_requested = 1;
5638 } else {
5639 reset_requested = 1;
5641 if (cpu_single_env)
5642 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5645 void qemu_system_shutdown_request(void)
5647 shutdown_requested = 1;
5648 if (cpu_single_env)
5649 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5652 void qemu_system_powerdown_request(void)
5654 powerdown_requested = 1;
5655 if (cpu_single_env)
5656 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5659 void main_loop_wait(int timeout)
5661 IOHandlerRecord *ioh, *ioh_next;
5662 fd_set rfds, wfds, xfds;
5663 int ret, nfds;
5664 struct timeval tv;
5665 PollingEntry *pe;
5668 /* XXX: need to suppress polling by better using win32 events */
5669 ret = 0;
5670 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5671 ret |= pe->func(pe->opaque);
5673 #ifdef _WIN32
5674 if (ret == 0 && timeout > 0) {
5675 int err;
5676 WaitObjects *w = &wait_objects;
5678 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5679 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5680 if (w->func[ret - WAIT_OBJECT_0])
5681 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5682 } else if (ret == WAIT_TIMEOUT) {
5683 } else {
5684 err = GetLastError();
5685 fprintf(stderr, "Wait error %d %d\n", ret, err);
5688 #endif
5689 /* poll any events */
5690 /* XXX: separate device handlers from system ones */
5691 nfds = -1;
5692 FD_ZERO(&rfds);
5693 FD_ZERO(&wfds);
5694 FD_ZERO(&xfds);
5695 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5696 if (ioh->fd_read &&
5697 (!ioh->fd_read_poll ||
5698 ioh->fd_read_poll(ioh->opaque) != 0)) {
5699 FD_SET(ioh->fd, &rfds);
5700 if (ioh->fd > nfds)
5701 nfds = ioh->fd;
5703 if (ioh->fd_write) {
5704 FD_SET(ioh->fd, &wfds);
5705 if (ioh->fd > nfds)
5706 nfds = ioh->fd;
5710 tv.tv_sec = 0;
5711 #ifdef _WIN32
5712 tv.tv_usec = 0;
5713 #else
5714 tv.tv_usec = timeout * 1000;
5715 #endif
5716 #if defined(CONFIG_SLIRP)
5717 if (slirp_inited) {
5718 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5720 #endif
5721 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5722 if (ret > 0) {
5723 /* XXX: better handling of removal */
5724 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5725 ioh_next = ioh->next;
5726 if (FD_ISSET(ioh->fd, &rfds)) {
5727 ioh->fd_read(ioh->opaque);
5729 if (FD_ISSET(ioh->fd, &wfds)) {
5730 ioh->fd_write(ioh->opaque);
5734 #if defined(CONFIG_SLIRP)
5735 if (slirp_inited) {
5736 if (ret < 0) {
5737 FD_ZERO(&rfds);
5738 FD_ZERO(&wfds);
5739 FD_ZERO(&xfds);
5741 slirp_select_poll(&rfds, &wfds, &xfds);
5743 #endif
5744 qemu_aio_poll();
5745 qemu_bh_poll();
5747 if (vm_running) {
5748 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5749 qemu_get_clock(vm_clock));
5750 /* run dma transfers, if any */
5751 DMA_run();
5754 /* real time timers */
5755 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5756 qemu_get_clock(rt_clock));
5759 static CPUState *cur_cpu;
5761 int main_loop(void)
5763 int ret, timeout;
5764 #ifdef CONFIG_PROFILER
5765 int64_t ti;
5766 #endif
5767 CPUState *env;
5769 cur_cpu = first_cpu;
5770 for(;;) {
5771 if (vm_running) {
5773 env = cur_cpu;
5774 for(;;) {
5775 /* get next cpu */
5776 env = env->next_cpu;
5777 if (!env)
5778 env = first_cpu;
5779 #ifdef CONFIG_PROFILER
5780 ti = profile_getclock();
5781 #endif
5782 ret = cpu_exec(env);
5783 #ifdef CONFIG_PROFILER
5784 qemu_time += profile_getclock() - ti;
5785 #endif
5786 if (ret != EXCP_HALTED)
5787 break;
5788 /* all CPUs are halted ? */
5789 if (env == cur_cpu) {
5790 ret = EXCP_HLT;
5791 break;
5794 cur_cpu = env;
5796 if (shutdown_requested) {
5797 ret = EXCP_INTERRUPT;
5798 break;
5800 if (reset_requested) {
5801 reset_requested = 0;
5802 qemu_system_reset();
5803 ret = EXCP_INTERRUPT;
5805 if (powerdown_requested) {
5806 powerdown_requested = 0;
5807 qemu_system_powerdown();
5808 ret = EXCP_INTERRUPT;
5810 if (ret == EXCP_DEBUG) {
5811 vm_stop(EXCP_DEBUG);
5813 /* if hlt instruction, we wait until the next IRQ */
5814 /* XXX: use timeout computed from timers */
5815 if (ret == EXCP_HLT)
5816 timeout = 10;
5817 else
5818 timeout = 0;
5819 } else {
5820 timeout = 10;
5822 #ifdef CONFIG_PROFILER
5823 ti = profile_getclock();
5824 #endif
5825 main_loop_wait(timeout);
5826 #ifdef CONFIG_PROFILER
5827 dev_time += profile_getclock() - ti;
5828 #endif
5830 cpu_disable_ticks();
5831 return ret;
5834 void help(void)
5836 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2006 Fabrice Bellard\n"
5837 "usage: %s [options] [disk_image]\n"
5838 "\n"
5839 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5840 "\n"
5841 "Standard options:\n"
5842 "-M machine select emulated machine (-M ? for list)\n"
5843 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5844 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5845 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5846 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5847 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5848 "-snapshot write to temporary files instead of disk image files\n"
5849 #ifdef TARGET_I386
5850 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5851 #endif
5852 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5853 "-smp n set the number of CPUs to 'n' [default=1]\n"
5854 "-nographic disable graphical output and redirect serial I/Os to console\n"
5855 #ifndef _WIN32
5856 "-k language use keyboard layout (for example \"fr\" for French)\n"
5857 #endif
5858 #ifdef HAS_AUDIO
5859 "-audio-help print list of audio drivers and their options\n"
5860 "-soundhw c1,... enable audio support\n"
5861 " and only specified sound cards (comma separated list)\n"
5862 " use -soundhw ? to get the list of supported cards\n"
5863 " use -soundhw all to enable all of them\n"
5864 #endif
5865 "-localtime set the real time clock to local time [default=utc]\n"
5866 "-full-screen start in full screen\n"
5867 #ifdef TARGET_I386
5868 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5869 #endif
5870 "-usb enable the USB driver (will be the default soon)\n"
5871 "-usbdevice name add the host or guest USB device 'name'\n"
5872 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5873 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5874 #endif
5875 "\n"
5876 "Network options:\n"
5877 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5878 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5879 #ifdef CONFIG_SLIRP
5880 "-net user[,vlan=n][,hostname=host]\n"
5881 " connect the user mode network stack to VLAN 'n' and send\n"
5882 " hostname 'host' to DHCP clients\n"
5883 #endif
5884 #ifdef _WIN32
5885 "-net tap[,vlan=n],ifname=name\n"
5886 " connect the host TAP network interface to VLAN 'n'\n"
5887 #else
5888 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
5889 " connect the host TAP network interface to VLAN 'n' and use\n"
5890 " the network script 'file' (default=%s);\n"
5891 " use 'fd=h' to connect to an already opened TAP interface\n"
5892 #endif
5893 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5894 " connect the vlan 'n' to another VLAN using a socket connection\n"
5895 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5896 " connect the vlan 'n' to multicast maddr and port\n"
5897 "-net none use it alone to have zero network devices; if no -net option\n"
5898 " is provided, the default is '-net nic -net user'\n"
5899 "\n"
5900 #ifdef CONFIG_SLIRP
5901 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5902 #ifndef _WIN32
5903 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5904 #endif
5905 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5906 " redirect TCP or UDP connections from host to guest [-net user]\n"
5907 #endif
5908 "\n"
5909 "Linux boot specific:\n"
5910 "-kernel bzImage use 'bzImage' as kernel image\n"
5911 "-append cmdline use 'cmdline' as kernel command line\n"
5912 "-initrd file use 'file' as initial ram disk\n"
5913 "\n"
5914 "Debug/Expert options:\n"
5915 "-monitor dev redirect the monitor to char device 'dev'\n"
5916 "-serial dev redirect the serial port to char device 'dev'\n"
5917 "-parallel dev redirect the parallel port to char device 'dev'\n"
5918 "-pidfile file Write PID to 'file'\n"
5919 "-S freeze CPU at startup (use 'c' to start execution)\n"
5920 "-s wait gdb connection to port %d\n"
5921 "-p port change gdb connection port\n"
5922 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
5923 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5924 " translation (t=none or lba) (usually qemu can guess them)\n"
5925 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
5926 #ifdef USE_KQEMU
5927 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5928 "-no-kqemu disable KQEMU kernel module usage\n"
5929 #endif
5930 #ifdef USE_CODE_COPY
5931 "-no-code-copy disable code copy acceleration\n"
5932 #endif
5933 #ifdef TARGET_I386
5934 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5935 " (default is CL-GD5446 PCI VGA)\n"
5936 "-no-acpi disable ACPI\n"
5937 #endif
5938 "-no-reboot exit instead of rebooting\n"
5939 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5940 "-vnc display start a VNC server on display\n"
5941 "\n"
5942 "During emulation, the following keys are useful:\n"
5943 "ctrl-alt-f toggle full screen\n"
5944 "ctrl-alt-n switch to virtual console 'n'\n"
5945 "ctrl-alt toggle mouse and keyboard grab\n"
5946 "\n"
5947 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5949 "qemu",
5950 DEFAULT_RAM_SIZE,
5951 #ifndef _WIN32
5952 DEFAULT_NETWORK_SCRIPT,
5953 #endif
5954 DEFAULT_GDBSTUB_PORT,
5955 "/tmp/qemu.log");
5956 exit(1);
5959 #define HAS_ARG 0x0001
5961 enum {
5962 QEMU_OPTION_h,
5964 QEMU_OPTION_M,
5965 QEMU_OPTION_fda,
5966 QEMU_OPTION_fdb,
5967 QEMU_OPTION_hda,
5968 QEMU_OPTION_hdb,
5969 QEMU_OPTION_hdc,
5970 QEMU_OPTION_hdd,
5971 QEMU_OPTION_cdrom,
5972 QEMU_OPTION_boot,
5973 QEMU_OPTION_snapshot,
5974 #ifdef TARGET_I386
5975 QEMU_OPTION_no_fd_bootchk,
5976 #endif
5977 QEMU_OPTION_m,
5978 QEMU_OPTION_nographic,
5979 #ifdef HAS_AUDIO
5980 QEMU_OPTION_audio_help,
5981 QEMU_OPTION_soundhw,
5982 #endif
5984 QEMU_OPTION_net,
5985 QEMU_OPTION_tftp,
5986 QEMU_OPTION_smb,
5987 QEMU_OPTION_redir,
5989 QEMU_OPTION_kernel,
5990 QEMU_OPTION_append,
5991 QEMU_OPTION_initrd,
5993 QEMU_OPTION_S,
5994 QEMU_OPTION_s,
5995 QEMU_OPTION_p,
5996 QEMU_OPTION_d,
5997 QEMU_OPTION_hdachs,
5998 QEMU_OPTION_L,
5999 QEMU_OPTION_no_code_copy,
6000 QEMU_OPTION_k,
6001 QEMU_OPTION_localtime,
6002 QEMU_OPTION_cirrusvga,
6003 QEMU_OPTION_g,
6004 QEMU_OPTION_std_vga,
6005 QEMU_OPTION_monitor,
6006 QEMU_OPTION_serial,
6007 QEMU_OPTION_parallel,
6008 QEMU_OPTION_loadvm,
6009 QEMU_OPTION_full_screen,
6010 QEMU_OPTION_pidfile,
6011 QEMU_OPTION_no_kqemu,
6012 QEMU_OPTION_kernel_kqemu,
6013 QEMU_OPTION_win2k_hack,
6014 QEMU_OPTION_usb,
6015 QEMU_OPTION_usbdevice,
6016 QEMU_OPTION_smp,
6017 QEMU_OPTION_vnc,
6018 QEMU_OPTION_no_acpi,
6019 QEMU_OPTION_no_reboot,
6022 typedef struct QEMUOption {
6023 const char *name;
6024 int flags;
6025 int index;
6026 } QEMUOption;
6028 const QEMUOption qemu_options[] = {
6029 { "h", 0, QEMU_OPTION_h },
6031 { "M", HAS_ARG, QEMU_OPTION_M },
6032 { "fda", HAS_ARG, QEMU_OPTION_fda },
6033 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6034 { "hda", HAS_ARG, QEMU_OPTION_hda },
6035 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6036 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6037 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6038 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6039 { "boot", HAS_ARG, QEMU_OPTION_boot },
6040 { "snapshot", 0, QEMU_OPTION_snapshot },
6041 #ifdef TARGET_I386
6042 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6043 #endif
6044 { "m", HAS_ARG, QEMU_OPTION_m },
6045 { "nographic", 0, QEMU_OPTION_nographic },
6046 { "k", HAS_ARG, QEMU_OPTION_k },
6047 #ifdef HAS_AUDIO
6048 { "audio-help", 0, QEMU_OPTION_audio_help },
6049 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6050 #endif
6052 { "net", HAS_ARG, QEMU_OPTION_net},
6053 #ifdef CONFIG_SLIRP
6054 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6055 #ifndef _WIN32
6056 { "smb", HAS_ARG, QEMU_OPTION_smb },
6057 #endif
6058 { "redir", HAS_ARG, QEMU_OPTION_redir },
6059 #endif
6061 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6062 { "append", HAS_ARG, QEMU_OPTION_append },
6063 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6065 { "S", 0, QEMU_OPTION_S },
6066 { "s", 0, QEMU_OPTION_s },
6067 { "p", HAS_ARG, QEMU_OPTION_p },
6068 { "d", HAS_ARG, QEMU_OPTION_d },
6069 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6070 { "L", HAS_ARG, QEMU_OPTION_L },
6071 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6072 #ifdef USE_KQEMU
6073 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6074 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6075 #endif
6076 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6077 { "g", 1, QEMU_OPTION_g },
6078 #endif
6079 { "localtime", 0, QEMU_OPTION_localtime },
6080 { "std-vga", 0, QEMU_OPTION_std_vga },
6081 { "monitor", 1, QEMU_OPTION_monitor },
6082 { "serial", 1, QEMU_OPTION_serial },
6083 { "parallel", 1, QEMU_OPTION_parallel },
6084 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6085 { "full-screen", 0, QEMU_OPTION_full_screen },
6086 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6087 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6088 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6089 { "smp", HAS_ARG, QEMU_OPTION_smp },
6090 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6092 /* temporary options */
6093 { "usb", 0, QEMU_OPTION_usb },
6094 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6095 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6096 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6097 { NULL },
6100 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6102 /* this stack is only used during signal handling */
6103 #define SIGNAL_STACK_SIZE 32768
6105 static uint8_t *signal_stack;
6107 #endif
6109 /* password input */
6111 static BlockDriverState *get_bdrv(int index)
6113 BlockDriverState *bs;
6115 if (index < 4) {
6116 bs = bs_table[index];
6117 } else if (index < 6) {
6118 bs = fd_table[index - 4];
6119 } else {
6120 bs = NULL;
6122 return bs;
6125 static void read_passwords(void)
6127 BlockDriverState *bs;
6128 int i, j;
6129 char password[256];
6131 for(i = 0; i < 6; i++) {
6132 bs = get_bdrv(i);
6133 if (bs && bdrv_is_encrypted(bs)) {
6134 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6135 for(j = 0; j < 3; j++) {
6136 monitor_readline("Password: ",
6137 1, password, sizeof(password));
6138 if (bdrv_set_key(bs, password) == 0)
6139 break;
6140 term_printf("invalid password\n");
6146 /* XXX: currently we cannot use simultaneously different CPUs */
6147 void register_machines(void)
6149 #if defined(TARGET_I386)
6150 qemu_register_machine(&pc_machine);
6151 qemu_register_machine(&isapc_machine);
6152 #elif defined(TARGET_PPC)
6153 qemu_register_machine(&heathrow_machine);
6154 qemu_register_machine(&core99_machine);
6155 qemu_register_machine(&prep_machine);
6156 #elif defined(TARGET_MIPS)
6157 qemu_register_machine(&mips_machine);
6158 #elif defined(TARGET_SPARC)
6159 #ifdef TARGET_SPARC64
6160 qemu_register_machine(&sun4u_machine);
6161 #else
6162 qemu_register_machine(&sun4m_machine);
6163 #endif
6164 #elif defined(TARGET_ARM)
6165 qemu_register_machine(&integratorcp926_machine);
6166 qemu_register_machine(&integratorcp1026_machine);
6167 qemu_register_machine(&versatilepb_machine);
6168 qemu_register_machine(&versatileab_machine);
6169 qemu_register_machine(&realview_machine);
6170 #elif defined(TARGET_SH4)
6171 qemu_register_machine(&shix_machine);
6172 #else
6173 #error unsupported CPU
6174 #endif
6177 #ifdef HAS_AUDIO
6178 struct soundhw soundhw[] = {
6179 #ifdef TARGET_I386
6181 "pcspk",
6182 "PC speaker",
6185 { .init_isa = pcspk_audio_init }
6187 #endif
6189 "sb16",
6190 "Creative Sound Blaster 16",
6193 { .init_isa = SB16_init }
6196 #ifdef CONFIG_ADLIB
6198 "adlib",
6199 #ifdef HAS_YMF262
6200 "Yamaha YMF262 (OPL3)",
6201 #else
6202 "Yamaha YM3812 (OPL2)",
6203 #endif
6206 { .init_isa = Adlib_init }
6208 #endif
6210 #ifdef CONFIG_GUS
6212 "gus",
6213 "Gravis Ultrasound GF1",
6216 { .init_isa = GUS_init }
6218 #endif
6221 "es1370",
6222 "ENSONIQ AudioPCI ES1370",
6225 { .init_pci = es1370_init }
6228 { NULL, NULL, 0, 0, { NULL } }
6231 static void select_soundhw (const char *optarg)
6233 struct soundhw *c;
6235 if (*optarg == '?') {
6236 show_valid_cards:
6238 printf ("Valid sound card names (comma separated):\n");
6239 for (c = soundhw; c->name; ++c) {
6240 printf ("%-11s %s\n", c->name, c->descr);
6242 printf ("\n-soundhw all will enable all of the above\n");
6243 exit (*optarg != '?');
6245 else {
6246 size_t l;
6247 const char *p;
6248 char *e;
6249 int bad_card = 0;
6251 if (!strcmp (optarg, "all")) {
6252 for (c = soundhw; c->name; ++c) {
6253 c->enabled = 1;
6255 return;
6258 p = optarg;
6259 while (*p) {
6260 e = strchr (p, ',');
6261 l = !e ? strlen (p) : (size_t) (e - p);
6263 for (c = soundhw; c->name; ++c) {
6264 if (!strncmp (c->name, p, l)) {
6265 c->enabled = 1;
6266 break;
6270 if (!c->name) {
6271 if (l > 80) {
6272 fprintf (stderr,
6273 "Unknown sound card name (too big to show)\n");
6275 else {
6276 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6277 (int) l, p);
6279 bad_card = 1;
6281 p += l + (e != NULL);
6284 if (bad_card)
6285 goto show_valid_cards;
6288 #endif
6290 #ifdef _WIN32
6291 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6293 exit(STATUS_CONTROL_C_EXIT);
6294 return TRUE;
6296 #endif
6298 #define MAX_NET_CLIENTS 32
6300 int main(int argc, char **argv)
6302 #ifdef CONFIG_GDBSTUB
6303 int use_gdbstub, gdbstub_port;
6304 #endif
6305 int i, cdrom_index;
6306 int snapshot, linux_boot;
6307 const char *initrd_filename;
6308 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6309 const char *kernel_filename, *kernel_cmdline;
6310 DisplayState *ds = &display_state;
6311 int cyls, heads, secs, translation;
6312 int start_emulation = 1;
6313 char net_clients[MAX_NET_CLIENTS][256];
6314 int nb_net_clients;
6315 int optind;
6316 const char *r, *optarg;
6317 CharDriverState *monitor_hd;
6318 char monitor_device[128];
6319 char serial_devices[MAX_SERIAL_PORTS][128];
6320 int serial_device_index;
6321 char parallel_devices[MAX_PARALLEL_PORTS][128];
6322 int parallel_device_index;
6323 const char *loadvm = NULL;
6324 QEMUMachine *machine;
6325 char usb_devices[MAX_USB_CMDLINE][128];
6326 int usb_devices_index;
6328 LIST_INIT (&vm_change_state_head);
6329 #ifndef _WIN32
6331 struct sigaction act;
6332 sigfillset(&act.sa_mask);
6333 act.sa_flags = 0;
6334 act.sa_handler = SIG_IGN;
6335 sigaction(SIGPIPE, &act, NULL);
6337 #else
6338 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6339 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6340 QEMU to run on a single CPU */
6342 HANDLE h;
6343 DWORD mask, smask;
6344 int i;
6345 h = GetCurrentProcess();
6346 if (GetProcessAffinityMask(h, &mask, &smask)) {
6347 for(i = 0; i < 32; i++) {
6348 if (mask & (1 << i))
6349 break;
6351 if (i != 32) {
6352 mask = 1 << i;
6353 SetProcessAffinityMask(h, mask);
6357 #endif
6359 register_machines();
6360 machine = first_machine;
6361 initrd_filename = NULL;
6362 for(i = 0; i < MAX_FD; i++)
6363 fd_filename[i] = NULL;
6364 for(i = 0; i < MAX_DISKS; i++)
6365 hd_filename[i] = NULL;
6366 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6367 vga_ram_size = VGA_RAM_SIZE;
6368 bios_size = BIOS_SIZE;
6369 #ifdef CONFIG_GDBSTUB
6370 use_gdbstub = 0;
6371 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6372 #endif
6373 snapshot = 0;
6374 nographic = 0;
6375 kernel_filename = NULL;
6376 kernel_cmdline = "";
6377 #ifdef TARGET_PPC
6378 cdrom_index = 1;
6379 #else
6380 cdrom_index = 2;
6381 #endif
6382 cyls = heads = secs = 0;
6383 translation = BIOS_ATA_TRANSLATION_AUTO;
6384 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6386 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6387 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6388 serial_devices[i][0] = '\0';
6389 serial_device_index = 0;
6391 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6392 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6393 parallel_devices[i][0] = '\0';
6394 parallel_device_index = 0;
6396 usb_devices_index = 0;
6398 nb_net_clients = 0;
6400 nb_nics = 0;
6401 /* default mac address of the first network interface */
6403 optind = 1;
6404 for(;;) {
6405 if (optind >= argc)
6406 break;
6407 r = argv[optind];
6408 if (r[0] != '-') {
6409 hd_filename[0] = argv[optind++];
6410 } else {
6411 const QEMUOption *popt;
6413 optind++;
6414 popt = qemu_options;
6415 for(;;) {
6416 if (!popt->name) {
6417 fprintf(stderr, "%s: invalid option -- '%s'\n",
6418 argv[0], r);
6419 exit(1);
6421 if (!strcmp(popt->name, r + 1))
6422 break;
6423 popt++;
6425 if (popt->flags & HAS_ARG) {
6426 if (optind >= argc) {
6427 fprintf(stderr, "%s: option '%s' requires an argument\n",
6428 argv[0], r);
6429 exit(1);
6431 optarg = argv[optind++];
6432 } else {
6433 optarg = NULL;
6436 switch(popt->index) {
6437 case QEMU_OPTION_M:
6438 machine = find_machine(optarg);
6439 if (!machine) {
6440 QEMUMachine *m;
6441 printf("Supported machines are:\n");
6442 for(m = first_machine; m != NULL; m = m->next) {
6443 printf("%-10s %s%s\n",
6444 m->name, m->desc,
6445 m == first_machine ? " (default)" : "");
6447 exit(1);
6449 break;
6450 case QEMU_OPTION_initrd:
6451 initrd_filename = optarg;
6452 break;
6453 case QEMU_OPTION_hda:
6454 case QEMU_OPTION_hdb:
6455 case QEMU_OPTION_hdc:
6456 case QEMU_OPTION_hdd:
6458 int hd_index;
6459 hd_index = popt->index - QEMU_OPTION_hda;
6460 hd_filename[hd_index] = optarg;
6461 if (hd_index == cdrom_index)
6462 cdrom_index = -1;
6464 break;
6465 case QEMU_OPTION_snapshot:
6466 snapshot = 1;
6467 break;
6468 case QEMU_OPTION_hdachs:
6470 const char *p;
6471 p = optarg;
6472 cyls = strtol(p, (char **)&p, 0);
6473 if (cyls < 1 || cyls > 16383)
6474 goto chs_fail;
6475 if (*p != ',')
6476 goto chs_fail;
6477 p++;
6478 heads = strtol(p, (char **)&p, 0);
6479 if (heads < 1 || heads > 16)
6480 goto chs_fail;
6481 if (*p != ',')
6482 goto chs_fail;
6483 p++;
6484 secs = strtol(p, (char **)&p, 0);
6485 if (secs < 1 || secs > 63)
6486 goto chs_fail;
6487 if (*p == ',') {
6488 p++;
6489 if (!strcmp(p, "none"))
6490 translation = BIOS_ATA_TRANSLATION_NONE;
6491 else if (!strcmp(p, "lba"))
6492 translation = BIOS_ATA_TRANSLATION_LBA;
6493 else if (!strcmp(p, "auto"))
6494 translation = BIOS_ATA_TRANSLATION_AUTO;
6495 else
6496 goto chs_fail;
6497 } else if (*p != '\0') {
6498 chs_fail:
6499 fprintf(stderr, "qemu: invalid physical CHS format\n");
6500 exit(1);
6503 break;
6504 case QEMU_OPTION_nographic:
6505 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
6506 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
6507 nographic = 1;
6508 break;
6509 case QEMU_OPTION_kernel:
6510 kernel_filename = optarg;
6511 break;
6512 case QEMU_OPTION_append:
6513 kernel_cmdline = optarg;
6514 break;
6515 case QEMU_OPTION_cdrom:
6516 if (cdrom_index >= 0) {
6517 hd_filename[cdrom_index] = optarg;
6519 break;
6520 case QEMU_OPTION_boot:
6521 boot_device = optarg[0];
6522 if (boot_device != 'a' &&
6523 #ifdef TARGET_SPARC
6524 // Network boot
6525 boot_device != 'n' &&
6526 #endif
6527 boot_device != 'c' && boot_device != 'd') {
6528 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
6529 exit(1);
6531 break;
6532 case QEMU_OPTION_fda:
6533 fd_filename[0] = optarg;
6534 break;
6535 case QEMU_OPTION_fdb:
6536 fd_filename[1] = optarg;
6537 break;
6538 #ifdef TARGET_I386
6539 case QEMU_OPTION_no_fd_bootchk:
6540 fd_bootchk = 0;
6541 break;
6542 #endif
6543 case QEMU_OPTION_no_code_copy:
6544 code_copy_enabled = 0;
6545 break;
6546 case QEMU_OPTION_net:
6547 if (nb_net_clients >= MAX_NET_CLIENTS) {
6548 fprintf(stderr, "qemu: too many network clients\n");
6549 exit(1);
6551 pstrcpy(net_clients[nb_net_clients],
6552 sizeof(net_clients[0]),
6553 optarg);
6554 nb_net_clients++;
6555 break;
6556 #ifdef CONFIG_SLIRP
6557 case QEMU_OPTION_tftp:
6558 tftp_prefix = optarg;
6559 break;
6560 #ifndef _WIN32
6561 case QEMU_OPTION_smb:
6562 net_slirp_smb(optarg);
6563 break;
6564 #endif
6565 case QEMU_OPTION_redir:
6566 net_slirp_redir(optarg);
6567 break;
6568 #endif
6569 #ifdef HAS_AUDIO
6570 case QEMU_OPTION_audio_help:
6571 AUD_help ();
6572 exit (0);
6573 break;
6574 case QEMU_OPTION_soundhw:
6575 select_soundhw (optarg);
6576 break;
6577 #endif
6578 case QEMU_OPTION_h:
6579 help();
6580 break;
6581 case QEMU_OPTION_m:
6582 ram_size = atoi(optarg) * 1024 * 1024;
6583 if (ram_size <= 0)
6584 help();
6585 if (ram_size > PHYS_RAM_MAX_SIZE) {
6586 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6587 PHYS_RAM_MAX_SIZE / (1024 * 1024));
6588 exit(1);
6590 break;
6591 case QEMU_OPTION_d:
6593 int mask;
6594 CPULogItem *item;
6596 mask = cpu_str_to_log_mask(optarg);
6597 if (!mask) {
6598 printf("Log items (comma separated):\n");
6599 for(item = cpu_log_items; item->mask != 0; item++) {
6600 printf("%-10s %s\n", item->name, item->help);
6602 exit(1);
6604 cpu_set_log(mask);
6606 break;
6607 #ifdef CONFIG_GDBSTUB
6608 case QEMU_OPTION_s:
6609 use_gdbstub = 1;
6610 break;
6611 case QEMU_OPTION_p:
6612 gdbstub_port = atoi(optarg);
6613 break;
6614 #endif
6615 case QEMU_OPTION_L:
6616 bios_dir = optarg;
6617 break;
6618 case QEMU_OPTION_S:
6619 start_emulation = 0;
6620 break;
6621 case QEMU_OPTION_k:
6622 keyboard_layout = optarg;
6623 break;
6624 case QEMU_OPTION_localtime:
6625 rtc_utc = 0;
6626 break;
6627 case QEMU_OPTION_cirrusvga:
6628 cirrus_vga_enabled = 1;
6629 break;
6630 case QEMU_OPTION_std_vga:
6631 cirrus_vga_enabled = 0;
6632 break;
6633 case QEMU_OPTION_g:
6635 const char *p;
6636 int w, h, depth;
6637 p = optarg;
6638 w = strtol(p, (char **)&p, 10);
6639 if (w <= 0) {
6640 graphic_error:
6641 fprintf(stderr, "qemu: invalid resolution or depth\n");
6642 exit(1);
6644 if (*p != 'x')
6645 goto graphic_error;
6646 p++;
6647 h = strtol(p, (char **)&p, 10);
6648 if (h <= 0)
6649 goto graphic_error;
6650 if (*p == 'x') {
6651 p++;
6652 depth = strtol(p, (char **)&p, 10);
6653 if (depth != 8 && depth != 15 && depth != 16 &&
6654 depth != 24 && depth != 32)
6655 goto graphic_error;
6656 } else if (*p == '\0') {
6657 depth = graphic_depth;
6658 } else {
6659 goto graphic_error;
6662 graphic_width = w;
6663 graphic_height = h;
6664 graphic_depth = depth;
6666 break;
6667 case QEMU_OPTION_monitor:
6668 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6669 break;
6670 case QEMU_OPTION_serial:
6671 if (serial_device_index >= MAX_SERIAL_PORTS) {
6672 fprintf(stderr, "qemu: too many serial ports\n");
6673 exit(1);
6675 pstrcpy(serial_devices[serial_device_index],
6676 sizeof(serial_devices[0]), optarg);
6677 serial_device_index++;
6678 break;
6679 case QEMU_OPTION_parallel:
6680 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6681 fprintf(stderr, "qemu: too many parallel ports\n");
6682 exit(1);
6684 pstrcpy(parallel_devices[parallel_device_index],
6685 sizeof(parallel_devices[0]), optarg);
6686 parallel_device_index++;
6687 break;
6688 case QEMU_OPTION_loadvm:
6689 loadvm = optarg;
6690 break;
6691 case QEMU_OPTION_full_screen:
6692 full_screen = 1;
6693 break;
6694 case QEMU_OPTION_pidfile:
6695 create_pidfile(optarg);
6696 break;
6697 #ifdef TARGET_I386
6698 case QEMU_OPTION_win2k_hack:
6699 win2k_install_hack = 1;
6700 break;
6701 #endif
6702 #ifdef USE_KQEMU
6703 case QEMU_OPTION_no_kqemu:
6704 kqemu_allowed = 0;
6705 break;
6706 case QEMU_OPTION_kernel_kqemu:
6707 kqemu_allowed = 2;
6708 break;
6709 #endif
6710 case QEMU_OPTION_usb:
6711 usb_enabled = 1;
6712 break;
6713 case QEMU_OPTION_usbdevice:
6714 usb_enabled = 1;
6715 if (usb_devices_index >= MAX_USB_CMDLINE) {
6716 fprintf(stderr, "Too many USB devices\n");
6717 exit(1);
6719 pstrcpy(usb_devices[usb_devices_index],
6720 sizeof(usb_devices[usb_devices_index]),
6721 optarg);
6722 usb_devices_index++;
6723 break;
6724 case QEMU_OPTION_smp:
6725 smp_cpus = atoi(optarg);
6726 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6727 fprintf(stderr, "Invalid number of CPUs\n");
6728 exit(1);
6730 break;
6731 case QEMU_OPTION_vnc:
6732 vnc_display = atoi(optarg);
6733 if (vnc_display < 0) {
6734 fprintf(stderr, "Invalid VNC display\n");
6735 exit(1);
6737 break;
6738 case QEMU_OPTION_no_acpi:
6739 acpi_enabled = 0;
6740 break;
6741 case QEMU_OPTION_no_reboot:
6742 no_reboot = 1;
6743 break;
6748 #ifdef USE_KQEMU
6749 if (smp_cpus > 1)
6750 kqemu_allowed = 0;
6751 #endif
6752 linux_boot = (kernel_filename != NULL);
6754 if (!linux_boot &&
6755 hd_filename[0] == '\0' &&
6756 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6757 fd_filename[0] == '\0')
6758 help();
6760 /* boot to cd by default if no hard disk */
6761 if (hd_filename[0] == '\0' && boot_device == 'c') {
6762 if (fd_filename[0] != '\0')
6763 boot_device = 'a';
6764 else
6765 boot_device = 'd';
6768 setvbuf(stdout, NULL, _IOLBF, 0);
6770 init_timers();
6771 init_timer_alarm();
6772 qemu_aio_init();
6774 #ifdef _WIN32
6775 socket_init();
6776 #endif
6778 /* init network clients */
6779 if (nb_net_clients == 0) {
6780 /* if no clients, we use a default config */
6781 pstrcpy(net_clients[0], sizeof(net_clients[0]),
6782 "nic");
6783 pstrcpy(net_clients[1], sizeof(net_clients[0]),
6784 "user");
6785 nb_net_clients = 2;
6788 for(i = 0;i < nb_net_clients; i++) {
6789 if (net_client_init(net_clients[i]) < 0)
6790 exit(1);
6793 /* init the memory */
6794 phys_ram_size = ram_size + vga_ram_size + bios_size;
6796 phys_ram_base = qemu_vmalloc(phys_ram_size);
6797 if (!phys_ram_base) {
6798 fprintf(stderr, "Could not allocate physical memory\n");
6799 exit(1);
6802 /* we always create the cdrom drive, even if no disk is there */
6803 bdrv_init();
6804 if (cdrom_index >= 0) {
6805 bs_table[cdrom_index] = bdrv_new("cdrom");
6806 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6809 /* open the virtual block devices */
6810 for(i = 0; i < MAX_DISKS; i++) {
6811 if (hd_filename[i]) {
6812 if (!bs_table[i]) {
6813 char buf[64];
6814 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6815 bs_table[i] = bdrv_new(buf);
6817 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
6818 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6819 hd_filename[i]);
6820 exit(1);
6822 if (i == 0 && cyls != 0) {
6823 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6824 bdrv_set_translation_hint(bs_table[i], translation);
6829 /* we always create at least one floppy disk */
6830 fd_table[0] = bdrv_new("fda");
6831 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6833 for(i = 0; i < MAX_FD; i++) {
6834 if (fd_filename[i]) {
6835 if (!fd_table[i]) {
6836 char buf[64];
6837 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6838 fd_table[i] = bdrv_new(buf);
6839 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6841 if (fd_filename[i] != '\0') {
6842 if (bdrv_open(fd_table[i], fd_filename[i],
6843 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
6844 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6845 fd_filename[i]);
6846 exit(1);
6852 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6853 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
6855 init_ioports();
6857 /* terminal init */
6858 if (nographic) {
6859 dumb_display_init(ds);
6860 } else if (vnc_display != -1) {
6861 vnc_display_init(ds, vnc_display);
6862 } else {
6863 #if defined(CONFIG_SDL)
6864 sdl_display_init(ds, full_screen);
6865 #elif defined(CONFIG_COCOA)
6866 cocoa_display_init(ds, full_screen);
6867 #else
6868 dumb_display_init(ds);
6869 #endif
6872 monitor_hd = qemu_chr_open(monitor_device);
6873 if (!monitor_hd) {
6874 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6875 exit(1);
6877 monitor_init(monitor_hd, !nographic);
6879 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6880 const char *devname = serial_devices[i];
6881 if (devname[0] != '\0' && strcmp(devname, "none")) {
6882 serial_hds[i] = qemu_chr_open(devname);
6883 if (!serial_hds[i]) {
6884 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6885 devname);
6886 exit(1);
6888 if (!strcmp(devname, "vc"))
6889 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6893 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6894 const char *devname = parallel_devices[i];
6895 if (devname[0] != '\0' && strcmp(devname, "none")) {
6896 parallel_hds[i] = qemu_chr_open(devname);
6897 if (!parallel_hds[i]) {
6898 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6899 devname);
6900 exit(1);
6902 if (!strcmp(devname, "vc"))
6903 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6907 machine->init(ram_size, vga_ram_size, boot_device,
6908 ds, fd_filename, snapshot,
6909 kernel_filename, kernel_cmdline, initrd_filename);
6911 /* init USB devices */
6912 if (usb_enabled) {
6913 for(i = 0; i < usb_devices_index; i++) {
6914 if (usb_device_add(usb_devices[i]) < 0) {
6915 fprintf(stderr, "Warning: could not add USB device %s\n",
6916 usb_devices[i]);
6921 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6922 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6924 #ifdef CONFIG_GDBSTUB
6925 if (use_gdbstub) {
6926 if (gdbserver_start(gdbstub_port) < 0) {
6927 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6928 gdbstub_port);
6929 exit(1);
6930 } else {
6931 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6933 } else
6934 #endif
6935 if (loadvm)
6936 do_loadvm(loadvm);
6939 /* XXX: simplify init */
6940 read_passwords();
6941 if (start_emulation) {
6942 vm_start();
6945 main_loop();
6946 quit_timers();
6947 return 0;