kvm: host suspend/resume support
[qemu-kvm/fedora.git] / vl.c
blob5f57c2ca1c19d330632ac6e327313b3caeb1d906
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2005 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "vl.h"
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <sys/time.h>
33 #ifndef _WIN32
34 #include <sys/times.h>
35 #include <sys/wait.h>
36 #include <termios.h>
37 #include <sys/poll.h>
38 #include <sys/mman.h>
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
41 #include <sys/un.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 <linux/if_ether.h>
55 #include <pty.h>
56 #include <malloc.h>
57 #include <linux/rtc.h>
58 #include <linux/ppdev.h>
59 #endif
60 #endif
61 #endif
63 #if defined(CONFIG_SLIRP)
64 #include "libslirp.h"
65 #endif
67 #ifdef _WIN32
68 #include <malloc.h>
69 #include <sys/timeb.h>
70 #include <windows.h>
71 #define getopt_long_only getopt_long
72 #define memalign(align, size) malloc(size)
73 #endif
75 #include "qemu_socket.h"
77 #ifdef CONFIG_SDL
78 #ifdef __APPLE__
79 #include <SDL/SDL.h>
80 #endif
81 #endif /* CONFIG_SDL */
83 #ifdef CONFIG_COCOA
84 #undef main
85 #define main qemu_main
86 #endif /* CONFIG_COCOA */
88 #include "disas.h"
90 #include "exec-all.h"
92 #if USE_KVM
93 #include "qemu-kvm.h"
94 #endif
96 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
98 //#define DEBUG_UNUSED_IOPORT
99 //#define DEBUG_IOPORT
101 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
103 #ifdef TARGET_PPC
104 #define DEFAULT_RAM_SIZE 144
105 #else
106 #define DEFAULT_RAM_SIZE 128
107 #endif
108 /* in ms */
109 #define GUI_REFRESH_INTERVAL 30
111 /* Max number of USB devices that can be specified on the commandline. */
112 #define MAX_USB_CMDLINE 8
114 /* XXX: use a two level table to limit memory usage */
115 #define MAX_IOPORTS 65536
117 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
118 char phys_ram_file[1024];
119 void *ioport_opaque[MAX_IOPORTS];
120 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
121 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
122 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
123 int vga_ram_size;
124 int bios_size;
125 static DisplayState display_state;
126 int nographic;
127 const char* keyboard_layout = NULL;
128 int64_t ticks_per_sec;
129 int boot_device = 'c';
130 int ram_size;
131 int pit_min_timer_count = 0;
132 int nb_nics;
133 NICInfo nd_table[MAX_NICS];
134 QEMUTimer *gui_timer;
135 int vm_running;
136 int rtc_utc = 1;
137 int cirrus_vga_enabled = 1;
138 #ifdef TARGET_SPARC
139 int graphic_width = 1024;
140 int graphic_height = 768;
141 #else
142 int graphic_width = 800;
143 int graphic_height = 600;
144 #endif
145 int graphic_depth = 15;
146 int full_screen = 0;
147 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
148 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
149 #ifdef TARGET_I386
150 int win2k_install_hack = 0;
151 #endif
152 int usb_enabled = 0;
153 static VLANState *first_vlan;
154 int smp_cpus = 1;
155 int vnc_display = -1;
156 #if defined(TARGET_SPARC)
157 #define MAX_CPUS 16
158 #elif defined(TARGET_I386)
159 #define MAX_CPUS 255
160 #else
161 #define MAX_CPUS 1
162 #endif
163 int acpi_enabled = 1;
164 int fd_bootchk = 1;
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)
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 qemu_get_be64s(f, &cpu_clock_offset);
840 return 0;
843 #ifdef _WIN32
844 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
845 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
846 #else
847 static void host_alarm_handler(int host_signum)
848 #endif
850 #if 0
851 #define DISP_FREQ 1000
853 static int64_t delta_min = INT64_MAX;
854 static int64_t delta_max, delta_cum, last_clock, delta, ti;
855 static int count;
856 ti = qemu_get_clock(vm_clock);
857 if (last_clock != 0) {
858 delta = ti - last_clock;
859 if (delta < delta_min)
860 delta_min = delta;
861 if (delta > delta_max)
862 delta_max = delta;
863 delta_cum += delta;
864 if (++count == DISP_FREQ) {
865 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
866 muldiv64(delta_min, 1000000, ticks_per_sec),
867 muldiv64(delta_max, 1000000, ticks_per_sec),
868 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
869 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
870 count = 0;
871 delta_min = INT64_MAX;
872 delta_max = 0;
873 delta_cum = 0;
876 last_clock = ti;
878 #endif
879 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
880 qemu_get_clock(vm_clock)) ||
881 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
882 qemu_get_clock(rt_clock))) {
883 #ifdef _WIN32
884 SetEvent(host_alarm);
885 #endif
886 CPUState *env = cpu_single_env;
887 if (env) {
888 /* stop the currently executing cpu because a timer occured */
889 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
890 #ifdef USE_KQEMU
891 if (env->kqemu_enabled) {
892 kqemu_cpu_interrupt(env);
894 #endif
899 #ifndef _WIN32
901 #if defined(__linux__)
903 #define RTC_FREQ 1024
905 static int rtc_fd;
907 static int start_rtc_timer(void)
909 rtc_fd = open("/dev/rtc", O_RDONLY);
910 if (rtc_fd < 0)
911 return -1;
912 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
913 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
914 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
915 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
916 goto fail;
918 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
919 fail:
920 close(rtc_fd);
921 return -1;
923 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
924 return 0;
927 #else
929 static int start_rtc_timer(void)
931 return -1;
934 #endif /* !defined(__linux__) */
936 #endif /* !defined(_WIN32) */
938 static void init_timer_alarm(void)
940 #ifdef _WIN32
942 int count=0;
943 TIMECAPS tc;
945 ZeroMemory(&tc, sizeof(TIMECAPS));
946 timeGetDevCaps(&tc, sizeof(TIMECAPS));
947 if (period < tc.wPeriodMin)
948 period = tc.wPeriodMin;
949 timeBeginPeriod(period);
950 timerID = timeSetEvent(1, // interval (ms)
951 period, // resolution
952 host_alarm_handler, // function
953 (DWORD)&count, // user parameter
954 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
955 if( !timerID ) {
956 perror("failed timer alarm");
957 exit(1);
959 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
960 if (!host_alarm) {
961 perror("failed CreateEvent");
962 exit(1);
964 qemu_add_wait_object(host_alarm, NULL, NULL);
966 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
967 #else
969 struct sigaction act;
970 struct itimerval itv;
972 /* get times() syscall frequency */
973 timer_freq = sysconf(_SC_CLK_TCK);
975 /* timer signal */
976 sigfillset(&act.sa_mask);
977 act.sa_flags = 0;
978 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
979 act.sa_flags |= SA_ONSTACK;
980 #endif
981 act.sa_handler = host_alarm_handler;
982 sigaction(SIGALRM, &act, NULL);
984 itv.it_interval.tv_sec = 0;
985 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
986 itv.it_value.tv_sec = 0;
987 itv.it_value.tv_usec = 10 * 1000;
988 setitimer(ITIMER_REAL, &itv, NULL);
989 /* we probe the tick duration of the kernel to inform the user if
990 the emulated kernel requested a too high timer frequency */
991 getitimer(ITIMER_REAL, &itv);
993 #if defined(__linux__)
994 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
995 have timers with 1 ms resolution. The correct solution will
996 be to use the POSIX real time timers available in recent
997 2.6 kernels */
998 if (itv.it_interval.tv_usec > 1000 || 1) {
999 /* try to use /dev/rtc to have a faster timer */
1000 if (start_rtc_timer() < 0)
1001 goto use_itimer;
1002 /* disable itimer */
1003 itv.it_interval.tv_sec = 0;
1004 itv.it_interval.tv_usec = 0;
1005 itv.it_value.tv_sec = 0;
1006 itv.it_value.tv_usec = 0;
1007 setitimer(ITIMER_REAL, &itv, NULL);
1009 /* use the RTC */
1010 sigaction(SIGIO, &act, NULL);
1011 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1012 fcntl(rtc_fd, F_SETOWN, getpid());
1013 } else
1014 #endif /* defined(__linux__) */
1016 use_itimer:
1017 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1018 PIT_FREQ) / 1000000;
1021 #endif
1024 void quit_timers(void)
1026 #ifdef _WIN32
1027 timeKillEvent(timerID);
1028 timeEndPeriod(period);
1029 if (host_alarm) {
1030 CloseHandle(host_alarm);
1031 host_alarm = NULL;
1033 #endif
1036 /***********************************************************/
1037 /* character device */
1039 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1041 return s->chr_write(s, buf, len);
1044 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1046 if (!s->chr_ioctl)
1047 return -ENOTSUP;
1048 return s->chr_ioctl(s, cmd, arg);
1051 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1053 char buf[4096];
1054 va_list ap;
1055 va_start(ap, fmt);
1056 vsnprintf(buf, sizeof(buf), fmt, ap);
1057 qemu_chr_write(s, buf, strlen(buf));
1058 va_end(ap);
1061 void qemu_chr_send_event(CharDriverState *s, int event)
1063 if (s->chr_send_event)
1064 s->chr_send_event(s, event);
1067 void qemu_chr_add_read_handler(CharDriverState *s,
1068 IOCanRWHandler *fd_can_read,
1069 IOReadHandler *fd_read, void *opaque)
1071 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1074 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1076 s->chr_event = chr_event;
1079 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1081 return len;
1084 static void null_chr_add_read_handler(CharDriverState *chr,
1085 IOCanRWHandler *fd_can_read,
1086 IOReadHandler *fd_read, void *opaque)
1090 CharDriverState *qemu_chr_open_null(void)
1092 CharDriverState *chr;
1094 chr = qemu_mallocz(sizeof(CharDriverState));
1095 if (!chr)
1096 return NULL;
1097 chr->chr_write = null_chr_write;
1098 chr->chr_add_read_handler = null_chr_add_read_handler;
1099 return chr;
1102 #ifdef _WIN32
1104 static void socket_cleanup(void)
1106 WSACleanup();
1109 static int socket_init(void)
1111 WSADATA Data;
1112 int ret, err;
1114 ret = WSAStartup(MAKEWORD(2,2), &Data);
1115 if (ret != 0) {
1116 err = WSAGetLastError();
1117 fprintf(stderr, "WSAStartup: %d\n", err);
1118 return -1;
1120 atexit(socket_cleanup);
1121 return 0;
1124 static int send_all(int fd, const uint8_t *buf, int len1)
1126 int ret, len;
1128 len = len1;
1129 while (len > 0) {
1130 ret = send(fd, buf, len, 0);
1131 if (ret < 0) {
1132 int errno;
1133 errno = WSAGetLastError();
1134 if (errno != WSAEWOULDBLOCK) {
1135 return -1;
1137 } else if (ret == 0) {
1138 break;
1139 } else {
1140 buf += ret;
1141 len -= ret;
1144 return len1 - len;
1147 void socket_set_nonblock(int fd)
1149 unsigned long opt = 1;
1150 ioctlsocket(fd, FIONBIO, &opt);
1153 #else
1155 static int unix_write(int fd, const uint8_t *buf, int len1)
1157 int ret, len;
1159 len = len1;
1160 while (len > 0) {
1161 ret = write(fd, buf, len);
1162 if (ret < 0) {
1163 if (errno != EINTR && errno != EAGAIN)
1164 return -1;
1165 } else if (ret == 0) {
1166 break;
1167 } else {
1168 buf += ret;
1169 len -= ret;
1172 return len1 - len;
1175 static inline int send_all(int fd, const uint8_t *buf, int len1)
1177 return unix_write(fd, buf, len1);
1180 void socket_set_nonblock(int fd)
1182 fcntl(fd, F_SETFL, O_NONBLOCK);
1184 #endif /* !_WIN32 */
1186 #ifndef _WIN32
1188 typedef struct {
1189 int fd_in, fd_out;
1190 IOCanRWHandler *fd_can_read;
1191 IOReadHandler *fd_read;
1192 void *fd_opaque;
1193 int max_size;
1194 } FDCharDriver;
1196 #define STDIO_MAX_CLIENTS 2
1198 static int stdio_nb_clients;
1199 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1201 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1203 FDCharDriver *s = chr->opaque;
1204 return unix_write(s->fd_out, buf, len);
1207 static int fd_chr_read_poll(void *opaque)
1209 CharDriverState *chr = opaque;
1210 FDCharDriver *s = chr->opaque;
1212 s->max_size = s->fd_can_read(s->fd_opaque);
1213 return s->max_size;
1216 static void fd_chr_read(void *opaque)
1218 CharDriverState *chr = opaque;
1219 FDCharDriver *s = chr->opaque;
1220 int size, len;
1221 uint8_t buf[1024];
1223 len = sizeof(buf);
1224 if (len > s->max_size)
1225 len = s->max_size;
1226 if (len == 0)
1227 return;
1228 size = read(s->fd_in, buf, len);
1229 if (size > 0) {
1230 s->fd_read(s->fd_opaque, buf, size);
1234 static void fd_chr_add_read_handler(CharDriverState *chr,
1235 IOCanRWHandler *fd_can_read,
1236 IOReadHandler *fd_read, void *opaque)
1238 FDCharDriver *s = chr->opaque;
1240 if (s->fd_in >= 0) {
1241 s->fd_can_read = fd_can_read;
1242 s->fd_read = fd_read;
1243 s->fd_opaque = opaque;
1244 if (nographic && s->fd_in == 0) {
1245 } else {
1246 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1247 fd_chr_read, NULL, chr);
1252 /* open a character device to a unix fd */
1253 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1255 CharDriverState *chr;
1256 FDCharDriver *s;
1258 chr = qemu_mallocz(sizeof(CharDriverState));
1259 if (!chr)
1260 return NULL;
1261 s = qemu_mallocz(sizeof(FDCharDriver));
1262 if (!s) {
1263 free(chr);
1264 return NULL;
1266 s->fd_in = fd_in;
1267 s->fd_out = fd_out;
1268 chr->opaque = s;
1269 chr->chr_write = fd_chr_write;
1270 chr->chr_add_read_handler = fd_chr_add_read_handler;
1271 return chr;
1274 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1276 int fd_out;
1278 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1279 if (fd_out < 0)
1280 return NULL;
1281 return qemu_chr_open_fd(-1, fd_out);
1284 CharDriverState *qemu_chr_open_pipe(const char *filename)
1286 int fd;
1288 fd = open(filename, O_RDWR | O_BINARY);
1289 if (fd < 0)
1290 return NULL;
1291 return qemu_chr_open_fd(fd, fd);
1295 /* for STDIO, we handle the case where several clients use it
1296 (nographic mode) */
1298 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1300 #define TERM_FIFO_MAX_SIZE 1
1302 static int term_got_escape, client_index;
1303 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1304 static int term_fifo_size;
1305 static int term_timestamps;
1306 static int64_t term_timestamps_start;
1308 void term_print_help(void)
1310 printf("\n"
1311 "C-a h print this help\n"
1312 "C-a x exit emulator\n"
1313 "C-a s save disk data back to file (if -snapshot)\n"
1314 "C-a b send break (magic sysrq)\n"
1315 "C-a t toggle console timestamps\n"
1316 "C-a c switch between console and monitor\n"
1317 "C-a C-a send C-a\n"
1321 /* called when a char is received */
1322 static void stdio_received_byte(int ch)
1324 if (term_got_escape) {
1325 term_got_escape = 0;
1326 switch(ch) {
1327 case 'h':
1328 term_print_help();
1329 break;
1330 case 'x':
1331 exit(0);
1332 break;
1333 case 's':
1335 int i;
1336 for (i = 0; i < MAX_DISKS; i++) {
1337 if (bs_table[i])
1338 bdrv_commit(bs_table[i]);
1341 break;
1342 case 'b':
1343 if (client_index < stdio_nb_clients) {
1344 CharDriverState *chr;
1345 FDCharDriver *s;
1347 chr = stdio_clients[client_index];
1348 s = chr->opaque;
1349 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1351 break;
1352 case 'c':
1353 client_index++;
1354 if (client_index >= stdio_nb_clients)
1355 client_index = 0;
1356 if (client_index == 0) {
1357 /* send a new line in the monitor to get the prompt */
1358 ch = '\r';
1359 goto send_char;
1361 break;
1362 case 't':
1363 term_timestamps = !term_timestamps;
1364 term_timestamps_start = -1;
1365 break;
1366 case TERM_ESCAPE:
1367 goto send_char;
1369 } else if (ch == TERM_ESCAPE) {
1370 term_got_escape = 1;
1371 } else {
1372 send_char:
1373 if (client_index < stdio_nb_clients) {
1374 uint8_t buf[1];
1375 CharDriverState *chr;
1376 FDCharDriver *s;
1378 chr = stdio_clients[client_index];
1379 s = chr->opaque;
1380 if (s->fd_can_read(s->fd_opaque) > 0) {
1381 buf[0] = ch;
1382 s->fd_read(s->fd_opaque, buf, 1);
1383 } else if (term_fifo_size == 0) {
1384 term_fifo[term_fifo_size++] = ch;
1390 static int stdio_read_poll(void *opaque)
1392 CharDriverState *chr;
1393 FDCharDriver *s;
1395 if (client_index < stdio_nb_clients) {
1396 chr = stdio_clients[client_index];
1397 s = chr->opaque;
1398 /* try to flush the queue if needed */
1399 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1400 s->fd_read(s->fd_opaque, term_fifo, 1);
1401 term_fifo_size = 0;
1403 /* see if we can absorb more chars */
1404 if (term_fifo_size == 0)
1405 return 1;
1406 else
1407 return 0;
1408 } else {
1409 return 1;
1413 static void stdio_read(void *opaque)
1415 int size;
1416 uint8_t buf[1];
1418 size = read(0, buf, 1);
1419 if (size > 0)
1420 stdio_received_byte(buf[0]);
1423 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1425 FDCharDriver *s = chr->opaque;
1426 if (!term_timestamps) {
1427 return unix_write(s->fd_out, buf, len);
1428 } else {
1429 int i;
1430 char buf1[64];
1432 for(i = 0; i < len; i++) {
1433 unix_write(s->fd_out, buf + i, 1);
1434 if (buf[i] == '\n') {
1435 int64_t ti;
1436 int secs;
1438 ti = get_clock();
1439 if (term_timestamps_start == -1)
1440 term_timestamps_start = ti;
1441 ti -= term_timestamps_start;
1442 secs = ti / 1000000000;
1443 snprintf(buf1, sizeof(buf1),
1444 "[%02d:%02d:%02d.%03d] ",
1445 secs / 3600,
1446 (secs / 60) % 60,
1447 secs % 60,
1448 (int)((ti / 1000000) % 1000));
1449 unix_write(s->fd_out, buf1, strlen(buf1));
1452 return len;
1456 /* init terminal so that we can grab keys */
1457 static struct termios oldtty;
1458 static int old_fd0_flags;
1460 static void term_exit(void)
1462 tcsetattr (0, TCSANOW, &oldtty);
1463 fcntl(0, F_SETFL, old_fd0_flags);
1466 static void term_init(void)
1468 struct termios tty;
1470 tcgetattr (0, &tty);
1471 oldtty = tty;
1472 old_fd0_flags = fcntl(0, F_GETFL);
1474 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1475 |INLCR|IGNCR|ICRNL|IXON);
1476 tty.c_oflag |= OPOST;
1477 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1478 /* if graphical mode, we allow Ctrl-C handling */
1479 if (nographic)
1480 tty.c_lflag &= ~ISIG;
1481 tty.c_cflag &= ~(CSIZE|PARENB);
1482 tty.c_cflag |= CS8;
1483 tty.c_cc[VMIN] = 1;
1484 tty.c_cc[VTIME] = 0;
1486 tcsetattr (0, TCSANOW, &tty);
1488 atexit(term_exit);
1490 fcntl(0, F_SETFL, O_NONBLOCK);
1493 CharDriverState *qemu_chr_open_stdio(void)
1495 CharDriverState *chr;
1497 if (nographic) {
1498 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1499 return NULL;
1500 chr = qemu_chr_open_fd(0, 1);
1501 chr->chr_write = stdio_write;
1502 if (stdio_nb_clients == 0)
1503 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1504 client_index = stdio_nb_clients;
1505 } else {
1506 if (stdio_nb_clients != 0)
1507 return NULL;
1508 chr = qemu_chr_open_fd(0, 1);
1510 stdio_clients[stdio_nb_clients++] = chr;
1511 if (stdio_nb_clients == 1) {
1512 /* set the terminal in raw mode */
1513 term_init();
1515 return chr;
1518 #if defined(__linux__)
1519 CharDriverState *qemu_chr_open_pty(void)
1521 struct termios tty;
1522 char slave_name[1024];
1523 int master_fd, slave_fd;
1525 /* Not satisfying */
1526 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1527 return NULL;
1530 /* Disabling local echo and line-buffered output */
1531 tcgetattr (master_fd, &tty);
1532 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1533 tty.c_cc[VMIN] = 1;
1534 tty.c_cc[VTIME] = 0;
1535 tcsetattr (master_fd, TCSAFLUSH, &tty);
1537 fprintf(stderr, "char device redirected to %s\n", slave_name);
1538 return qemu_chr_open_fd(master_fd, master_fd);
1541 static void tty_serial_init(int fd, int speed,
1542 int parity, int data_bits, int stop_bits)
1544 struct termios tty;
1545 speed_t spd;
1547 #if 0
1548 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1549 speed, parity, data_bits, stop_bits);
1550 #endif
1551 tcgetattr (fd, &tty);
1553 switch(speed) {
1554 case 50:
1555 spd = B50;
1556 break;
1557 case 75:
1558 spd = B75;
1559 break;
1560 case 300:
1561 spd = B300;
1562 break;
1563 case 600:
1564 spd = B600;
1565 break;
1566 case 1200:
1567 spd = B1200;
1568 break;
1569 case 2400:
1570 spd = B2400;
1571 break;
1572 case 4800:
1573 spd = B4800;
1574 break;
1575 case 9600:
1576 spd = B9600;
1577 break;
1578 case 19200:
1579 spd = B19200;
1580 break;
1581 case 38400:
1582 spd = B38400;
1583 break;
1584 case 57600:
1585 spd = B57600;
1586 break;
1587 default:
1588 case 115200:
1589 spd = B115200;
1590 break;
1593 cfsetispeed(&tty, spd);
1594 cfsetospeed(&tty, spd);
1596 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1597 |INLCR|IGNCR|ICRNL|IXON);
1598 tty.c_oflag |= OPOST;
1599 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1600 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1601 switch(data_bits) {
1602 default:
1603 case 8:
1604 tty.c_cflag |= CS8;
1605 break;
1606 case 7:
1607 tty.c_cflag |= CS7;
1608 break;
1609 case 6:
1610 tty.c_cflag |= CS6;
1611 break;
1612 case 5:
1613 tty.c_cflag |= CS5;
1614 break;
1616 switch(parity) {
1617 default:
1618 case 'N':
1619 break;
1620 case 'E':
1621 tty.c_cflag |= PARENB;
1622 break;
1623 case 'O':
1624 tty.c_cflag |= PARENB | PARODD;
1625 break;
1628 tcsetattr (fd, TCSANOW, &tty);
1631 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1633 FDCharDriver *s = chr->opaque;
1635 switch(cmd) {
1636 case CHR_IOCTL_SERIAL_SET_PARAMS:
1638 QEMUSerialSetParams *ssp = arg;
1639 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1640 ssp->data_bits, ssp->stop_bits);
1642 break;
1643 case CHR_IOCTL_SERIAL_SET_BREAK:
1645 int enable = *(int *)arg;
1646 if (enable)
1647 tcsendbreak(s->fd_in, 1);
1649 break;
1650 default:
1651 return -ENOTSUP;
1653 return 0;
1656 CharDriverState *qemu_chr_open_tty(const char *filename)
1658 CharDriverState *chr;
1659 int fd;
1661 fd = open(filename, O_RDWR | O_NONBLOCK);
1662 if (fd < 0)
1663 return NULL;
1664 fcntl(fd, F_SETFL, O_NONBLOCK);
1665 tty_serial_init(fd, 115200, 'N', 8, 1);
1666 chr = qemu_chr_open_fd(fd, fd);
1667 if (!chr)
1668 return NULL;
1669 chr->chr_ioctl = tty_serial_ioctl;
1670 return chr;
1673 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1675 int fd = (int)chr->opaque;
1676 uint8_t b;
1678 switch(cmd) {
1679 case CHR_IOCTL_PP_READ_DATA:
1680 if (ioctl(fd, PPRDATA, &b) < 0)
1681 return -ENOTSUP;
1682 *(uint8_t *)arg = b;
1683 break;
1684 case CHR_IOCTL_PP_WRITE_DATA:
1685 b = *(uint8_t *)arg;
1686 if (ioctl(fd, PPWDATA, &b) < 0)
1687 return -ENOTSUP;
1688 break;
1689 case CHR_IOCTL_PP_READ_CONTROL:
1690 if (ioctl(fd, PPRCONTROL, &b) < 0)
1691 return -ENOTSUP;
1692 *(uint8_t *)arg = b;
1693 break;
1694 case CHR_IOCTL_PP_WRITE_CONTROL:
1695 b = *(uint8_t *)arg;
1696 if (ioctl(fd, PPWCONTROL, &b) < 0)
1697 return -ENOTSUP;
1698 break;
1699 case CHR_IOCTL_PP_READ_STATUS:
1700 if (ioctl(fd, PPRSTATUS, &b) < 0)
1701 return -ENOTSUP;
1702 *(uint8_t *)arg = b;
1703 break;
1704 default:
1705 return -ENOTSUP;
1707 return 0;
1710 CharDriverState *qemu_chr_open_pp(const char *filename)
1712 CharDriverState *chr;
1713 int fd;
1715 fd = open(filename, O_RDWR);
1716 if (fd < 0)
1717 return NULL;
1719 if (ioctl(fd, PPCLAIM) < 0) {
1720 close(fd);
1721 return NULL;
1724 chr = qemu_mallocz(sizeof(CharDriverState));
1725 if (!chr) {
1726 close(fd);
1727 return NULL;
1729 chr->opaque = (void *)fd;
1730 chr->chr_write = null_chr_write;
1731 chr->chr_add_read_handler = null_chr_add_read_handler;
1732 chr->chr_ioctl = pp_ioctl;
1733 return chr;
1736 #else
1737 CharDriverState *qemu_chr_open_pty(void)
1739 return NULL;
1741 #endif
1743 #endif /* !defined(_WIN32) */
1745 #ifdef _WIN32
1746 typedef struct {
1747 IOCanRWHandler *fd_can_read;
1748 IOReadHandler *fd_read;
1749 void *win_opaque;
1750 int max_size;
1751 HANDLE hcom, hrecv, hsend;
1752 OVERLAPPED orecv, osend;
1753 BOOL fpipe;
1754 DWORD len;
1755 } WinCharState;
1757 #define NSENDBUF 2048
1758 #define NRECVBUF 2048
1759 #define MAXCONNECT 1
1760 #define NTIMEOUT 5000
1762 static int win_chr_poll(void *opaque);
1763 static int win_chr_pipe_poll(void *opaque);
1765 static void win_chr_close2(WinCharState *s)
1767 if (s->hsend) {
1768 CloseHandle(s->hsend);
1769 s->hsend = NULL;
1771 if (s->hrecv) {
1772 CloseHandle(s->hrecv);
1773 s->hrecv = NULL;
1775 if (s->hcom) {
1776 CloseHandle(s->hcom);
1777 s->hcom = NULL;
1779 if (s->fpipe)
1780 qemu_del_polling_cb(win_chr_pipe_poll, s);
1781 else
1782 qemu_del_polling_cb(win_chr_poll, s);
1785 static void win_chr_close(CharDriverState *chr)
1787 WinCharState *s = chr->opaque;
1788 win_chr_close2(s);
1791 static int win_chr_init(WinCharState *s, const char *filename)
1793 COMMCONFIG comcfg;
1794 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1795 COMSTAT comstat;
1796 DWORD size;
1797 DWORD err;
1799 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1800 if (!s->hsend) {
1801 fprintf(stderr, "Failed CreateEvent\n");
1802 goto fail;
1804 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1805 if (!s->hrecv) {
1806 fprintf(stderr, "Failed CreateEvent\n");
1807 goto fail;
1810 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1811 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1812 if (s->hcom == INVALID_HANDLE_VALUE) {
1813 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1814 s->hcom = NULL;
1815 goto fail;
1818 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1819 fprintf(stderr, "Failed SetupComm\n");
1820 goto fail;
1823 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1824 size = sizeof(COMMCONFIG);
1825 GetDefaultCommConfig(filename, &comcfg, &size);
1826 comcfg.dcb.DCBlength = sizeof(DCB);
1827 CommConfigDialog(filename, NULL, &comcfg);
1829 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1830 fprintf(stderr, "Failed SetCommState\n");
1831 goto fail;
1834 if (!SetCommMask(s->hcom, EV_ERR)) {
1835 fprintf(stderr, "Failed SetCommMask\n");
1836 goto fail;
1839 cto.ReadIntervalTimeout = MAXDWORD;
1840 if (!SetCommTimeouts(s->hcom, &cto)) {
1841 fprintf(stderr, "Failed SetCommTimeouts\n");
1842 goto fail;
1845 if (!ClearCommError(s->hcom, &err, &comstat)) {
1846 fprintf(stderr, "Failed ClearCommError\n");
1847 goto fail;
1849 qemu_add_polling_cb(win_chr_poll, s);
1850 return 0;
1852 fail:
1853 win_chr_close2(s);
1854 return -1;
1857 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1859 WinCharState *s = chr->opaque;
1860 DWORD len, ret, size, err;
1862 len = len1;
1863 ZeroMemory(&s->osend, sizeof(s->osend));
1864 s->osend.hEvent = s->hsend;
1865 while (len > 0) {
1866 if (s->hsend)
1867 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1868 else
1869 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1870 if (!ret) {
1871 err = GetLastError();
1872 if (err == ERROR_IO_PENDING) {
1873 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1874 if (ret) {
1875 buf += size;
1876 len -= size;
1877 } else {
1878 break;
1880 } else {
1881 break;
1883 } else {
1884 buf += size;
1885 len -= size;
1888 return len1 - len;
1891 static int win_chr_read_poll(WinCharState *s)
1893 s->max_size = s->fd_can_read(s->win_opaque);
1894 return s->max_size;
1897 static void win_chr_readfile(WinCharState *s)
1899 int ret, err;
1900 uint8_t buf[1024];
1901 DWORD size;
1903 ZeroMemory(&s->orecv, sizeof(s->orecv));
1904 s->orecv.hEvent = s->hrecv;
1905 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1906 if (!ret) {
1907 err = GetLastError();
1908 if (err == ERROR_IO_PENDING) {
1909 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1913 if (size > 0) {
1914 s->fd_read(s->win_opaque, buf, size);
1918 static void win_chr_read(WinCharState *s)
1920 if (s->len > s->max_size)
1921 s->len = s->max_size;
1922 if (s->len == 0)
1923 return;
1925 win_chr_readfile(s);
1928 static int win_chr_poll(void *opaque)
1930 WinCharState *s = opaque;
1931 COMSTAT status;
1932 DWORD comerr;
1934 ClearCommError(s->hcom, &comerr, &status);
1935 if (status.cbInQue > 0) {
1936 s->len = status.cbInQue;
1937 win_chr_read_poll(s);
1938 win_chr_read(s);
1939 return 1;
1941 return 0;
1944 static void win_chr_add_read_handler(CharDriverState *chr,
1945 IOCanRWHandler *fd_can_read,
1946 IOReadHandler *fd_read, void *opaque)
1948 WinCharState *s = chr->opaque;
1950 s->fd_can_read = fd_can_read;
1951 s->fd_read = fd_read;
1952 s->win_opaque = opaque;
1955 CharDriverState *qemu_chr_open_win(const char *filename)
1957 CharDriverState *chr;
1958 WinCharState *s;
1960 chr = qemu_mallocz(sizeof(CharDriverState));
1961 if (!chr)
1962 return NULL;
1963 s = qemu_mallocz(sizeof(WinCharState));
1964 if (!s) {
1965 free(chr);
1966 return NULL;
1968 chr->opaque = s;
1969 chr->chr_write = win_chr_write;
1970 chr->chr_add_read_handler = win_chr_add_read_handler;
1971 chr->chr_close = win_chr_close;
1973 if (win_chr_init(s, filename) < 0) {
1974 free(s);
1975 free(chr);
1976 return NULL;
1978 return chr;
1981 static int win_chr_pipe_poll(void *opaque)
1983 WinCharState *s = opaque;
1984 DWORD size;
1986 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1987 if (size > 0) {
1988 s->len = size;
1989 win_chr_read_poll(s);
1990 win_chr_read(s);
1991 return 1;
1993 return 0;
1996 static int win_chr_pipe_init(WinCharState *s, const char *filename)
1998 OVERLAPPED ov;
1999 int ret;
2000 DWORD size;
2001 char openname[256];
2003 s->fpipe = TRUE;
2005 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2006 if (!s->hsend) {
2007 fprintf(stderr, "Failed CreateEvent\n");
2008 goto fail;
2010 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2011 if (!s->hrecv) {
2012 fprintf(stderr, "Failed CreateEvent\n");
2013 goto fail;
2016 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2017 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2018 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2019 PIPE_WAIT,
2020 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2021 if (s->hcom == INVALID_HANDLE_VALUE) {
2022 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2023 s->hcom = NULL;
2024 goto fail;
2027 ZeroMemory(&ov, sizeof(ov));
2028 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2029 ret = ConnectNamedPipe(s->hcom, &ov);
2030 if (ret) {
2031 fprintf(stderr, "Failed ConnectNamedPipe\n");
2032 goto fail;
2035 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2036 if (!ret) {
2037 fprintf(stderr, "Failed GetOverlappedResult\n");
2038 if (ov.hEvent) {
2039 CloseHandle(ov.hEvent);
2040 ov.hEvent = NULL;
2042 goto fail;
2045 if (ov.hEvent) {
2046 CloseHandle(ov.hEvent);
2047 ov.hEvent = NULL;
2049 qemu_add_polling_cb(win_chr_pipe_poll, s);
2050 return 0;
2052 fail:
2053 win_chr_close2(s);
2054 return -1;
2058 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2060 CharDriverState *chr;
2061 WinCharState *s;
2063 chr = qemu_mallocz(sizeof(CharDriverState));
2064 if (!chr)
2065 return NULL;
2066 s = qemu_mallocz(sizeof(WinCharState));
2067 if (!s) {
2068 free(chr);
2069 return NULL;
2071 chr->opaque = s;
2072 chr->chr_write = win_chr_write;
2073 chr->chr_add_read_handler = win_chr_add_read_handler;
2074 chr->chr_close = win_chr_close;
2076 if (win_chr_pipe_init(s, filename) < 0) {
2077 free(s);
2078 free(chr);
2079 return NULL;
2081 return chr;
2084 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2086 CharDriverState *chr;
2087 WinCharState *s;
2089 chr = qemu_mallocz(sizeof(CharDriverState));
2090 if (!chr)
2091 return NULL;
2092 s = qemu_mallocz(sizeof(WinCharState));
2093 if (!s) {
2094 free(chr);
2095 return NULL;
2097 s->hcom = fd_out;
2098 chr->opaque = s;
2099 chr->chr_write = win_chr_write;
2100 chr->chr_add_read_handler = win_chr_add_read_handler;
2101 return chr;
2104 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2106 HANDLE fd_out;
2108 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2109 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2110 if (fd_out == INVALID_HANDLE_VALUE)
2111 return NULL;
2113 return qemu_chr_open_win_file(fd_out);
2115 #endif
2117 /***********************************************************/
2118 /* UDP Net console */
2120 typedef struct {
2121 IOCanRWHandler *fd_can_read;
2122 IOReadHandler *fd_read;
2123 void *fd_opaque;
2124 int fd;
2125 struct sockaddr_in daddr;
2126 char buf[1024];
2127 int bufcnt;
2128 int bufptr;
2129 int max_size;
2130 } NetCharDriver;
2132 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2134 NetCharDriver *s = chr->opaque;
2136 return sendto(s->fd, buf, len, 0,
2137 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2140 static int udp_chr_read_poll(void *opaque)
2142 CharDriverState *chr = opaque;
2143 NetCharDriver *s = chr->opaque;
2145 s->max_size = s->fd_can_read(s->fd_opaque);
2147 /* If there were any stray characters in the queue process them
2148 * first
2150 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2151 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2152 s->bufptr++;
2153 s->max_size = s->fd_can_read(s->fd_opaque);
2155 return s->max_size;
2158 static void udp_chr_read(void *opaque)
2160 CharDriverState *chr = opaque;
2161 NetCharDriver *s = chr->opaque;
2163 if (s->max_size == 0)
2164 return;
2165 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2166 s->bufptr = s->bufcnt;
2167 if (s->bufcnt <= 0)
2168 return;
2170 s->bufptr = 0;
2171 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2172 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2173 s->bufptr++;
2174 s->max_size = s->fd_can_read(s->fd_opaque);
2178 static void udp_chr_add_read_handler(CharDriverState *chr,
2179 IOCanRWHandler *fd_can_read,
2180 IOReadHandler *fd_read, void *opaque)
2182 NetCharDriver *s = chr->opaque;
2184 if (s->fd >= 0) {
2185 s->fd_can_read = fd_can_read;
2186 s->fd_read = fd_read;
2187 s->fd_opaque = opaque;
2188 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2189 udp_chr_read, NULL, chr);
2193 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2194 int parse_host_unix_path(struct sockaddr_un *uaddr,
2195 const char *str,
2196 int sep);
2197 int parse_host_src_port(struct sockaddr_in *haddr,
2198 struct sockaddr_in *saddr,
2199 const char *str);
2201 CharDriverState *qemu_chr_open_udp(const char *def)
2203 CharDriverState *chr = NULL;
2204 NetCharDriver *s = NULL;
2205 int fd = -1;
2206 struct sockaddr_in saddr;
2208 chr = qemu_mallocz(sizeof(CharDriverState));
2209 if (!chr)
2210 goto return_err;
2211 s = qemu_mallocz(sizeof(NetCharDriver));
2212 if (!s)
2213 goto return_err;
2215 fd = socket(PF_INET, SOCK_DGRAM, 0);
2216 if (fd < 0) {
2217 perror("socket(PF_INET, SOCK_DGRAM)");
2218 goto return_err;
2221 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2222 printf("Could not parse: %s\n", def);
2223 goto return_err;
2226 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2228 perror("bind");
2229 goto return_err;
2232 s->fd = fd;
2233 s->bufcnt = 0;
2234 s->bufptr = 0;
2235 chr->opaque = s;
2236 chr->chr_write = udp_chr_write;
2237 chr->chr_add_read_handler = udp_chr_add_read_handler;
2238 return chr;
2240 return_err:
2241 if (chr)
2242 free(chr);
2243 if (s)
2244 free(s);
2245 if (fd >= 0)
2246 closesocket(fd);
2247 return NULL;
2250 /***********************************************************/
2251 /* TCP Net console */
2253 typedef struct {
2254 IOCanRWHandler *fd_can_read;
2255 IOReadHandler *fd_read;
2256 void *fd_opaque;
2257 int fd, listen_fd;
2258 int connected;
2259 int max_size;
2260 int do_telnetopt;
2261 } TCPCharDriver;
2263 static void tcp_chr_accept(void *opaque);
2265 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2267 TCPCharDriver *s = chr->opaque;
2268 if (s->connected) {
2269 return send_all(s->fd, buf, len);
2270 } else {
2271 /* XXX: indicate an error ? */
2272 return len;
2276 static int tcp_chr_read_poll(void *opaque)
2278 CharDriverState *chr = opaque;
2279 TCPCharDriver *s = chr->opaque;
2280 if (!s->connected)
2281 return 0;
2282 s->max_size = s->fd_can_read(s->fd_opaque);
2283 return s->max_size;
2286 #define IAC 255
2287 #define IAC_BREAK 243
2288 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2289 TCPCharDriver *s,
2290 char *buf, int *size)
2292 /* Handle any telnet client's basic IAC options to satisfy char by
2293 * char mode with no echo. All IAC options will be removed from
2294 * the buf and the do_telnetopt variable will be used to track the
2295 * state of the width of the IAC information.
2297 * IAC commands come in sets of 3 bytes with the exception of the
2298 * "IAC BREAK" command and the double IAC.
2301 int i;
2302 int j = 0;
2304 for (i = 0; i < *size; i++) {
2305 if (s->do_telnetopt > 1) {
2306 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2307 /* Double IAC means send an IAC */
2308 if (j != i)
2309 buf[j] = buf[i];
2310 j++;
2311 s->do_telnetopt = 1;
2312 } else {
2313 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2314 /* Handle IAC break commands by sending a serial break */
2315 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2316 s->do_telnetopt++;
2318 s->do_telnetopt++;
2320 if (s->do_telnetopt >= 4) {
2321 s->do_telnetopt = 1;
2323 } else {
2324 if ((unsigned char)buf[i] == IAC) {
2325 s->do_telnetopt = 2;
2326 } else {
2327 if (j != i)
2328 buf[j] = buf[i];
2329 j++;
2333 *size = j;
2336 static void tcp_chr_read(void *opaque)
2338 CharDriverState *chr = opaque;
2339 TCPCharDriver *s = chr->opaque;
2340 uint8_t buf[1024];
2341 int len, size;
2343 if (!s->connected || s->max_size <= 0)
2344 return;
2345 len = sizeof(buf);
2346 if (len > s->max_size)
2347 len = s->max_size;
2348 size = recv(s->fd, buf, len, 0);
2349 if (size == 0) {
2350 /* connection closed */
2351 s->connected = 0;
2352 if (s->listen_fd >= 0) {
2353 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2355 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2356 closesocket(s->fd);
2357 s->fd = -1;
2358 } else if (size > 0) {
2359 if (s->do_telnetopt)
2360 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2361 if (size > 0)
2362 s->fd_read(s->fd_opaque, buf, size);
2366 static void tcp_chr_add_read_handler(CharDriverState *chr,
2367 IOCanRWHandler *fd_can_read,
2368 IOReadHandler *fd_read, void *opaque)
2370 TCPCharDriver *s = chr->opaque;
2372 s->fd_can_read = fd_can_read;
2373 s->fd_read = fd_read;
2374 s->fd_opaque = opaque;
2377 static void tcp_chr_connect(void *opaque)
2379 CharDriverState *chr = opaque;
2380 TCPCharDriver *s = chr->opaque;
2382 s->connected = 1;
2383 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2384 tcp_chr_read, NULL, chr);
2387 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2388 static void tcp_chr_telnet_init(int fd)
2390 char buf[3];
2391 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2392 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2393 send(fd, (char *)buf, 3, 0);
2394 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2395 send(fd, (char *)buf, 3, 0);
2396 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2397 send(fd, (char *)buf, 3, 0);
2398 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2399 send(fd, (char *)buf, 3, 0);
2402 static void tcp_chr_accept(void *opaque)
2404 CharDriverState *chr = opaque;
2405 TCPCharDriver *s = chr->opaque;
2406 struct sockaddr_in saddr;
2407 socklen_t len;
2408 int fd;
2410 for(;;) {
2411 len = sizeof(saddr);
2412 fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2413 if (fd < 0 && errno != EINTR) {
2414 return;
2415 } else if (fd >= 0) {
2416 if (s->do_telnetopt)
2417 tcp_chr_telnet_init(fd);
2418 break;
2421 socket_set_nonblock(fd);
2422 s->fd = fd;
2423 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2424 tcp_chr_connect(chr);
2427 static void tcp_chr_close(CharDriverState *chr)
2429 TCPCharDriver *s = chr->opaque;
2430 if (s->fd >= 0)
2431 closesocket(s->fd);
2432 if (s->listen_fd >= 0)
2433 closesocket(s->listen_fd);
2434 qemu_free(s);
2437 static CharDriverState *qemu_chr_open_stream(const char *host_str,
2438 int is_telnet,
2439 int is_unix_domain)
2441 CharDriverState *chr = NULL;
2442 TCPCharDriver *s = NULL;
2443 int fd = -1, ret, err, val;
2444 int is_listen = 0;
2445 int is_waitconnect = 1;
2446 const char *ptr;
2447 struct sockaddr* addr;
2448 struct sockaddr_in saddr;
2449 struct sockaddr_un uaddr;
2450 int addrlen;
2452 #ifndef _WIN32
2453 if (is_unix_domain) {
2454 parse_host_unix_path(&uaddr, host_str, ',');
2455 addr = (struct sockaddr *)&uaddr;
2456 addrlen = sizeof(uaddr);
2457 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2458 } else
2459 #endif
2461 if (parse_host_port(&saddr, host_str) < 0)
2462 goto fail;
2463 addr = (struct sockaddr *)&saddr;
2464 addrlen = sizeof(saddr);
2465 fd = socket(PF_INET, SOCK_STREAM, 0);
2467 if (fd < 0)
2468 goto fail;
2470 ptr = host_str;
2471 while((ptr = strchr(ptr,','))) {
2472 ptr++;
2473 if (!strncmp(ptr,"server",6)) {
2474 is_listen = 1;
2475 } else if (!strncmp(ptr,"nowait",6)) {
2476 is_waitconnect = 0;
2477 } else {
2478 printf("Unknown option: %s\n", ptr);
2479 goto fail;
2482 if (!is_listen)
2483 is_waitconnect = 0;
2485 chr = qemu_mallocz(sizeof(CharDriverState));
2486 if (!chr)
2487 goto fail;
2488 s = qemu_mallocz(sizeof(TCPCharDriver));
2489 if (!s)
2490 goto fail;
2492 if (!is_waitconnect)
2493 socket_set_nonblock(fd);
2495 s->connected = 0;
2496 s->fd = -1;
2497 s->listen_fd = -1;
2498 if (is_listen) {
2499 /* allow fast reuse */
2500 val = 1;
2501 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2502 ret = bind(fd, (struct sockaddr *)addr, addrlen);
2503 if (ret < 0)
2504 goto fail;
2505 ret = listen(fd, 0);
2506 if (ret < 0)
2507 goto fail;
2508 s->listen_fd = fd;
2509 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2510 if (is_telnet)
2511 s->do_telnetopt = 1;
2512 } else {
2513 for(;;) {
2514 ret = connect(fd, (struct sockaddr *)addr, addrlen);
2515 if (ret < 0) {
2516 err = socket_error();
2517 if (err == EINTR || err == EWOULDBLOCK) {
2518 } else if (err == EINPROGRESS) {
2519 break;
2520 } else {
2521 goto fail;
2523 } else {
2524 s->connected = 1;
2525 break;
2528 s->fd = fd;
2529 if (s->connected)
2530 tcp_chr_connect(chr);
2531 else
2532 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2535 chr->opaque = s;
2536 chr->chr_write = tcp_chr_write;
2537 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2538 chr->chr_close = tcp_chr_close;
2539 if (is_listen && is_waitconnect) {
2540 printf("QEMU waiting for connection on: %s\n", host_str);
2541 tcp_chr_accept(chr);
2542 socket_set_nonblock(s->listen_fd);
2545 return chr;
2546 fail:
2547 if (fd >= 0)
2548 closesocket(fd);
2549 qemu_free(s);
2550 qemu_free(chr);
2551 return NULL;
2554 CharDriverState *qemu_chr_open(const char *filename)
2556 const char *p;
2558 if (!strcmp(filename, "vc")) {
2559 return text_console_init(&display_state);
2560 } else if (!strcmp(filename, "null")) {
2561 return qemu_chr_open_null();
2562 } else
2563 if (strstart(filename, "tcp:", &p)) {
2564 return qemu_chr_open_stream(p, 0, 0);
2565 } else
2566 if (strstart(filename, "telnet:", &p)) {
2567 return qemu_chr_open_stream(p, 1, 0);
2568 } else
2569 if (strstart(filename, "udp:", &p)) {
2570 return qemu_chr_open_udp(p);
2571 } else
2572 #ifndef _WIN32
2573 if (strstart(filename, "file:", &p)) {
2574 return qemu_chr_open_file_out(p);
2575 } else if (strstart(filename, "pipe:", &p)) {
2576 return qemu_chr_open_pipe(p);
2577 } else if (!strcmp(filename, "pty")) {
2578 return qemu_chr_open_pty();
2579 } else if (!strcmp(filename, "stdio")) {
2580 return qemu_chr_open_stdio();
2581 } else if (strstart(filename, "unix:", &p)) {
2582 return qemu_chr_open_stream(p, 0, 1);
2583 } else
2584 #endif
2585 #if defined(__linux__)
2586 if (strstart(filename, "/dev/parport", NULL)) {
2587 return qemu_chr_open_pp(filename);
2588 } else
2589 if (strstart(filename, "/dev/", NULL)) {
2590 return qemu_chr_open_tty(filename);
2591 } else
2592 #endif
2593 #ifdef _WIN32
2594 if (strstart(filename, "COM", NULL)) {
2595 return qemu_chr_open_win(filename);
2596 } else
2597 if (strstart(filename, "pipe:", &p)) {
2598 return qemu_chr_open_win_pipe(p);
2599 } else
2600 if (strstart(filename, "file:", &p)) {
2601 return qemu_chr_open_win_file_out(p);
2603 #endif
2605 return NULL;
2609 void qemu_chr_close(CharDriverState *chr)
2611 if (chr->chr_close)
2612 chr->chr_close(chr);
2615 /***********************************************************/
2616 /* network device redirectors */
2618 void hex_dump(FILE *f, const uint8_t *buf, int size)
2620 int len, i, j, c;
2622 for(i=0;i<size;i+=16) {
2623 len = size - i;
2624 if (len > 16)
2625 len = 16;
2626 fprintf(f, "%08x ", i);
2627 for(j=0;j<16;j++) {
2628 if (j < len)
2629 fprintf(f, " %02x", buf[i+j]);
2630 else
2631 fprintf(f, " ");
2633 fprintf(f, " ");
2634 for(j=0;j<len;j++) {
2635 c = buf[i+j];
2636 if (c < ' ' || c > '~')
2637 c = '.';
2638 fprintf(f, "%c", c);
2640 fprintf(f, "\n");
2644 static int parse_macaddr(uint8_t *macaddr, const char *p)
2646 int i;
2647 for(i = 0; i < 6; i++) {
2648 macaddr[i] = strtol(p, (char **)&p, 16);
2649 if (i == 5) {
2650 if (*p != '\0')
2651 return -1;
2652 } else {
2653 if (*p != ':')
2654 return -1;
2655 p++;
2658 return 0;
2661 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2663 const char *p, *p1;
2664 int len;
2665 p = *pp;
2666 p1 = strchr(p, sep);
2667 if (!p1)
2668 return -1;
2669 len = p1 - p;
2670 p1++;
2671 if (buf_size > 0) {
2672 if (len > buf_size - 1)
2673 len = buf_size - 1;
2674 memcpy(buf, p, len);
2675 buf[len] = '\0';
2677 *pp = p1;
2678 return 0;
2681 int parse_host_src_port(struct sockaddr_in *haddr,
2682 struct sockaddr_in *saddr,
2683 const char *input_str)
2685 char *str = strdup(input_str);
2686 char *host_str = str;
2687 char *src_str;
2688 char *ptr;
2691 * Chop off any extra arguments at the end of the string which
2692 * would start with a comma, then fill in the src port information
2693 * if it was provided else use the "any address" and "any port".
2695 if ((ptr = strchr(str,',')))
2696 *ptr = '\0';
2698 if ((src_str = strchr(input_str,'@'))) {
2699 *src_str = '\0';
2700 src_str++;
2703 if (parse_host_port(haddr, host_str) < 0)
2704 goto fail;
2706 if (!src_str || *src_str == '\0')
2707 src_str = ":0";
2709 if (parse_host_port(saddr, src_str) < 0)
2710 goto fail;
2712 free(str);
2713 return(0);
2715 fail:
2716 free(str);
2717 return -1;
2720 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2722 char buf[512];
2723 struct hostent *he;
2724 const char *p, *r;
2725 int port;
2727 p = str;
2728 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2729 return -1;
2730 saddr->sin_family = AF_INET;
2731 if (buf[0] == '\0') {
2732 saddr->sin_addr.s_addr = 0;
2733 } else {
2734 if (isdigit(buf[0])) {
2735 if (!inet_aton(buf, &saddr->sin_addr))
2736 return -1;
2737 } else {
2738 if ((he = gethostbyname(buf)) == NULL)
2739 return - 1;
2740 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2743 port = strtol(p, (char **)&r, 0);
2744 if (r == p)
2745 return -1;
2746 saddr->sin_port = htons(port);
2747 return 0;
2750 int parse_host_unix_path(struct sockaddr_un *uaddr, const char *str, int sep)
2752 const char *p;
2754 p = strchrnul(str, sep);
2755 uaddr->sun_family = AF_UNIX;
2756 memcpy(uaddr->sun_path, str, p - str);
2757 uaddr->sun_path[p-str] = '\0';
2758 unlink(uaddr->sun_path);
2760 return 0;
2764 /* find or alloc a new VLAN */
2765 VLANState *qemu_find_vlan(int id)
2767 VLANState **pvlan, *vlan;
2768 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2769 if (vlan->id == id)
2770 return vlan;
2772 vlan = qemu_mallocz(sizeof(VLANState));
2773 if (!vlan)
2774 return NULL;
2775 vlan->id = id;
2776 vlan->next = NULL;
2777 pvlan = &first_vlan;
2778 while (*pvlan != NULL)
2779 pvlan = &(*pvlan)->next;
2780 *pvlan = vlan;
2781 return vlan;
2784 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2785 IOReadHandler *fd_read,
2786 IOCanRWHandler *fd_can_read,
2787 void *opaque)
2789 VLANClientState *vc, **pvc;
2790 vc = qemu_mallocz(sizeof(VLANClientState));
2791 if (!vc)
2792 return NULL;
2793 vc->fd_read = fd_read;
2794 vc->fd_can_read = fd_can_read;
2795 vc->opaque = opaque;
2796 vc->vlan = vlan;
2798 vc->next = NULL;
2799 pvc = &vlan->first_client;
2800 while (*pvc != NULL)
2801 pvc = &(*pvc)->next;
2802 *pvc = vc;
2803 return vc;
2806 int qemu_can_send_packet(VLANClientState *vc1)
2808 VLANState *vlan = vc1->vlan;
2809 VLANClientState *vc;
2811 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2812 if (vc != vc1) {
2813 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2814 return 0;
2817 return 1;
2820 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2822 VLANState *vlan = vc1->vlan;
2823 VLANClientState *vc;
2825 #if 0
2826 printf("vlan %d send:\n", vlan->id);
2827 hex_dump(stdout, buf, size);
2828 #endif
2829 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2830 if (vc != vc1) {
2831 vc->fd_read(vc->opaque, buf, size);
2836 #if defined(CONFIG_SLIRP)
2838 /* slirp network adapter */
2840 static int slirp_inited;
2841 static VLANClientState *slirp_vc;
2843 int slirp_can_output(void)
2845 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2848 void slirp_output(const uint8_t *pkt, int pkt_len)
2850 #if 0
2851 printf("slirp output:\n");
2852 hex_dump(stdout, pkt, pkt_len);
2853 #endif
2854 if (!slirp_vc)
2855 return;
2856 qemu_send_packet(slirp_vc, pkt, pkt_len);
2859 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2861 #if 0
2862 printf("slirp input:\n");
2863 hex_dump(stdout, buf, size);
2864 #endif
2865 slirp_input(buf, size);
2868 static int net_slirp_init(VLANState *vlan)
2870 if (!slirp_inited) {
2871 slirp_inited = 1;
2872 slirp_init();
2874 slirp_vc = qemu_new_vlan_client(vlan,
2875 slirp_receive, NULL, NULL);
2876 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2877 return 0;
2880 static void net_slirp_redir(const char *redir_str)
2882 int is_udp;
2883 char buf[256], *r;
2884 const char *p;
2885 struct in_addr guest_addr;
2886 int host_port, guest_port;
2888 if (!slirp_inited) {
2889 slirp_inited = 1;
2890 slirp_init();
2893 p = redir_str;
2894 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2895 goto fail;
2896 if (!strcmp(buf, "tcp")) {
2897 is_udp = 0;
2898 } else if (!strcmp(buf, "udp")) {
2899 is_udp = 1;
2900 } else {
2901 goto fail;
2904 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2905 goto fail;
2906 host_port = strtol(buf, &r, 0);
2907 if (r == buf)
2908 goto fail;
2910 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2911 goto fail;
2912 if (buf[0] == '\0') {
2913 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2915 if (!inet_aton(buf, &guest_addr))
2916 goto fail;
2918 guest_port = strtol(p, &r, 0);
2919 if (r == p)
2920 goto fail;
2922 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2923 fprintf(stderr, "qemu: could not set up redirection\n");
2924 exit(1);
2926 return;
2927 fail:
2928 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2929 exit(1);
2932 #ifndef _WIN32
2934 char smb_dir[1024];
2936 static void smb_exit(void)
2938 DIR *d;
2939 struct dirent *de;
2940 char filename[1024];
2942 /* erase all the files in the directory */
2943 d = opendir(smb_dir);
2944 for(;;) {
2945 de = readdir(d);
2946 if (!de)
2947 break;
2948 if (strcmp(de->d_name, ".") != 0 &&
2949 strcmp(de->d_name, "..") != 0) {
2950 snprintf(filename, sizeof(filename), "%s/%s",
2951 smb_dir, de->d_name);
2952 unlink(filename);
2955 closedir(d);
2956 rmdir(smb_dir);
2959 /* automatic user mode samba server configuration */
2960 void net_slirp_smb(const char *exported_dir)
2962 char smb_conf[1024];
2963 char smb_cmdline[1024];
2964 FILE *f;
2966 if (!slirp_inited) {
2967 slirp_inited = 1;
2968 slirp_init();
2971 /* XXX: better tmp dir construction */
2972 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2973 if (mkdir(smb_dir, 0700) < 0) {
2974 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2975 exit(1);
2977 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2979 f = fopen(smb_conf, "w");
2980 if (!f) {
2981 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2982 exit(1);
2984 fprintf(f,
2985 "[global]\n"
2986 "private dir=%s\n"
2987 "smb ports=0\n"
2988 "socket address=127.0.0.1\n"
2989 "pid directory=%s\n"
2990 "lock directory=%s\n"
2991 "log file=%s/log.smbd\n"
2992 "smb passwd file=%s/smbpasswd\n"
2993 "security = share\n"
2994 "[qemu]\n"
2995 "path=%s\n"
2996 "read only=no\n"
2997 "guest ok=yes\n",
2998 smb_dir,
2999 smb_dir,
3000 smb_dir,
3001 smb_dir,
3002 smb_dir,
3003 exported_dir
3005 fclose(f);
3006 atexit(smb_exit);
3008 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
3009 smb_conf);
3011 slirp_add_exec(0, smb_cmdline, 4, 139);
3014 #endif /* !defined(_WIN32) */
3016 #endif /* CONFIG_SLIRP */
3018 #if !defined(_WIN32)
3020 typedef struct TAPState {
3021 VLANClientState *vc;
3022 int fd;
3023 } TAPState;
3025 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3027 TAPState *s = opaque;
3028 int ret;
3029 for(;;) {
3030 ret = write(s->fd, buf, size);
3031 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3032 } else {
3033 break;
3038 static void tap_send(void *opaque)
3040 TAPState *s = opaque;
3041 uint8_t buf[4096];
3042 int size;
3044 size = read(s->fd, buf, sizeof(buf));
3045 if (size > 0) {
3046 qemu_send_packet(s->vc, buf, size);
3050 /* fd support */
3052 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3054 TAPState *s;
3056 s = qemu_mallocz(sizeof(TAPState));
3057 if (!s)
3058 return NULL;
3059 s->fd = fd;
3060 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3061 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3062 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3063 return s;
3066 #ifdef _BSD
3067 static int tap_open(char *ifname, int ifname_size)
3069 int fd;
3070 char *dev;
3071 struct stat s;
3073 fd = open("/dev/tap", O_RDWR);
3074 if (fd < 0) {
3075 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3076 return -1;
3079 fstat(fd, &s);
3080 dev = devname(s.st_rdev, S_IFCHR);
3081 pstrcpy(ifname, ifname_size, dev);
3083 fcntl(fd, F_SETFL, O_NONBLOCK);
3084 return fd;
3086 #elif defined(__sun__)
3087 static int tap_open(char *ifname, int ifname_size)
3089 fprintf(stderr, "warning: tap_open not yet implemented\n");
3090 return -1;
3092 #else
3093 static int tap_open(char *ifname, int ifname_size)
3095 struct ifreq ifr;
3096 int fd, ret;
3098 fd = open("/dev/net/tun", O_RDWR);
3099 if (fd < 0) {
3100 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3101 return -1;
3103 memset(&ifr, 0, sizeof(ifr));
3104 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3105 if (ifname[0] != '\0')
3106 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3107 else
3108 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3109 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3110 if (ret != 0) {
3111 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3112 close(fd);
3113 return -1;
3115 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3116 fcntl(fd, F_SETFL, O_NONBLOCK);
3117 return fd;
3119 #endif
3121 static int net_tap_init(VLANState *vlan, const char *ifname1,
3122 const char *setup_script)
3124 TAPState *s;
3125 int pid, status, fd;
3126 char *args[3];
3127 char **parg;
3128 char ifname[128];
3130 if (ifname1 != NULL)
3131 pstrcpy(ifname, sizeof(ifname), ifname1);
3132 else
3133 ifname[0] = '\0';
3134 fd = tap_open(ifname, sizeof(ifname));
3135 if (fd < 0)
3136 return -1;
3138 if (!setup_script)
3139 setup_script = "";
3140 if (setup_script[0] != '\0') {
3141 /* try to launch network init script */
3142 pid = fork();
3143 if (pid >= 0) {
3144 if (pid == 0) {
3145 parg = args;
3146 *parg++ = (char *)setup_script;
3147 *parg++ = ifname;
3148 *parg++ = NULL;
3149 execv(setup_script, args);
3150 _exit(1);
3152 while (waitpid(pid, &status, 0) != pid);
3153 if (!WIFEXITED(status) ||
3154 WEXITSTATUS(status) != 0) {
3155 fprintf(stderr, "%s: could not launch network script\n",
3156 setup_script);
3157 return -1;
3161 s = net_tap_fd_init(vlan, fd);
3162 if (!s)
3163 return -1;
3164 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3165 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3166 return 0;
3169 #endif /* !_WIN32 */
3171 /* network connection */
3172 typedef struct NetSocketState {
3173 VLANClientState *vc;
3174 int fd;
3175 int state; /* 0 = getting length, 1 = getting data */
3176 int index;
3177 int packet_len;
3178 uint8_t buf[4096];
3179 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3180 } NetSocketState;
3182 typedef struct NetSocketListenState {
3183 VLANState *vlan;
3184 int fd;
3185 } NetSocketListenState;
3187 /* XXX: we consider we can send the whole packet without blocking */
3188 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3190 NetSocketState *s = opaque;
3191 uint32_t len;
3192 len = htonl(size);
3194 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3195 send_all(s->fd, buf, size);
3198 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3200 NetSocketState *s = opaque;
3201 sendto(s->fd, buf, size, 0,
3202 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3205 static void net_socket_send(void *opaque)
3207 NetSocketState *s = opaque;
3208 int l, size, err;
3209 uint8_t buf1[4096];
3210 const uint8_t *buf;
3212 size = recv(s->fd, buf1, sizeof(buf1), 0);
3213 if (size < 0) {
3214 err = socket_error();
3215 if (err != EWOULDBLOCK)
3216 goto eoc;
3217 } else if (size == 0) {
3218 /* end of connection */
3219 eoc:
3220 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3221 closesocket(s->fd);
3222 return;
3224 buf = buf1;
3225 while (size > 0) {
3226 /* reassemble a packet from the network */
3227 switch(s->state) {
3228 case 0:
3229 l = 4 - s->index;
3230 if (l > size)
3231 l = size;
3232 memcpy(s->buf + s->index, buf, l);
3233 buf += l;
3234 size -= l;
3235 s->index += l;
3236 if (s->index == 4) {
3237 /* got length */
3238 s->packet_len = ntohl(*(uint32_t *)s->buf);
3239 s->index = 0;
3240 s->state = 1;
3242 break;
3243 case 1:
3244 l = s->packet_len - s->index;
3245 if (l > size)
3246 l = size;
3247 memcpy(s->buf + s->index, buf, l);
3248 s->index += l;
3249 buf += l;
3250 size -= l;
3251 if (s->index >= s->packet_len) {
3252 qemu_send_packet(s->vc, s->buf, s->packet_len);
3253 s->index = 0;
3254 s->state = 0;
3256 break;
3261 static void net_socket_send_dgram(void *opaque)
3263 NetSocketState *s = opaque;
3264 int size;
3266 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3267 if (size < 0)
3268 return;
3269 if (size == 0) {
3270 /* end of connection */
3271 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3272 return;
3274 qemu_send_packet(s->vc, s->buf, size);
3277 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3279 struct ip_mreq imr;
3280 int fd;
3281 int val, ret;
3282 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3283 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3284 inet_ntoa(mcastaddr->sin_addr),
3285 (int)ntohl(mcastaddr->sin_addr.s_addr));
3286 return -1;
3289 fd = socket(PF_INET, SOCK_DGRAM, 0);
3290 if (fd < 0) {
3291 perror("socket(PF_INET, SOCK_DGRAM)");
3292 return -1;
3295 val = 1;
3296 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3297 (const char *)&val, sizeof(val));
3298 if (ret < 0) {
3299 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3300 goto fail;
3303 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3304 if (ret < 0) {
3305 perror("bind");
3306 goto fail;
3309 /* Add host to multicast group */
3310 imr.imr_multiaddr = mcastaddr->sin_addr;
3311 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3313 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3314 (const char *)&imr, sizeof(struct ip_mreq));
3315 if (ret < 0) {
3316 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3317 goto fail;
3320 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3321 val = 1;
3322 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3323 (const char *)&val, sizeof(val));
3324 if (ret < 0) {
3325 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3326 goto fail;
3329 socket_set_nonblock(fd);
3330 return fd;
3331 fail:
3332 if (fd >= 0)
3333 closesocket(fd);
3334 return -1;
3337 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3338 int is_connected)
3340 struct sockaddr_in saddr;
3341 int newfd;
3342 socklen_t saddr_len;
3343 NetSocketState *s;
3345 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3346 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3347 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3350 if (is_connected) {
3351 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3352 /* must be bound */
3353 if (saddr.sin_addr.s_addr==0) {
3354 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3355 fd);
3356 return NULL;
3358 /* clone dgram socket */
3359 newfd = net_socket_mcast_create(&saddr);
3360 if (newfd < 0) {
3361 /* error already reported by net_socket_mcast_create() */
3362 close(fd);
3363 return NULL;
3365 /* clone newfd to fd, close newfd */
3366 dup2(newfd, fd);
3367 close(newfd);
3369 } else {
3370 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3371 fd, strerror(errno));
3372 return NULL;
3376 s = qemu_mallocz(sizeof(NetSocketState));
3377 if (!s)
3378 return NULL;
3379 s->fd = fd;
3381 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3382 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3384 /* mcast: save bound address as dst */
3385 if (is_connected) s->dgram_dst=saddr;
3387 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3388 "socket: fd=%d (%s mcast=%s:%d)",
3389 fd, is_connected? "cloned" : "",
3390 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3391 return s;
3394 static void net_socket_connect(void *opaque)
3396 NetSocketState *s = opaque;
3397 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3400 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3401 int is_connected)
3403 NetSocketState *s;
3404 s = qemu_mallocz(sizeof(NetSocketState));
3405 if (!s)
3406 return NULL;
3407 s->fd = fd;
3408 s->vc = qemu_new_vlan_client(vlan,
3409 net_socket_receive, NULL, s);
3410 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3411 "socket: fd=%d", fd);
3412 if (is_connected) {
3413 net_socket_connect(s);
3414 } else {
3415 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3417 return s;
3420 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3421 int is_connected)
3423 int so_type=-1, optlen=sizeof(so_type);
3425 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3426 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3427 return NULL;
3429 switch(so_type) {
3430 case SOCK_DGRAM:
3431 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3432 case SOCK_STREAM:
3433 return net_socket_fd_init_stream(vlan, fd, is_connected);
3434 default:
3435 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3436 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3437 return net_socket_fd_init_stream(vlan, fd, is_connected);
3439 return NULL;
3442 static void net_socket_accept(void *opaque)
3444 NetSocketListenState *s = opaque;
3445 NetSocketState *s1;
3446 struct sockaddr_in saddr;
3447 socklen_t len;
3448 int fd;
3450 for(;;) {
3451 len = sizeof(saddr);
3452 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3453 if (fd < 0 && errno != EINTR) {
3454 return;
3455 } else if (fd >= 0) {
3456 break;
3459 s1 = net_socket_fd_init(s->vlan, fd, 1);
3460 if (!s1) {
3461 closesocket(fd);
3462 } else {
3463 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3464 "socket: connection from %s:%d",
3465 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3469 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3471 NetSocketListenState *s;
3472 int fd, val, ret;
3473 struct sockaddr_in saddr;
3475 if (parse_host_port(&saddr, host_str) < 0)
3476 return -1;
3478 s = qemu_mallocz(sizeof(NetSocketListenState));
3479 if (!s)
3480 return -1;
3482 fd = socket(PF_INET, SOCK_STREAM, 0);
3483 if (fd < 0) {
3484 perror("socket");
3485 return -1;
3487 socket_set_nonblock(fd);
3489 /* allow fast reuse */
3490 val = 1;
3491 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3493 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3494 if (ret < 0) {
3495 perror("bind");
3496 return -1;
3498 ret = listen(fd, 0);
3499 if (ret < 0) {
3500 perror("listen");
3501 return -1;
3503 s->vlan = vlan;
3504 s->fd = fd;
3505 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3506 return 0;
3509 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3511 NetSocketState *s;
3512 int fd, connected, ret, err;
3513 struct sockaddr_in saddr;
3515 if (parse_host_port(&saddr, host_str) < 0)
3516 return -1;
3518 fd = socket(PF_INET, SOCK_STREAM, 0);
3519 if (fd < 0) {
3520 perror("socket");
3521 return -1;
3523 socket_set_nonblock(fd);
3525 connected = 0;
3526 for(;;) {
3527 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3528 if (ret < 0) {
3529 err = socket_error();
3530 if (err == EINTR || err == EWOULDBLOCK) {
3531 } else if (err == EINPROGRESS) {
3532 break;
3533 } else {
3534 perror("connect");
3535 closesocket(fd);
3536 return -1;
3538 } else {
3539 connected = 1;
3540 break;
3543 s = net_socket_fd_init(vlan, fd, connected);
3544 if (!s)
3545 return -1;
3546 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3547 "socket: connect to %s:%d",
3548 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3549 return 0;
3552 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3554 NetSocketState *s;
3555 int fd;
3556 struct sockaddr_in saddr;
3558 if (parse_host_port(&saddr, host_str) < 0)
3559 return -1;
3562 fd = net_socket_mcast_create(&saddr);
3563 if (fd < 0)
3564 return -1;
3566 s = net_socket_fd_init(vlan, fd, 0);
3567 if (!s)
3568 return -1;
3570 s->dgram_dst = saddr;
3572 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3573 "socket: mcast=%s:%d",
3574 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3575 return 0;
3579 static int get_param_value(char *buf, int buf_size,
3580 const char *tag, const char *str)
3582 const char *p;
3583 char *q;
3584 char option[128];
3586 p = str;
3587 for(;;) {
3588 q = option;
3589 while (*p != '\0' && *p != '=') {
3590 if ((q - option) < sizeof(option) - 1)
3591 *q++ = *p;
3592 p++;
3594 *q = '\0';
3595 if (*p != '=')
3596 break;
3597 p++;
3598 if (!strcmp(tag, option)) {
3599 q = buf;
3600 while (*p != '\0' && *p != ',') {
3601 if ((q - buf) < buf_size - 1)
3602 *q++ = *p;
3603 p++;
3605 *q = '\0';
3606 return q - buf;
3607 } else {
3608 while (*p != '\0' && *p != ',') {
3609 p++;
3612 if (*p != ',')
3613 break;
3614 p++;
3616 return 0;
3619 int net_client_init(const char *str)
3621 const char *p;
3622 char *q;
3623 char device[64];
3624 char buf[1024];
3625 int vlan_id, ret;
3626 VLANState *vlan;
3628 p = str;
3629 q = device;
3630 while (*p != '\0' && *p != ',') {
3631 if ((q - device) < sizeof(device) - 1)
3632 *q++ = *p;
3633 p++;
3635 *q = '\0';
3636 if (*p == ',')
3637 p++;
3638 vlan_id = 0;
3639 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3640 vlan_id = strtol(buf, NULL, 0);
3642 vlan = qemu_find_vlan(vlan_id);
3643 if (!vlan) {
3644 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3645 return -1;
3647 if (!strcmp(device, "nic")) {
3648 NICInfo *nd;
3649 uint8_t *macaddr;
3651 if (nb_nics >= MAX_NICS) {
3652 fprintf(stderr, "Too Many NICs\n");
3653 return -1;
3655 nd = &nd_table[nb_nics];
3656 macaddr = nd->macaddr;
3657 macaddr[0] = 0x52;
3658 macaddr[1] = 0x54;
3659 macaddr[2] = 0x00;
3660 macaddr[3] = 0x12;
3661 macaddr[4] = 0x34;
3662 macaddr[5] = 0x56 + nb_nics;
3664 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3665 if (parse_macaddr(macaddr, buf) < 0) {
3666 fprintf(stderr, "invalid syntax for ethernet address\n");
3667 return -1;
3670 if (get_param_value(buf, sizeof(buf), "model", p)) {
3671 nd->model = strdup(buf);
3673 nd->vlan = vlan;
3674 nb_nics++;
3675 ret = 0;
3676 } else
3677 if (!strcmp(device, "none")) {
3678 /* does nothing. It is needed to signal that no network cards
3679 are wanted */
3680 ret = 0;
3681 } else
3682 #ifdef CONFIG_SLIRP
3683 if (!strcmp(device, "user")) {
3684 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3685 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3687 ret = net_slirp_init(vlan);
3688 } else
3689 #endif
3690 #ifdef _WIN32
3691 if (!strcmp(device, "tap")) {
3692 char ifname[64];
3693 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3694 fprintf(stderr, "tap: no interface name\n");
3695 return -1;
3697 ret = tap_win32_init(vlan, ifname);
3698 } else
3699 #else
3700 if (!strcmp(device, "tap")) {
3701 char ifname[64];
3702 char setup_script[1024];
3703 int fd;
3704 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3705 fd = strtol(buf, NULL, 0);
3706 ret = -1;
3707 if (net_tap_fd_init(vlan, fd))
3708 ret = 0;
3709 } else {
3710 get_param_value(ifname, sizeof(ifname), "ifname", p);
3711 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3712 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3714 ret = net_tap_init(vlan, ifname, setup_script);
3716 } else
3717 #endif
3718 if (!strcmp(device, "socket")) {
3719 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3720 int fd;
3721 fd = strtol(buf, NULL, 0);
3722 ret = -1;
3723 if (net_socket_fd_init(vlan, fd, 1))
3724 ret = 0;
3725 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3726 ret = net_socket_listen_init(vlan, buf);
3727 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3728 ret = net_socket_connect_init(vlan, buf);
3729 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3730 ret = net_socket_mcast_init(vlan, buf);
3731 } else {
3732 fprintf(stderr, "Unknown socket options: %s\n", p);
3733 return -1;
3735 } else
3737 fprintf(stderr, "Unknown network device: %s\n", device);
3738 return -1;
3740 if (ret < 0) {
3741 fprintf(stderr, "Could not initialize device '%s'\n", device);
3744 return ret;
3747 void do_info_network(void)
3749 VLANState *vlan;
3750 VLANClientState *vc;
3752 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3753 term_printf("VLAN %d devices:\n", vlan->id);
3754 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3755 term_printf(" %s\n", vc->info_str);
3759 #if defined(__linux__)
3760 #define SELF_ANNOUNCE_ROUNDS 5
3761 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
3762 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
3763 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
3764 int announce_self_create(unsigned char *buf,
3765 unsigned char mac_addr[ETH_ALEN])
3767 struct ethhdr *eh = (struct ethhdr*)buf;
3768 uint32_t *magic = (uint32_t*)(eh+1);
3769 unsigned char *p = (unsigned char*)(magic + 1);
3771 /* FIXME: should we send a different packet (arp/rarp/ping)? */
3773 /* ethernet header */
3774 memset(eh->h_dest, 0xff, ETH_ALEN);
3775 memcpy(eh->h_source, mac_addr, ETH_ALEN);
3776 eh->h_proto = htons(ETH_P_EXPERIMENTAL);
3778 /* magic data */
3779 *magic = EXPERIMENTAL_MAGIC;
3781 return p - buf; /* sizeof(*eh) + sizeof(*magic) */
3784 void qemu_tap_announce_self(void)
3786 int i, j, len;
3787 VLANState *vlan;
3788 VLANClientState *vc;
3789 uint8_t buf[256];
3791 for (i=0; i<nb_nics; i++) { /* for all nics */
3792 len = announce_self_create(buf, nd_table[i].macaddr);
3793 vlan = nd_table[i].vlan;
3794 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3795 if (vc->fd_read == tap_receive) { /* send only if tap */
3796 for (j=0; j<SELF_ANNOUNCE_ROUNDS ; j++) {
3797 vc->fd_read(vc->opaque, buf, len);
3800 } /* for vc -- look for tap_receive */
3801 } /* for i -- all nics */
3803 #else
3804 void qemu_tap_announce_self(void) {}
3805 #endif
3806 /***********************************************************/
3807 /* USB devices */
3809 static USBPort *used_usb_ports;
3810 static USBPort *free_usb_ports;
3812 /* ??? Maybe change this to register a hub to keep track of the topology. */
3813 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3814 usb_attachfn attach)
3816 port->opaque = opaque;
3817 port->index = index;
3818 port->attach = attach;
3819 port->next = free_usb_ports;
3820 free_usb_ports = port;
3823 static int usb_device_add(const char *devname)
3825 const char *p;
3826 USBDevice *dev;
3827 USBPort *port;
3829 if (!free_usb_ports)
3830 return -1;
3832 if (strstart(devname, "host:", &p)) {
3833 dev = usb_host_device_open(p);
3834 } else if (!strcmp(devname, "mouse")) {
3835 dev = usb_mouse_init();
3836 } else if (!strcmp(devname, "tablet")) {
3837 dev = usb_tablet_init();
3838 } else if (strstart(devname, "disk:", &p)) {
3839 dev = usb_msd_init(p);
3840 } else {
3841 return -1;
3843 if (!dev)
3844 return -1;
3846 /* Find a USB port to add the device to. */
3847 port = free_usb_ports;
3848 if (!port->next) {
3849 USBDevice *hub;
3851 /* Create a new hub and chain it on. */
3852 free_usb_ports = NULL;
3853 port->next = used_usb_ports;
3854 used_usb_ports = port;
3856 hub = usb_hub_init(VM_USB_HUB_SIZE);
3857 usb_attach(port, hub);
3858 port = free_usb_ports;
3861 free_usb_ports = port->next;
3862 port->next = used_usb_ports;
3863 used_usb_ports = port;
3864 usb_attach(port, dev);
3865 return 0;
3868 static int usb_device_del(const char *devname)
3870 USBPort *port;
3871 USBPort **lastp;
3872 USBDevice *dev;
3873 int bus_num, addr;
3874 const char *p;
3876 if (!used_usb_ports)
3877 return -1;
3879 p = strchr(devname, '.');
3880 if (!p)
3881 return -1;
3882 bus_num = strtoul(devname, NULL, 0);
3883 addr = strtoul(p + 1, NULL, 0);
3884 if (bus_num != 0)
3885 return -1;
3887 lastp = &used_usb_ports;
3888 port = used_usb_ports;
3889 while (port && port->dev->addr != addr) {
3890 lastp = &port->next;
3891 port = port->next;
3894 if (!port)
3895 return -1;
3897 dev = port->dev;
3898 *lastp = port->next;
3899 usb_attach(port, NULL);
3900 dev->handle_destroy(dev);
3901 port->next = free_usb_ports;
3902 free_usb_ports = port;
3903 return 0;
3906 void do_usb_add(const char *devname)
3908 int ret;
3909 ret = usb_device_add(devname);
3910 if (ret < 0)
3911 term_printf("Could not add USB device '%s'\n", devname);
3914 void do_usb_del(const char *devname)
3916 int ret;
3917 ret = usb_device_del(devname);
3918 if (ret < 0)
3919 term_printf("Could not remove USB device '%s'\n", devname);
3922 void usb_info(void)
3924 USBDevice *dev;
3925 USBPort *port;
3926 const char *speed_str;
3928 if (!usb_enabled) {
3929 term_printf("USB support not enabled\n");
3930 return;
3933 for (port = used_usb_ports; port; port = port->next) {
3934 dev = port->dev;
3935 if (!dev)
3936 continue;
3937 switch(dev->speed) {
3938 case USB_SPEED_LOW:
3939 speed_str = "1.5";
3940 break;
3941 case USB_SPEED_FULL:
3942 speed_str = "12";
3943 break;
3944 case USB_SPEED_HIGH:
3945 speed_str = "480";
3946 break;
3947 default:
3948 speed_str = "?";
3949 break;
3951 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
3952 0, dev->addr, speed_str, dev->devname);
3956 /***********************************************************/
3957 /* pid file */
3959 static char *pid_filename;
3961 /* Remove PID file. Called on normal exit */
3963 static void remove_pidfile(void)
3965 unlink (pid_filename);
3968 static void create_pidfile(const char *filename)
3970 struct stat pidstat;
3971 FILE *f;
3973 /* Try to write our PID to the named file */
3974 if (stat(filename, &pidstat) < 0) {
3975 if (errno == ENOENT) {
3976 if ((f = fopen (filename, "w")) == NULL) {
3977 perror("Opening pidfile");
3978 exit(1);
3980 fprintf(f, "%d\n", getpid());
3981 fclose(f);
3982 pid_filename = qemu_strdup(filename);
3983 if (!pid_filename) {
3984 fprintf(stderr, "Could not save PID filename");
3985 exit(1);
3987 atexit(remove_pidfile);
3989 } else {
3990 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3991 filename);
3992 exit(1);
3996 /***********************************************************/
3997 /* dumb display */
3999 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4003 static void dumb_resize(DisplayState *ds, int w, int h)
4007 static void dumb_refresh(DisplayState *ds)
4009 vga_hw_update();
4012 void dumb_display_init(DisplayState *ds)
4014 ds->data = NULL;
4015 ds->linesize = 0;
4016 ds->depth = 0;
4017 ds->dpy_update = dumb_update;
4018 ds->dpy_resize = dumb_resize;
4019 ds->dpy_refresh = dumb_refresh;
4022 /***********************************************************/
4023 /* I/O handling */
4025 #define MAX_IO_HANDLERS 64
4027 typedef struct IOHandlerRecord {
4028 int fd;
4029 IOCanRWHandler *fd_read_poll;
4030 IOHandler *fd_read;
4031 IOHandler *fd_write;
4032 void *opaque;
4033 /* temporary data */
4034 struct pollfd *ufd;
4035 struct IOHandlerRecord *next;
4036 } IOHandlerRecord;
4038 static IOHandlerRecord *first_io_handler;
4040 /* XXX: fd_read_poll should be suppressed, but an API change is
4041 necessary in the character devices to suppress fd_can_read(). */
4042 int qemu_set_fd_handler2(int fd,
4043 IOCanRWHandler *fd_read_poll,
4044 IOHandler *fd_read,
4045 IOHandler *fd_write,
4046 void *opaque)
4048 IOHandlerRecord **pioh, *ioh;
4050 if (!fd_read && !fd_write) {
4051 pioh = &first_io_handler;
4052 for(;;) {
4053 ioh = *pioh;
4054 if (ioh == NULL)
4055 break;
4056 if (ioh->fd == fd) {
4057 *pioh = ioh->next;
4058 qemu_free(ioh);
4059 break;
4061 pioh = &ioh->next;
4063 } else {
4064 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4065 if (ioh->fd == fd)
4066 goto found;
4068 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4069 if (!ioh)
4070 return -1;
4071 ioh->next = first_io_handler;
4072 first_io_handler = ioh;
4073 found:
4074 ioh->fd = fd;
4075 ioh->fd_read_poll = fd_read_poll;
4076 ioh->fd_read = fd_read;
4077 ioh->fd_write = fd_write;
4078 ioh->opaque = opaque;
4080 return 0;
4083 int qemu_set_fd_handler(int fd,
4084 IOHandler *fd_read,
4085 IOHandler *fd_write,
4086 void *opaque)
4088 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4091 /***********************************************************/
4092 /* Polling handling */
4094 typedef struct PollingEntry {
4095 PollingFunc *func;
4096 void *opaque;
4097 struct PollingEntry *next;
4098 } PollingEntry;
4100 static PollingEntry *first_polling_entry;
4102 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4104 PollingEntry **ppe, *pe;
4105 pe = qemu_mallocz(sizeof(PollingEntry));
4106 if (!pe)
4107 return -1;
4108 pe->func = func;
4109 pe->opaque = opaque;
4110 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4111 *ppe = pe;
4112 return 0;
4115 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4117 PollingEntry **ppe, *pe;
4118 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4119 pe = *ppe;
4120 if (pe->func == func && pe->opaque == opaque) {
4121 *ppe = pe->next;
4122 qemu_free(pe);
4123 break;
4128 #ifdef _WIN32
4129 /***********************************************************/
4130 /* Wait objects support */
4131 typedef struct WaitObjects {
4132 int num;
4133 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4134 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4135 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4136 } WaitObjects;
4138 static WaitObjects wait_objects = {0};
4140 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4142 WaitObjects *w = &wait_objects;
4144 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4145 return -1;
4146 w->events[w->num] = handle;
4147 w->func[w->num] = func;
4148 w->opaque[w->num] = opaque;
4149 w->num++;
4150 return 0;
4153 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4155 int i, found;
4156 WaitObjects *w = &wait_objects;
4158 found = 0;
4159 for (i = 0; i < w->num; i++) {
4160 if (w->events[i] == handle)
4161 found = 1;
4162 if (found) {
4163 w->events[i] = w->events[i + 1];
4164 w->func[i] = w->func[i + 1];
4165 w->opaque[i] = w->opaque[i + 1];
4168 if (found)
4169 w->num--;
4171 #endif
4173 /***********************************************************/
4174 /* savevm/loadvm support */
4176 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4178 f->put_buffer(f, buf, size);
4181 void qemu_put_byte(QEMUFile *f, int v)
4183 f->put_byte(f, v);
4186 void qemu_put_be16(QEMUFile *f, unsigned int v)
4188 qemu_put_byte(f, v >> 8);
4189 qemu_put_byte(f, v);
4192 void qemu_put_be32(QEMUFile *f, unsigned int v)
4194 qemu_put_byte(f, v >> 24);
4195 qemu_put_byte(f, v >> 16);
4196 qemu_put_byte(f, v >> 8);
4197 qemu_put_byte(f, v);
4200 void qemu_put_be64(QEMUFile *f, uint64_t v)
4202 qemu_put_be32(f, v >> 32);
4203 qemu_put_be32(f, v);
4206 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4208 return f->get_buffer(f, buf, size);
4211 int qemu_get_byte(QEMUFile *f)
4213 return f->get_byte(f);
4216 unsigned int qemu_get_be16(QEMUFile *f)
4218 unsigned int v;
4219 v = qemu_get_byte(f) << 8;
4220 v |= qemu_get_byte(f);
4221 return v;
4224 unsigned int qemu_get_be32(QEMUFile *f)
4226 unsigned int v;
4227 v = qemu_get_byte(f) << 24;
4228 v |= qemu_get_byte(f) << 16;
4229 v |= qemu_get_byte(f) << 8;
4230 v |= qemu_get_byte(f);
4231 return v;
4234 uint64_t qemu_get_be64(QEMUFile *f)
4236 uint64_t v;
4237 v = (uint64_t)qemu_get_be32(f) << 32;
4238 v |= qemu_get_be32(f);
4239 return v;
4242 int64_t qemu_ftell(QEMUFile *f)
4244 return f->tell(f);
4247 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4249 return f->seek(f, pos, whence);
4252 typedef struct SaveStateEntry {
4253 char idstr[256];
4254 int instance_id;
4255 int version_id;
4256 SaveStateHandler *save_state;
4257 LoadStateHandler *load_state;
4258 void *opaque;
4259 struct SaveStateEntry *next;
4260 } SaveStateEntry;
4262 static SaveStateEntry *first_se;
4264 int register_savevm(const char *idstr,
4265 int instance_id,
4266 int version_id,
4267 SaveStateHandler *save_state,
4268 LoadStateHandler *load_state,
4269 void *opaque)
4271 SaveStateEntry *se, **pse;
4273 se = qemu_malloc(sizeof(SaveStateEntry));
4274 if (!se)
4275 return -1;
4276 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4277 se->instance_id = instance_id;
4278 se->version_id = version_id;
4279 se->save_state = save_state;
4280 se->load_state = load_state;
4281 se->opaque = opaque;
4282 se->next = NULL;
4284 /* add at the end of list */
4285 pse = &first_se;
4286 while (*pse != NULL)
4287 pse = &(*pse)->next;
4288 *pse = se;
4289 return 0;
4292 #define QEMU_VM_FILE_MAGIC 0x5145564d
4293 #define QEMU_VM_FILE_VERSION 0x00000001
4296 static int qemu_savevm_method_file_open(QEMUFile *f, const char *filename,
4297 const char *flags)
4299 FILE *fp = fopen(filename, flags);
4300 f->opaque = (void*)fp;
4301 if (!fp)
4302 return -1;
4303 return 0;
4306 static void qemu_savevm_method_file_close(QEMUFile *f)
4308 FILE *fp = (FILE*)f->opaque;
4309 if (fp)
4310 fclose(fp);
4313 static void qemu_savevm_method_file_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4315 FILE *fp = (FILE*)f->opaque;
4316 fwrite(buf, 1, size, fp);
4319 static void qemu_savevm_method_file_put_byte(QEMUFile *f, int v)
4321 FILE *fp = (FILE*)f->opaque;
4322 fputc(v, fp);
4325 static int qemu_savevm_method_file_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4327 FILE *fp = (FILE*)f->opaque;
4328 return fread(buf, 1, size, fp);
4331 static int qemu_savevm_method_file_get_byte(QEMUFile *f)
4333 FILE *fp = (FILE*)f->opaque;
4334 int v;
4336 v = fgetc(fp);
4337 if (v == EOF)
4338 return 0;
4339 else
4340 return v;
4343 static int64_t qemu_savevm_method_file_tell(QEMUFile *f)
4345 FILE *fp = (FILE*)f->opaque;
4346 return ftell(fp);
4349 static int64_t qemu_savevm_method_file_seek(QEMUFile *f, int64_t pos, int whence)
4351 FILE *fp = (FILE*)f->opaque;
4352 if (fseek(fp, pos, whence) < 0)
4353 return -1;
4354 return ftell(fp);
4357 static int qemu_savevm_method_file_eof(QEMUFile *f)
4359 FILE *fp = (FILE*)f->opaque;
4360 return feof(fp);
4363 QEMUFile qemu_savevm_method_file = {
4364 .opaque = NULL,
4365 .open = qemu_savevm_method_file_open,
4366 .close = qemu_savevm_method_file_close,
4367 .put_byte = qemu_savevm_method_file_put_byte,
4368 .get_byte = qemu_savevm_method_file_get_byte,
4369 .put_buffer = qemu_savevm_method_file_put_buffer,
4370 .get_buffer = qemu_savevm_method_file_get_buffer,
4371 .tell = qemu_savevm_method_file_tell,
4372 .seek = qemu_savevm_method_file_seek,
4373 .eof = qemu_savevm_method_file_eof
4377 int qemu_savevm(const char *filename, QEMUFile *f)
4379 SaveStateEntry *se;
4380 int len, len_pos, cur_pos, saved_vm_running, ret;
4382 saved_vm_running = vm_running;
4383 vm_stop(0);
4385 if (f->open(f, filename, "wb")) {
4386 ret = -1;
4387 goto the_end;
4390 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4391 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4393 for(se = first_se; se != NULL; se = se->next) {
4394 /* ID string */
4395 len = strlen(se->idstr);
4396 qemu_put_byte(f, len);
4397 qemu_put_buffer(f, se->idstr, len);
4399 qemu_put_be32(f, se->instance_id);
4400 qemu_put_be32(f, se->version_id);
4402 /* record size: filled later */
4403 len_pos = qemu_ftell(f);
4404 qemu_put_be32(f, 0);
4406 se->save_state(f, se->opaque);
4408 /* fill record size */
4409 cur_pos = qemu_ftell(f);
4410 len = qemu_ftell(f) - len_pos - 4;
4411 qemu_fseek(f, len_pos, SEEK_SET);
4412 qemu_put_be32(f, len);
4413 qemu_fseek(f, cur_pos, SEEK_SET);
4415 qemu_put_byte(f, 0); /* len==0 represents end of state */
4416 f->close(f);
4417 ret = 0;
4418 the_end:
4419 if (saved_vm_running)
4420 vm_start();
4421 return ret;
4424 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4426 SaveStateEntry *se;
4428 for(se = first_se; se != NULL; se = se->next) {
4429 if (!strcmp(se->idstr, idstr) &&
4430 instance_id == se->instance_id)
4431 return se;
4433 return NULL;
4436 int qemu_loadvm(const char *filename, QEMUFile *f)
4438 SaveStateEntry *se;
4439 int len, cur_pos, ret, instance_id, record_len, version_id;
4440 int saved_vm_running;
4441 unsigned int v;
4442 char idstr[256];
4444 saved_vm_running = vm_running;
4445 vm_stop(0);
4447 if (f->open(f, filename, "rb")) {
4448 ret = -1;
4449 goto the_end;
4452 v = qemu_get_be32(f);
4453 if (v != QEMU_VM_FILE_MAGIC)
4454 goto fail;
4455 v = qemu_get_be32(f);
4456 if (v != QEMU_VM_FILE_VERSION) {
4457 fail:
4458 f->close(f);
4459 ret = -1;
4460 goto the_end;
4462 for(;;) {
4463 len = qemu_get_byte(f);
4464 if (f->eof(f) || len==0)
4465 break;
4466 qemu_get_buffer(f, idstr, len);
4467 idstr[len] = '\0';
4468 instance_id = qemu_get_be32(f);
4469 version_id = qemu_get_be32(f);
4470 record_len = qemu_get_be32(f);
4471 #if 0
4472 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4473 idstr, instance_id, version_id, record_len);
4474 #endif
4475 cur_pos = qemu_ftell(f);
4476 se = find_se(idstr, instance_id);
4477 if (!se) {
4478 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4479 instance_id, idstr);
4480 } else {
4481 ret = se->load_state(f, se->opaque, version_id);
4482 if (ret < 0) {
4483 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4484 instance_id, idstr);
4487 /* always seek to exact end of record */
4488 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4490 f->close(f);
4491 qemu_tap_announce_self(); /* FIXME: should this move to vm_start? */
4492 ret = 0;
4493 the_end:
4494 if (saved_vm_running)
4495 vm_start();
4496 return ret;
4499 /***********************************************************/
4500 /* cpu save/restore */
4502 #if defined(TARGET_I386)
4504 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4506 qemu_put_be32(f, dt->selector);
4507 qemu_put_betl(f, dt->base);
4508 qemu_put_be32(f, dt->limit);
4509 qemu_put_be32(f, dt->flags);
4512 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4514 dt->selector = qemu_get_be32(f);
4515 dt->base = qemu_get_betl(f);
4516 dt->limit = qemu_get_be32(f);
4517 dt->flags = qemu_get_be32(f);
4520 void cpu_save(QEMUFile *f, void *opaque)
4522 CPUState *env = opaque;
4523 uint16_t fptag, fpus, fpuc, fpregs_format;
4524 uint32_t hflags;
4525 int i;
4527 #ifdef USE_KVM
4528 if (kvm_allowed)
4529 kvm_save_registers(env);
4530 #endif
4532 for(i = 0; i < CPU_NB_REGS; i++)
4533 qemu_put_betls(f, &env->regs[i]);
4534 qemu_put_betls(f, &env->eip);
4535 qemu_put_betls(f, &env->eflags);
4536 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4537 qemu_put_be32s(f, &hflags);
4539 /* FPU */
4540 fpuc = env->fpuc;
4541 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4542 fptag = 0;
4543 for(i = 0; i < 8; i++) {
4544 fptag |= ((!env->fptags[i]) << i);
4547 qemu_put_be16s(f, &fpuc);
4548 qemu_put_be16s(f, &fpus);
4549 qemu_put_be16s(f, &fptag);
4551 #ifdef USE_X86LDOUBLE
4552 fpregs_format = 0;
4553 #else
4554 fpregs_format = 1;
4555 #endif
4556 qemu_put_be16s(f, &fpregs_format);
4558 for(i = 0; i < 8; i++) {
4559 #ifdef USE_X86LDOUBLE
4561 uint64_t mant;
4562 uint16_t exp;
4563 /* we save the real CPU data (in case of MMX usage only 'mant'
4564 contains the MMX register */
4565 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4566 qemu_put_be64(f, mant);
4567 qemu_put_be16(f, exp);
4569 #else
4570 /* if we use doubles for float emulation, we save the doubles to
4571 avoid losing information in case of MMX usage. It can give
4572 problems if the image is restored on a CPU where long
4573 doubles are used instead. */
4574 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4575 #endif
4578 for(i = 0; i < 6; i++)
4579 cpu_put_seg(f, &env->segs[i]);
4580 cpu_put_seg(f, &env->ldt);
4581 cpu_put_seg(f, &env->tr);
4582 cpu_put_seg(f, &env->gdt);
4583 cpu_put_seg(f, &env->idt);
4585 qemu_put_be32s(f, &env->sysenter_cs);
4586 qemu_put_be32s(f, &env->sysenter_esp);
4587 qemu_put_be32s(f, &env->sysenter_eip);
4589 qemu_put_betls(f, &env->cr[0]);
4590 qemu_put_betls(f, &env->cr[2]);
4591 qemu_put_betls(f, &env->cr[3]);
4592 qemu_put_betls(f, &env->cr[4]);
4594 for(i = 0; i < 8; i++)
4595 qemu_put_betls(f, &env->dr[i]);
4597 /* MMU */
4598 qemu_put_be32s(f, &env->a20_mask);
4600 /* XMM */
4601 qemu_put_be32s(f, &env->mxcsr);
4602 for(i = 0; i < CPU_NB_REGS; i++) {
4603 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4604 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4607 #ifdef TARGET_X86_64
4608 qemu_put_be64s(f, &env->efer);
4609 qemu_put_be64s(f, &env->star);
4610 qemu_put_be64s(f, &env->lstar);
4611 qemu_put_be64s(f, &env->cstar);
4612 qemu_put_be64s(f, &env->fmask);
4613 qemu_put_be64s(f, &env->kernelgsbase);
4614 #endif
4616 #ifdef USE_KVM
4617 if (kvm_allowed) {
4618 for (i = 0; i < NR_IRQ_WORDS ; i++) {
4619 qemu_put_betls(f, &env->kvm_interrupt_bitmap[i]);
4621 qemu_put_be64s(f, &env->tsc);
4623 #endif
4626 #ifdef USE_X86LDOUBLE
4627 /* XXX: add that in a FPU generic layer */
4628 union x86_longdouble {
4629 uint64_t mant;
4630 uint16_t exp;
4633 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4634 #define EXPBIAS1 1023
4635 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4636 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4638 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4640 int e;
4641 /* mantissa */
4642 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4643 /* exponent + sign */
4644 e = EXPD1(temp) - EXPBIAS1 + 16383;
4645 e |= SIGND1(temp) >> 16;
4646 p->exp = e;
4648 #endif
4650 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4652 CPUState *env = opaque;
4653 int i, guess_mmx;
4654 uint32_t hflags;
4655 uint16_t fpus, fpuc, fptag, fpregs_format;
4657 if (version_id != 3)
4658 return -EINVAL;
4659 for(i = 0; i < CPU_NB_REGS; i++)
4660 qemu_get_betls(f, &env->regs[i]);
4661 qemu_get_betls(f, &env->eip);
4662 qemu_get_betls(f, &env->eflags);
4663 qemu_get_be32s(f, &hflags);
4665 qemu_get_be16s(f, &fpuc);
4666 qemu_get_be16s(f, &fpus);
4667 qemu_get_be16s(f, &fptag);
4668 qemu_get_be16s(f, &fpregs_format);
4670 /* NOTE: we cannot always restore the FPU state if the image come
4671 from a host with a different 'USE_X86LDOUBLE' define. We guess
4672 if we are in an MMX state to restore correctly in that case. */
4673 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4674 for(i = 0; i < 8; i++) {
4675 uint64_t mant;
4676 uint16_t exp;
4678 switch(fpregs_format) {
4679 case 0:
4680 mant = qemu_get_be64(f);
4681 exp = qemu_get_be16(f);
4682 #ifdef USE_X86LDOUBLE
4683 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4684 #else
4685 /* difficult case */
4686 if (guess_mmx)
4687 env->fpregs[i].mmx.MMX_Q(0) = mant;
4688 else
4689 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4690 #endif
4691 break;
4692 case 1:
4693 mant = qemu_get_be64(f);
4694 #ifdef USE_X86LDOUBLE
4696 union x86_longdouble *p;
4697 /* difficult case */
4698 p = (void *)&env->fpregs[i];
4699 if (guess_mmx) {
4700 p->mant = mant;
4701 p->exp = 0xffff;
4702 } else {
4703 fp64_to_fp80(p, mant);
4706 #else
4707 env->fpregs[i].mmx.MMX_Q(0) = mant;
4708 #endif
4709 break;
4710 default:
4711 return -EINVAL;
4715 env->fpuc = fpuc;
4716 /* XXX: restore FPU round state */
4717 env->fpstt = (fpus >> 11) & 7;
4718 env->fpus = fpus & ~0x3800;
4719 fptag ^= 0xff;
4720 for(i = 0; i < 8; i++) {
4721 env->fptags[i] = (fptag >> i) & 1;
4724 for(i = 0; i < 6; i++)
4725 cpu_get_seg(f, &env->segs[i]);
4726 cpu_get_seg(f, &env->ldt);
4727 cpu_get_seg(f, &env->tr);
4728 cpu_get_seg(f, &env->gdt);
4729 cpu_get_seg(f, &env->idt);
4731 qemu_get_be32s(f, &env->sysenter_cs);
4732 qemu_get_be32s(f, &env->sysenter_esp);
4733 qemu_get_be32s(f, &env->sysenter_eip);
4735 qemu_get_betls(f, &env->cr[0]);
4736 qemu_get_betls(f, &env->cr[2]);
4737 qemu_get_betls(f, &env->cr[3]);
4738 qemu_get_betls(f, &env->cr[4]);
4740 for(i = 0; i < 8; i++)
4741 qemu_get_betls(f, &env->dr[i]);
4743 /* MMU */
4744 qemu_get_be32s(f, &env->a20_mask);
4746 qemu_get_be32s(f, &env->mxcsr);
4747 for(i = 0; i < CPU_NB_REGS; i++) {
4748 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4749 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4752 #ifdef TARGET_X86_64
4753 qemu_get_be64s(f, &env->efer);
4754 qemu_get_be64s(f, &env->star);
4755 qemu_get_be64s(f, &env->lstar);
4756 qemu_get_be64s(f, &env->cstar);
4757 qemu_get_be64s(f, &env->fmask);
4758 qemu_get_be64s(f, &env->kernelgsbase);
4759 #endif
4761 /* XXX: compute hflags from scratch, except for CPL and IIF */
4762 env->hflags = hflags;
4763 tlb_flush(env, 1);
4764 #ifdef USE_KVM
4765 if (kvm_allowed) {
4766 for (i = 0; i < NR_IRQ_WORDS ; i++) {
4767 qemu_get_betls(f, &env->kvm_interrupt_bitmap[i]);
4769 qemu_get_be64s(f, &env->tsc);
4770 kvm_load_registers(env);
4772 #endif
4773 return 0;
4776 #elif defined(TARGET_PPC)
4777 void cpu_save(QEMUFile *f, void *opaque)
4781 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4783 return 0;
4786 #elif defined(TARGET_MIPS)
4787 void cpu_save(QEMUFile *f, void *opaque)
4791 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4793 return 0;
4796 #elif defined(TARGET_SPARC)
4797 void cpu_save(QEMUFile *f, void *opaque)
4799 CPUState *env = opaque;
4800 int i;
4801 uint32_t tmp;
4803 for(i = 0; i < 8; i++)
4804 qemu_put_betls(f, &env->gregs[i]);
4805 for(i = 0; i < NWINDOWS * 16; i++)
4806 qemu_put_betls(f, &env->regbase[i]);
4808 /* FPU */
4809 for(i = 0; i < TARGET_FPREGS; i++) {
4810 union {
4811 float32 f;
4812 uint32_t i;
4813 } u;
4814 u.f = env->fpr[i];
4815 qemu_put_be32(f, u.i);
4818 qemu_put_betls(f, &env->pc);
4819 qemu_put_betls(f, &env->npc);
4820 qemu_put_betls(f, &env->y);
4821 tmp = GET_PSR(env);
4822 qemu_put_be32(f, tmp);
4823 qemu_put_betls(f, &env->fsr);
4824 qemu_put_betls(f, &env->tbr);
4825 #ifndef TARGET_SPARC64
4826 qemu_put_be32s(f, &env->wim);
4827 /* MMU */
4828 for(i = 0; i < 16; i++)
4829 qemu_put_be32s(f, &env->mmuregs[i]);
4830 #endif
4833 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4835 CPUState *env = opaque;
4836 int i;
4837 uint32_t tmp;
4839 for(i = 0; i < 8; i++)
4840 qemu_get_betls(f, &env->gregs[i]);
4841 for(i = 0; i < NWINDOWS * 16; i++)
4842 qemu_get_betls(f, &env->regbase[i]);
4844 /* FPU */
4845 for(i = 0; i < TARGET_FPREGS; i++) {
4846 union {
4847 float32 f;
4848 uint32_t i;
4849 } u;
4850 u.i = qemu_get_be32(f);
4851 env->fpr[i] = u.f;
4854 qemu_get_betls(f, &env->pc);
4855 qemu_get_betls(f, &env->npc);
4856 qemu_get_betls(f, &env->y);
4857 tmp = qemu_get_be32(f);
4858 env->cwp = 0; /* needed to ensure that the wrapping registers are
4859 correctly updated */
4860 PUT_PSR(env, tmp);
4861 qemu_get_betls(f, &env->fsr);
4862 qemu_get_betls(f, &env->tbr);
4863 #ifndef TARGET_SPARC64
4864 qemu_get_be32s(f, &env->wim);
4865 /* MMU */
4866 for(i = 0; i < 16; i++)
4867 qemu_get_be32s(f, &env->mmuregs[i]);
4868 #endif
4869 tlb_flush(env, 1);
4870 return 0;
4873 #elif defined(TARGET_ARM)
4875 /* ??? Need to implement these. */
4876 void cpu_save(QEMUFile *f, void *opaque)
4880 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4882 return 0;
4885 #else
4887 #warning No CPU save/restore functions
4889 #endif
4891 /***********************************************************/
4892 /* ram save/restore */
4894 /* we just avoid storing empty pages */
4895 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4897 int i, v;
4899 v = buf[0];
4900 for(i = 1; i < len; i++) {
4901 if (buf[i] != v)
4902 goto normal_save;
4904 qemu_put_byte(f, 1);
4905 qemu_put_byte(f, v);
4906 return;
4907 normal_save:
4908 qemu_put_byte(f, 0);
4909 qemu_put_buffer(f, buf, len);
4912 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4914 int v;
4916 v = qemu_get_byte(f);
4917 switch(v) {
4918 case 0:
4919 if (qemu_get_buffer(f, buf, len) != len)
4920 return -EIO;
4921 break;
4922 case 1:
4923 v = qemu_get_byte(f);
4924 memset(buf, v, len);
4925 break;
4926 default:
4927 return -EINVAL;
4929 return 0;
4932 static void ram_save(QEMUFile *f, void *opaque)
4934 int i;
4935 qemu_put_be32(f, phys_ram_size);
4936 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4937 #ifdef USE_KVM
4938 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
4939 continue;
4940 #endif
4941 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4945 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4947 int i, ret;
4948 if (version_id != 1)
4949 return -EINVAL;
4950 if (qemu_get_be32(f) != phys_ram_size)
4951 return -EINVAL;
4952 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4953 #ifdef USE_KVM
4954 if (kvm_allowed && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
4955 continue;
4956 #endif
4957 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4958 if (ret)
4959 return ret;
4961 return 0;
4964 /***********************************************************/
4965 /* machine registration */
4967 QEMUMachine *first_machine = NULL;
4969 int qemu_register_machine(QEMUMachine *m)
4971 QEMUMachine **pm;
4972 pm = &first_machine;
4973 while (*pm != NULL)
4974 pm = &(*pm)->next;
4975 m->next = NULL;
4976 *pm = m;
4977 return 0;
4980 QEMUMachine *find_machine(const char *name)
4982 QEMUMachine *m;
4984 for(m = first_machine; m != NULL; m = m->next) {
4985 if (!strcmp(m->name, name))
4986 return m;
4988 return NULL;
4991 /***********************************************************/
4992 /* main execution loop */
4994 void gui_update(void *opaque)
4996 display_state.dpy_refresh(&display_state);
4997 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5000 struct vm_change_state_entry {
5001 VMChangeStateHandler *cb;
5002 void *opaque;
5003 LIST_ENTRY (vm_change_state_entry) entries;
5006 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5008 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5009 void *opaque)
5011 VMChangeStateEntry *e;
5013 e = qemu_mallocz(sizeof (*e));
5014 if (!e)
5015 return NULL;
5017 e->cb = cb;
5018 e->opaque = opaque;
5019 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5020 return e;
5023 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5025 LIST_REMOVE (e, entries);
5026 qemu_free (e);
5029 static void vm_state_notify(int running)
5031 VMChangeStateEntry *e;
5033 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5034 e->cb(e->opaque, running);
5038 /* XXX: support several handlers */
5039 static VMStopHandler *vm_stop_cb;
5040 static void *vm_stop_opaque;
5042 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5044 vm_stop_cb = cb;
5045 vm_stop_opaque = opaque;
5046 return 0;
5049 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5051 vm_stop_cb = NULL;
5054 void vm_start(void)
5056 if (!vm_running) {
5057 cpu_enable_ticks();
5058 vm_running = 1;
5059 vm_state_notify(1);
5060 console_select(0); /* focus on guest's display */
5064 void vm_stop(int reason)
5066 if (vm_running) {
5067 cpu_disable_ticks();
5068 vm_running = 0;
5069 if (reason != 0) {
5070 if (vm_stop_cb) {
5071 vm_stop_cb(vm_stop_opaque, reason);
5074 vm_state_notify(0);
5078 /* reset/shutdown handler */
5080 typedef struct QEMUResetEntry {
5081 QEMUResetHandler *func;
5082 void *opaque;
5083 struct QEMUResetEntry *next;
5084 } QEMUResetEntry;
5086 static QEMUResetEntry *first_reset_entry;
5087 static int reset_requested;
5088 static int shutdown_requested;
5089 static int powerdown_requested;
5091 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5093 QEMUResetEntry **pre, *re;
5095 pre = &first_reset_entry;
5096 while (*pre != NULL)
5097 pre = &(*pre)->next;
5098 re = qemu_mallocz(sizeof(QEMUResetEntry));
5099 re->func = func;
5100 re->opaque = opaque;
5101 re->next = NULL;
5102 *pre = re;
5105 void qemu_system_reset(void)
5107 QEMUResetEntry *re;
5109 /* reset all devices */
5110 for(re = first_reset_entry; re != NULL; re = re->next) {
5111 re->func(re->opaque);
5115 void qemu_system_reset_request(void)
5117 reset_requested = 1;
5118 if (cpu_single_env)
5119 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5122 void qemu_system_shutdown_request(void)
5124 shutdown_requested = 1;
5125 if (cpu_single_env)
5126 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5129 void qemu_system_powerdown_request(void)
5131 powerdown_requested = 1;
5132 if (cpu_single_env)
5133 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5136 void main_loop_wait(int timeout)
5138 IOHandlerRecord *ioh, *ioh_next;
5139 fd_set rfds, wfds, xfds;
5140 int ret, nfds;
5141 struct timeval tv;
5142 PollingEntry *pe;
5145 /* XXX: need to suppress polling by better using win32 events */
5146 ret = 0;
5147 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5148 ret |= pe->func(pe->opaque);
5150 #ifdef _WIN32
5151 if (ret == 0 && timeout > 0) {
5152 int err;
5153 WaitObjects *w = &wait_objects;
5155 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5156 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5157 if (w->func[ret - WAIT_OBJECT_0])
5158 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5159 } else if (ret == WAIT_TIMEOUT) {
5160 } else {
5161 err = GetLastError();
5162 fprintf(stderr, "Wait error %d %d\n", ret, err);
5165 #endif
5166 /* poll any events */
5167 /* XXX: separate device handlers from system ones */
5168 nfds = -1;
5169 FD_ZERO(&rfds);
5170 FD_ZERO(&wfds);
5171 FD_ZERO(&xfds);
5172 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5173 if (ioh->fd_read &&
5174 (!ioh->fd_read_poll ||
5175 ioh->fd_read_poll(ioh->opaque) != 0)) {
5176 FD_SET(ioh->fd, &rfds);
5177 if (ioh->fd > nfds)
5178 nfds = ioh->fd;
5180 if (ioh->fd_write) {
5181 FD_SET(ioh->fd, &wfds);
5182 if (ioh->fd > nfds)
5183 nfds = ioh->fd;
5187 tv.tv_sec = 0;
5188 #ifdef _WIN32
5189 tv.tv_usec = 0;
5190 #else
5191 tv.tv_usec = timeout * 1000;
5192 #endif
5193 #if defined(CONFIG_SLIRP)
5194 if (slirp_inited) {
5195 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5197 #endif
5198 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5199 if (ret > 0) {
5200 /* XXX: better handling of removal */
5201 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5202 ioh_next = ioh->next;
5203 if (FD_ISSET(ioh->fd, &rfds)) {
5204 ioh->fd_read(ioh->opaque);
5207 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5208 ioh_next = ioh->next;
5209 if (FD_ISSET(ioh->fd, &wfds)) {
5210 ioh->fd_write(ioh->opaque);
5214 #if defined(CONFIG_SLIRP)
5215 if (slirp_inited) {
5216 if (ret < 0) {
5217 FD_ZERO(&rfds);
5218 FD_ZERO(&wfds);
5219 FD_ZERO(&xfds);
5221 slirp_select_poll(&rfds, &wfds, &xfds);
5223 #endif
5224 #ifdef _WIN32
5225 tap_win32_poll();
5226 #endif
5228 if (vm_running) {
5229 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5230 qemu_get_clock(vm_clock));
5231 /* run dma transfers, if any */
5232 DMA_run();
5235 /* real time timers */
5236 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5237 qemu_get_clock(rt_clock));
5240 static CPUState *cur_cpu;
5242 int main_loop(void)
5244 int ret, timeout;
5245 #ifdef CONFIG_PROFILER
5246 int64_t ti;
5247 #endif
5248 CPUState *env;
5250 cur_cpu = first_cpu;
5251 for(;;) {
5252 if (vm_running) {
5254 env = cur_cpu;
5255 for(;;) {
5256 /* get next cpu */
5257 env = env->next_cpu;
5258 if (!env)
5259 env = first_cpu;
5260 #ifdef CONFIG_PROFILER
5261 ti = profile_getclock();
5262 #endif
5263 ret = cpu_exec(env);
5264 #ifdef CONFIG_PROFILER
5265 qemu_time += profile_getclock() - ti;
5266 #endif
5267 if (ret != EXCP_HALTED)
5268 break;
5269 /* all CPUs are halted ? */
5270 if (env == cur_cpu) {
5271 ret = EXCP_HLT;
5272 break;
5275 cur_cpu = env;
5277 if (shutdown_requested) {
5278 ret = EXCP_INTERRUPT;
5279 break;
5281 if (reset_requested) {
5282 reset_requested = 0;
5283 qemu_system_reset();
5284 ret = EXCP_INTERRUPT;
5286 if (powerdown_requested) {
5287 powerdown_requested = 0;
5288 qemu_system_powerdown();
5289 ret = EXCP_INTERRUPT;
5291 if (ret == EXCP_DEBUG) {
5292 vm_stop(EXCP_DEBUG);
5294 /* if hlt instruction, we wait until the next IRQ */
5295 /* XXX: use timeout computed from timers */
5296 if (ret == EXCP_HLT)
5297 timeout = 10;
5298 else
5299 timeout = 0;
5300 } else {
5301 timeout = 10;
5303 #ifdef CONFIG_PROFILER
5304 ti = profile_getclock();
5305 #endif
5306 main_loop_wait(timeout);
5307 #ifdef CONFIG_PROFILER
5308 dev_time += profile_getclock() - ti;
5309 #endif
5311 cpu_disable_ticks();
5312 return ret;
5315 void help(void)
5317 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
5318 "usage: %s [options] [disk_image]\n"
5319 "\n"
5320 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5321 "\n"
5322 "Standard options:\n"
5323 "-M machine select emulated machine (-M ? for list)\n"
5324 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5325 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5326 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5327 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5328 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5329 "-snapshot write to temporary files instead of disk image files\n"
5330 #ifdef TARGET_I386
5331 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5332 #endif
5333 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5334 "-smp n set the number of CPUs to 'n' [default=1]\n"
5335 "-nographic disable graphical output and redirect serial I/Os to console\n"
5336 #ifndef _WIN32
5337 "-k language use keyboard layout (for example \"fr\" for French)\n"
5338 #endif
5339 #ifdef HAS_AUDIO
5340 "-audio-help print list of audio drivers and their options\n"
5341 "-soundhw c1,... enable audio support\n"
5342 " and only specified sound cards (comma separated list)\n"
5343 " use -soundhw ? to get the list of supported cards\n"
5344 " use -soundhw all to enable all of them\n"
5345 #endif
5346 "-localtime set the real time clock to local time [default=utc]\n"
5347 "-full-screen start in full screen\n"
5348 #ifdef TARGET_I386
5349 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5350 #endif
5351 "-usb enable the USB driver (will be the default soon)\n"
5352 "-usbdevice name add the host or guest USB device 'name'\n"
5353 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5354 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5355 #endif
5356 "\n"
5357 "Network options:\n"
5358 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5359 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5360 #ifdef CONFIG_SLIRP
5361 "-net user[,vlan=n][,hostname=host]\n"
5362 " connect the user mode network stack to VLAN 'n' and send\n"
5363 " hostname 'host' to DHCP clients\n"
5364 #endif
5365 #ifdef _WIN32
5366 "-net tap[,vlan=n],ifname=name\n"
5367 " connect the host TAP network interface to VLAN 'n'\n"
5368 #else
5369 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
5370 " connect the host TAP network interface to VLAN 'n' and use\n"
5371 " the network script 'file' (default=%s);\n"
5372 " use 'fd=h' to connect to an already opened TAP interface\n"
5373 #endif
5374 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5375 " connect the vlan 'n' to another VLAN using a socket connection\n"
5376 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5377 " connect the vlan 'n' to multicast maddr and port\n"
5378 "-net none use it alone to have zero network devices; if no -net option\n"
5379 " is provided, the default is '-net nic -net user'\n"
5380 "\n"
5381 #ifdef CONFIG_SLIRP
5382 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5383 #ifndef _WIN32
5384 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5385 #endif
5386 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5387 " redirect TCP or UDP connections from host to guest [-net user]\n"
5388 #endif
5389 "\n"
5390 "Linux boot specific:\n"
5391 "-kernel bzImage use 'bzImage' as kernel image\n"
5392 "-append cmdline use 'cmdline' as kernel command line\n"
5393 "-initrd file use 'file' as initial ram disk\n"
5394 "\n"
5395 "Debug/Expert options:\n"
5396 "-monitor dev redirect the monitor to char device 'dev'\n"
5397 "-serial dev redirect the serial port to char device 'dev'\n"
5398 "-parallel dev redirect the parallel port to char device 'dev'\n"
5399 "-pidfile file Write PID to 'file'\n"
5400 "-S freeze CPU at startup (use 'c' to start execution)\n"
5401 "-s wait gdb connection to port %d\n"
5402 "-p port change gdb connection port\n"
5403 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
5404 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5405 " translation (t=none or lba) (usually qemu can guess them)\n"
5406 "-L path set the directory for the BIOS and VGA BIOS\n"
5407 #ifdef USE_KQEMU
5408 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5409 "-no-kqemu disable KQEMU kernel module usage\n"
5410 #endif
5411 #ifdef USE_KVM
5412 "-no-kvm disable KVM hardware virtualization\n"
5413 #endif
5414 #ifdef USE_CODE_COPY
5415 "-no-code-copy disable code copy acceleration\n"
5416 #endif
5417 #ifdef TARGET_I386
5418 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5419 " (default is CL-GD5446 PCI VGA)\n"
5420 "-no-acpi disable ACPI\n"
5421 #endif
5422 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5423 "-vnc display start a VNC server on display\n"
5424 "\n"
5425 "During emulation, the following keys are useful:\n"
5426 "ctrl-alt-f toggle full screen\n"
5427 "ctrl-alt-n switch to virtual console 'n'\n"
5428 "ctrl-alt toggle mouse and keyboard grab\n"
5429 "\n"
5430 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5432 "qemu",
5433 DEFAULT_RAM_SIZE,
5434 #ifndef _WIN32
5435 DEFAULT_NETWORK_SCRIPT,
5436 #endif
5437 DEFAULT_GDBSTUB_PORT,
5438 "/tmp/qemu.log");
5439 exit(1);
5442 #define HAS_ARG 0x0001
5444 enum {
5445 QEMU_OPTION_h,
5447 QEMU_OPTION_M,
5448 QEMU_OPTION_fda,
5449 QEMU_OPTION_fdb,
5450 QEMU_OPTION_hda,
5451 QEMU_OPTION_hdb,
5452 QEMU_OPTION_hdc,
5453 QEMU_OPTION_hdd,
5454 QEMU_OPTION_cdrom,
5455 QEMU_OPTION_boot,
5456 QEMU_OPTION_snapshot,
5457 #ifdef TARGET_I386
5458 QEMU_OPTION_no_fd_bootchk,
5459 #endif
5460 QEMU_OPTION_m,
5461 QEMU_OPTION_nographic,
5462 #ifdef HAS_AUDIO
5463 QEMU_OPTION_audio_help,
5464 QEMU_OPTION_soundhw,
5465 #endif
5467 QEMU_OPTION_net,
5468 QEMU_OPTION_tftp,
5469 QEMU_OPTION_smb,
5470 QEMU_OPTION_redir,
5472 QEMU_OPTION_kernel,
5473 QEMU_OPTION_append,
5474 QEMU_OPTION_initrd,
5476 QEMU_OPTION_S,
5477 QEMU_OPTION_s,
5478 QEMU_OPTION_p,
5479 QEMU_OPTION_d,
5480 QEMU_OPTION_hdachs,
5481 QEMU_OPTION_L,
5482 QEMU_OPTION_no_code_copy,
5483 QEMU_OPTION_k,
5484 QEMU_OPTION_localtime,
5485 QEMU_OPTION_cirrusvga,
5486 QEMU_OPTION_g,
5487 QEMU_OPTION_std_vga,
5488 QEMU_OPTION_monitor,
5489 QEMU_OPTION_vmchannel,
5490 QEMU_OPTION_serial,
5491 QEMU_OPTION_parallel,
5492 QEMU_OPTION_loadvm,
5493 QEMU_OPTION_full_screen,
5494 QEMU_OPTION_pidfile,
5495 QEMU_OPTION_no_kqemu,
5496 QEMU_OPTION_kernel_kqemu,
5497 QEMU_OPTION_win2k_hack,
5498 QEMU_OPTION_usb,
5499 QEMU_OPTION_usbdevice,
5500 QEMU_OPTION_smp,
5501 QEMU_OPTION_vnc,
5502 QEMU_OPTION_no_acpi,
5503 QEMU_OPTION_no_kvm,
5506 typedef struct QEMUOption {
5507 const char *name;
5508 int flags;
5509 int index;
5510 } QEMUOption;
5512 const QEMUOption qemu_options[] = {
5513 { "h", 0, QEMU_OPTION_h },
5515 { "M", HAS_ARG, QEMU_OPTION_M },
5516 { "fda", HAS_ARG, QEMU_OPTION_fda },
5517 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5518 { "hda", HAS_ARG, QEMU_OPTION_hda },
5519 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5520 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5521 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5522 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5523 { "boot", HAS_ARG, QEMU_OPTION_boot },
5524 { "snapshot", 0, QEMU_OPTION_snapshot },
5525 #ifdef TARGET_I386
5526 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5527 #endif
5528 { "m", HAS_ARG, QEMU_OPTION_m },
5529 { "nographic", 0, QEMU_OPTION_nographic },
5530 { "k", HAS_ARG, QEMU_OPTION_k },
5531 #ifdef HAS_AUDIO
5532 { "audio-help", 0, QEMU_OPTION_audio_help },
5533 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5534 #endif
5536 { "net", HAS_ARG, QEMU_OPTION_net},
5537 #ifdef CONFIG_SLIRP
5538 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5539 #ifndef _WIN32
5540 { "smb", HAS_ARG, QEMU_OPTION_smb },
5541 #endif
5542 { "redir", HAS_ARG, QEMU_OPTION_redir },
5543 #endif
5545 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5546 { "append", HAS_ARG, QEMU_OPTION_append },
5547 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5549 { "S", 0, QEMU_OPTION_S },
5550 { "s", 0, QEMU_OPTION_s },
5551 { "p", HAS_ARG, QEMU_OPTION_p },
5552 { "d", HAS_ARG, QEMU_OPTION_d },
5553 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5554 { "L", HAS_ARG, QEMU_OPTION_L },
5555 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
5556 #ifdef USE_KQEMU
5557 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5558 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5559 #endif
5560 #ifdef USE_KVM
5561 { "no-kvm", 0, QEMU_OPTION_no_kvm },
5562 #endif
5563 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5564 { "g", 1, QEMU_OPTION_g },
5565 #endif
5566 { "localtime", 0, QEMU_OPTION_localtime },
5567 { "std-vga", 0, QEMU_OPTION_std_vga },
5568 { "monitor", 1, QEMU_OPTION_monitor },
5569 { "vmchannel", 1, QEMU_OPTION_vmchannel },
5570 { "serial", 1, QEMU_OPTION_serial },
5571 { "parallel", 1, QEMU_OPTION_parallel },
5572 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5573 { "full-screen", 0, QEMU_OPTION_full_screen },
5574 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5575 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5576 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5577 { "smp", HAS_ARG, QEMU_OPTION_smp },
5578 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5580 /* temporary options */
5581 { "usb", 0, QEMU_OPTION_usb },
5582 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
5583 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5584 { NULL },
5587 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5589 /* this stack is only used during signal handling */
5590 #define SIGNAL_STACK_SIZE 32768
5592 static uint8_t *signal_stack;
5594 #endif
5596 /* password input */
5598 static BlockDriverState *get_bdrv(int index)
5600 BlockDriverState *bs;
5602 if (index < 4) {
5603 bs = bs_table[index];
5604 } else if (index < 6) {
5605 bs = fd_table[index - 4];
5606 } else {
5607 bs = NULL;
5609 return bs;
5612 static void read_passwords(void)
5614 BlockDriverState *bs;
5615 int i, j;
5616 char password[256];
5618 for(i = 0; i < 6; i++) {
5619 bs = get_bdrv(i);
5620 if (bs && bdrv_is_encrypted(bs)) {
5621 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5622 for(j = 0; j < 3; j++) {
5623 monitor_readline("Password: ",
5624 1, password, sizeof(password));
5625 if (bdrv_set_key(bs, password) == 0)
5626 break;
5627 term_printf("invalid password\n");
5633 /* XXX: currently we cannot use simultaneously different CPUs */
5634 void register_machines(void)
5636 #if defined(TARGET_I386)
5637 qemu_register_machine(&pc_machine);
5638 qemu_register_machine(&isapc_machine);
5639 #elif defined(TARGET_PPC)
5640 qemu_register_machine(&heathrow_machine);
5641 qemu_register_machine(&core99_machine);
5642 qemu_register_machine(&prep_machine);
5643 #elif defined(TARGET_MIPS)
5644 qemu_register_machine(&mips_machine);
5645 #elif defined(TARGET_SPARC)
5646 #ifdef TARGET_SPARC64
5647 qemu_register_machine(&sun4u_machine);
5648 #else
5649 qemu_register_machine(&sun4m_machine);
5650 #endif
5651 #elif defined(TARGET_ARM)
5652 qemu_register_machine(&integratorcp926_machine);
5653 qemu_register_machine(&integratorcp1026_machine);
5654 qemu_register_machine(&versatilepb_machine);
5655 qemu_register_machine(&versatileab_machine);
5656 #elif defined(TARGET_SH4)
5657 qemu_register_machine(&shix_machine);
5658 #else
5659 #error unsupported CPU
5660 #endif
5663 #ifdef HAS_AUDIO
5664 struct soundhw soundhw[] = {
5665 #ifdef TARGET_I386
5667 "pcspk",
5668 "PC speaker",
5671 { .init_isa = pcspk_audio_init }
5673 #endif
5675 "sb16",
5676 "Creative Sound Blaster 16",
5679 { .init_isa = SB16_init }
5682 #ifdef CONFIG_ADLIB
5684 "adlib",
5685 #ifdef HAS_YMF262
5686 "Yamaha YMF262 (OPL3)",
5687 #else
5688 "Yamaha YM3812 (OPL2)",
5689 #endif
5692 { .init_isa = Adlib_init }
5694 #endif
5696 #ifdef CONFIG_GUS
5698 "gus",
5699 "Gravis Ultrasound GF1",
5702 { .init_isa = GUS_init }
5704 #endif
5707 "es1370",
5708 "ENSONIQ AudioPCI ES1370",
5711 { .init_pci = es1370_init }
5714 { NULL, NULL, 0, 0, { NULL } }
5717 static void select_soundhw (const char *optarg)
5719 struct soundhw *c;
5721 if (*optarg == '?') {
5722 show_valid_cards:
5724 printf ("Valid sound card names (comma separated):\n");
5725 for (c = soundhw; c->name; ++c) {
5726 printf ("%-11s %s\n", c->name, c->descr);
5728 printf ("\n-soundhw all will enable all of the above\n");
5729 exit (*optarg != '?');
5731 else {
5732 size_t l;
5733 const char *p;
5734 char *e;
5735 int bad_card = 0;
5737 if (!strcmp (optarg, "all")) {
5738 for (c = soundhw; c->name; ++c) {
5739 c->enabled = 1;
5741 return;
5744 p = optarg;
5745 while (*p) {
5746 e = strchr (p, ',');
5747 l = !e ? strlen (p) : (size_t) (e - p);
5749 for (c = soundhw; c->name; ++c) {
5750 if (!strncmp (c->name, p, l)) {
5751 c->enabled = 1;
5752 break;
5756 if (!c->name) {
5757 if (l > 80) {
5758 fprintf (stderr,
5759 "Unknown sound card name (too big to show)\n");
5761 else {
5762 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5763 (int) l, p);
5765 bad_card = 1;
5767 p += l + (e != NULL);
5770 if (bad_card)
5771 goto show_valid_cards;
5774 #endif
5776 #ifdef _WIN32
5777 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5779 exit(STATUS_CONTROL_C_EXIT);
5780 return TRUE;
5782 #endif
5784 #define MAX_NET_CLIENTS 32
5786 int main(int argc, char **argv)
5788 #ifdef CONFIG_GDBSTUB
5789 int use_gdbstub, gdbstub_port;
5790 #endif
5791 int i, cdrom_index;
5792 int snapshot, linux_boot;
5793 const char *initrd_filename;
5794 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5795 const char *kernel_filename, *kernel_cmdline;
5796 DisplayState *ds = &display_state;
5797 int cyls, heads, secs, translation;
5798 int start_emulation = 1;
5799 char net_clients[MAX_NET_CLIENTS][256];
5800 int nb_net_clients;
5801 int optind;
5802 const char *r, *optarg;
5803 CharDriverState *monitor_hd;
5804 char monitor_device[128];
5805 CharDriverState *vmchannel_hd;
5806 char vmchannel_device[128];
5807 char serial_devices[MAX_SERIAL_PORTS][128];
5808 int serial_device_index;
5809 char parallel_devices[MAX_PARALLEL_PORTS][128];
5810 int parallel_device_index;
5811 const char *loadvm = NULL;
5812 QEMUMachine *machine;
5813 char usb_devices[MAX_USB_CMDLINE][128];
5814 int usb_devices_index;
5816 LIST_INIT (&vm_change_state_head);
5817 #ifndef _WIN32
5819 struct sigaction act;
5820 sigfillset(&act.sa_mask);
5821 act.sa_flags = 0;
5822 act.sa_handler = SIG_IGN;
5823 sigaction(SIGPIPE, &act, NULL);
5825 #else
5826 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5827 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5828 QEMU to run on a single CPU */
5830 HANDLE h;
5831 DWORD mask, smask;
5832 int i;
5833 h = GetCurrentProcess();
5834 if (GetProcessAffinityMask(h, &mask, &smask)) {
5835 for(i = 0; i < 32; i++) {
5836 if (mask & (1 << i))
5837 break;
5839 if (i != 32) {
5840 mask = 1 << i;
5841 SetProcessAffinityMask(h, mask);
5845 #endif
5847 register_machines();
5848 machine = first_machine;
5849 initrd_filename = NULL;
5850 for(i = 0; i < MAX_FD; i++)
5851 fd_filename[i] = NULL;
5852 for(i = 0; i < MAX_DISKS; i++)
5853 hd_filename[i] = NULL;
5854 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5855 vga_ram_size = VGA_RAM_SIZE;
5856 bios_size = BIOS_SIZE;
5857 #ifdef CONFIG_GDBSTUB
5858 use_gdbstub = 0;
5859 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5860 #endif
5861 snapshot = 0;
5862 nographic = 0;
5863 kernel_filename = NULL;
5864 kernel_cmdline = "";
5865 #ifdef TARGET_PPC
5866 cdrom_index = 1;
5867 #else
5868 cdrom_index = 2;
5869 #endif
5870 cyls = heads = secs = 0;
5871 translation = BIOS_ATA_TRANSLATION_AUTO;
5872 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5874 vmchannel_device[0] = '\0';
5876 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5877 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5878 serial_devices[i][0] = '\0';
5879 serial_device_index = 0;
5881 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5882 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5883 parallel_devices[i][0] = '\0';
5884 parallel_device_index = 0;
5886 usb_devices_index = 0;
5888 nb_net_clients = 0;
5890 nb_nics = 0;
5891 /* default mac address of the first network interface */
5893 optind = 1;
5894 for(;;) {
5895 if (optind >= argc)
5896 break;
5897 r = argv[optind];
5898 if (r[0] != '-') {
5899 hd_filename[0] = argv[optind++];
5900 } else {
5901 const QEMUOption *popt;
5903 optind++;
5904 popt = qemu_options;
5905 for(;;) {
5906 if (!popt->name) {
5907 fprintf(stderr, "%s: invalid option -- '%s'\n",
5908 argv[0], r);
5909 exit(1);
5911 if (!strcmp(popt->name, r + 1))
5912 break;
5913 popt++;
5915 if (popt->flags & HAS_ARG) {
5916 if (optind >= argc) {
5917 fprintf(stderr, "%s: option '%s' requires an argument\n",
5918 argv[0], r);
5919 exit(1);
5921 optarg = argv[optind++];
5922 } else {
5923 optarg = NULL;
5926 switch(popt->index) {
5927 case QEMU_OPTION_M:
5928 machine = find_machine(optarg);
5929 if (!machine) {
5930 QEMUMachine *m;
5931 printf("Supported machines are:\n");
5932 for(m = first_machine; m != NULL; m = m->next) {
5933 printf("%-10s %s%s\n",
5934 m->name, m->desc,
5935 m == first_machine ? " (default)" : "");
5937 exit(1);
5939 break;
5940 case QEMU_OPTION_initrd:
5941 initrd_filename = optarg;
5942 break;
5943 case QEMU_OPTION_hda:
5944 case QEMU_OPTION_hdb:
5945 case QEMU_OPTION_hdc:
5946 case QEMU_OPTION_hdd:
5948 int hd_index;
5949 hd_index = popt->index - QEMU_OPTION_hda;
5950 hd_filename[hd_index] = optarg;
5951 if (hd_index == cdrom_index)
5952 cdrom_index = -1;
5954 break;
5955 case QEMU_OPTION_snapshot:
5956 snapshot = 1;
5957 break;
5958 case QEMU_OPTION_hdachs:
5960 const char *p;
5961 p = optarg;
5962 cyls = strtol(p, (char **)&p, 0);
5963 if (cyls < 1 || cyls > 16383)
5964 goto chs_fail;
5965 if (*p != ',')
5966 goto chs_fail;
5967 p++;
5968 heads = strtol(p, (char **)&p, 0);
5969 if (heads < 1 || heads > 16)
5970 goto chs_fail;
5971 if (*p != ',')
5972 goto chs_fail;
5973 p++;
5974 secs = strtol(p, (char **)&p, 0);
5975 if (secs < 1 || secs > 63)
5976 goto chs_fail;
5977 if (*p == ',') {
5978 p++;
5979 if (!strcmp(p, "none"))
5980 translation = BIOS_ATA_TRANSLATION_NONE;
5981 else if (!strcmp(p, "lba"))
5982 translation = BIOS_ATA_TRANSLATION_LBA;
5983 else if (!strcmp(p, "auto"))
5984 translation = BIOS_ATA_TRANSLATION_AUTO;
5985 else
5986 goto chs_fail;
5987 } else if (*p != '\0') {
5988 chs_fail:
5989 fprintf(stderr, "qemu: invalid physical CHS format\n");
5990 exit(1);
5993 break;
5994 case QEMU_OPTION_nographic:
5995 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5996 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5997 nographic = 1;
5998 break;
5999 case QEMU_OPTION_kernel:
6000 kernel_filename = optarg;
6001 break;
6002 case QEMU_OPTION_append:
6003 kernel_cmdline = optarg;
6004 break;
6005 case QEMU_OPTION_cdrom:
6006 if (cdrom_index >= 0) {
6007 hd_filename[cdrom_index] = optarg;
6009 break;
6010 case QEMU_OPTION_boot:
6011 boot_device = optarg[0];
6012 if (boot_device != 'a' &&
6013 #ifdef TARGET_SPARC
6014 // Network boot
6015 boot_device != 'n' &&
6016 #endif
6017 boot_device != 'c' && boot_device != 'd') {
6018 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
6019 exit(1);
6021 break;
6022 case QEMU_OPTION_fda:
6023 fd_filename[0] = optarg;
6024 break;
6025 case QEMU_OPTION_fdb:
6026 fd_filename[1] = optarg;
6027 break;
6028 #ifdef TARGET_I386
6029 case QEMU_OPTION_no_fd_bootchk:
6030 fd_bootchk = 0;
6031 break;
6032 #endif
6033 case QEMU_OPTION_no_code_copy:
6034 code_copy_enabled = 0;
6035 break;
6036 case QEMU_OPTION_net:
6037 if (nb_net_clients >= MAX_NET_CLIENTS) {
6038 fprintf(stderr, "qemu: too many network clients\n");
6039 exit(1);
6041 pstrcpy(net_clients[nb_net_clients],
6042 sizeof(net_clients[0]),
6043 optarg);
6044 nb_net_clients++;
6045 break;
6046 #ifdef CONFIG_SLIRP
6047 case QEMU_OPTION_tftp:
6048 tftp_prefix = optarg;
6049 break;
6050 #ifndef _WIN32
6051 case QEMU_OPTION_smb:
6052 net_slirp_smb(optarg);
6053 break;
6054 #endif
6055 case QEMU_OPTION_redir:
6056 net_slirp_redir(optarg);
6057 break;
6058 #endif
6059 #ifdef HAS_AUDIO
6060 case QEMU_OPTION_audio_help:
6061 AUD_help ();
6062 exit (0);
6063 break;
6064 case QEMU_OPTION_soundhw:
6065 select_soundhw (optarg);
6066 break;
6067 #endif
6068 case QEMU_OPTION_h:
6069 help();
6070 break;
6071 case QEMU_OPTION_m:
6072 ram_size = atoi(optarg) * 1024 * 1024;
6073 if (ram_size <= 0)
6074 help();
6075 if (ram_size > PHYS_RAM_MAX_SIZE) {
6076 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6077 PHYS_RAM_MAX_SIZE / (1024 * 1024));
6078 exit(1);
6080 break;
6081 case QEMU_OPTION_d:
6083 int mask;
6084 CPULogItem *item;
6086 mask = cpu_str_to_log_mask(optarg);
6087 if (!mask) {
6088 printf("Log items (comma separated):\n");
6089 for(item = cpu_log_items; item->mask != 0; item++) {
6090 printf("%-10s %s\n", item->name, item->help);
6092 exit(1);
6094 cpu_set_log(mask);
6096 break;
6097 #ifdef CONFIG_GDBSTUB
6098 case QEMU_OPTION_s:
6099 use_gdbstub = 1;
6100 break;
6101 case QEMU_OPTION_p:
6102 gdbstub_port = atoi(optarg);
6103 break;
6104 #endif
6105 case QEMU_OPTION_L:
6106 bios_dir = optarg;
6107 break;
6108 case QEMU_OPTION_S:
6109 start_emulation = 0;
6110 break;
6111 case QEMU_OPTION_k:
6112 keyboard_layout = optarg;
6113 break;
6114 case QEMU_OPTION_localtime:
6115 rtc_utc = 0;
6116 break;
6117 case QEMU_OPTION_cirrusvga:
6118 cirrus_vga_enabled = 1;
6119 break;
6120 case QEMU_OPTION_std_vga:
6121 cirrus_vga_enabled = 0;
6122 break;
6123 case QEMU_OPTION_g:
6125 const char *p;
6126 int w, h, depth;
6127 p = optarg;
6128 w = strtol(p, (char **)&p, 10);
6129 if (w <= 0) {
6130 graphic_error:
6131 fprintf(stderr, "qemu: invalid resolution or depth\n");
6132 exit(1);
6134 if (*p != 'x')
6135 goto graphic_error;
6136 p++;
6137 h = strtol(p, (char **)&p, 10);
6138 if (h <= 0)
6139 goto graphic_error;
6140 if (*p == 'x') {
6141 p++;
6142 depth = strtol(p, (char **)&p, 10);
6143 if (depth != 8 && depth != 15 && depth != 16 &&
6144 depth != 24 && depth != 32)
6145 goto graphic_error;
6146 } else if (*p == '\0') {
6147 depth = graphic_depth;
6148 } else {
6149 goto graphic_error;
6152 graphic_width = w;
6153 graphic_height = h;
6154 graphic_depth = depth;
6156 break;
6157 case QEMU_OPTION_monitor:
6158 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6159 break;
6160 case QEMU_OPTION_vmchannel:
6161 pstrcpy(vmchannel_device, sizeof(vmchannel_device), optarg);
6162 break;
6163 case QEMU_OPTION_serial:
6164 if (serial_device_index >= MAX_SERIAL_PORTS) {
6165 fprintf(stderr, "qemu: too many serial ports\n");
6166 exit(1);
6168 pstrcpy(serial_devices[serial_device_index],
6169 sizeof(serial_devices[0]), optarg);
6170 serial_device_index++;
6171 break;
6172 case QEMU_OPTION_parallel:
6173 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6174 fprintf(stderr, "qemu: too many parallel ports\n");
6175 exit(1);
6177 pstrcpy(parallel_devices[parallel_device_index],
6178 sizeof(parallel_devices[0]), optarg);
6179 parallel_device_index++;
6180 break;
6181 case QEMU_OPTION_loadvm:
6182 loadvm = optarg;
6183 break;
6184 case QEMU_OPTION_full_screen:
6185 full_screen = 1;
6186 break;
6187 case QEMU_OPTION_pidfile:
6188 create_pidfile(optarg);
6189 break;
6190 #ifdef TARGET_I386
6191 case QEMU_OPTION_win2k_hack:
6192 win2k_install_hack = 1;
6193 break;
6194 #endif
6195 #ifdef USE_KQEMU
6196 case QEMU_OPTION_no_kqemu:
6197 kqemu_allowed = 0;
6198 break;
6199 case QEMU_OPTION_kernel_kqemu:
6200 kqemu_allowed = 2;
6201 break;
6202 #endif
6203 #ifdef USE_KVM
6204 case QEMU_OPTION_no_kvm:
6205 kvm_allowed = 0;
6206 break;
6207 #endif
6208 case QEMU_OPTION_usb:
6209 usb_enabled = 1;
6210 break;
6211 case QEMU_OPTION_usbdevice:
6212 usb_enabled = 1;
6213 if (usb_devices_index >= MAX_USB_CMDLINE) {
6214 fprintf(stderr, "Too many USB devices\n");
6215 exit(1);
6217 pstrcpy(usb_devices[usb_devices_index],
6218 sizeof(usb_devices[usb_devices_index]),
6219 optarg);
6220 usb_devices_index++;
6221 break;
6222 case QEMU_OPTION_smp:
6223 smp_cpus = atoi(optarg);
6224 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6225 fprintf(stderr, "Invalid number of CPUs\n");
6226 exit(1);
6228 break;
6229 case QEMU_OPTION_vnc:
6230 vnc_display = atoi(optarg);
6231 if (vnc_display < 0) {
6232 fprintf(stderr, "Invalid VNC display\n");
6233 exit(1);
6235 break;
6236 case QEMU_OPTION_no_acpi:
6237 acpi_enabled = 0;
6238 break;
6243 #if USE_KVM
6244 if (kvm_allowed) {
6245 if (kvm_qemu_init() < 0) {
6246 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
6247 kvm_allowed = 0;
6250 #endif
6252 #ifdef USE_KQEMU
6253 if (smp_cpus > 1)
6254 kqemu_allowed = 0;
6255 #endif
6256 linux_boot = (kernel_filename != NULL);
6258 if (!linux_boot &&
6259 hd_filename[0] == '\0' &&
6260 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6261 fd_filename[0] == '\0')
6262 help();
6264 /* boot to cd by default if no hard disk */
6265 if (hd_filename[0] == '\0' && boot_device == 'c') {
6266 if (fd_filename[0] != '\0')
6267 boot_device = 'a';
6268 else
6269 boot_device = 'd';
6272 setvbuf(stdout, NULL, _IOLBF, 0);
6274 init_timers();
6275 init_timer_alarm();
6277 #ifdef _WIN32
6278 socket_init();
6279 #endif
6281 /* init network clients */
6282 if (nb_net_clients == 0) {
6283 /* if no clients, we use a default config */
6284 pstrcpy(net_clients[0], sizeof(net_clients[0]),
6285 "nic");
6286 pstrcpy(net_clients[1], sizeof(net_clients[0]),
6287 "user");
6288 nb_net_clients = 2;
6291 for(i = 0;i < nb_net_clients; i++) {
6292 if (net_client_init(net_clients[i]) < 0)
6293 exit(1);
6296 /* init the memory */
6297 phys_ram_size = ram_size + vga_ram_size + bios_size;
6298 #if USE_KVM
6299 /* Initialize kvm */
6300 if (kvm_allowed) {
6301 phys_ram_size += KVM_EXTRA_PAGES * 4096;
6302 if (kvm_qemu_create_context() < 0) {
6303 fprintf(stderr, "Could not create KVM context\n");
6304 exit(1);
6306 } else {
6307 phys_ram_base = qemu_vmalloc(phys_ram_size);
6308 if (!phys_ram_base) {
6309 fprintf(stderr, "Could not allocate physical memory\n");
6310 exit(1);
6313 #else
6314 phys_ram_base = qemu_vmalloc(phys_ram_size);
6315 if (!phys_ram_base) {
6316 fprintf(stderr, "Could not allocate physical memory\n");
6317 exit(1);
6319 #endif
6321 /* we always create the cdrom drive, even if no disk is there */
6322 bdrv_init();
6323 if (cdrom_index >= 0) {
6324 bs_table[cdrom_index] = bdrv_new("cdrom");
6325 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6328 /* open the virtual block devices */
6329 for(i = 0; i < MAX_DISKS; i++) {
6330 if (hd_filename[i]) {
6331 if (!bs_table[i]) {
6332 char buf[64];
6333 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6334 bs_table[i] = bdrv_new(buf);
6336 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
6337 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6338 hd_filename[i]);
6339 exit(1);
6341 if (i == 0 && cyls != 0) {
6342 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6343 bdrv_set_translation_hint(bs_table[i], translation);
6348 /* we always create at least one floppy disk */
6349 fd_table[0] = bdrv_new("fda");
6350 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6352 for(i = 0; i < MAX_FD; i++) {
6353 if (fd_filename[i]) {
6354 if (!fd_table[i]) {
6355 char buf[64];
6356 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6357 fd_table[i] = bdrv_new(buf);
6358 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6360 if (fd_filename[i] != '\0') {
6361 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
6362 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6363 fd_filename[i]);
6364 exit(1);
6370 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
6371 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
6373 init_ioports();
6375 /* terminal init */
6376 if (nographic) {
6377 dumb_display_init(ds);
6378 } else if (vnc_display != -1) {
6379 vnc_display_init(ds, vnc_display);
6380 } else {
6381 #if defined(CONFIG_SDL)
6382 sdl_display_init(ds, full_screen);
6383 #elif defined(CONFIG_COCOA)
6384 cocoa_display_init(ds, full_screen);
6385 #else
6386 dumb_display_init(ds);
6387 #endif
6390 monitor_hd = qemu_chr_open(monitor_device);
6391 if (!monitor_hd) {
6392 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6393 exit(1);
6395 monitor_init(monitor_hd, !nographic);
6397 if (*vmchannel_device) {
6398 vmchannel_hd = qemu_chr_open(vmchannel_device);
6399 if (!vmchannel_hd) {
6400 fprintf(stderr, "qemu: could not open vmchannel device '%s'\n", vmchannel_device);
6401 exit(1);
6403 vmchannel_init(vmchannel_hd);
6406 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6407 if (serial_devices[i][0] != '\0') {
6408 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6409 if (!serial_hds[i]) {
6410 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6411 serial_devices[i]);
6412 exit(1);
6414 if (!strcmp(serial_devices[i], "vc"))
6415 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6419 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6420 if (parallel_devices[i][0] != '\0') {
6421 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6422 if (!parallel_hds[i]) {
6423 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6424 parallel_devices[i]);
6425 exit(1);
6427 if (!strcmp(parallel_devices[i], "vc"))
6428 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6432 machine->init(ram_size, vga_ram_size, boot_device,
6433 ds, fd_filename, snapshot,
6434 kernel_filename, kernel_cmdline, initrd_filename);
6436 /* init USB devices */
6437 if (usb_enabled) {
6438 for(i = 0; i < usb_devices_index; i++) {
6439 if (usb_device_add(usb_devices[i]) < 0) {
6440 fprintf(stderr, "Warning: could not add USB device %s\n",
6441 usb_devices[i]);
6446 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6447 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6449 #ifdef CONFIG_GDBSTUB
6450 if (use_gdbstub) {
6451 if (gdbserver_start(gdbstub_port) < 0) {
6452 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6453 gdbstub_port);
6454 exit(1);
6455 } else {
6456 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6458 } else
6459 #endif
6460 if (loadvm)
6461 qemu_loadvm(loadvm, &qemu_savevm_method_file);
6464 /* XXX: simplify init */
6465 read_passwords();
6466 if (start_emulation) {
6467 vm_start();
6469 else {
6470 console_select(1); /* focus on monitor */
6473 main_loop();
6474 quit_timers();
6475 return 0;