Fix CPU type zapped by system_reset
[qemu/qemu_0_9_1_stable.git] / vl.c
blob3691f38fd1396e8feeecaf2033b26c1cfe2613b2
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2007 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "vl.h"
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <sys/time.h>
32 #include <zlib.h>
34 #ifndef _WIN32
35 #include <sys/times.h>
36 #include <sys/wait.h>
37 #include <termios.h>
38 #include <sys/poll.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <dirent.h>
44 #include <netdb.h>
45 #ifdef _BSD
46 #include <sys/stat.h>
47 #ifndef __APPLE__
48 #include <libutil.h>
49 #endif
50 #else
51 #ifndef __sun__
52 #include <linux/if.h>
53 #include <linux/if_tun.h>
54 #include <pty.h>
55 #include <malloc.h>
56 #include <linux/rtc.h>
57 #include <linux/ppdev.h>
58 #include <linux/parport.h>
59 #else
60 #include <sys/stat.h>
61 #include <sys/ethernet.h>
62 #include <sys/sockio.h>
63 #include <arpa/inet.h>
64 #include <netinet/arp.h>
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/ip.h>
68 #include <netinet/ip_icmp.h> // must come after ip.h
69 #include <netinet/udp.h>
70 #include <netinet/tcp.h>
71 #include <net/if.h>
72 #include <syslog.h>
73 #include <stropts.h>
74 #endif
75 #endif
76 #endif
78 #if defined(CONFIG_SLIRP)
79 #include "libslirp.h"
80 #endif
82 #ifdef _WIN32
83 #include <malloc.h>
84 #include <sys/timeb.h>
85 #include <windows.h>
86 #define getopt_long_only getopt_long
87 #define memalign(align, size) malloc(size)
88 #endif
90 #include "qemu_socket.h"
92 #ifdef CONFIG_SDL
93 #ifdef __APPLE__
94 #include <SDL/SDL.h>
95 #endif
96 #endif /* CONFIG_SDL */
98 #ifdef CONFIG_COCOA
99 #undef main
100 #define main qemu_main
101 #endif /* CONFIG_COCOA */
103 #include "disas.h"
105 #include "exec-all.h"
107 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
108 #ifdef __sun__
109 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
110 #else
111 #define SMBD_COMMAND "/usr/sbin/smbd"
112 #endif
114 //#define DEBUG_UNUSED_IOPORT
115 //#define DEBUG_IOPORT
117 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
119 #ifdef TARGET_PPC
120 #define DEFAULT_RAM_SIZE 144
121 #else
122 #define DEFAULT_RAM_SIZE 128
123 #endif
124 /* in ms */
125 #define GUI_REFRESH_INTERVAL 30
127 /* Max number of USB devices that can be specified on the commandline. */
128 #define MAX_USB_CMDLINE 8
130 /* XXX: use a two level table to limit memory usage */
131 #define MAX_IOPORTS 65536
133 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
134 char phys_ram_file[1024];
135 void *ioport_opaque[MAX_IOPORTS];
136 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
137 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
138 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
139 to store the VM snapshots */
140 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
141 BlockDriverState *pflash_table[MAX_PFLASH];
142 BlockDriverState *sd_bdrv;
143 /* point to the block driver where the snapshots are managed */
144 BlockDriverState *bs_snapshots;
145 int vga_ram_size;
146 static DisplayState display_state;
147 int nographic;
148 const char* keyboard_layout = NULL;
149 int64_t ticks_per_sec;
150 int boot_device = 'c';
151 int ram_size;
152 int pit_min_timer_count = 0;
153 int nb_nics;
154 NICInfo nd_table[MAX_NICS];
155 QEMUTimer *gui_timer;
156 int vm_running;
157 int rtc_utc = 1;
158 int cirrus_vga_enabled = 1;
159 int vmsvga_enabled = 0;
160 #ifdef TARGET_SPARC
161 int graphic_width = 1024;
162 int graphic_height = 768;
163 int graphic_depth = 8;
164 #else
165 int graphic_width = 800;
166 int graphic_height = 600;
167 int graphic_depth = 15;
168 #endif
169 int full_screen = 0;
170 int no_frame = 0;
171 int no_quit = 0;
172 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
173 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
174 #ifdef TARGET_I386
175 int win2k_install_hack = 0;
176 #endif
177 int usb_enabled = 0;
178 static VLANState *first_vlan;
179 int smp_cpus = 1;
180 const char *vnc_display;
181 #if defined(TARGET_SPARC)
182 #define MAX_CPUS 16
183 #elif defined(TARGET_I386)
184 #define MAX_CPUS 255
185 #else
186 #define MAX_CPUS 1
187 #endif
188 int acpi_enabled = 1;
189 int fd_bootchk = 1;
190 int no_reboot = 0;
191 int daemonize = 0;
192 const char *option_rom[MAX_OPTION_ROMS];
193 int nb_option_roms;
194 int semihosting_enabled = 0;
195 int autostart = 1;
196 const char *qemu_name;
198 /***********************************************************/
199 /* x86 ISA bus support */
201 target_phys_addr_t isa_mem_base = 0;
202 PicState2 *isa_pic;
204 uint32_t default_ioport_readb(void *opaque, uint32_t address)
206 #ifdef DEBUG_UNUSED_IOPORT
207 fprintf(stderr, "unused inb: port=0x%04x\n", address);
208 #endif
209 return 0xff;
212 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
214 #ifdef DEBUG_UNUSED_IOPORT
215 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
216 #endif
219 /* default is to make two byte accesses */
220 uint32_t default_ioport_readw(void *opaque, uint32_t address)
222 uint32_t data;
223 data = ioport_read_table[0][address](ioport_opaque[address], address);
224 address = (address + 1) & (MAX_IOPORTS - 1);
225 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
226 return data;
229 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
231 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
232 address = (address + 1) & (MAX_IOPORTS - 1);
233 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
236 uint32_t default_ioport_readl(void *opaque, uint32_t address)
238 #ifdef DEBUG_UNUSED_IOPORT
239 fprintf(stderr, "unused inl: port=0x%04x\n", address);
240 #endif
241 return 0xffffffff;
244 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
246 #ifdef DEBUG_UNUSED_IOPORT
247 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
248 #endif
251 void init_ioports(void)
253 int i;
255 for(i = 0; i < MAX_IOPORTS; i++) {
256 ioport_read_table[0][i] = default_ioport_readb;
257 ioport_write_table[0][i] = default_ioport_writeb;
258 ioport_read_table[1][i] = default_ioport_readw;
259 ioport_write_table[1][i] = default_ioport_writew;
260 ioport_read_table[2][i] = default_ioport_readl;
261 ioport_write_table[2][i] = default_ioport_writel;
265 /* size is the word size in byte */
266 int register_ioport_read(int start, int length, int size,
267 IOPortReadFunc *func, void *opaque)
269 int i, bsize;
271 if (size == 1) {
272 bsize = 0;
273 } else if (size == 2) {
274 bsize = 1;
275 } else if (size == 4) {
276 bsize = 2;
277 } else {
278 hw_error("register_ioport_read: invalid size");
279 return -1;
281 for(i = start; i < start + length; i += size) {
282 ioport_read_table[bsize][i] = func;
283 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
284 hw_error("register_ioport_read: invalid opaque");
285 ioport_opaque[i] = opaque;
287 return 0;
290 /* size is the word size in byte */
291 int register_ioport_write(int start, int length, int size,
292 IOPortWriteFunc *func, void *opaque)
294 int i, bsize;
296 if (size == 1) {
297 bsize = 0;
298 } else if (size == 2) {
299 bsize = 1;
300 } else if (size == 4) {
301 bsize = 2;
302 } else {
303 hw_error("register_ioport_write: invalid size");
304 return -1;
306 for(i = start; i < start + length; i += size) {
307 ioport_write_table[bsize][i] = func;
308 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
309 hw_error("register_ioport_write: invalid opaque");
310 ioport_opaque[i] = opaque;
312 return 0;
315 void isa_unassign_ioport(int start, int length)
317 int i;
319 for(i = start; i < start + length; i++) {
320 ioport_read_table[0][i] = default_ioport_readb;
321 ioport_read_table[1][i] = default_ioport_readw;
322 ioport_read_table[2][i] = default_ioport_readl;
324 ioport_write_table[0][i] = default_ioport_writeb;
325 ioport_write_table[1][i] = default_ioport_writew;
326 ioport_write_table[2][i] = default_ioport_writel;
330 /***********************************************************/
332 void cpu_outb(CPUState *env, int addr, int val)
334 #ifdef DEBUG_IOPORT
335 if (loglevel & CPU_LOG_IOPORT)
336 fprintf(logfile, "outb: %04x %02x\n", addr, val);
337 #endif
338 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
339 #ifdef USE_KQEMU
340 if (env)
341 env->last_io_time = cpu_get_time_fast();
342 #endif
345 void cpu_outw(CPUState *env, int addr, int val)
347 #ifdef DEBUG_IOPORT
348 if (loglevel & CPU_LOG_IOPORT)
349 fprintf(logfile, "outw: %04x %04x\n", addr, val);
350 #endif
351 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
352 #ifdef USE_KQEMU
353 if (env)
354 env->last_io_time = cpu_get_time_fast();
355 #endif
358 void cpu_outl(CPUState *env, int addr, int val)
360 #ifdef DEBUG_IOPORT
361 if (loglevel & CPU_LOG_IOPORT)
362 fprintf(logfile, "outl: %04x %08x\n", addr, val);
363 #endif
364 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
365 #ifdef USE_KQEMU
366 if (env)
367 env->last_io_time = cpu_get_time_fast();
368 #endif
371 int cpu_inb(CPUState *env, int addr)
373 int val;
374 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
375 #ifdef DEBUG_IOPORT
376 if (loglevel & CPU_LOG_IOPORT)
377 fprintf(logfile, "inb : %04x %02x\n", addr, val);
378 #endif
379 #ifdef USE_KQEMU
380 if (env)
381 env->last_io_time = cpu_get_time_fast();
382 #endif
383 return val;
386 int cpu_inw(CPUState *env, int addr)
388 int val;
389 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
390 #ifdef DEBUG_IOPORT
391 if (loglevel & CPU_LOG_IOPORT)
392 fprintf(logfile, "inw : %04x %04x\n", addr, val);
393 #endif
394 #ifdef USE_KQEMU
395 if (env)
396 env->last_io_time = cpu_get_time_fast();
397 #endif
398 return val;
401 int cpu_inl(CPUState *env, int addr)
403 int val;
404 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
405 #ifdef DEBUG_IOPORT
406 if (loglevel & CPU_LOG_IOPORT)
407 fprintf(logfile, "inl : %04x %08x\n", addr, val);
408 #endif
409 #ifdef USE_KQEMU
410 if (env)
411 env->last_io_time = cpu_get_time_fast();
412 #endif
413 return val;
416 /***********************************************************/
417 void hw_error(const char *fmt, ...)
419 va_list ap;
420 CPUState *env;
422 va_start(ap, fmt);
423 fprintf(stderr, "qemu: hardware error: ");
424 vfprintf(stderr, fmt, ap);
425 fprintf(stderr, "\n");
426 for(env = first_cpu; env != NULL; env = env->next_cpu) {
427 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
428 #ifdef TARGET_I386
429 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
430 #else
431 cpu_dump_state(env, stderr, fprintf, 0);
432 #endif
434 va_end(ap);
435 abort();
438 /***********************************************************/
439 /* keyboard/mouse */
441 static QEMUPutKBDEvent *qemu_put_kbd_event;
442 static void *qemu_put_kbd_event_opaque;
443 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
444 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
446 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
448 qemu_put_kbd_event_opaque = opaque;
449 qemu_put_kbd_event = func;
452 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
453 void *opaque, int absolute,
454 const char *name)
456 QEMUPutMouseEntry *s, *cursor;
458 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
459 if (!s)
460 return NULL;
462 s->qemu_put_mouse_event = func;
463 s->qemu_put_mouse_event_opaque = opaque;
464 s->qemu_put_mouse_event_absolute = absolute;
465 s->qemu_put_mouse_event_name = qemu_strdup(name);
466 s->next = NULL;
468 if (!qemu_put_mouse_event_head) {
469 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
470 return s;
473 cursor = qemu_put_mouse_event_head;
474 while (cursor->next != NULL)
475 cursor = cursor->next;
477 cursor->next = s;
478 qemu_put_mouse_event_current = s;
480 return s;
483 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
485 QEMUPutMouseEntry *prev = NULL, *cursor;
487 if (!qemu_put_mouse_event_head || entry == NULL)
488 return;
490 cursor = qemu_put_mouse_event_head;
491 while (cursor != NULL && cursor != entry) {
492 prev = cursor;
493 cursor = cursor->next;
496 if (cursor == NULL) // does not exist or list empty
497 return;
498 else if (prev == NULL) { // entry is head
499 qemu_put_mouse_event_head = cursor->next;
500 if (qemu_put_mouse_event_current == entry)
501 qemu_put_mouse_event_current = cursor->next;
502 qemu_free(entry->qemu_put_mouse_event_name);
503 qemu_free(entry);
504 return;
507 prev->next = entry->next;
509 if (qemu_put_mouse_event_current == entry)
510 qemu_put_mouse_event_current = prev;
512 qemu_free(entry->qemu_put_mouse_event_name);
513 qemu_free(entry);
516 void kbd_put_keycode(int keycode)
518 if (qemu_put_kbd_event) {
519 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
523 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
525 QEMUPutMouseEvent *mouse_event;
526 void *mouse_event_opaque;
528 if (!qemu_put_mouse_event_current) {
529 return;
532 mouse_event =
533 qemu_put_mouse_event_current->qemu_put_mouse_event;
534 mouse_event_opaque =
535 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
537 if (mouse_event) {
538 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
542 int kbd_mouse_is_absolute(void)
544 if (!qemu_put_mouse_event_current)
545 return 0;
547 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
550 void (*kbd_mouse_set)(int x, int y, int on) = NULL;
551 void (*kbd_cursor_define)(int width, int height, int bpp, int hot_x, int hot_y,
552 uint8_t *image, uint8_t *mask) = NULL;
554 void do_info_mice(void)
556 QEMUPutMouseEntry *cursor;
557 int index = 0;
559 if (!qemu_put_mouse_event_head) {
560 term_printf("No mouse devices connected\n");
561 return;
564 term_printf("Mouse devices available:\n");
565 cursor = qemu_put_mouse_event_head;
566 while (cursor != NULL) {
567 term_printf("%c Mouse #%d: %s\n",
568 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
569 index, cursor->qemu_put_mouse_event_name);
570 index++;
571 cursor = cursor->next;
575 void do_mouse_set(int index)
577 QEMUPutMouseEntry *cursor;
578 int i = 0;
580 if (!qemu_put_mouse_event_head) {
581 term_printf("No mouse devices connected\n");
582 return;
585 cursor = qemu_put_mouse_event_head;
586 while (cursor != NULL && index != i) {
587 i++;
588 cursor = cursor->next;
591 if (cursor != NULL)
592 qemu_put_mouse_event_current = cursor;
593 else
594 term_printf("Mouse at given index not found\n");
597 /* compute with 96 bit intermediate result: (a*b)/c */
598 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
600 union {
601 uint64_t ll;
602 struct {
603 #ifdef WORDS_BIGENDIAN
604 uint32_t high, low;
605 #else
606 uint32_t low, high;
607 #endif
608 } l;
609 } u, res;
610 uint64_t rl, rh;
612 u.ll = a;
613 rl = (uint64_t)u.l.low * (uint64_t)b;
614 rh = (uint64_t)u.l.high * (uint64_t)b;
615 rh += (rl >> 32);
616 res.l.high = rh / c;
617 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
618 return res.ll;
621 /***********************************************************/
622 /* real time host monotonic timer */
624 #define QEMU_TIMER_BASE 1000000000LL
626 #ifdef WIN32
628 static int64_t clock_freq;
630 static void init_get_clock(void)
632 LARGE_INTEGER freq;
633 int ret;
634 ret = QueryPerformanceFrequency(&freq);
635 if (ret == 0) {
636 fprintf(stderr, "Could not calibrate ticks\n");
637 exit(1);
639 clock_freq = freq.QuadPart;
642 static int64_t get_clock(void)
644 LARGE_INTEGER ti;
645 QueryPerformanceCounter(&ti);
646 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
649 #else
651 static int use_rt_clock;
653 static void init_get_clock(void)
655 use_rt_clock = 0;
656 #if defined(__linux__)
658 struct timespec ts;
659 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
660 use_rt_clock = 1;
663 #endif
666 static int64_t get_clock(void)
668 #if defined(__linux__)
669 if (use_rt_clock) {
670 struct timespec ts;
671 clock_gettime(CLOCK_MONOTONIC, &ts);
672 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
673 } else
674 #endif
676 /* XXX: using gettimeofday leads to problems if the date
677 changes, so it should be avoided. */
678 struct timeval tv;
679 gettimeofday(&tv, NULL);
680 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
684 #endif
686 /***********************************************************/
687 /* guest cycle counter */
689 static int64_t cpu_ticks_prev;
690 static int64_t cpu_ticks_offset;
691 static int64_t cpu_clock_offset;
692 static int cpu_ticks_enabled;
694 /* return the host CPU cycle counter and handle stop/restart */
695 int64_t cpu_get_ticks(void)
697 if (!cpu_ticks_enabled) {
698 return cpu_ticks_offset;
699 } else {
700 int64_t ticks;
701 ticks = cpu_get_real_ticks();
702 if (cpu_ticks_prev > ticks) {
703 /* Note: non increasing ticks may happen if the host uses
704 software suspend */
705 cpu_ticks_offset += cpu_ticks_prev - ticks;
707 cpu_ticks_prev = ticks;
708 return ticks + cpu_ticks_offset;
712 /* return the host CPU monotonic timer and handle stop/restart */
713 static int64_t cpu_get_clock(void)
715 int64_t ti;
716 if (!cpu_ticks_enabled) {
717 return cpu_clock_offset;
718 } else {
719 ti = get_clock();
720 return ti + cpu_clock_offset;
724 /* enable cpu_get_ticks() */
725 void cpu_enable_ticks(void)
727 if (!cpu_ticks_enabled) {
728 cpu_ticks_offset -= cpu_get_real_ticks();
729 cpu_clock_offset -= get_clock();
730 cpu_ticks_enabled = 1;
734 /* disable cpu_get_ticks() : the clock is stopped. You must not call
735 cpu_get_ticks() after that. */
736 void cpu_disable_ticks(void)
738 if (cpu_ticks_enabled) {
739 cpu_ticks_offset = cpu_get_ticks();
740 cpu_clock_offset = cpu_get_clock();
741 cpu_ticks_enabled = 0;
745 /***********************************************************/
746 /* timers */
748 #define QEMU_TIMER_REALTIME 0
749 #define QEMU_TIMER_VIRTUAL 1
751 struct QEMUClock {
752 int type;
753 /* XXX: add frequency */
756 struct QEMUTimer {
757 QEMUClock *clock;
758 int64_t expire_time;
759 QEMUTimerCB *cb;
760 void *opaque;
761 struct QEMUTimer *next;
764 QEMUClock *rt_clock;
765 QEMUClock *vm_clock;
767 static QEMUTimer *active_timers[2];
768 #ifdef _WIN32
769 static MMRESULT timerID;
770 static HANDLE host_alarm = NULL;
771 static unsigned int period = 1;
772 #else
773 /* frequency of the times() clock tick */
774 static int timer_freq;
775 #endif
777 QEMUClock *qemu_new_clock(int type)
779 QEMUClock *clock;
780 clock = qemu_mallocz(sizeof(QEMUClock));
781 if (!clock)
782 return NULL;
783 clock->type = type;
784 return clock;
787 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
789 QEMUTimer *ts;
791 ts = qemu_mallocz(sizeof(QEMUTimer));
792 ts->clock = clock;
793 ts->cb = cb;
794 ts->opaque = opaque;
795 return ts;
798 void qemu_free_timer(QEMUTimer *ts)
800 qemu_free(ts);
803 /* stop a timer, but do not dealloc it */
804 void qemu_del_timer(QEMUTimer *ts)
806 QEMUTimer **pt, *t;
808 /* NOTE: this code must be signal safe because
809 qemu_timer_expired() can be called from a signal. */
810 pt = &active_timers[ts->clock->type];
811 for(;;) {
812 t = *pt;
813 if (!t)
814 break;
815 if (t == ts) {
816 *pt = t->next;
817 break;
819 pt = &t->next;
823 /* modify the current timer so that it will be fired when current_time
824 >= expire_time. The corresponding callback will be called. */
825 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
827 QEMUTimer **pt, *t;
829 qemu_del_timer(ts);
831 /* add the timer in the sorted list */
832 /* NOTE: this code must be signal safe because
833 qemu_timer_expired() can be called from a signal. */
834 pt = &active_timers[ts->clock->type];
835 for(;;) {
836 t = *pt;
837 if (!t)
838 break;
839 if (t->expire_time > expire_time)
840 break;
841 pt = &t->next;
843 ts->expire_time = expire_time;
844 ts->next = *pt;
845 *pt = ts;
848 int qemu_timer_pending(QEMUTimer *ts)
850 QEMUTimer *t;
851 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
852 if (t == ts)
853 return 1;
855 return 0;
858 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
860 if (!timer_head)
861 return 0;
862 return (timer_head->expire_time <= current_time);
865 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
867 QEMUTimer *ts;
869 for(;;) {
870 ts = *ptimer_head;
871 if (!ts || ts->expire_time > current_time)
872 break;
873 /* remove timer from the list before calling the callback */
874 *ptimer_head = ts->next;
875 ts->next = NULL;
877 /* run the callback (the timer list can be modified) */
878 ts->cb(ts->opaque);
882 int64_t qemu_get_clock(QEMUClock *clock)
884 switch(clock->type) {
885 case QEMU_TIMER_REALTIME:
886 return get_clock() / 1000000;
887 default:
888 case QEMU_TIMER_VIRTUAL:
889 return cpu_get_clock();
893 static void init_timers(void)
895 init_get_clock();
896 ticks_per_sec = QEMU_TIMER_BASE;
897 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
898 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
901 /* save a timer */
902 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
904 uint64_t expire_time;
906 if (qemu_timer_pending(ts)) {
907 expire_time = ts->expire_time;
908 } else {
909 expire_time = -1;
911 qemu_put_be64(f, expire_time);
914 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
916 uint64_t expire_time;
918 expire_time = qemu_get_be64(f);
919 if (expire_time != -1) {
920 qemu_mod_timer(ts, expire_time);
921 } else {
922 qemu_del_timer(ts);
926 static void timer_save(QEMUFile *f, void *opaque)
928 if (cpu_ticks_enabled) {
929 hw_error("cannot save state if virtual timers are running");
931 qemu_put_be64s(f, &cpu_ticks_offset);
932 qemu_put_be64s(f, &ticks_per_sec);
933 qemu_put_be64s(f, &cpu_clock_offset);
936 static int timer_load(QEMUFile *f, void *opaque, int version_id)
938 if (version_id != 1 && version_id != 2)
939 return -EINVAL;
940 if (cpu_ticks_enabled) {
941 return -EINVAL;
943 qemu_get_be64s(f, &cpu_ticks_offset);
944 qemu_get_be64s(f, &ticks_per_sec);
945 if (version_id == 2) {
946 qemu_get_be64s(f, &cpu_clock_offset);
948 return 0;
951 #ifdef _WIN32
952 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
953 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
954 #else
955 static void host_alarm_handler(int host_signum)
956 #endif
958 #if 0
959 #define DISP_FREQ 1000
961 static int64_t delta_min = INT64_MAX;
962 static int64_t delta_max, delta_cum, last_clock, delta, ti;
963 static int count;
964 ti = qemu_get_clock(vm_clock);
965 if (last_clock != 0) {
966 delta = ti - last_clock;
967 if (delta < delta_min)
968 delta_min = delta;
969 if (delta > delta_max)
970 delta_max = delta;
971 delta_cum += delta;
972 if (++count == DISP_FREQ) {
973 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
974 muldiv64(delta_min, 1000000, ticks_per_sec),
975 muldiv64(delta_max, 1000000, ticks_per_sec),
976 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
977 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
978 count = 0;
979 delta_min = INT64_MAX;
980 delta_max = 0;
981 delta_cum = 0;
984 last_clock = ti;
986 #endif
987 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
988 qemu_get_clock(vm_clock)) ||
989 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
990 qemu_get_clock(rt_clock))) {
991 #ifdef _WIN32
992 SetEvent(host_alarm);
993 #endif
994 CPUState *env = cpu_single_env;
995 if (env) {
996 /* stop the currently executing cpu because a timer occured */
997 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
998 #ifdef USE_KQEMU
999 if (env->kqemu_enabled) {
1000 kqemu_cpu_interrupt(env);
1002 #endif
1007 #ifndef _WIN32
1009 #if defined(__linux__)
1011 #define RTC_FREQ 1024
1013 static int rtc_fd;
1015 static int start_rtc_timer(void)
1017 rtc_fd = open("/dev/rtc", O_RDONLY);
1018 if (rtc_fd < 0)
1019 return -1;
1020 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1021 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1022 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1023 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1024 goto fail;
1026 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1027 fail:
1028 close(rtc_fd);
1029 return -1;
1031 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1032 return 0;
1035 #else
1037 static int start_rtc_timer(void)
1039 return -1;
1042 #endif /* !defined(__linux__) */
1044 #endif /* !defined(_WIN32) */
1046 static void init_timer_alarm(void)
1048 #ifdef _WIN32
1050 int count=0;
1051 TIMECAPS tc;
1053 ZeroMemory(&tc, sizeof(TIMECAPS));
1054 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1055 if (period < tc.wPeriodMin)
1056 period = tc.wPeriodMin;
1057 timeBeginPeriod(period);
1058 timerID = timeSetEvent(1, // interval (ms)
1059 period, // resolution
1060 host_alarm_handler, // function
1061 (DWORD)&count, // user parameter
1062 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1063 if( !timerID ) {
1064 perror("failed timer alarm");
1065 exit(1);
1067 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1068 if (!host_alarm) {
1069 perror("failed CreateEvent");
1070 exit(1);
1072 qemu_add_wait_object(host_alarm, NULL, NULL);
1074 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1075 #else
1077 struct sigaction act;
1078 struct itimerval itv;
1080 /* get times() syscall frequency */
1081 timer_freq = sysconf(_SC_CLK_TCK);
1083 /* timer signal */
1084 sigfillset(&act.sa_mask);
1085 act.sa_flags = 0;
1086 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1087 act.sa_flags |= SA_ONSTACK;
1088 #endif
1089 act.sa_handler = host_alarm_handler;
1090 sigaction(SIGALRM, &act, NULL);
1092 itv.it_interval.tv_sec = 0;
1093 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1094 itv.it_value.tv_sec = 0;
1095 itv.it_value.tv_usec = 10 * 1000;
1096 setitimer(ITIMER_REAL, &itv, NULL);
1097 /* we probe the tick duration of the kernel to inform the user if
1098 the emulated kernel requested a too high timer frequency */
1099 getitimer(ITIMER_REAL, &itv);
1101 #if defined(__linux__)
1102 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1103 have timers with 1 ms resolution. The correct solution will
1104 be to use the POSIX real time timers available in recent
1105 2.6 kernels */
1106 if (itv.it_interval.tv_usec > 1000 || 1) {
1107 /* try to use /dev/rtc to have a faster timer */
1108 if (start_rtc_timer() < 0)
1109 goto use_itimer;
1110 /* disable itimer */
1111 itv.it_interval.tv_sec = 0;
1112 itv.it_interval.tv_usec = 0;
1113 itv.it_value.tv_sec = 0;
1114 itv.it_value.tv_usec = 0;
1115 setitimer(ITIMER_REAL, &itv, NULL);
1117 /* use the RTC */
1118 sigaction(SIGIO, &act, NULL);
1119 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1120 fcntl(rtc_fd, F_SETOWN, getpid());
1121 } else
1122 #endif /* defined(__linux__) */
1124 use_itimer:
1125 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1126 PIT_FREQ) / 1000000;
1129 #endif
1132 void quit_timers(void)
1134 #ifdef _WIN32
1135 timeKillEvent(timerID);
1136 timeEndPeriod(period);
1137 if (host_alarm) {
1138 CloseHandle(host_alarm);
1139 host_alarm = NULL;
1141 #endif
1144 /***********************************************************/
1145 /* character device */
1147 static void qemu_chr_event(CharDriverState *s, int event)
1149 if (!s->chr_event)
1150 return;
1151 s->chr_event(s->handler_opaque, event);
1154 static void qemu_chr_reset_bh(void *opaque)
1156 CharDriverState *s = opaque;
1157 qemu_chr_event(s, CHR_EVENT_RESET);
1158 qemu_bh_delete(s->bh);
1159 s->bh = NULL;
1162 void qemu_chr_reset(CharDriverState *s)
1164 if (s->bh == NULL) {
1165 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1166 qemu_bh_schedule(s->bh);
1170 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1172 return s->chr_write(s, buf, len);
1175 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1177 if (!s->chr_ioctl)
1178 return -ENOTSUP;
1179 return s->chr_ioctl(s, cmd, arg);
1182 int qemu_chr_can_read(CharDriverState *s)
1184 if (!s->chr_can_read)
1185 return 0;
1186 return s->chr_can_read(s->handler_opaque);
1189 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1191 s->chr_read(s->handler_opaque, buf, len);
1195 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1197 char buf[4096];
1198 va_list ap;
1199 va_start(ap, fmt);
1200 vsnprintf(buf, sizeof(buf), fmt, ap);
1201 qemu_chr_write(s, buf, strlen(buf));
1202 va_end(ap);
1205 void qemu_chr_send_event(CharDriverState *s, int event)
1207 if (s->chr_send_event)
1208 s->chr_send_event(s, event);
1211 void qemu_chr_add_handlers(CharDriverState *s,
1212 IOCanRWHandler *fd_can_read,
1213 IOReadHandler *fd_read,
1214 IOEventHandler *fd_event,
1215 void *opaque)
1217 s->chr_can_read = fd_can_read;
1218 s->chr_read = fd_read;
1219 s->chr_event = fd_event;
1220 s->handler_opaque = opaque;
1221 if (s->chr_update_read_handler)
1222 s->chr_update_read_handler(s);
1225 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1227 return len;
1230 static CharDriverState *qemu_chr_open_null(void)
1232 CharDriverState *chr;
1234 chr = qemu_mallocz(sizeof(CharDriverState));
1235 if (!chr)
1236 return NULL;
1237 chr->chr_write = null_chr_write;
1238 return chr;
1241 /* MUX driver for serial I/O splitting */
1242 static int term_timestamps;
1243 static int64_t term_timestamps_start;
1244 #define MAX_MUX 4
1245 typedef struct {
1246 IOCanRWHandler *chr_can_read[MAX_MUX];
1247 IOReadHandler *chr_read[MAX_MUX];
1248 IOEventHandler *chr_event[MAX_MUX];
1249 void *ext_opaque[MAX_MUX];
1250 CharDriverState *drv;
1251 int mux_cnt;
1252 int term_got_escape;
1253 int max_size;
1254 } MuxDriver;
1257 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1259 MuxDriver *d = chr->opaque;
1260 int ret;
1261 if (!term_timestamps) {
1262 ret = d->drv->chr_write(d->drv, buf, len);
1263 } else {
1264 int i;
1266 ret = 0;
1267 for(i = 0; i < len; i++) {
1268 ret += d->drv->chr_write(d->drv, buf+i, 1);
1269 if (buf[i] == '\n') {
1270 char buf1[64];
1271 int64_t ti;
1272 int secs;
1274 ti = get_clock();
1275 if (term_timestamps_start == -1)
1276 term_timestamps_start = ti;
1277 ti -= term_timestamps_start;
1278 secs = ti / 1000000000;
1279 snprintf(buf1, sizeof(buf1),
1280 "[%02d:%02d:%02d.%03d] ",
1281 secs / 3600,
1282 (secs / 60) % 60,
1283 secs % 60,
1284 (int)((ti / 1000000) % 1000));
1285 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1289 return ret;
1292 static char *mux_help[] = {
1293 "% h print this help\n\r",
1294 "% x exit emulator\n\r",
1295 "% s save disk data back to file (if -snapshot)\n\r",
1296 "% t toggle console timestamps\n\r"
1297 "% b send break (magic sysrq)\n\r",
1298 "% c switch between console and monitor\n\r",
1299 "% % sends %\n\r",
1300 NULL
1303 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1304 static void mux_print_help(CharDriverState *chr)
1306 int i, j;
1307 char ebuf[15] = "Escape-Char";
1308 char cbuf[50] = "\n\r";
1310 if (term_escape_char > 0 && term_escape_char < 26) {
1311 sprintf(cbuf,"\n\r");
1312 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1313 } else {
1314 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1316 chr->chr_write(chr, cbuf, strlen(cbuf));
1317 for (i = 0; mux_help[i] != NULL; i++) {
1318 for (j=0; mux_help[i][j] != '\0'; j++) {
1319 if (mux_help[i][j] == '%')
1320 chr->chr_write(chr, ebuf, strlen(ebuf));
1321 else
1322 chr->chr_write(chr, &mux_help[i][j], 1);
1327 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1329 if (d->term_got_escape) {
1330 d->term_got_escape = 0;
1331 if (ch == term_escape_char)
1332 goto send_char;
1333 switch(ch) {
1334 case '?':
1335 case 'h':
1336 mux_print_help(chr);
1337 break;
1338 case 'x':
1340 char *term = "QEMU: Terminated\n\r";
1341 chr->chr_write(chr,term,strlen(term));
1342 exit(0);
1343 break;
1345 case 's':
1347 int i;
1348 for (i = 0; i < MAX_DISKS; i++) {
1349 if (bs_table[i])
1350 bdrv_commit(bs_table[i]);
1353 break;
1354 case 'b':
1355 if (chr->chr_event)
1356 chr->chr_event(chr->opaque, CHR_EVENT_BREAK);
1357 break;
1358 case 'c':
1359 /* Switch to the next registered device */
1360 chr->focus++;
1361 if (chr->focus >= d->mux_cnt)
1362 chr->focus = 0;
1363 break;
1364 case 't':
1365 term_timestamps = !term_timestamps;
1366 term_timestamps_start = -1;
1367 break;
1369 } else if (ch == term_escape_char) {
1370 d->term_got_escape = 1;
1371 } else {
1372 send_char:
1373 return 1;
1375 return 0;
1378 static int mux_chr_can_read(void *opaque)
1380 CharDriverState *chr = opaque;
1381 MuxDriver *d = chr->opaque;
1382 if (d->chr_can_read[chr->focus])
1383 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1384 return 0;
1387 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1389 CharDriverState *chr = opaque;
1390 MuxDriver *d = chr->opaque;
1391 int i;
1392 for(i = 0; i < size; i++)
1393 if (mux_proc_byte(chr, d, buf[i]))
1394 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1397 static void mux_chr_event(void *opaque, int event)
1399 CharDriverState *chr = opaque;
1400 MuxDriver *d = chr->opaque;
1401 int i;
1403 /* Send the event to all registered listeners */
1404 for (i = 0; i < d->mux_cnt; i++)
1405 if (d->chr_event[i])
1406 d->chr_event[i](d->ext_opaque[i], event);
1409 static void mux_chr_update_read_handler(CharDriverState *chr)
1411 MuxDriver *d = chr->opaque;
1413 if (d->mux_cnt >= MAX_MUX) {
1414 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1415 return;
1417 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1418 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1419 d->chr_read[d->mux_cnt] = chr->chr_read;
1420 d->chr_event[d->mux_cnt] = chr->chr_event;
1421 /* Fix up the real driver with mux routines */
1422 if (d->mux_cnt == 0) {
1423 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1424 mux_chr_event, chr);
1426 chr->focus = d->mux_cnt;
1427 d->mux_cnt++;
1430 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1432 CharDriverState *chr;
1433 MuxDriver *d;
1435 chr = qemu_mallocz(sizeof(CharDriverState));
1436 if (!chr)
1437 return NULL;
1438 d = qemu_mallocz(sizeof(MuxDriver));
1439 if (!d) {
1440 free(chr);
1441 return NULL;
1444 chr->opaque = d;
1445 d->drv = drv;
1446 chr->focus = -1;
1447 chr->chr_write = mux_chr_write;
1448 chr->chr_update_read_handler = mux_chr_update_read_handler;
1449 return chr;
1453 #ifdef _WIN32
1455 static void socket_cleanup(void)
1457 WSACleanup();
1460 static int socket_init(void)
1462 WSADATA Data;
1463 int ret, err;
1465 ret = WSAStartup(MAKEWORD(2,2), &Data);
1466 if (ret != 0) {
1467 err = WSAGetLastError();
1468 fprintf(stderr, "WSAStartup: %d\n", err);
1469 return -1;
1471 atexit(socket_cleanup);
1472 return 0;
1475 static int send_all(int fd, const uint8_t *buf, int len1)
1477 int ret, len;
1479 len = len1;
1480 while (len > 0) {
1481 ret = send(fd, buf, len, 0);
1482 if (ret < 0) {
1483 int errno;
1484 errno = WSAGetLastError();
1485 if (errno != WSAEWOULDBLOCK) {
1486 return -1;
1488 } else if (ret == 0) {
1489 break;
1490 } else {
1491 buf += ret;
1492 len -= ret;
1495 return len1 - len;
1498 void socket_set_nonblock(int fd)
1500 unsigned long opt = 1;
1501 ioctlsocket(fd, FIONBIO, &opt);
1504 #else
1506 static int unix_write(int fd, const uint8_t *buf, int len1)
1508 int ret, len;
1510 len = len1;
1511 while (len > 0) {
1512 ret = write(fd, buf, len);
1513 if (ret < 0) {
1514 if (errno != EINTR && errno != EAGAIN)
1515 return -1;
1516 } else if (ret == 0) {
1517 break;
1518 } else {
1519 buf += ret;
1520 len -= ret;
1523 return len1 - len;
1526 static inline int send_all(int fd, const uint8_t *buf, int len1)
1528 return unix_write(fd, buf, len1);
1531 void socket_set_nonblock(int fd)
1533 fcntl(fd, F_SETFL, O_NONBLOCK);
1535 #endif /* !_WIN32 */
1537 #ifndef _WIN32
1539 typedef struct {
1540 int fd_in, fd_out;
1541 int max_size;
1542 } FDCharDriver;
1544 #define STDIO_MAX_CLIENTS 1
1545 static int stdio_nb_clients = 0;
1547 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1549 FDCharDriver *s = chr->opaque;
1550 return unix_write(s->fd_out, buf, len);
1553 static int fd_chr_read_poll(void *opaque)
1555 CharDriverState *chr = opaque;
1556 FDCharDriver *s = chr->opaque;
1558 s->max_size = qemu_chr_can_read(chr);
1559 return s->max_size;
1562 static void fd_chr_read(void *opaque)
1564 CharDriverState *chr = opaque;
1565 FDCharDriver *s = chr->opaque;
1566 int size, len;
1567 uint8_t buf[1024];
1569 len = sizeof(buf);
1570 if (len > s->max_size)
1571 len = s->max_size;
1572 if (len == 0)
1573 return;
1574 size = read(s->fd_in, buf, len);
1575 if (size == 0) {
1576 /* FD has been closed. Remove it from the active list. */
1577 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1578 return;
1580 if (size > 0) {
1581 qemu_chr_read(chr, buf, size);
1585 static void fd_chr_update_read_handler(CharDriverState *chr)
1587 FDCharDriver *s = chr->opaque;
1589 if (s->fd_in >= 0) {
1590 if (nographic && s->fd_in == 0) {
1591 } else {
1592 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1593 fd_chr_read, NULL, chr);
1598 /* open a character device to a unix fd */
1599 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1601 CharDriverState *chr;
1602 FDCharDriver *s;
1604 chr = qemu_mallocz(sizeof(CharDriverState));
1605 if (!chr)
1606 return NULL;
1607 s = qemu_mallocz(sizeof(FDCharDriver));
1608 if (!s) {
1609 free(chr);
1610 return NULL;
1612 s->fd_in = fd_in;
1613 s->fd_out = fd_out;
1614 chr->opaque = s;
1615 chr->chr_write = fd_chr_write;
1616 chr->chr_update_read_handler = fd_chr_update_read_handler;
1618 qemu_chr_reset(chr);
1620 return chr;
1623 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1625 int fd_out;
1627 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1628 if (fd_out < 0)
1629 return NULL;
1630 return qemu_chr_open_fd(-1, fd_out);
1633 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1635 int fd_in, fd_out;
1636 char filename_in[256], filename_out[256];
1638 snprintf(filename_in, 256, "%s.in", filename);
1639 snprintf(filename_out, 256, "%s.out", filename);
1640 fd_in = open(filename_in, O_RDWR | O_BINARY);
1641 fd_out = open(filename_out, O_RDWR | O_BINARY);
1642 if (fd_in < 0 || fd_out < 0) {
1643 if (fd_in >= 0)
1644 close(fd_in);
1645 if (fd_out >= 0)
1646 close(fd_out);
1647 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1648 if (fd_in < 0)
1649 return NULL;
1651 return qemu_chr_open_fd(fd_in, fd_out);
1655 /* for STDIO, we handle the case where several clients use it
1656 (nographic mode) */
1658 #define TERM_FIFO_MAX_SIZE 1
1660 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1661 static int term_fifo_size;
1663 static int stdio_read_poll(void *opaque)
1665 CharDriverState *chr = opaque;
1667 /* try to flush the queue if needed */
1668 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1669 qemu_chr_read(chr, term_fifo, 1);
1670 term_fifo_size = 0;
1672 /* see if we can absorb more chars */
1673 if (term_fifo_size == 0)
1674 return 1;
1675 else
1676 return 0;
1679 static void stdio_read(void *opaque)
1681 int size;
1682 uint8_t buf[1];
1683 CharDriverState *chr = opaque;
1685 size = read(0, buf, 1);
1686 if (size == 0) {
1687 /* stdin has been closed. Remove it from the active list. */
1688 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1689 return;
1691 if (size > 0) {
1692 if (qemu_chr_can_read(chr) > 0) {
1693 qemu_chr_read(chr, buf, 1);
1694 } else if (term_fifo_size == 0) {
1695 term_fifo[term_fifo_size++] = buf[0];
1700 /* init terminal so that we can grab keys */
1701 static struct termios oldtty;
1702 static int old_fd0_flags;
1704 static void term_exit(void)
1706 tcsetattr (0, TCSANOW, &oldtty);
1707 fcntl(0, F_SETFL, old_fd0_flags);
1710 static void term_init(void)
1712 struct termios tty;
1714 tcgetattr (0, &tty);
1715 oldtty = tty;
1716 old_fd0_flags = fcntl(0, F_GETFL);
1718 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1719 |INLCR|IGNCR|ICRNL|IXON);
1720 tty.c_oflag |= OPOST;
1721 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1722 /* if graphical mode, we allow Ctrl-C handling */
1723 if (nographic)
1724 tty.c_lflag &= ~ISIG;
1725 tty.c_cflag &= ~(CSIZE|PARENB);
1726 tty.c_cflag |= CS8;
1727 tty.c_cc[VMIN] = 1;
1728 tty.c_cc[VTIME] = 0;
1730 tcsetattr (0, TCSANOW, &tty);
1732 atexit(term_exit);
1734 fcntl(0, F_SETFL, O_NONBLOCK);
1737 static CharDriverState *qemu_chr_open_stdio(void)
1739 CharDriverState *chr;
1741 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1742 return NULL;
1743 chr = qemu_chr_open_fd(0, 1);
1744 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1745 stdio_nb_clients++;
1746 term_init();
1748 return chr;
1751 #if defined(__linux__)
1752 static CharDriverState *qemu_chr_open_pty(void)
1754 struct termios tty;
1755 char slave_name[1024];
1756 int master_fd, slave_fd;
1758 /* Not satisfying */
1759 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1760 return NULL;
1763 /* Disabling local echo and line-buffered output */
1764 tcgetattr (master_fd, &tty);
1765 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1766 tty.c_cc[VMIN] = 1;
1767 tty.c_cc[VTIME] = 0;
1768 tcsetattr (master_fd, TCSAFLUSH, &tty);
1770 fprintf(stderr, "char device redirected to %s\n", slave_name);
1771 return qemu_chr_open_fd(master_fd, master_fd);
1774 static void tty_serial_init(int fd, int speed,
1775 int parity, int data_bits, int stop_bits)
1777 struct termios tty;
1778 speed_t spd;
1780 #if 0
1781 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1782 speed, parity, data_bits, stop_bits);
1783 #endif
1784 tcgetattr (fd, &tty);
1786 switch(speed) {
1787 case 50:
1788 spd = B50;
1789 break;
1790 case 75:
1791 spd = B75;
1792 break;
1793 case 300:
1794 spd = B300;
1795 break;
1796 case 600:
1797 spd = B600;
1798 break;
1799 case 1200:
1800 spd = B1200;
1801 break;
1802 case 2400:
1803 spd = B2400;
1804 break;
1805 case 4800:
1806 spd = B4800;
1807 break;
1808 case 9600:
1809 spd = B9600;
1810 break;
1811 case 19200:
1812 spd = B19200;
1813 break;
1814 case 38400:
1815 spd = B38400;
1816 break;
1817 case 57600:
1818 spd = B57600;
1819 break;
1820 default:
1821 case 115200:
1822 spd = B115200;
1823 break;
1826 cfsetispeed(&tty, spd);
1827 cfsetospeed(&tty, spd);
1829 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1830 |INLCR|IGNCR|ICRNL|IXON);
1831 tty.c_oflag |= OPOST;
1832 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1833 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1834 switch(data_bits) {
1835 default:
1836 case 8:
1837 tty.c_cflag |= CS8;
1838 break;
1839 case 7:
1840 tty.c_cflag |= CS7;
1841 break;
1842 case 6:
1843 tty.c_cflag |= CS6;
1844 break;
1845 case 5:
1846 tty.c_cflag |= CS5;
1847 break;
1849 switch(parity) {
1850 default:
1851 case 'N':
1852 break;
1853 case 'E':
1854 tty.c_cflag |= PARENB;
1855 break;
1856 case 'O':
1857 tty.c_cflag |= PARENB | PARODD;
1858 break;
1860 if (stop_bits == 2)
1861 tty.c_cflag |= CSTOPB;
1863 tcsetattr (fd, TCSANOW, &tty);
1866 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1868 FDCharDriver *s = chr->opaque;
1870 switch(cmd) {
1871 case CHR_IOCTL_SERIAL_SET_PARAMS:
1873 QEMUSerialSetParams *ssp = arg;
1874 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1875 ssp->data_bits, ssp->stop_bits);
1877 break;
1878 case CHR_IOCTL_SERIAL_SET_BREAK:
1880 int enable = *(int *)arg;
1881 if (enable)
1882 tcsendbreak(s->fd_in, 1);
1884 break;
1885 default:
1886 return -ENOTSUP;
1888 return 0;
1891 static CharDriverState *qemu_chr_open_tty(const char *filename)
1893 CharDriverState *chr;
1894 int fd;
1896 fd = open(filename, O_RDWR | O_NONBLOCK);
1897 if (fd < 0)
1898 return NULL;
1899 fcntl(fd, F_SETFL, O_NONBLOCK);
1900 tty_serial_init(fd, 115200, 'N', 8, 1);
1901 chr = qemu_chr_open_fd(fd, fd);
1902 if (!chr)
1903 return NULL;
1904 chr->chr_ioctl = tty_serial_ioctl;
1905 qemu_chr_reset(chr);
1906 return chr;
1909 typedef struct {
1910 int fd;
1911 int mode;
1912 } ParallelCharDriver;
1914 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1916 if (s->mode != mode) {
1917 int m = mode;
1918 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1919 return 0;
1920 s->mode = mode;
1922 return 1;
1925 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1927 ParallelCharDriver *drv = chr->opaque;
1928 int fd = drv->fd;
1929 uint8_t b;
1931 switch(cmd) {
1932 case CHR_IOCTL_PP_READ_DATA:
1933 if (ioctl(fd, PPRDATA, &b) < 0)
1934 return -ENOTSUP;
1935 *(uint8_t *)arg = b;
1936 break;
1937 case CHR_IOCTL_PP_WRITE_DATA:
1938 b = *(uint8_t *)arg;
1939 if (ioctl(fd, PPWDATA, &b) < 0)
1940 return -ENOTSUP;
1941 break;
1942 case CHR_IOCTL_PP_READ_CONTROL:
1943 if (ioctl(fd, PPRCONTROL, &b) < 0)
1944 return -ENOTSUP;
1945 /* Linux gives only the lowest bits, and no way to know data
1946 direction! For better compatibility set the fixed upper
1947 bits. */
1948 *(uint8_t *)arg = b | 0xc0;
1949 break;
1950 case CHR_IOCTL_PP_WRITE_CONTROL:
1951 b = *(uint8_t *)arg;
1952 if (ioctl(fd, PPWCONTROL, &b) < 0)
1953 return -ENOTSUP;
1954 break;
1955 case CHR_IOCTL_PP_READ_STATUS:
1956 if (ioctl(fd, PPRSTATUS, &b) < 0)
1957 return -ENOTSUP;
1958 *(uint8_t *)arg = b;
1959 break;
1960 case CHR_IOCTL_PP_EPP_READ_ADDR:
1961 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1962 struct ParallelIOArg *parg = arg;
1963 int n = read(fd, parg->buffer, parg->count);
1964 if (n != parg->count) {
1965 return -EIO;
1968 break;
1969 case CHR_IOCTL_PP_EPP_READ:
1970 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1971 struct ParallelIOArg *parg = arg;
1972 int n = read(fd, parg->buffer, parg->count);
1973 if (n != parg->count) {
1974 return -EIO;
1977 break;
1978 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1979 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1980 struct ParallelIOArg *parg = arg;
1981 int n = write(fd, parg->buffer, parg->count);
1982 if (n != parg->count) {
1983 return -EIO;
1986 break;
1987 case CHR_IOCTL_PP_EPP_WRITE:
1988 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1989 struct ParallelIOArg *parg = arg;
1990 int n = write(fd, parg->buffer, parg->count);
1991 if (n != parg->count) {
1992 return -EIO;
1995 break;
1996 default:
1997 return -ENOTSUP;
1999 return 0;
2002 static void pp_close(CharDriverState *chr)
2004 ParallelCharDriver *drv = chr->opaque;
2005 int fd = drv->fd;
2007 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2008 ioctl(fd, PPRELEASE);
2009 close(fd);
2010 qemu_free(drv);
2013 static CharDriverState *qemu_chr_open_pp(const char *filename)
2015 CharDriverState *chr;
2016 ParallelCharDriver *drv;
2017 int fd;
2019 fd = open(filename, O_RDWR);
2020 if (fd < 0)
2021 return NULL;
2023 if (ioctl(fd, PPCLAIM) < 0) {
2024 close(fd);
2025 return NULL;
2028 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2029 if (!drv) {
2030 close(fd);
2031 return NULL;
2033 drv->fd = fd;
2034 drv->mode = IEEE1284_MODE_COMPAT;
2036 chr = qemu_mallocz(sizeof(CharDriverState));
2037 if (!chr) {
2038 qemu_free(drv);
2039 close(fd);
2040 return NULL;
2042 chr->chr_write = null_chr_write;
2043 chr->chr_ioctl = pp_ioctl;
2044 chr->chr_close = pp_close;
2045 chr->opaque = drv;
2047 qemu_chr_reset(chr);
2049 return chr;
2052 #else
2053 static CharDriverState *qemu_chr_open_pty(void)
2055 return NULL;
2057 #endif
2059 #endif /* !defined(_WIN32) */
2061 #ifdef _WIN32
2062 typedef struct {
2063 int max_size;
2064 HANDLE hcom, hrecv, hsend;
2065 OVERLAPPED orecv, osend;
2066 BOOL fpipe;
2067 DWORD len;
2068 } WinCharState;
2070 #define NSENDBUF 2048
2071 #define NRECVBUF 2048
2072 #define MAXCONNECT 1
2073 #define NTIMEOUT 5000
2075 static int win_chr_poll(void *opaque);
2076 static int win_chr_pipe_poll(void *opaque);
2078 static void win_chr_close(CharDriverState *chr)
2080 WinCharState *s = chr->opaque;
2082 if (s->hsend) {
2083 CloseHandle(s->hsend);
2084 s->hsend = NULL;
2086 if (s->hrecv) {
2087 CloseHandle(s->hrecv);
2088 s->hrecv = NULL;
2090 if (s->hcom) {
2091 CloseHandle(s->hcom);
2092 s->hcom = NULL;
2094 if (s->fpipe)
2095 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2096 else
2097 qemu_del_polling_cb(win_chr_poll, chr);
2100 static int win_chr_init(CharDriverState *chr, const char *filename)
2102 WinCharState *s = chr->opaque;
2103 COMMCONFIG comcfg;
2104 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2105 COMSTAT comstat;
2106 DWORD size;
2107 DWORD err;
2109 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2110 if (!s->hsend) {
2111 fprintf(stderr, "Failed CreateEvent\n");
2112 goto fail;
2114 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2115 if (!s->hrecv) {
2116 fprintf(stderr, "Failed CreateEvent\n");
2117 goto fail;
2120 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2121 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2122 if (s->hcom == INVALID_HANDLE_VALUE) {
2123 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2124 s->hcom = NULL;
2125 goto fail;
2128 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2129 fprintf(stderr, "Failed SetupComm\n");
2130 goto fail;
2133 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2134 size = sizeof(COMMCONFIG);
2135 GetDefaultCommConfig(filename, &comcfg, &size);
2136 comcfg.dcb.DCBlength = sizeof(DCB);
2137 CommConfigDialog(filename, NULL, &comcfg);
2139 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2140 fprintf(stderr, "Failed SetCommState\n");
2141 goto fail;
2144 if (!SetCommMask(s->hcom, EV_ERR)) {
2145 fprintf(stderr, "Failed SetCommMask\n");
2146 goto fail;
2149 cto.ReadIntervalTimeout = MAXDWORD;
2150 if (!SetCommTimeouts(s->hcom, &cto)) {
2151 fprintf(stderr, "Failed SetCommTimeouts\n");
2152 goto fail;
2155 if (!ClearCommError(s->hcom, &err, &comstat)) {
2156 fprintf(stderr, "Failed ClearCommError\n");
2157 goto fail;
2159 qemu_add_polling_cb(win_chr_poll, chr);
2160 return 0;
2162 fail:
2163 win_chr_close(chr);
2164 return -1;
2167 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2169 WinCharState *s = chr->opaque;
2170 DWORD len, ret, size, err;
2172 len = len1;
2173 ZeroMemory(&s->osend, sizeof(s->osend));
2174 s->osend.hEvent = s->hsend;
2175 while (len > 0) {
2176 if (s->hsend)
2177 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2178 else
2179 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2180 if (!ret) {
2181 err = GetLastError();
2182 if (err == ERROR_IO_PENDING) {
2183 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2184 if (ret) {
2185 buf += size;
2186 len -= size;
2187 } else {
2188 break;
2190 } else {
2191 break;
2193 } else {
2194 buf += size;
2195 len -= size;
2198 return len1 - len;
2201 static int win_chr_read_poll(CharDriverState *chr)
2203 WinCharState *s = chr->opaque;
2205 s->max_size = qemu_chr_can_read(chr);
2206 return s->max_size;
2209 static void win_chr_readfile(CharDriverState *chr)
2211 WinCharState *s = chr->opaque;
2212 int ret, err;
2213 uint8_t buf[1024];
2214 DWORD size;
2216 ZeroMemory(&s->orecv, sizeof(s->orecv));
2217 s->orecv.hEvent = s->hrecv;
2218 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2219 if (!ret) {
2220 err = GetLastError();
2221 if (err == ERROR_IO_PENDING) {
2222 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2226 if (size > 0) {
2227 qemu_chr_read(chr, buf, size);
2231 static void win_chr_read(CharDriverState *chr)
2233 WinCharState *s = chr->opaque;
2235 if (s->len > s->max_size)
2236 s->len = s->max_size;
2237 if (s->len == 0)
2238 return;
2240 win_chr_readfile(chr);
2243 static int win_chr_poll(void *opaque)
2245 CharDriverState *chr = opaque;
2246 WinCharState *s = chr->opaque;
2247 COMSTAT status;
2248 DWORD comerr;
2250 ClearCommError(s->hcom, &comerr, &status);
2251 if (status.cbInQue > 0) {
2252 s->len = status.cbInQue;
2253 win_chr_read_poll(chr);
2254 win_chr_read(chr);
2255 return 1;
2257 return 0;
2260 static CharDriverState *qemu_chr_open_win(const char *filename)
2262 CharDriverState *chr;
2263 WinCharState *s;
2265 chr = qemu_mallocz(sizeof(CharDriverState));
2266 if (!chr)
2267 return NULL;
2268 s = qemu_mallocz(sizeof(WinCharState));
2269 if (!s) {
2270 free(chr);
2271 return NULL;
2273 chr->opaque = s;
2274 chr->chr_write = win_chr_write;
2275 chr->chr_close = win_chr_close;
2277 if (win_chr_init(chr, filename) < 0) {
2278 free(s);
2279 free(chr);
2280 return NULL;
2282 qemu_chr_reset(chr);
2283 return chr;
2286 static int win_chr_pipe_poll(void *opaque)
2288 CharDriverState *chr = opaque;
2289 WinCharState *s = chr->opaque;
2290 DWORD size;
2292 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2293 if (size > 0) {
2294 s->len = size;
2295 win_chr_read_poll(chr);
2296 win_chr_read(chr);
2297 return 1;
2299 return 0;
2302 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2304 WinCharState *s = chr->opaque;
2305 OVERLAPPED ov;
2306 int ret;
2307 DWORD size;
2308 char openname[256];
2310 s->fpipe = TRUE;
2312 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2313 if (!s->hsend) {
2314 fprintf(stderr, "Failed CreateEvent\n");
2315 goto fail;
2317 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2318 if (!s->hrecv) {
2319 fprintf(stderr, "Failed CreateEvent\n");
2320 goto fail;
2323 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2324 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2325 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2326 PIPE_WAIT,
2327 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2328 if (s->hcom == INVALID_HANDLE_VALUE) {
2329 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2330 s->hcom = NULL;
2331 goto fail;
2334 ZeroMemory(&ov, sizeof(ov));
2335 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2336 ret = ConnectNamedPipe(s->hcom, &ov);
2337 if (ret) {
2338 fprintf(stderr, "Failed ConnectNamedPipe\n");
2339 goto fail;
2342 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2343 if (!ret) {
2344 fprintf(stderr, "Failed GetOverlappedResult\n");
2345 if (ov.hEvent) {
2346 CloseHandle(ov.hEvent);
2347 ov.hEvent = NULL;
2349 goto fail;
2352 if (ov.hEvent) {
2353 CloseHandle(ov.hEvent);
2354 ov.hEvent = NULL;
2356 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2357 return 0;
2359 fail:
2360 win_chr_close(chr);
2361 return -1;
2365 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2367 CharDriverState *chr;
2368 WinCharState *s;
2370 chr = qemu_mallocz(sizeof(CharDriverState));
2371 if (!chr)
2372 return NULL;
2373 s = qemu_mallocz(sizeof(WinCharState));
2374 if (!s) {
2375 free(chr);
2376 return NULL;
2378 chr->opaque = s;
2379 chr->chr_write = win_chr_write;
2380 chr->chr_close = win_chr_close;
2382 if (win_chr_pipe_init(chr, filename) < 0) {
2383 free(s);
2384 free(chr);
2385 return NULL;
2387 qemu_chr_reset(chr);
2388 return chr;
2391 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2393 CharDriverState *chr;
2394 WinCharState *s;
2396 chr = qemu_mallocz(sizeof(CharDriverState));
2397 if (!chr)
2398 return NULL;
2399 s = qemu_mallocz(sizeof(WinCharState));
2400 if (!s) {
2401 free(chr);
2402 return NULL;
2404 s->hcom = fd_out;
2405 chr->opaque = s;
2406 chr->chr_write = win_chr_write;
2407 qemu_chr_reset(chr);
2408 return chr;
2411 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2413 HANDLE fd_out;
2415 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2416 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2417 if (fd_out == INVALID_HANDLE_VALUE)
2418 return NULL;
2420 return qemu_chr_open_win_file(fd_out);
2422 #endif
2424 /***********************************************************/
2425 /* UDP Net console */
2427 typedef struct {
2428 int fd;
2429 struct sockaddr_in daddr;
2430 char buf[1024];
2431 int bufcnt;
2432 int bufptr;
2433 int max_size;
2434 } NetCharDriver;
2436 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2438 NetCharDriver *s = chr->opaque;
2440 return sendto(s->fd, buf, len, 0,
2441 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2444 static int udp_chr_read_poll(void *opaque)
2446 CharDriverState *chr = opaque;
2447 NetCharDriver *s = chr->opaque;
2449 s->max_size = qemu_chr_can_read(chr);
2451 /* If there were any stray characters in the queue process them
2452 * first
2454 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2455 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2456 s->bufptr++;
2457 s->max_size = qemu_chr_can_read(chr);
2459 return s->max_size;
2462 static void udp_chr_read(void *opaque)
2464 CharDriverState *chr = opaque;
2465 NetCharDriver *s = chr->opaque;
2467 if (s->max_size == 0)
2468 return;
2469 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2470 s->bufptr = s->bufcnt;
2471 if (s->bufcnt <= 0)
2472 return;
2474 s->bufptr = 0;
2475 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2476 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2477 s->bufptr++;
2478 s->max_size = qemu_chr_can_read(chr);
2482 static void udp_chr_update_read_handler(CharDriverState *chr)
2484 NetCharDriver *s = chr->opaque;
2486 if (s->fd >= 0) {
2487 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2488 udp_chr_read, NULL, chr);
2492 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2493 #ifndef _WIN32
2494 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2495 #endif
2496 int parse_host_src_port(struct sockaddr_in *haddr,
2497 struct sockaddr_in *saddr,
2498 const char *str);
2500 static CharDriverState *qemu_chr_open_udp(const char *def)
2502 CharDriverState *chr = NULL;
2503 NetCharDriver *s = NULL;
2504 int fd = -1;
2505 struct sockaddr_in saddr;
2507 chr = qemu_mallocz(sizeof(CharDriverState));
2508 if (!chr)
2509 goto return_err;
2510 s = qemu_mallocz(sizeof(NetCharDriver));
2511 if (!s)
2512 goto return_err;
2514 fd = socket(PF_INET, SOCK_DGRAM, 0);
2515 if (fd < 0) {
2516 perror("socket(PF_INET, SOCK_DGRAM)");
2517 goto return_err;
2520 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2521 printf("Could not parse: %s\n", def);
2522 goto return_err;
2525 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2527 perror("bind");
2528 goto return_err;
2531 s->fd = fd;
2532 s->bufcnt = 0;
2533 s->bufptr = 0;
2534 chr->opaque = s;
2535 chr->chr_write = udp_chr_write;
2536 chr->chr_update_read_handler = udp_chr_update_read_handler;
2537 return chr;
2539 return_err:
2540 if (chr)
2541 free(chr);
2542 if (s)
2543 free(s);
2544 if (fd >= 0)
2545 closesocket(fd);
2546 return NULL;
2549 /***********************************************************/
2550 /* TCP Net console */
2552 typedef struct {
2553 int fd, listen_fd;
2554 int connected;
2555 int max_size;
2556 int do_telnetopt;
2557 int do_nodelay;
2558 int is_unix;
2559 } TCPCharDriver;
2561 static void tcp_chr_accept(void *opaque);
2563 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2565 TCPCharDriver *s = chr->opaque;
2566 if (s->connected) {
2567 return send_all(s->fd, buf, len);
2568 } else {
2569 /* XXX: indicate an error ? */
2570 return len;
2574 static int tcp_chr_read_poll(void *opaque)
2576 CharDriverState *chr = opaque;
2577 TCPCharDriver *s = chr->opaque;
2578 if (!s->connected)
2579 return 0;
2580 s->max_size = qemu_chr_can_read(chr);
2581 return s->max_size;
2584 #define IAC 255
2585 #define IAC_BREAK 243
2586 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2587 TCPCharDriver *s,
2588 char *buf, int *size)
2590 /* Handle any telnet client's basic IAC options to satisfy char by
2591 * char mode with no echo. All IAC options will be removed from
2592 * the buf and the do_telnetopt variable will be used to track the
2593 * state of the width of the IAC information.
2595 * IAC commands come in sets of 3 bytes with the exception of the
2596 * "IAC BREAK" command and the double IAC.
2599 int i;
2600 int j = 0;
2602 for (i = 0; i < *size; i++) {
2603 if (s->do_telnetopt > 1) {
2604 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2605 /* Double IAC means send an IAC */
2606 if (j != i)
2607 buf[j] = buf[i];
2608 j++;
2609 s->do_telnetopt = 1;
2610 } else {
2611 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2612 /* Handle IAC break commands by sending a serial break */
2613 qemu_chr_event(chr, CHR_EVENT_BREAK);
2614 s->do_telnetopt++;
2616 s->do_telnetopt++;
2618 if (s->do_telnetopt >= 4) {
2619 s->do_telnetopt = 1;
2621 } else {
2622 if ((unsigned char)buf[i] == IAC) {
2623 s->do_telnetopt = 2;
2624 } else {
2625 if (j != i)
2626 buf[j] = buf[i];
2627 j++;
2631 *size = j;
2634 static void tcp_chr_read(void *opaque)
2636 CharDriverState *chr = opaque;
2637 TCPCharDriver *s = chr->opaque;
2638 uint8_t buf[1024];
2639 int len, size;
2641 if (!s->connected || s->max_size <= 0)
2642 return;
2643 len = sizeof(buf);
2644 if (len > s->max_size)
2645 len = s->max_size;
2646 size = recv(s->fd, buf, len, 0);
2647 if (size == 0) {
2648 /* connection closed */
2649 s->connected = 0;
2650 if (s->listen_fd >= 0) {
2651 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2653 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2654 closesocket(s->fd);
2655 s->fd = -1;
2656 } else if (size > 0) {
2657 if (s->do_telnetopt)
2658 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2659 if (size > 0)
2660 qemu_chr_read(chr, buf, size);
2664 static void tcp_chr_connect(void *opaque)
2666 CharDriverState *chr = opaque;
2667 TCPCharDriver *s = chr->opaque;
2669 s->connected = 1;
2670 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2671 tcp_chr_read, NULL, chr);
2672 qemu_chr_reset(chr);
2675 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2676 static void tcp_chr_telnet_init(int fd)
2678 char buf[3];
2679 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2680 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2681 send(fd, (char *)buf, 3, 0);
2682 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2683 send(fd, (char *)buf, 3, 0);
2684 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2685 send(fd, (char *)buf, 3, 0);
2686 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2687 send(fd, (char *)buf, 3, 0);
2690 static void socket_set_nodelay(int fd)
2692 int val = 1;
2693 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2696 static void tcp_chr_accept(void *opaque)
2698 CharDriverState *chr = opaque;
2699 TCPCharDriver *s = chr->opaque;
2700 struct sockaddr_in saddr;
2701 #ifndef _WIN32
2702 struct sockaddr_un uaddr;
2703 #endif
2704 struct sockaddr *addr;
2705 socklen_t len;
2706 int fd;
2708 for(;;) {
2709 #ifndef _WIN32
2710 if (s->is_unix) {
2711 len = sizeof(uaddr);
2712 addr = (struct sockaddr *)&uaddr;
2713 } else
2714 #endif
2716 len = sizeof(saddr);
2717 addr = (struct sockaddr *)&saddr;
2719 fd = accept(s->listen_fd, addr, &len);
2720 if (fd < 0 && errno != EINTR) {
2721 return;
2722 } else if (fd >= 0) {
2723 if (s->do_telnetopt)
2724 tcp_chr_telnet_init(fd);
2725 break;
2728 socket_set_nonblock(fd);
2729 if (s->do_nodelay)
2730 socket_set_nodelay(fd);
2731 s->fd = fd;
2732 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2733 tcp_chr_connect(chr);
2736 static void tcp_chr_close(CharDriverState *chr)
2738 TCPCharDriver *s = chr->opaque;
2739 if (s->fd >= 0)
2740 closesocket(s->fd);
2741 if (s->listen_fd >= 0)
2742 closesocket(s->listen_fd);
2743 qemu_free(s);
2746 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2747 int is_telnet,
2748 int is_unix)
2750 CharDriverState *chr = NULL;
2751 TCPCharDriver *s = NULL;
2752 int fd = -1, ret, err, val;
2753 int is_listen = 0;
2754 int is_waitconnect = 1;
2755 int do_nodelay = 0;
2756 const char *ptr;
2757 struct sockaddr_in saddr;
2758 #ifndef _WIN32
2759 struct sockaddr_un uaddr;
2760 #endif
2761 struct sockaddr *addr;
2762 socklen_t addrlen;
2764 #ifndef _WIN32
2765 if (is_unix) {
2766 addr = (struct sockaddr *)&uaddr;
2767 addrlen = sizeof(uaddr);
2768 if (parse_unix_path(&uaddr, host_str) < 0)
2769 goto fail;
2770 } else
2771 #endif
2773 addr = (struct sockaddr *)&saddr;
2774 addrlen = sizeof(saddr);
2775 if (parse_host_port(&saddr, host_str) < 0)
2776 goto fail;
2779 ptr = host_str;
2780 while((ptr = strchr(ptr,','))) {
2781 ptr++;
2782 if (!strncmp(ptr,"server",6)) {
2783 is_listen = 1;
2784 } else if (!strncmp(ptr,"nowait",6)) {
2785 is_waitconnect = 0;
2786 } else if (!strncmp(ptr,"nodelay",6)) {
2787 do_nodelay = 1;
2788 } else {
2789 printf("Unknown option: %s\n", ptr);
2790 goto fail;
2793 if (!is_listen)
2794 is_waitconnect = 0;
2796 chr = qemu_mallocz(sizeof(CharDriverState));
2797 if (!chr)
2798 goto fail;
2799 s = qemu_mallocz(sizeof(TCPCharDriver));
2800 if (!s)
2801 goto fail;
2803 #ifndef _WIN32
2804 if (is_unix)
2805 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2806 else
2807 #endif
2808 fd = socket(PF_INET, SOCK_STREAM, 0);
2810 if (fd < 0)
2811 goto fail;
2813 if (!is_waitconnect)
2814 socket_set_nonblock(fd);
2816 s->connected = 0;
2817 s->fd = -1;
2818 s->listen_fd = -1;
2819 s->is_unix = is_unix;
2820 s->do_nodelay = do_nodelay && !is_unix;
2822 chr->opaque = s;
2823 chr->chr_write = tcp_chr_write;
2824 chr->chr_close = tcp_chr_close;
2826 if (is_listen) {
2827 /* allow fast reuse */
2828 #ifndef _WIN32
2829 if (is_unix) {
2830 char path[109];
2831 strncpy(path, uaddr.sun_path, 108);
2832 path[108] = 0;
2833 unlink(path);
2834 } else
2835 #endif
2837 val = 1;
2838 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2841 ret = bind(fd, addr, addrlen);
2842 if (ret < 0)
2843 goto fail;
2845 ret = listen(fd, 0);
2846 if (ret < 0)
2847 goto fail;
2849 s->listen_fd = fd;
2850 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2851 if (is_telnet)
2852 s->do_telnetopt = 1;
2853 } else {
2854 for(;;) {
2855 ret = connect(fd, addr, addrlen);
2856 if (ret < 0) {
2857 err = socket_error();
2858 if (err == EINTR || err == EWOULDBLOCK) {
2859 } else if (err == EINPROGRESS) {
2860 break;
2861 #ifdef _WIN32
2862 } else if (err == WSAEALREADY) {
2863 break;
2864 #endif
2865 } else {
2866 goto fail;
2868 } else {
2869 s->connected = 1;
2870 break;
2873 s->fd = fd;
2874 socket_set_nodelay(fd);
2875 if (s->connected)
2876 tcp_chr_connect(chr);
2877 else
2878 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2881 if (is_listen && is_waitconnect) {
2882 printf("QEMU waiting for connection on: %s\n", host_str);
2883 tcp_chr_accept(chr);
2884 socket_set_nonblock(s->listen_fd);
2887 return chr;
2888 fail:
2889 if (fd >= 0)
2890 closesocket(fd);
2891 qemu_free(s);
2892 qemu_free(chr);
2893 return NULL;
2896 CharDriverState *qemu_chr_open(const char *filename)
2898 const char *p;
2900 if (!strcmp(filename, "vc")) {
2901 return text_console_init(&display_state);
2902 } else if (!strcmp(filename, "null")) {
2903 return qemu_chr_open_null();
2904 } else
2905 if (strstart(filename, "tcp:", &p)) {
2906 return qemu_chr_open_tcp(p, 0, 0);
2907 } else
2908 if (strstart(filename, "telnet:", &p)) {
2909 return qemu_chr_open_tcp(p, 1, 0);
2910 } else
2911 if (strstart(filename, "udp:", &p)) {
2912 return qemu_chr_open_udp(p);
2913 } else
2914 if (strstart(filename, "mon:", &p)) {
2915 CharDriverState *drv = qemu_chr_open(p);
2916 if (drv) {
2917 drv = qemu_chr_open_mux(drv);
2918 monitor_init(drv, !nographic);
2919 return drv;
2921 printf("Unable to open driver: %s\n", p);
2922 return 0;
2923 } else
2924 #ifndef _WIN32
2925 if (strstart(filename, "unix:", &p)) {
2926 return qemu_chr_open_tcp(p, 0, 1);
2927 } else if (strstart(filename, "file:", &p)) {
2928 return qemu_chr_open_file_out(p);
2929 } else if (strstart(filename, "pipe:", &p)) {
2930 return qemu_chr_open_pipe(p);
2931 } else if (!strcmp(filename, "pty")) {
2932 return qemu_chr_open_pty();
2933 } else if (!strcmp(filename, "stdio")) {
2934 return qemu_chr_open_stdio();
2935 } else
2936 #endif
2937 #if defined(__linux__)
2938 if (strstart(filename, "/dev/parport", NULL)) {
2939 return qemu_chr_open_pp(filename);
2940 } else
2941 if (strstart(filename, "/dev/", NULL)) {
2942 return qemu_chr_open_tty(filename);
2943 } else
2944 #endif
2945 #ifdef _WIN32
2946 if (strstart(filename, "COM", NULL)) {
2947 return qemu_chr_open_win(filename);
2948 } else
2949 if (strstart(filename, "pipe:", &p)) {
2950 return qemu_chr_open_win_pipe(p);
2951 } else
2952 if (strstart(filename, "file:", &p)) {
2953 return qemu_chr_open_win_file_out(p);
2955 #endif
2957 return NULL;
2961 void qemu_chr_close(CharDriverState *chr)
2963 if (chr->chr_close)
2964 chr->chr_close(chr);
2967 /***********************************************************/
2968 /* network device redirectors */
2970 void hex_dump(FILE *f, const uint8_t *buf, int size)
2972 int len, i, j, c;
2974 for(i=0;i<size;i+=16) {
2975 len = size - i;
2976 if (len > 16)
2977 len = 16;
2978 fprintf(f, "%08x ", i);
2979 for(j=0;j<16;j++) {
2980 if (j < len)
2981 fprintf(f, " %02x", buf[i+j]);
2982 else
2983 fprintf(f, " ");
2985 fprintf(f, " ");
2986 for(j=0;j<len;j++) {
2987 c = buf[i+j];
2988 if (c < ' ' || c > '~')
2989 c = '.';
2990 fprintf(f, "%c", c);
2992 fprintf(f, "\n");
2996 static int parse_macaddr(uint8_t *macaddr, const char *p)
2998 int i;
2999 for(i = 0; i < 6; i++) {
3000 macaddr[i] = strtol(p, (char **)&p, 16);
3001 if (i == 5) {
3002 if (*p != '\0')
3003 return -1;
3004 } else {
3005 if (*p != ':')
3006 return -1;
3007 p++;
3010 return 0;
3013 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3015 const char *p, *p1;
3016 int len;
3017 p = *pp;
3018 p1 = strchr(p, sep);
3019 if (!p1)
3020 return -1;
3021 len = p1 - p;
3022 p1++;
3023 if (buf_size > 0) {
3024 if (len > buf_size - 1)
3025 len = buf_size - 1;
3026 memcpy(buf, p, len);
3027 buf[len] = '\0';
3029 *pp = p1;
3030 return 0;
3033 int parse_host_src_port(struct sockaddr_in *haddr,
3034 struct sockaddr_in *saddr,
3035 const char *input_str)
3037 char *str = strdup(input_str);
3038 char *host_str = str;
3039 char *src_str;
3040 char *ptr;
3043 * Chop off any extra arguments at the end of the string which
3044 * would start with a comma, then fill in the src port information
3045 * if it was provided else use the "any address" and "any port".
3047 if ((ptr = strchr(str,',')))
3048 *ptr = '\0';
3050 if ((src_str = strchr(input_str,'@'))) {
3051 *src_str = '\0';
3052 src_str++;
3055 if (parse_host_port(haddr, host_str) < 0)
3056 goto fail;
3058 if (!src_str || *src_str == '\0')
3059 src_str = ":0";
3061 if (parse_host_port(saddr, src_str) < 0)
3062 goto fail;
3064 free(str);
3065 return(0);
3067 fail:
3068 free(str);
3069 return -1;
3072 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3074 char buf[512];
3075 struct hostent *he;
3076 const char *p, *r;
3077 int port;
3079 p = str;
3080 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3081 return -1;
3082 saddr->sin_family = AF_INET;
3083 if (buf[0] == '\0') {
3084 saddr->sin_addr.s_addr = 0;
3085 } else {
3086 if (isdigit(buf[0])) {
3087 if (!inet_aton(buf, &saddr->sin_addr))
3088 return -1;
3089 } else {
3090 if ((he = gethostbyname(buf)) == NULL)
3091 return - 1;
3092 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3095 port = strtol(p, (char **)&r, 0);
3096 if (r == p)
3097 return -1;
3098 saddr->sin_port = htons(port);
3099 return 0;
3102 #ifndef _WIN32
3103 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3105 const char *p;
3106 int len;
3108 len = MIN(108, strlen(str));
3109 p = strchr(str, ',');
3110 if (p)
3111 len = MIN(len, p - str);
3113 memset(uaddr, 0, sizeof(*uaddr));
3115 uaddr->sun_family = AF_UNIX;
3116 memcpy(uaddr->sun_path, str, len);
3118 return 0;
3120 #endif
3122 /* find or alloc a new VLAN */
3123 VLANState *qemu_find_vlan(int id)
3125 VLANState **pvlan, *vlan;
3126 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3127 if (vlan->id == id)
3128 return vlan;
3130 vlan = qemu_mallocz(sizeof(VLANState));
3131 if (!vlan)
3132 return NULL;
3133 vlan->id = id;
3134 vlan->next = NULL;
3135 pvlan = &first_vlan;
3136 while (*pvlan != NULL)
3137 pvlan = &(*pvlan)->next;
3138 *pvlan = vlan;
3139 return vlan;
3142 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3143 IOReadHandler *fd_read,
3144 IOCanRWHandler *fd_can_read,
3145 void *opaque)
3147 VLANClientState *vc, **pvc;
3148 vc = qemu_mallocz(sizeof(VLANClientState));
3149 if (!vc)
3150 return NULL;
3151 vc->fd_read = fd_read;
3152 vc->fd_can_read = fd_can_read;
3153 vc->opaque = opaque;
3154 vc->vlan = vlan;
3156 vc->next = NULL;
3157 pvc = &vlan->first_client;
3158 while (*pvc != NULL)
3159 pvc = &(*pvc)->next;
3160 *pvc = vc;
3161 return vc;
3164 int qemu_can_send_packet(VLANClientState *vc1)
3166 VLANState *vlan = vc1->vlan;
3167 VLANClientState *vc;
3169 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3170 if (vc != vc1) {
3171 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3172 return 0;
3175 return 1;
3178 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3180 VLANState *vlan = vc1->vlan;
3181 VLANClientState *vc;
3183 #if 0
3184 printf("vlan %d send:\n", vlan->id);
3185 hex_dump(stdout, buf, size);
3186 #endif
3187 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3188 if (vc != vc1) {
3189 vc->fd_read(vc->opaque, buf, size);
3194 #if defined(CONFIG_SLIRP)
3196 /* slirp network adapter */
3198 static int slirp_inited;
3199 static VLANClientState *slirp_vc;
3201 int slirp_can_output(void)
3203 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3206 void slirp_output(const uint8_t *pkt, int pkt_len)
3208 #if 0
3209 printf("slirp output:\n");
3210 hex_dump(stdout, pkt, pkt_len);
3211 #endif
3212 if (!slirp_vc)
3213 return;
3214 qemu_send_packet(slirp_vc, pkt, pkt_len);
3217 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3219 #if 0
3220 printf("slirp input:\n");
3221 hex_dump(stdout, buf, size);
3222 #endif
3223 slirp_input(buf, size);
3226 static int net_slirp_init(VLANState *vlan)
3228 if (!slirp_inited) {
3229 slirp_inited = 1;
3230 slirp_init();
3232 slirp_vc = qemu_new_vlan_client(vlan,
3233 slirp_receive, NULL, NULL);
3234 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3235 return 0;
3238 static void net_slirp_redir(const char *redir_str)
3240 int is_udp;
3241 char buf[256], *r;
3242 const char *p;
3243 struct in_addr guest_addr;
3244 int host_port, guest_port;
3246 if (!slirp_inited) {
3247 slirp_inited = 1;
3248 slirp_init();
3251 p = redir_str;
3252 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3253 goto fail;
3254 if (!strcmp(buf, "tcp")) {
3255 is_udp = 0;
3256 } else if (!strcmp(buf, "udp")) {
3257 is_udp = 1;
3258 } else {
3259 goto fail;
3262 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3263 goto fail;
3264 host_port = strtol(buf, &r, 0);
3265 if (r == buf)
3266 goto fail;
3268 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3269 goto fail;
3270 if (buf[0] == '\0') {
3271 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3273 if (!inet_aton(buf, &guest_addr))
3274 goto fail;
3276 guest_port = strtol(p, &r, 0);
3277 if (r == p)
3278 goto fail;
3280 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3281 fprintf(stderr, "qemu: could not set up redirection\n");
3282 exit(1);
3284 return;
3285 fail:
3286 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3287 exit(1);
3290 #ifndef _WIN32
3292 char smb_dir[1024];
3294 static void smb_exit(void)
3296 DIR *d;
3297 struct dirent *de;
3298 char filename[1024];
3300 /* erase all the files in the directory */
3301 d = opendir(smb_dir);
3302 for(;;) {
3303 de = readdir(d);
3304 if (!de)
3305 break;
3306 if (strcmp(de->d_name, ".") != 0 &&
3307 strcmp(de->d_name, "..") != 0) {
3308 snprintf(filename, sizeof(filename), "%s/%s",
3309 smb_dir, de->d_name);
3310 unlink(filename);
3313 closedir(d);
3314 rmdir(smb_dir);
3317 /* automatic user mode samba server configuration */
3318 void net_slirp_smb(const char *exported_dir)
3320 char smb_conf[1024];
3321 char smb_cmdline[1024];
3322 FILE *f;
3324 if (!slirp_inited) {
3325 slirp_inited = 1;
3326 slirp_init();
3329 /* XXX: better tmp dir construction */
3330 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3331 if (mkdir(smb_dir, 0700) < 0) {
3332 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3333 exit(1);
3335 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3337 f = fopen(smb_conf, "w");
3338 if (!f) {
3339 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3340 exit(1);
3342 fprintf(f,
3343 "[global]\n"
3344 "private dir=%s\n"
3345 "smb ports=0\n"
3346 "socket address=127.0.0.1\n"
3347 "pid directory=%s\n"
3348 "lock directory=%s\n"
3349 "log file=%s/log.smbd\n"
3350 "smb passwd file=%s/smbpasswd\n"
3351 "security = share\n"
3352 "[qemu]\n"
3353 "path=%s\n"
3354 "read only=no\n"
3355 "guest ok=yes\n",
3356 smb_dir,
3357 smb_dir,
3358 smb_dir,
3359 smb_dir,
3360 smb_dir,
3361 exported_dir
3363 fclose(f);
3364 atexit(smb_exit);
3366 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3367 SMBD_COMMAND, smb_conf);
3369 slirp_add_exec(0, smb_cmdline, 4, 139);
3372 #endif /* !defined(_WIN32) */
3374 #endif /* CONFIG_SLIRP */
3376 #if !defined(_WIN32)
3378 typedef struct TAPState {
3379 VLANClientState *vc;
3380 int fd;
3381 } TAPState;
3383 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3385 TAPState *s = opaque;
3386 int ret;
3387 for(;;) {
3388 ret = write(s->fd, buf, size);
3389 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3390 } else {
3391 break;
3396 static void tap_send(void *opaque)
3398 TAPState *s = opaque;
3399 uint8_t buf[4096];
3400 int size;
3402 #ifdef __sun__
3403 struct strbuf sbuf;
3404 int f = 0;
3405 sbuf.maxlen = sizeof(buf);
3406 sbuf.buf = buf;
3407 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3408 #else
3409 size = read(s->fd, buf, sizeof(buf));
3410 #endif
3411 if (size > 0) {
3412 qemu_send_packet(s->vc, buf, size);
3416 /* fd support */
3418 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3420 TAPState *s;
3422 s = qemu_mallocz(sizeof(TAPState));
3423 if (!s)
3424 return NULL;
3425 s->fd = fd;
3426 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3427 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3428 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3429 return s;
3432 #ifdef _BSD
3433 static int tap_open(char *ifname, int ifname_size)
3435 int fd;
3436 char *dev;
3437 struct stat s;
3439 fd = open("/dev/tap", O_RDWR);
3440 if (fd < 0) {
3441 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3442 return -1;
3445 fstat(fd, &s);
3446 dev = devname(s.st_rdev, S_IFCHR);
3447 pstrcpy(ifname, ifname_size, dev);
3449 fcntl(fd, F_SETFL, O_NONBLOCK);
3450 return fd;
3452 #elif defined(__sun__)
3453 #define TUNNEWPPA (('T'<<16) | 0x0001)
3455 * Allocate TAP device, returns opened fd.
3456 * Stores dev name in the first arg(must be large enough).
3458 int tap_alloc(char *dev)
3460 int tap_fd, if_fd, ppa = -1;
3461 static int ip_fd = 0;
3462 char *ptr;
3464 static int arp_fd = 0;
3465 int ip_muxid, arp_muxid;
3466 struct strioctl strioc_if, strioc_ppa;
3467 int link_type = I_PLINK;;
3468 struct lifreq ifr;
3469 char actual_name[32] = "";
3471 memset(&ifr, 0x0, sizeof(ifr));
3473 if( *dev ){
3474 ptr = dev;
3475 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3476 ppa = atoi(ptr);
3479 /* Check if IP device was opened */
3480 if( ip_fd )
3481 close(ip_fd);
3483 if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3484 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3485 return -1;
3488 if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3489 syslog(LOG_ERR, "Can't open /dev/tap");
3490 return -1;
3493 /* Assign a new PPA and get its unit number. */
3494 strioc_ppa.ic_cmd = TUNNEWPPA;
3495 strioc_ppa.ic_timout = 0;
3496 strioc_ppa.ic_len = sizeof(ppa);
3497 strioc_ppa.ic_dp = (char *)&ppa;
3498 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3499 syslog (LOG_ERR, "Can't assign new interface");
3501 if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3502 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3503 return -1;
3505 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3506 syslog(LOG_ERR, "Can't push IP module");
3507 return -1;
3510 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3511 syslog(LOG_ERR, "Can't get flags\n");
3513 snprintf (actual_name, 32, "tap%d", ppa);
3514 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3516 ifr.lifr_ppa = ppa;
3517 /* Assign ppa according to the unit number returned by tun device */
3519 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3520 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3521 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3522 syslog (LOG_ERR, "Can't get flags\n");
3523 /* Push arp module to if_fd */
3524 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3525 syslog (LOG_ERR, "Can't push ARP module (2)");
3527 /* Push arp module to ip_fd */
3528 if (ioctl (ip_fd, I_POP, NULL) < 0)
3529 syslog (LOG_ERR, "I_POP failed\n");
3530 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3531 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3532 /* Open arp_fd */
3533 if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3534 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3536 /* Set ifname to arp */
3537 strioc_if.ic_cmd = SIOCSLIFNAME;
3538 strioc_if.ic_timout = 0;
3539 strioc_if.ic_len = sizeof(ifr);
3540 strioc_if.ic_dp = (char *)&ifr;
3541 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3542 syslog (LOG_ERR, "Can't set ifname to arp\n");
3545 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3546 syslog(LOG_ERR, "Can't link TAP device to IP");
3547 return -1;
3550 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3551 syslog (LOG_ERR, "Can't link TAP device to ARP");
3553 close (if_fd);
3555 memset(&ifr, 0x0, sizeof(ifr));
3556 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3557 ifr.lifr_ip_muxid = ip_muxid;
3558 ifr.lifr_arp_muxid = arp_muxid;
3560 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3562 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3563 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3564 syslog (LOG_ERR, "Can't set multiplexor id");
3567 sprintf(dev, "tap%d", ppa);
3568 return tap_fd;
3571 static int tap_open(char *ifname, int ifname_size)
3573 char dev[10]="";
3574 int fd;
3575 if( (fd = tap_alloc(dev)) < 0 ){
3576 fprintf(stderr, "Cannot allocate TAP device\n");
3577 return -1;
3579 pstrcpy(ifname, ifname_size, dev);
3580 fcntl(fd, F_SETFL, O_NONBLOCK);
3581 return fd;
3583 #else
3584 static int tap_open(char *ifname, int ifname_size)
3586 struct ifreq ifr;
3587 int fd, ret;
3589 fd = open("/dev/net/tun", O_RDWR);
3590 if (fd < 0) {
3591 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3592 return -1;
3594 memset(&ifr, 0, sizeof(ifr));
3595 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3596 if (ifname[0] != '\0')
3597 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3598 else
3599 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3600 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3601 if (ret != 0) {
3602 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3603 close(fd);
3604 return -1;
3606 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3607 fcntl(fd, F_SETFL, O_NONBLOCK);
3608 return fd;
3610 #endif
3612 static int net_tap_init(VLANState *vlan, const char *ifname1,
3613 const char *setup_script)
3615 TAPState *s;
3616 int pid, status, fd;
3617 char *args[3];
3618 char **parg;
3619 char ifname[128];
3621 if (ifname1 != NULL)
3622 pstrcpy(ifname, sizeof(ifname), ifname1);
3623 else
3624 ifname[0] = '\0';
3625 fd = tap_open(ifname, sizeof(ifname));
3626 if (fd < 0)
3627 return -1;
3629 if (!setup_script || !strcmp(setup_script, "no"))
3630 setup_script = "";
3631 if (setup_script[0] != '\0') {
3632 /* try to launch network init script */
3633 pid = fork();
3634 if (pid >= 0) {
3635 if (pid == 0) {
3636 int open_max = sysconf (_SC_OPEN_MAX), i;
3637 for (i = 0; i < open_max; i++)
3638 if (i != STDIN_FILENO &&
3639 i != STDOUT_FILENO &&
3640 i != STDERR_FILENO &&
3641 i != fd)
3642 close(i);
3644 parg = args;
3645 *parg++ = (char *)setup_script;
3646 *parg++ = ifname;
3647 *parg++ = NULL;
3648 execv(setup_script, args);
3649 _exit(1);
3651 while (waitpid(pid, &status, 0) != pid);
3652 if (!WIFEXITED(status) ||
3653 WEXITSTATUS(status) != 0) {
3654 fprintf(stderr, "%s: could not launch network script\n",
3655 setup_script);
3656 return -1;
3660 s = net_tap_fd_init(vlan, fd);
3661 if (!s)
3662 return -1;
3663 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3664 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3665 return 0;
3668 #endif /* !_WIN32 */
3670 /* network connection */
3671 typedef struct NetSocketState {
3672 VLANClientState *vc;
3673 int fd;
3674 int state; /* 0 = getting length, 1 = getting data */
3675 int index;
3676 int packet_len;
3677 uint8_t buf[4096];
3678 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3679 } NetSocketState;
3681 typedef struct NetSocketListenState {
3682 VLANState *vlan;
3683 int fd;
3684 } NetSocketListenState;
3686 /* XXX: we consider we can send the whole packet without blocking */
3687 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3689 NetSocketState *s = opaque;
3690 uint32_t len;
3691 len = htonl(size);
3693 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3694 send_all(s->fd, buf, size);
3697 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3699 NetSocketState *s = opaque;
3700 sendto(s->fd, buf, size, 0,
3701 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3704 static void net_socket_send(void *opaque)
3706 NetSocketState *s = opaque;
3707 int l, size, err;
3708 uint8_t buf1[4096];
3709 const uint8_t *buf;
3711 size = recv(s->fd, buf1, sizeof(buf1), 0);
3712 if (size < 0) {
3713 err = socket_error();
3714 if (err != EWOULDBLOCK)
3715 goto eoc;
3716 } else if (size == 0) {
3717 /* end of connection */
3718 eoc:
3719 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3720 closesocket(s->fd);
3721 return;
3723 buf = buf1;
3724 while (size > 0) {
3725 /* reassemble a packet from the network */
3726 switch(s->state) {
3727 case 0:
3728 l = 4 - s->index;
3729 if (l > size)
3730 l = size;
3731 memcpy(s->buf + s->index, buf, l);
3732 buf += l;
3733 size -= l;
3734 s->index += l;
3735 if (s->index == 4) {
3736 /* got length */
3737 s->packet_len = ntohl(*(uint32_t *)s->buf);
3738 s->index = 0;
3739 s->state = 1;
3741 break;
3742 case 1:
3743 l = s->packet_len - s->index;
3744 if (l > size)
3745 l = size;
3746 memcpy(s->buf + s->index, buf, l);
3747 s->index += l;
3748 buf += l;
3749 size -= l;
3750 if (s->index >= s->packet_len) {
3751 qemu_send_packet(s->vc, s->buf, s->packet_len);
3752 s->index = 0;
3753 s->state = 0;
3755 break;
3760 static void net_socket_send_dgram(void *opaque)
3762 NetSocketState *s = opaque;
3763 int size;
3765 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3766 if (size < 0)
3767 return;
3768 if (size == 0) {
3769 /* end of connection */
3770 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3771 return;
3773 qemu_send_packet(s->vc, s->buf, size);
3776 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3778 struct ip_mreq imr;
3779 int fd;
3780 int val, ret;
3781 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3782 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3783 inet_ntoa(mcastaddr->sin_addr),
3784 (int)ntohl(mcastaddr->sin_addr.s_addr));
3785 return -1;
3788 fd = socket(PF_INET, SOCK_DGRAM, 0);
3789 if (fd < 0) {
3790 perror("socket(PF_INET, SOCK_DGRAM)");
3791 return -1;
3794 val = 1;
3795 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3796 (const char *)&val, sizeof(val));
3797 if (ret < 0) {
3798 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3799 goto fail;
3802 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3803 if (ret < 0) {
3804 perror("bind");
3805 goto fail;
3808 /* Add host to multicast group */
3809 imr.imr_multiaddr = mcastaddr->sin_addr;
3810 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3812 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3813 (const char *)&imr, sizeof(struct ip_mreq));
3814 if (ret < 0) {
3815 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3816 goto fail;
3819 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3820 val = 1;
3821 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3822 (const char *)&val, sizeof(val));
3823 if (ret < 0) {
3824 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3825 goto fail;
3828 socket_set_nonblock(fd);
3829 return fd;
3830 fail:
3831 if (fd >= 0)
3832 closesocket(fd);
3833 return -1;
3836 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3837 int is_connected)
3839 struct sockaddr_in saddr;
3840 int newfd;
3841 socklen_t saddr_len;
3842 NetSocketState *s;
3844 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3845 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3846 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3849 if (is_connected) {
3850 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3851 /* must be bound */
3852 if (saddr.sin_addr.s_addr==0) {
3853 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3854 fd);
3855 return NULL;
3857 /* clone dgram socket */
3858 newfd = net_socket_mcast_create(&saddr);
3859 if (newfd < 0) {
3860 /* error already reported by net_socket_mcast_create() */
3861 close(fd);
3862 return NULL;
3864 /* clone newfd to fd, close newfd */
3865 dup2(newfd, fd);
3866 close(newfd);
3868 } else {
3869 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3870 fd, strerror(errno));
3871 return NULL;
3875 s = qemu_mallocz(sizeof(NetSocketState));
3876 if (!s)
3877 return NULL;
3878 s->fd = fd;
3880 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3881 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3883 /* mcast: save bound address as dst */
3884 if (is_connected) s->dgram_dst=saddr;
3886 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3887 "socket: fd=%d (%s mcast=%s:%d)",
3888 fd, is_connected? "cloned" : "",
3889 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3890 return s;
3893 static void net_socket_connect(void *opaque)
3895 NetSocketState *s = opaque;
3896 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3899 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3900 int is_connected)
3902 NetSocketState *s;
3903 s = qemu_mallocz(sizeof(NetSocketState));
3904 if (!s)
3905 return NULL;
3906 s->fd = fd;
3907 s->vc = qemu_new_vlan_client(vlan,
3908 net_socket_receive, NULL, s);
3909 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3910 "socket: fd=%d", fd);
3911 if (is_connected) {
3912 net_socket_connect(s);
3913 } else {
3914 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3916 return s;
3919 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3920 int is_connected)
3922 int so_type=-1, optlen=sizeof(so_type);
3924 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3925 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3926 return NULL;
3928 switch(so_type) {
3929 case SOCK_DGRAM:
3930 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3931 case SOCK_STREAM:
3932 return net_socket_fd_init_stream(vlan, fd, is_connected);
3933 default:
3934 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3935 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3936 return net_socket_fd_init_stream(vlan, fd, is_connected);
3938 return NULL;
3941 static void net_socket_accept(void *opaque)
3943 NetSocketListenState *s = opaque;
3944 NetSocketState *s1;
3945 struct sockaddr_in saddr;
3946 socklen_t len;
3947 int fd;
3949 for(;;) {
3950 len = sizeof(saddr);
3951 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3952 if (fd < 0 && errno != EINTR) {
3953 return;
3954 } else if (fd >= 0) {
3955 break;
3958 s1 = net_socket_fd_init(s->vlan, fd, 1);
3959 if (!s1) {
3960 closesocket(fd);
3961 } else {
3962 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3963 "socket: connection from %s:%d",
3964 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3968 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3970 NetSocketListenState *s;
3971 int fd, val, ret;
3972 struct sockaddr_in saddr;
3974 if (parse_host_port(&saddr, host_str) < 0)
3975 return -1;
3977 s = qemu_mallocz(sizeof(NetSocketListenState));
3978 if (!s)
3979 return -1;
3981 fd = socket(PF_INET, SOCK_STREAM, 0);
3982 if (fd < 0) {
3983 perror("socket");
3984 return -1;
3986 socket_set_nonblock(fd);
3988 /* allow fast reuse */
3989 val = 1;
3990 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3992 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3993 if (ret < 0) {
3994 perror("bind");
3995 return -1;
3997 ret = listen(fd, 0);
3998 if (ret < 0) {
3999 perror("listen");
4000 return -1;
4002 s->vlan = vlan;
4003 s->fd = fd;
4004 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4005 return 0;
4008 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4010 NetSocketState *s;
4011 int fd, connected, ret, err;
4012 struct sockaddr_in saddr;
4014 if (parse_host_port(&saddr, host_str) < 0)
4015 return -1;
4017 fd = socket(PF_INET, SOCK_STREAM, 0);
4018 if (fd < 0) {
4019 perror("socket");
4020 return -1;
4022 socket_set_nonblock(fd);
4024 connected = 0;
4025 for(;;) {
4026 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4027 if (ret < 0) {
4028 err = socket_error();
4029 if (err == EINTR || err == EWOULDBLOCK) {
4030 } else if (err == EINPROGRESS) {
4031 break;
4032 #ifdef _WIN32
4033 } else if (err == WSAEALREADY) {
4034 break;
4035 #endif
4036 } else {
4037 perror("connect");
4038 closesocket(fd);
4039 return -1;
4041 } else {
4042 connected = 1;
4043 break;
4046 s = net_socket_fd_init(vlan, fd, connected);
4047 if (!s)
4048 return -1;
4049 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4050 "socket: connect to %s:%d",
4051 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4052 return 0;
4055 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4057 NetSocketState *s;
4058 int fd;
4059 struct sockaddr_in saddr;
4061 if (parse_host_port(&saddr, host_str) < 0)
4062 return -1;
4065 fd = net_socket_mcast_create(&saddr);
4066 if (fd < 0)
4067 return -1;
4069 s = net_socket_fd_init(vlan, fd, 0);
4070 if (!s)
4071 return -1;
4073 s->dgram_dst = saddr;
4075 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4076 "socket: mcast=%s:%d",
4077 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4078 return 0;
4082 static int get_param_value(char *buf, int buf_size,
4083 const char *tag, const char *str)
4085 const char *p;
4086 char *q;
4087 char option[128];
4089 p = str;
4090 for(;;) {
4091 q = option;
4092 while (*p != '\0' && *p != '=') {
4093 if ((q - option) < sizeof(option) - 1)
4094 *q++ = *p;
4095 p++;
4097 *q = '\0';
4098 if (*p != '=')
4099 break;
4100 p++;
4101 if (!strcmp(tag, option)) {
4102 q = buf;
4103 while (*p != '\0' && *p != ',') {
4104 if ((q - buf) < buf_size - 1)
4105 *q++ = *p;
4106 p++;
4108 *q = '\0';
4109 return q - buf;
4110 } else {
4111 while (*p != '\0' && *p != ',') {
4112 p++;
4115 if (*p != ',')
4116 break;
4117 p++;
4119 return 0;
4122 static int net_client_init(const char *str)
4124 const char *p;
4125 char *q;
4126 char device[64];
4127 char buf[1024];
4128 int vlan_id, ret;
4129 VLANState *vlan;
4131 p = str;
4132 q = device;
4133 while (*p != '\0' && *p != ',') {
4134 if ((q - device) < sizeof(device) - 1)
4135 *q++ = *p;
4136 p++;
4138 *q = '\0';
4139 if (*p == ',')
4140 p++;
4141 vlan_id = 0;
4142 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4143 vlan_id = strtol(buf, NULL, 0);
4145 vlan = qemu_find_vlan(vlan_id);
4146 if (!vlan) {
4147 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4148 return -1;
4150 if (!strcmp(device, "nic")) {
4151 NICInfo *nd;
4152 uint8_t *macaddr;
4154 if (nb_nics >= MAX_NICS) {
4155 fprintf(stderr, "Too Many NICs\n");
4156 return -1;
4158 nd = &nd_table[nb_nics];
4159 macaddr = nd->macaddr;
4160 macaddr[0] = 0x52;
4161 macaddr[1] = 0x54;
4162 macaddr[2] = 0x00;
4163 macaddr[3] = 0x12;
4164 macaddr[4] = 0x34;
4165 macaddr[5] = 0x56 + nb_nics;
4167 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4168 if (parse_macaddr(macaddr, buf) < 0) {
4169 fprintf(stderr, "invalid syntax for ethernet address\n");
4170 return -1;
4173 if (get_param_value(buf, sizeof(buf), "model", p)) {
4174 nd->model = strdup(buf);
4176 nd->vlan = vlan;
4177 nb_nics++;
4178 ret = 0;
4179 } else
4180 if (!strcmp(device, "none")) {
4181 /* does nothing. It is needed to signal that no network cards
4182 are wanted */
4183 ret = 0;
4184 } else
4185 #ifdef CONFIG_SLIRP
4186 if (!strcmp(device, "user")) {
4187 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4188 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4190 ret = net_slirp_init(vlan);
4191 } else
4192 #endif
4193 #ifdef _WIN32
4194 if (!strcmp(device, "tap")) {
4195 char ifname[64];
4196 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4197 fprintf(stderr, "tap: no interface name\n");
4198 return -1;
4200 ret = tap_win32_init(vlan, ifname);
4201 } else
4202 #else
4203 if (!strcmp(device, "tap")) {
4204 char ifname[64];
4205 char setup_script[1024];
4206 int fd;
4207 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4208 fd = strtol(buf, NULL, 0);
4209 ret = -1;
4210 if (net_tap_fd_init(vlan, fd))
4211 ret = 0;
4212 } else {
4213 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4214 ifname[0] = '\0';
4216 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4217 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4219 ret = net_tap_init(vlan, ifname, setup_script);
4221 } else
4222 #endif
4223 if (!strcmp(device, "socket")) {
4224 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4225 int fd;
4226 fd = strtol(buf, NULL, 0);
4227 ret = -1;
4228 if (net_socket_fd_init(vlan, fd, 1))
4229 ret = 0;
4230 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4231 ret = net_socket_listen_init(vlan, buf);
4232 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4233 ret = net_socket_connect_init(vlan, buf);
4234 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4235 ret = net_socket_mcast_init(vlan, buf);
4236 } else {
4237 fprintf(stderr, "Unknown socket options: %s\n", p);
4238 return -1;
4240 } else
4242 fprintf(stderr, "Unknown network device: %s\n", device);
4243 return -1;
4245 if (ret < 0) {
4246 fprintf(stderr, "Could not initialize device '%s'\n", device);
4249 return ret;
4252 void do_info_network(void)
4254 VLANState *vlan;
4255 VLANClientState *vc;
4257 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4258 term_printf("VLAN %d devices:\n", vlan->id);
4259 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4260 term_printf(" %s\n", vc->info_str);
4264 /***********************************************************/
4265 /* USB devices */
4267 static USBPort *used_usb_ports;
4268 static USBPort *free_usb_ports;
4270 /* ??? Maybe change this to register a hub to keep track of the topology. */
4271 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4272 usb_attachfn attach)
4274 port->opaque = opaque;
4275 port->index = index;
4276 port->attach = attach;
4277 port->next = free_usb_ports;
4278 free_usb_ports = port;
4281 static int usb_device_add(const char *devname)
4283 const char *p;
4284 USBDevice *dev;
4285 USBPort *port;
4287 if (!free_usb_ports)
4288 return -1;
4290 if (strstart(devname, "host:", &p)) {
4291 dev = usb_host_device_open(p);
4292 } else if (!strcmp(devname, "mouse")) {
4293 dev = usb_mouse_init();
4294 } else if (!strcmp(devname, "tablet")) {
4295 dev = usb_tablet_init();
4296 } else if (strstart(devname, "disk:", &p)) {
4297 dev = usb_msd_init(p);
4298 } else {
4299 return -1;
4301 if (!dev)
4302 return -1;
4304 /* Find a USB port to add the device to. */
4305 port = free_usb_ports;
4306 if (!port->next) {
4307 USBDevice *hub;
4309 /* Create a new hub and chain it on. */
4310 free_usb_ports = NULL;
4311 port->next = used_usb_ports;
4312 used_usb_ports = port;
4314 hub = usb_hub_init(VM_USB_HUB_SIZE);
4315 usb_attach(port, hub);
4316 port = free_usb_ports;
4319 free_usb_ports = port->next;
4320 port->next = used_usb_ports;
4321 used_usb_ports = port;
4322 usb_attach(port, dev);
4323 return 0;
4326 static int usb_device_del(const char *devname)
4328 USBPort *port;
4329 USBPort **lastp;
4330 USBDevice *dev;
4331 int bus_num, addr;
4332 const char *p;
4334 if (!used_usb_ports)
4335 return -1;
4337 p = strchr(devname, '.');
4338 if (!p)
4339 return -1;
4340 bus_num = strtoul(devname, NULL, 0);
4341 addr = strtoul(p + 1, NULL, 0);
4342 if (bus_num != 0)
4343 return -1;
4345 lastp = &used_usb_ports;
4346 port = used_usb_ports;
4347 while (port && port->dev->addr != addr) {
4348 lastp = &port->next;
4349 port = port->next;
4352 if (!port)
4353 return -1;
4355 dev = port->dev;
4356 *lastp = port->next;
4357 usb_attach(port, NULL);
4358 dev->handle_destroy(dev);
4359 port->next = free_usb_ports;
4360 free_usb_ports = port;
4361 return 0;
4364 void do_usb_add(const char *devname)
4366 int ret;
4367 ret = usb_device_add(devname);
4368 if (ret < 0)
4369 term_printf("Could not add USB device '%s'\n", devname);
4372 void do_usb_del(const char *devname)
4374 int ret;
4375 ret = usb_device_del(devname);
4376 if (ret < 0)
4377 term_printf("Could not remove USB device '%s'\n", devname);
4380 void usb_info(void)
4382 USBDevice *dev;
4383 USBPort *port;
4384 const char *speed_str;
4386 if (!usb_enabled) {
4387 term_printf("USB support not enabled\n");
4388 return;
4391 for (port = used_usb_ports; port; port = port->next) {
4392 dev = port->dev;
4393 if (!dev)
4394 continue;
4395 switch(dev->speed) {
4396 case USB_SPEED_LOW:
4397 speed_str = "1.5";
4398 break;
4399 case USB_SPEED_FULL:
4400 speed_str = "12";
4401 break;
4402 case USB_SPEED_HIGH:
4403 speed_str = "480";
4404 break;
4405 default:
4406 speed_str = "?";
4407 break;
4409 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4410 0, dev->addr, speed_str, dev->devname);
4414 /***********************************************************/
4415 /* dumb display */
4417 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4421 static void dumb_resize(DisplayState *ds, int w, int h)
4425 static void dumb_refresh(DisplayState *ds)
4427 vga_hw_update();
4430 void dumb_display_init(DisplayState *ds)
4432 ds->data = NULL;
4433 ds->linesize = 0;
4434 ds->depth = 0;
4435 ds->dpy_update = dumb_update;
4436 ds->dpy_resize = dumb_resize;
4437 ds->dpy_refresh = dumb_refresh;
4440 /***********************************************************/
4441 /* I/O handling */
4443 #define MAX_IO_HANDLERS 64
4445 typedef struct IOHandlerRecord {
4446 int fd;
4447 IOCanRWHandler *fd_read_poll;
4448 IOHandler *fd_read;
4449 IOHandler *fd_write;
4450 int deleted;
4451 void *opaque;
4452 /* temporary data */
4453 struct pollfd *ufd;
4454 struct IOHandlerRecord *next;
4455 } IOHandlerRecord;
4457 static IOHandlerRecord *first_io_handler;
4459 /* XXX: fd_read_poll should be suppressed, but an API change is
4460 necessary in the character devices to suppress fd_can_read(). */
4461 int qemu_set_fd_handler2(int fd,
4462 IOCanRWHandler *fd_read_poll,
4463 IOHandler *fd_read,
4464 IOHandler *fd_write,
4465 void *opaque)
4467 IOHandlerRecord **pioh, *ioh;
4469 if (!fd_read && !fd_write) {
4470 pioh = &first_io_handler;
4471 for(;;) {
4472 ioh = *pioh;
4473 if (ioh == NULL)
4474 break;
4475 if (ioh->fd == fd) {
4476 ioh->deleted = 1;
4477 break;
4479 pioh = &ioh->next;
4481 } else {
4482 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4483 if (ioh->fd == fd)
4484 goto found;
4486 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4487 if (!ioh)
4488 return -1;
4489 ioh->next = first_io_handler;
4490 first_io_handler = ioh;
4491 found:
4492 ioh->fd = fd;
4493 ioh->fd_read_poll = fd_read_poll;
4494 ioh->fd_read = fd_read;
4495 ioh->fd_write = fd_write;
4496 ioh->opaque = opaque;
4497 ioh->deleted = 0;
4499 return 0;
4502 int qemu_set_fd_handler(int fd,
4503 IOHandler *fd_read,
4504 IOHandler *fd_write,
4505 void *opaque)
4507 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4510 /***********************************************************/
4511 /* Polling handling */
4513 typedef struct PollingEntry {
4514 PollingFunc *func;
4515 void *opaque;
4516 struct PollingEntry *next;
4517 } PollingEntry;
4519 static PollingEntry *first_polling_entry;
4521 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4523 PollingEntry **ppe, *pe;
4524 pe = qemu_mallocz(sizeof(PollingEntry));
4525 if (!pe)
4526 return -1;
4527 pe->func = func;
4528 pe->opaque = opaque;
4529 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4530 *ppe = pe;
4531 return 0;
4534 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4536 PollingEntry **ppe, *pe;
4537 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4538 pe = *ppe;
4539 if (pe->func == func && pe->opaque == opaque) {
4540 *ppe = pe->next;
4541 qemu_free(pe);
4542 break;
4547 #ifdef _WIN32
4548 /***********************************************************/
4549 /* Wait objects support */
4550 typedef struct WaitObjects {
4551 int num;
4552 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4553 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4554 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4555 } WaitObjects;
4557 static WaitObjects wait_objects = {0};
4559 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4561 WaitObjects *w = &wait_objects;
4563 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4564 return -1;
4565 w->events[w->num] = handle;
4566 w->func[w->num] = func;
4567 w->opaque[w->num] = opaque;
4568 w->num++;
4569 return 0;
4572 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4574 int i, found;
4575 WaitObjects *w = &wait_objects;
4577 found = 0;
4578 for (i = 0; i < w->num; i++) {
4579 if (w->events[i] == handle)
4580 found = 1;
4581 if (found) {
4582 w->events[i] = w->events[i + 1];
4583 w->func[i] = w->func[i + 1];
4584 w->opaque[i] = w->opaque[i + 1];
4587 if (found)
4588 w->num--;
4590 #endif
4592 /***********************************************************/
4593 /* savevm/loadvm support */
4595 #define IO_BUF_SIZE 32768
4597 struct QEMUFile {
4598 FILE *outfile;
4599 BlockDriverState *bs;
4600 int is_file;
4601 int is_writable;
4602 int64_t base_offset;
4603 int64_t buf_offset; /* start of buffer when writing, end of buffer
4604 when reading */
4605 int buf_index;
4606 int buf_size; /* 0 when writing */
4607 uint8_t buf[IO_BUF_SIZE];
4610 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4612 QEMUFile *f;
4614 f = qemu_mallocz(sizeof(QEMUFile));
4615 if (!f)
4616 return NULL;
4617 if (!strcmp(mode, "wb")) {
4618 f->is_writable = 1;
4619 } else if (!strcmp(mode, "rb")) {
4620 f->is_writable = 0;
4621 } else {
4622 goto fail;
4624 f->outfile = fopen(filename, mode);
4625 if (!f->outfile)
4626 goto fail;
4627 f->is_file = 1;
4628 return f;
4629 fail:
4630 if (f->outfile)
4631 fclose(f->outfile);
4632 qemu_free(f);
4633 return NULL;
4636 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4638 QEMUFile *f;
4640 f = qemu_mallocz(sizeof(QEMUFile));
4641 if (!f)
4642 return NULL;
4643 f->is_file = 0;
4644 f->bs = bs;
4645 f->is_writable = is_writable;
4646 f->base_offset = offset;
4647 return f;
4650 void qemu_fflush(QEMUFile *f)
4652 if (!f->is_writable)
4653 return;
4654 if (f->buf_index > 0) {
4655 if (f->is_file) {
4656 fseek(f->outfile, f->buf_offset, SEEK_SET);
4657 fwrite(f->buf, 1, f->buf_index, f->outfile);
4658 } else {
4659 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4660 f->buf, f->buf_index);
4662 f->buf_offset += f->buf_index;
4663 f->buf_index = 0;
4667 static void qemu_fill_buffer(QEMUFile *f)
4669 int len;
4671 if (f->is_writable)
4672 return;
4673 if (f->is_file) {
4674 fseek(f->outfile, f->buf_offset, SEEK_SET);
4675 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4676 if (len < 0)
4677 len = 0;
4678 } else {
4679 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4680 f->buf, IO_BUF_SIZE);
4681 if (len < 0)
4682 len = 0;
4684 f->buf_index = 0;
4685 f->buf_size = len;
4686 f->buf_offset += len;
4689 void qemu_fclose(QEMUFile *f)
4691 if (f->is_writable)
4692 qemu_fflush(f);
4693 if (f->is_file) {
4694 fclose(f->outfile);
4696 qemu_free(f);
4699 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4701 int l;
4702 while (size > 0) {
4703 l = IO_BUF_SIZE - f->buf_index;
4704 if (l > size)
4705 l = size;
4706 memcpy(f->buf + f->buf_index, buf, l);
4707 f->buf_index += l;
4708 buf += l;
4709 size -= l;
4710 if (f->buf_index >= IO_BUF_SIZE)
4711 qemu_fflush(f);
4715 void qemu_put_byte(QEMUFile *f, int v)
4717 f->buf[f->buf_index++] = v;
4718 if (f->buf_index >= IO_BUF_SIZE)
4719 qemu_fflush(f);
4722 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4724 int size, l;
4726 size = size1;
4727 while (size > 0) {
4728 l = f->buf_size - f->buf_index;
4729 if (l == 0) {
4730 qemu_fill_buffer(f);
4731 l = f->buf_size - f->buf_index;
4732 if (l == 0)
4733 break;
4735 if (l > size)
4736 l = size;
4737 memcpy(buf, f->buf + f->buf_index, l);
4738 f->buf_index += l;
4739 buf += l;
4740 size -= l;
4742 return size1 - size;
4745 int qemu_get_byte(QEMUFile *f)
4747 if (f->buf_index >= f->buf_size) {
4748 qemu_fill_buffer(f);
4749 if (f->buf_index >= f->buf_size)
4750 return 0;
4752 return f->buf[f->buf_index++];
4755 int64_t qemu_ftell(QEMUFile *f)
4757 return f->buf_offset - f->buf_size + f->buf_index;
4760 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4762 if (whence == SEEK_SET) {
4763 /* nothing to do */
4764 } else if (whence == SEEK_CUR) {
4765 pos += qemu_ftell(f);
4766 } else {
4767 /* SEEK_END not supported */
4768 return -1;
4770 if (f->is_writable) {
4771 qemu_fflush(f);
4772 f->buf_offset = pos;
4773 } else {
4774 f->buf_offset = pos;
4775 f->buf_index = 0;
4776 f->buf_size = 0;
4778 return pos;
4781 void qemu_put_be16(QEMUFile *f, unsigned int v)
4783 qemu_put_byte(f, v >> 8);
4784 qemu_put_byte(f, v);
4787 void qemu_put_be32(QEMUFile *f, unsigned int v)
4789 qemu_put_byte(f, v >> 24);
4790 qemu_put_byte(f, v >> 16);
4791 qemu_put_byte(f, v >> 8);
4792 qemu_put_byte(f, v);
4795 void qemu_put_be64(QEMUFile *f, uint64_t v)
4797 qemu_put_be32(f, v >> 32);
4798 qemu_put_be32(f, v);
4801 unsigned int qemu_get_be16(QEMUFile *f)
4803 unsigned int v;
4804 v = qemu_get_byte(f) << 8;
4805 v |= qemu_get_byte(f);
4806 return v;
4809 unsigned int qemu_get_be32(QEMUFile *f)
4811 unsigned int v;
4812 v = qemu_get_byte(f) << 24;
4813 v |= qemu_get_byte(f) << 16;
4814 v |= qemu_get_byte(f) << 8;
4815 v |= qemu_get_byte(f);
4816 return v;
4819 uint64_t qemu_get_be64(QEMUFile *f)
4821 uint64_t v;
4822 v = (uint64_t)qemu_get_be32(f) << 32;
4823 v |= qemu_get_be32(f);
4824 return v;
4827 typedef struct SaveStateEntry {
4828 char idstr[256];
4829 int instance_id;
4830 int version_id;
4831 SaveStateHandler *save_state;
4832 LoadStateHandler *load_state;
4833 void *opaque;
4834 struct SaveStateEntry *next;
4835 } SaveStateEntry;
4837 static SaveStateEntry *first_se;
4839 int register_savevm(const char *idstr,
4840 int instance_id,
4841 int version_id,
4842 SaveStateHandler *save_state,
4843 LoadStateHandler *load_state,
4844 void *opaque)
4846 SaveStateEntry *se, **pse;
4848 se = qemu_malloc(sizeof(SaveStateEntry));
4849 if (!se)
4850 return -1;
4851 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4852 se->instance_id = instance_id;
4853 se->version_id = version_id;
4854 se->save_state = save_state;
4855 se->load_state = load_state;
4856 se->opaque = opaque;
4857 se->next = NULL;
4859 /* add at the end of list */
4860 pse = &first_se;
4861 while (*pse != NULL)
4862 pse = &(*pse)->next;
4863 *pse = se;
4864 return 0;
4867 #define QEMU_VM_FILE_MAGIC 0x5145564d
4868 #define QEMU_VM_FILE_VERSION 0x00000002
4870 int qemu_savevm_state(QEMUFile *f)
4872 SaveStateEntry *se;
4873 int len, ret;
4874 int64_t cur_pos, len_pos, total_len_pos;
4876 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4877 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4878 total_len_pos = qemu_ftell(f);
4879 qemu_put_be64(f, 0); /* total size */
4881 for(se = first_se; se != NULL; se = se->next) {
4882 /* ID string */
4883 len = strlen(se->idstr);
4884 qemu_put_byte(f, len);
4885 qemu_put_buffer(f, se->idstr, len);
4887 qemu_put_be32(f, se->instance_id);
4888 qemu_put_be32(f, se->version_id);
4890 /* record size: filled later */
4891 len_pos = qemu_ftell(f);
4892 qemu_put_be32(f, 0);
4894 se->save_state(f, se->opaque);
4896 /* fill record size */
4897 cur_pos = qemu_ftell(f);
4898 len = cur_pos - len_pos - 4;
4899 qemu_fseek(f, len_pos, SEEK_SET);
4900 qemu_put_be32(f, len);
4901 qemu_fseek(f, cur_pos, SEEK_SET);
4903 cur_pos = qemu_ftell(f);
4904 qemu_fseek(f, total_len_pos, SEEK_SET);
4905 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4906 qemu_fseek(f, cur_pos, SEEK_SET);
4908 ret = 0;
4909 return ret;
4912 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4914 SaveStateEntry *se;
4916 for(se = first_se; se != NULL; se = se->next) {
4917 if (!strcmp(se->idstr, idstr) &&
4918 instance_id == se->instance_id)
4919 return se;
4921 return NULL;
4924 int qemu_loadvm_state(QEMUFile *f)
4926 SaveStateEntry *se;
4927 int len, ret, instance_id, record_len, version_id;
4928 int64_t total_len, end_pos, cur_pos;
4929 unsigned int v;
4930 char idstr[256];
4932 v = qemu_get_be32(f);
4933 if (v != QEMU_VM_FILE_MAGIC)
4934 goto fail;
4935 v = qemu_get_be32(f);
4936 if (v != QEMU_VM_FILE_VERSION) {
4937 fail:
4938 ret = -1;
4939 goto the_end;
4941 total_len = qemu_get_be64(f);
4942 end_pos = total_len + qemu_ftell(f);
4943 for(;;) {
4944 if (qemu_ftell(f) >= end_pos)
4945 break;
4946 len = qemu_get_byte(f);
4947 qemu_get_buffer(f, idstr, len);
4948 idstr[len] = '\0';
4949 instance_id = qemu_get_be32(f);
4950 version_id = qemu_get_be32(f);
4951 record_len = qemu_get_be32(f);
4952 #if 0
4953 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4954 idstr, instance_id, version_id, record_len);
4955 #endif
4956 cur_pos = qemu_ftell(f);
4957 se = find_se(idstr, instance_id);
4958 if (!se) {
4959 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4960 instance_id, idstr);
4961 } else {
4962 ret = se->load_state(f, se->opaque, version_id);
4963 if (ret < 0) {
4964 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4965 instance_id, idstr);
4968 /* always seek to exact end of record */
4969 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4971 ret = 0;
4972 the_end:
4973 return ret;
4976 /* device can contain snapshots */
4977 static int bdrv_can_snapshot(BlockDriverState *bs)
4979 return (bs &&
4980 !bdrv_is_removable(bs) &&
4981 !bdrv_is_read_only(bs));
4984 /* device must be snapshots in order to have a reliable snapshot */
4985 static int bdrv_has_snapshot(BlockDriverState *bs)
4987 return (bs &&
4988 !bdrv_is_removable(bs) &&
4989 !bdrv_is_read_only(bs));
4992 static BlockDriverState *get_bs_snapshots(void)
4994 BlockDriverState *bs;
4995 int i;
4997 if (bs_snapshots)
4998 return bs_snapshots;
4999 for(i = 0; i <= MAX_DISKS; i++) {
5000 bs = bs_table[i];
5001 if (bdrv_can_snapshot(bs))
5002 goto ok;
5004 return NULL;
5006 bs_snapshots = bs;
5007 return bs;
5010 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5011 const char *name)
5013 QEMUSnapshotInfo *sn_tab, *sn;
5014 int nb_sns, i, ret;
5016 ret = -ENOENT;
5017 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5018 if (nb_sns < 0)
5019 return ret;
5020 for(i = 0; i < nb_sns; i++) {
5021 sn = &sn_tab[i];
5022 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5023 *sn_info = *sn;
5024 ret = 0;
5025 break;
5028 qemu_free(sn_tab);
5029 return ret;
5032 void do_savevm(const char *name)
5034 BlockDriverState *bs, *bs1;
5035 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5036 int must_delete, ret, i;
5037 BlockDriverInfo bdi1, *bdi = &bdi1;
5038 QEMUFile *f;
5039 int saved_vm_running;
5040 #ifdef _WIN32
5041 struct _timeb tb;
5042 #else
5043 struct timeval tv;
5044 #endif
5046 bs = get_bs_snapshots();
5047 if (!bs) {
5048 term_printf("No block device can accept snapshots\n");
5049 return;
5052 /* ??? Should this occur after vm_stop? */
5053 qemu_aio_flush();
5055 saved_vm_running = vm_running;
5056 vm_stop(0);
5058 must_delete = 0;
5059 if (name) {
5060 ret = bdrv_snapshot_find(bs, old_sn, name);
5061 if (ret >= 0) {
5062 must_delete = 1;
5065 memset(sn, 0, sizeof(*sn));
5066 if (must_delete) {
5067 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5068 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5069 } else {
5070 if (name)
5071 pstrcpy(sn->name, sizeof(sn->name), name);
5074 /* fill auxiliary fields */
5075 #ifdef _WIN32
5076 _ftime(&tb);
5077 sn->date_sec = tb.time;
5078 sn->date_nsec = tb.millitm * 1000000;
5079 #else
5080 gettimeofday(&tv, NULL);
5081 sn->date_sec = tv.tv_sec;
5082 sn->date_nsec = tv.tv_usec * 1000;
5083 #endif
5084 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5086 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5087 term_printf("Device %s does not support VM state snapshots\n",
5088 bdrv_get_device_name(bs));
5089 goto the_end;
5092 /* save the VM state */
5093 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5094 if (!f) {
5095 term_printf("Could not open VM state file\n");
5096 goto the_end;
5098 ret = qemu_savevm_state(f);
5099 sn->vm_state_size = qemu_ftell(f);
5100 qemu_fclose(f);
5101 if (ret < 0) {
5102 term_printf("Error %d while writing VM\n", ret);
5103 goto the_end;
5106 /* create the snapshots */
5108 for(i = 0; i < MAX_DISKS; i++) {
5109 bs1 = bs_table[i];
5110 if (bdrv_has_snapshot(bs1)) {
5111 if (must_delete) {
5112 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5113 if (ret < 0) {
5114 term_printf("Error while deleting snapshot on '%s'\n",
5115 bdrv_get_device_name(bs1));
5118 ret = bdrv_snapshot_create(bs1, sn);
5119 if (ret < 0) {
5120 term_printf("Error while creating snapshot on '%s'\n",
5121 bdrv_get_device_name(bs1));
5126 the_end:
5127 if (saved_vm_running)
5128 vm_start();
5131 void do_loadvm(const char *name)
5133 BlockDriverState *bs, *bs1;
5134 BlockDriverInfo bdi1, *bdi = &bdi1;
5135 QEMUFile *f;
5136 int i, ret;
5137 int saved_vm_running;
5139 bs = get_bs_snapshots();
5140 if (!bs) {
5141 term_printf("No block device supports snapshots\n");
5142 return;
5145 /* Flush all IO requests so they don't interfere with the new state. */
5146 qemu_aio_flush();
5148 saved_vm_running = vm_running;
5149 vm_stop(0);
5151 for(i = 0; i <= MAX_DISKS; i++) {
5152 bs1 = bs_table[i];
5153 if (bdrv_has_snapshot(bs1)) {
5154 ret = bdrv_snapshot_goto(bs1, name);
5155 if (ret < 0) {
5156 if (bs != bs1)
5157 term_printf("Warning: ");
5158 switch(ret) {
5159 case -ENOTSUP:
5160 term_printf("Snapshots not supported on device '%s'\n",
5161 bdrv_get_device_name(bs1));
5162 break;
5163 case -ENOENT:
5164 term_printf("Could not find snapshot '%s' on device '%s'\n",
5165 name, bdrv_get_device_name(bs1));
5166 break;
5167 default:
5168 term_printf("Error %d while activating snapshot on '%s'\n",
5169 ret, bdrv_get_device_name(bs1));
5170 break;
5172 /* fatal on snapshot block device */
5173 if (bs == bs1)
5174 goto the_end;
5179 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5180 term_printf("Device %s does not support VM state snapshots\n",
5181 bdrv_get_device_name(bs));
5182 return;
5185 /* restore the VM state */
5186 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5187 if (!f) {
5188 term_printf("Could not open VM state file\n");
5189 goto the_end;
5191 ret = qemu_loadvm_state(f);
5192 qemu_fclose(f);
5193 if (ret < 0) {
5194 term_printf("Error %d while loading VM state\n", ret);
5196 the_end:
5197 if (saved_vm_running)
5198 vm_start();
5201 void do_delvm(const char *name)
5203 BlockDriverState *bs, *bs1;
5204 int i, ret;
5206 bs = get_bs_snapshots();
5207 if (!bs) {
5208 term_printf("No block device supports snapshots\n");
5209 return;
5212 for(i = 0; i <= MAX_DISKS; i++) {
5213 bs1 = bs_table[i];
5214 if (bdrv_has_snapshot(bs1)) {
5215 ret = bdrv_snapshot_delete(bs1, name);
5216 if (ret < 0) {
5217 if (ret == -ENOTSUP)
5218 term_printf("Snapshots not supported on device '%s'\n",
5219 bdrv_get_device_name(bs1));
5220 else
5221 term_printf("Error %d while deleting snapshot on '%s'\n",
5222 ret, bdrv_get_device_name(bs1));
5228 void do_info_snapshots(void)
5230 BlockDriverState *bs, *bs1;
5231 QEMUSnapshotInfo *sn_tab, *sn;
5232 int nb_sns, i;
5233 char buf[256];
5235 bs = get_bs_snapshots();
5236 if (!bs) {
5237 term_printf("No available block device supports snapshots\n");
5238 return;
5240 term_printf("Snapshot devices:");
5241 for(i = 0; i <= MAX_DISKS; i++) {
5242 bs1 = bs_table[i];
5243 if (bdrv_has_snapshot(bs1)) {
5244 if (bs == bs1)
5245 term_printf(" %s", bdrv_get_device_name(bs1));
5248 term_printf("\n");
5250 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5251 if (nb_sns < 0) {
5252 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5253 return;
5255 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5256 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5257 for(i = 0; i < nb_sns; i++) {
5258 sn = &sn_tab[i];
5259 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5261 qemu_free(sn_tab);
5264 /***********************************************************/
5265 /* cpu save/restore */
5267 #if defined(TARGET_I386)
5269 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5271 qemu_put_be32(f, dt->selector);
5272 qemu_put_betl(f, dt->base);
5273 qemu_put_be32(f, dt->limit);
5274 qemu_put_be32(f, dt->flags);
5277 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5279 dt->selector = qemu_get_be32(f);
5280 dt->base = qemu_get_betl(f);
5281 dt->limit = qemu_get_be32(f);
5282 dt->flags = qemu_get_be32(f);
5285 void cpu_save(QEMUFile *f, void *opaque)
5287 CPUState *env = opaque;
5288 uint16_t fptag, fpus, fpuc, fpregs_format;
5289 uint32_t hflags;
5290 int i;
5292 for(i = 0; i < CPU_NB_REGS; i++)
5293 qemu_put_betls(f, &env->regs[i]);
5294 qemu_put_betls(f, &env->eip);
5295 qemu_put_betls(f, &env->eflags);
5296 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5297 qemu_put_be32s(f, &hflags);
5299 /* FPU */
5300 fpuc = env->fpuc;
5301 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5302 fptag = 0;
5303 for(i = 0; i < 8; i++) {
5304 fptag |= ((!env->fptags[i]) << i);
5307 qemu_put_be16s(f, &fpuc);
5308 qemu_put_be16s(f, &fpus);
5309 qemu_put_be16s(f, &fptag);
5311 #ifdef USE_X86LDOUBLE
5312 fpregs_format = 0;
5313 #else
5314 fpregs_format = 1;
5315 #endif
5316 qemu_put_be16s(f, &fpregs_format);
5318 for(i = 0; i < 8; i++) {
5319 #ifdef USE_X86LDOUBLE
5321 uint64_t mant;
5322 uint16_t exp;
5323 /* we save the real CPU data (in case of MMX usage only 'mant'
5324 contains the MMX register */
5325 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5326 qemu_put_be64(f, mant);
5327 qemu_put_be16(f, exp);
5329 #else
5330 /* if we use doubles for float emulation, we save the doubles to
5331 avoid losing information in case of MMX usage. It can give
5332 problems if the image is restored on a CPU where long
5333 doubles are used instead. */
5334 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5335 #endif
5338 for(i = 0; i < 6; i++)
5339 cpu_put_seg(f, &env->segs[i]);
5340 cpu_put_seg(f, &env->ldt);
5341 cpu_put_seg(f, &env->tr);
5342 cpu_put_seg(f, &env->gdt);
5343 cpu_put_seg(f, &env->idt);
5345 qemu_put_be32s(f, &env->sysenter_cs);
5346 qemu_put_be32s(f, &env->sysenter_esp);
5347 qemu_put_be32s(f, &env->sysenter_eip);
5349 qemu_put_betls(f, &env->cr[0]);
5350 qemu_put_betls(f, &env->cr[2]);
5351 qemu_put_betls(f, &env->cr[3]);
5352 qemu_put_betls(f, &env->cr[4]);
5354 for(i = 0; i < 8; i++)
5355 qemu_put_betls(f, &env->dr[i]);
5357 /* MMU */
5358 qemu_put_be32s(f, &env->a20_mask);
5360 /* XMM */
5361 qemu_put_be32s(f, &env->mxcsr);
5362 for(i = 0; i < CPU_NB_REGS; i++) {
5363 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5364 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5367 #ifdef TARGET_X86_64
5368 qemu_put_be64s(f, &env->efer);
5369 qemu_put_be64s(f, &env->star);
5370 qemu_put_be64s(f, &env->lstar);
5371 qemu_put_be64s(f, &env->cstar);
5372 qemu_put_be64s(f, &env->fmask);
5373 qemu_put_be64s(f, &env->kernelgsbase);
5374 #endif
5375 qemu_put_be32s(f, &env->smbase);
5378 #ifdef USE_X86LDOUBLE
5379 /* XXX: add that in a FPU generic layer */
5380 union x86_longdouble {
5381 uint64_t mant;
5382 uint16_t exp;
5385 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5386 #define EXPBIAS1 1023
5387 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5388 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5390 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5392 int e;
5393 /* mantissa */
5394 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5395 /* exponent + sign */
5396 e = EXPD1(temp) - EXPBIAS1 + 16383;
5397 e |= SIGND1(temp) >> 16;
5398 p->exp = e;
5400 #endif
5402 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5404 CPUState *env = opaque;
5405 int i, guess_mmx;
5406 uint32_t hflags;
5407 uint16_t fpus, fpuc, fptag, fpregs_format;
5409 if (version_id != 3 && version_id != 4)
5410 return -EINVAL;
5411 for(i = 0; i < CPU_NB_REGS; i++)
5412 qemu_get_betls(f, &env->regs[i]);
5413 qemu_get_betls(f, &env->eip);
5414 qemu_get_betls(f, &env->eflags);
5415 qemu_get_be32s(f, &hflags);
5417 qemu_get_be16s(f, &fpuc);
5418 qemu_get_be16s(f, &fpus);
5419 qemu_get_be16s(f, &fptag);
5420 qemu_get_be16s(f, &fpregs_format);
5422 /* NOTE: we cannot always restore the FPU state if the image come
5423 from a host with a different 'USE_X86LDOUBLE' define. We guess
5424 if we are in an MMX state to restore correctly in that case. */
5425 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5426 for(i = 0; i < 8; i++) {
5427 uint64_t mant;
5428 uint16_t exp;
5430 switch(fpregs_format) {
5431 case 0:
5432 mant = qemu_get_be64(f);
5433 exp = qemu_get_be16(f);
5434 #ifdef USE_X86LDOUBLE
5435 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5436 #else
5437 /* difficult case */
5438 if (guess_mmx)
5439 env->fpregs[i].mmx.MMX_Q(0) = mant;
5440 else
5441 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5442 #endif
5443 break;
5444 case 1:
5445 mant = qemu_get_be64(f);
5446 #ifdef USE_X86LDOUBLE
5448 union x86_longdouble *p;
5449 /* difficult case */
5450 p = (void *)&env->fpregs[i];
5451 if (guess_mmx) {
5452 p->mant = mant;
5453 p->exp = 0xffff;
5454 } else {
5455 fp64_to_fp80(p, mant);
5458 #else
5459 env->fpregs[i].mmx.MMX_Q(0) = mant;
5460 #endif
5461 break;
5462 default:
5463 return -EINVAL;
5467 env->fpuc = fpuc;
5468 /* XXX: restore FPU round state */
5469 env->fpstt = (fpus >> 11) & 7;
5470 env->fpus = fpus & ~0x3800;
5471 fptag ^= 0xff;
5472 for(i = 0; i < 8; i++) {
5473 env->fptags[i] = (fptag >> i) & 1;
5476 for(i = 0; i < 6; i++)
5477 cpu_get_seg(f, &env->segs[i]);
5478 cpu_get_seg(f, &env->ldt);
5479 cpu_get_seg(f, &env->tr);
5480 cpu_get_seg(f, &env->gdt);
5481 cpu_get_seg(f, &env->idt);
5483 qemu_get_be32s(f, &env->sysenter_cs);
5484 qemu_get_be32s(f, &env->sysenter_esp);
5485 qemu_get_be32s(f, &env->sysenter_eip);
5487 qemu_get_betls(f, &env->cr[0]);
5488 qemu_get_betls(f, &env->cr[2]);
5489 qemu_get_betls(f, &env->cr[3]);
5490 qemu_get_betls(f, &env->cr[4]);
5492 for(i = 0; i < 8; i++)
5493 qemu_get_betls(f, &env->dr[i]);
5495 /* MMU */
5496 qemu_get_be32s(f, &env->a20_mask);
5498 qemu_get_be32s(f, &env->mxcsr);
5499 for(i = 0; i < CPU_NB_REGS; i++) {
5500 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5501 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5504 #ifdef TARGET_X86_64
5505 qemu_get_be64s(f, &env->efer);
5506 qemu_get_be64s(f, &env->star);
5507 qemu_get_be64s(f, &env->lstar);
5508 qemu_get_be64s(f, &env->cstar);
5509 qemu_get_be64s(f, &env->fmask);
5510 qemu_get_be64s(f, &env->kernelgsbase);
5511 #endif
5512 if (version_id >= 4)
5513 qemu_get_be32s(f, &env->smbase);
5515 /* XXX: compute hflags from scratch, except for CPL and IIF */
5516 env->hflags = hflags;
5517 tlb_flush(env, 1);
5518 return 0;
5521 #elif defined(TARGET_PPC)
5522 void cpu_save(QEMUFile *f, void *opaque)
5526 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5528 return 0;
5531 #elif defined(TARGET_MIPS)
5532 void cpu_save(QEMUFile *f, void *opaque)
5536 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5538 return 0;
5541 #elif defined(TARGET_SPARC)
5542 void cpu_save(QEMUFile *f, void *opaque)
5544 CPUState *env = opaque;
5545 int i;
5546 uint32_t tmp;
5548 for(i = 0; i < 8; i++)
5549 qemu_put_betls(f, &env->gregs[i]);
5550 for(i = 0; i < NWINDOWS * 16; i++)
5551 qemu_put_betls(f, &env->regbase[i]);
5553 /* FPU */
5554 for(i = 0; i < TARGET_FPREGS; i++) {
5555 union {
5556 float32 f;
5557 uint32_t i;
5558 } u;
5559 u.f = env->fpr[i];
5560 qemu_put_be32(f, u.i);
5563 qemu_put_betls(f, &env->pc);
5564 qemu_put_betls(f, &env->npc);
5565 qemu_put_betls(f, &env->y);
5566 tmp = GET_PSR(env);
5567 qemu_put_be32(f, tmp);
5568 qemu_put_betls(f, &env->fsr);
5569 qemu_put_betls(f, &env->tbr);
5570 #ifndef TARGET_SPARC64
5571 qemu_put_be32s(f, &env->wim);
5572 /* MMU */
5573 for(i = 0; i < 16; i++)
5574 qemu_put_be32s(f, &env->mmuregs[i]);
5575 #endif
5578 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5580 CPUState *env = opaque;
5581 int i;
5582 uint32_t tmp;
5584 for(i = 0; i < 8; i++)
5585 qemu_get_betls(f, &env->gregs[i]);
5586 for(i = 0; i < NWINDOWS * 16; i++)
5587 qemu_get_betls(f, &env->regbase[i]);
5589 /* FPU */
5590 for(i = 0; i < TARGET_FPREGS; i++) {
5591 union {
5592 float32 f;
5593 uint32_t i;
5594 } u;
5595 u.i = qemu_get_be32(f);
5596 env->fpr[i] = u.f;
5599 qemu_get_betls(f, &env->pc);
5600 qemu_get_betls(f, &env->npc);
5601 qemu_get_betls(f, &env->y);
5602 tmp = qemu_get_be32(f);
5603 env->cwp = 0; /* needed to ensure that the wrapping registers are
5604 correctly updated */
5605 PUT_PSR(env, tmp);
5606 qemu_get_betls(f, &env->fsr);
5607 qemu_get_betls(f, &env->tbr);
5608 #ifndef TARGET_SPARC64
5609 qemu_get_be32s(f, &env->wim);
5610 /* MMU */
5611 for(i = 0; i < 16; i++)
5612 qemu_get_be32s(f, &env->mmuregs[i]);
5613 #endif
5614 tlb_flush(env, 1);
5615 return 0;
5618 #elif defined(TARGET_ARM)
5620 /* ??? Need to implement these. */
5621 void cpu_save(QEMUFile *f, void *opaque)
5625 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5627 return 0;
5630 #else
5632 #warning No CPU save/restore functions
5634 #endif
5636 /***********************************************************/
5637 /* ram save/restore */
5639 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5641 int v;
5643 v = qemu_get_byte(f);
5644 switch(v) {
5645 case 0:
5646 if (qemu_get_buffer(f, buf, len) != len)
5647 return -EIO;
5648 break;
5649 case 1:
5650 v = qemu_get_byte(f);
5651 memset(buf, v, len);
5652 break;
5653 default:
5654 return -EINVAL;
5656 return 0;
5659 static int ram_load_v1(QEMUFile *f, void *opaque)
5661 int i, ret;
5663 if (qemu_get_be32(f) != phys_ram_size)
5664 return -EINVAL;
5665 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5666 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5667 if (ret)
5668 return ret;
5670 return 0;
5673 #define BDRV_HASH_BLOCK_SIZE 1024
5674 #define IOBUF_SIZE 4096
5675 #define RAM_CBLOCK_MAGIC 0xfabe
5677 typedef struct RamCompressState {
5678 z_stream zstream;
5679 QEMUFile *f;
5680 uint8_t buf[IOBUF_SIZE];
5681 } RamCompressState;
5683 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5685 int ret;
5686 memset(s, 0, sizeof(*s));
5687 s->f = f;
5688 ret = deflateInit2(&s->zstream, 1,
5689 Z_DEFLATED, 15,
5690 9, Z_DEFAULT_STRATEGY);
5691 if (ret != Z_OK)
5692 return -1;
5693 s->zstream.avail_out = IOBUF_SIZE;
5694 s->zstream.next_out = s->buf;
5695 return 0;
5698 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5700 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5701 qemu_put_be16(s->f, len);
5702 qemu_put_buffer(s->f, buf, len);
5705 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5707 int ret;
5709 s->zstream.avail_in = len;
5710 s->zstream.next_in = (uint8_t *)buf;
5711 while (s->zstream.avail_in > 0) {
5712 ret = deflate(&s->zstream, Z_NO_FLUSH);
5713 if (ret != Z_OK)
5714 return -1;
5715 if (s->zstream.avail_out == 0) {
5716 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5717 s->zstream.avail_out = IOBUF_SIZE;
5718 s->zstream.next_out = s->buf;
5721 return 0;
5724 static void ram_compress_close(RamCompressState *s)
5726 int len, ret;
5728 /* compress last bytes */
5729 for(;;) {
5730 ret = deflate(&s->zstream, Z_FINISH);
5731 if (ret == Z_OK || ret == Z_STREAM_END) {
5732 len = IOBUF_SIZE - s->zstream.avail_out;
5733 if (len > 0) {
5734 ram_put_cblock(s, s->buf, len);
5736 s->zstream.avail_out = IOBUF_SIZE;
5737 s->zstream.next_out = s->buf;
5738 if (ret == Z_STREAM_END)
5739 break;
5740 } else {
5741 goto fail;
5744 fail:
5745 deflateEnd(&s->zstream);
5748 typedef struct RamDecompressState {
5749 z_stream zstream;
5750 QEMUFile *f;
5751 uint8_t buf[IOBUF_SIZE];
5752 } RamDecompressState;
5754 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5756 int ret;
5757 memset(s, 0, sizeof(*s));
5758 s->f = f;
5759 ret = inflateInit(&s->zstream);
5760 if (ret != Z_OK)
5761 return -1;
5762 return 0;
5765 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5767 int ret, clen;
5769 s->zstream.avail_out = len;
5770 s->zstream.next_out = buf;
5771 while (s->zstream.avail_out > 0) {
5772 if (s->zstream.avail_in == 0) {
5773 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5774 return -1;
5775 clen = qemu_get_be16(s->f);
5776 if (clen > IOBUF_SIZE)
5777 return -1;
5778 qemu_get_buffer(s->f, s->buf, clen);
5779 s->zstream.avail_in = clen;
5780 s->zstream.next_in = s->buf;
5782 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5783 if (ret != Z_OK && ret != Z_STREAM_END) {
5784 return -1;
5787 return 0;
5790 static void ram_decompress_close(RamDecompressState *s)
5792 inflateEnd(&s->zstream);
5795 static void ram_save(QEMUFile *f, void *opaque)
5797 int i;
5798 RamCompressState s1, *s = &s1;
5799 uint8_t buf[10];
5801 qemu_put_be32(f, phys_ram_size);
5802 if (ram_compress_open(s, f) < 0)
5803 return;
5804 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5805 #if 0
5806 if (tight_savevm_enabled) {
5807 int64_t sector_num;
5808 int j;
5810 /* find if the memory block is available on a virtual
5811 block device */
5812 sector_num = -1;
5813 for(j = 0; j < MAX_DISKS; j++) {
5814 if (bs_table[j]) {
5815 sector_num = bdrv_hash_find(bs_table[j],
5816 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5817 if (sector_num >= 0)
5818 break;
5821 if (j == MAX_DISKS)
5822 goto normal_compress;
5823 buf[0] = 1;
5824 buf[1] = j;
5825 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5826 ram_compress_buf(s, buf, 10);
5827 } else
5828 #endif
5830 // normal_compress:
5831 buf[0] = 0;
5832 ram_compress_buf(s, buf, 1);
5833 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5836 ram_compress_close(s);
5839 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5841 RamDecompressState s1, *s = &s1;
5842 uint8_t buf[10];
5843 int i;
5845 if (version_id == 1)
5846 return ram_load_v1(f, opaque);
5847 if (version_id != 2)
5848 return -EINVAL;
5849 if (qemu_get_be32(f) != phys_ram_size)
5850 return -EINVAL;
5851 if (ram_decompress_open(s, f) < 0)
5852 return -EINVAL;
5853 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5854 if (ram_decompress_buf(s, buf, 1) < 0) {
5855 fprintf(stderr, "Error while reading ram block header\n");
5856 goto error;
5858 if (buf[0] == 0) {
5859 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5860 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5861 goto error;
5863 } else
5864 #if 0
5865 if (buf[0] == 1) {
5866 int bs_index;
5867 int64_t sector_num;
5869 ram_decompress_buf(s, buf + 1, 9);
5870 bs_index = buf[1];
5871 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5872 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5873 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5874 goto error;
5876 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5877 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5878 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5879 bs_index, sector_num);
5880 goto error;
5882 } else
5883 #endif
5885 error:
5886 printf("Error block header\n");
5887 return -EINVAL;
5890 ram_decompress_close(s);
5891 return 0;
5894 /***********************************************************/
5895 /* bottom halves (can be seen as timers which expire ASAP) */
5897 struct QEMUBH {
5898 QEMUBHFunc *cb;
5899 void *opaque;
5900 int scheduled;
5901 QEMUBH *next;
5904 static QEMUBH *first_bh = NULL;
5906 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5908 QEMUBH *bh;
5909 bh = qemu_mallocz(sizeof(QEMUBH));
5910 if (!bh)
5911 return NULL;
5912 bh->cb = cb;
5913 bh->opaque = opaque;
5914 return bh;
5917 int qemu_bh_poll(void)
5919 QEMUBH *bh, **pbh;
5920 int ret;
5922 ret = 0;
5923 for(;;) {
5924 pbh = &first_bh;
5925 bh = *pbh;
5926 if (!bh)
5927 break;
5928 ret = 1;
5929 *pbh = bh->next;
5930 bh->scheduled = 0;
5931 bh->cb(bh->opaque);
5933 return ret;
5936 void qemu_bh_schedule(QEMUBH *bh)
5938 CPUState *env = cpu_single_env;
5939 if (bh->scheduled)
5940 return;
5941 bh->scheduled = 1;
5942 bh->next = first_bh;
5943 first_bh = bh;
5945 /* stop the currently executing CPU to execute the BH ASAP */
5946 if (env) {
5947 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5951 void qemu_bh_cancel(QEMUBH *bh)
5953 QEMUBH **pbh;
5954 if (bh->scheduled) {
5955 pbh = &first_bh;
5956 while (*pbh != bh)
5957 pbh = &(*pbh)->next;
5958 *pbh = bh->next;
5959 bh->scheduled = 0;
5963 void qemu_bh_delete(QEMUBH *bh)
5965 qemu_bh_cancel(bh);
5966 qemu_free(bh);
5969 /***********************************************************/
5970 /* machine registration */
5972 QEMUMachine *first_machine = NULL;
5974 int qemu_register_machine(QEMUMachine *m)
5976 QEMUMachine **pm;
5977 pm = &first_machine;
5978 while (*pm != NULL)
5979 pm = &(*pm)->next;
5980 m->next = NULL;
5981 *pm = m;
5982 return 0;
5985 QEMUMachine *find_machine(const char *name)
5987 QEMUMachine *m;
5989 for(m = first_machine; m != NULL; m = m->next) {
5990 if (!strcmp(m->name, name))
5991 return m;
5993 return NULL;
5996 /***********************************************************/
5997 /* main execution loop */
5999 void gui_update(void *opaque)
6001 display_state.dpy_refresh(&display_state);
6002 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6005 struct vm_change_state_entry {
6006 VMChangeStateHandler *cb;
6007 void *opaque;
6008 LIST_ENTRY (vm_change_state_entry) entries;
6011 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6013 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6014 void *opaque)
6016 VMChangeStateEntry *e;
6018 e = qemu_mallocz(sizeof (*e));
6019 if (!e)
6020 return NULL;
6022 e->cb = cb;
6023 e->opaque = opaque;
6024 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6025 return e;
6028 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6030 LIST_REMOVE (e, entries);
6031 qemu_free (e);
6034 static void vm_state_notify(int running)
6036 VMChangeStateEntry *e;
6038 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6039 e->cb(e->opaque, running);
6043 /* XXX: support several handlers */
6044 static VMStopHandler *vm_stop_cb;
6045 static void *vm_stop_opaque;
6047 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6049 vm_stop_cb = cb;
6050 vm_stop_opaque = opaque;
6051 return 0;
6054 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6056 vm_stop_cb = NULL;
6059 void vm_start(void)
6061 if (!vm_running) {
6062 cpu_enable_ticks();
6063 vm_running = 1;
6064 vm_state_notify(1);
6068 void vm_stop(int reason)
6070 if (vm_running) {
6071 cpu_disable_ticks();
6072 vm_running = 0;
6073 if (reason != 0) {
6074 if (vm_stop_cb) {
6075 vm_stop_cb(vm_stop_opaque, reason);
6078 vm_state_notify(0);
6082 /* reset/shutdown handler */
6084 typedef struct QEMUResetEntry {
6085 QEMUResetHandler *func;
6086 void *opaque;
6087 struct QEMUResetEntry *next;
6088 } QEMUResetEntry;
6090 static QEMUResetEntry *first_reset_entry;
6091 static int reset_requested;
6092 static int shutdown_requested;
6093 static int powerdown_requested;
6095 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6097 QEMUResetEntry **pre, *re;
6099 pre = &first_reset_entry;
6100 while (*pre != NULL)
6101 pre = &(*pre)->next;
6102 re = qemu_mallocz(sizeof(QEMUResetEntry));
6103 re->func = func;
6104 re->opaque = opaque;
6105 re->next = NULL;
6106 *pre = re;
6109 static void qemu_system_reset(void)
6111 QEMUResetEntry *re;
6113 /* reset all devices */
6114 for(re = first_reset_entry; re != NULL; re = re->next) {
6115 re->func(re->opaque);
6119 void qemu_system_reset_request(void)
6121 if (no_reboot) {
6122 shutdown_requested = 1;
6123 } else {
6124 reset_requested = 1;
6126 if (cpu_single_env)
6127 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6130 void qemu_system_shutdown_request(void)
6132 shutdown_requested = 1;
6133 if (cpu_single_env)
6134 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6137 void qemu_system_powerdown_request(void)
6139 powerdown_requested = 1;
6140 if (cpu_single_env)
6141 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6144 void main_loop_wait(int timeout)
6146 IOHandlerRecord *ioh;
6147 fd_set rfds, wfds, xfds;
6148 int ret, nfds;
6149 #ifdef _WIN32
6150 int ret2, i;
6151 #endif
6152 struct timeval tv;
6153 PollingEntry *pe;
6156 /* XXX: need to suppress polling by better using win32 events */
6157 ret = 0;
6158 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6159 ret |= pe->func(pe->opaque);
6161 #ifdef _WIN32
6162 if (ret == 0) {
6163 int err;
6164 WaitObjects *w = &wait_objects;
6166 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6167 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6168 if (w->func[ret - WAIT_OBJECT_0])
6169 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6171 /* Check for additional signaled events */
6172 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6174 /* Check if event is signaled */
6175 ret2 = WaitForSingleObject(w->events[i], 0);
6176 if(ret2 == WAIT_OBJECT_0) {
6177 if (w->func[i])
6178 w->func[i](w->opaque[i]);
6179 } else if (ret2 == WAIT_TIMEOUT) {
6180 } else {
6181 err = GetLastError();
6182 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6185 } else if (ret == WAIT_TIMEOUT) {
6186 } else {
6187 err = GetLastError();
6188 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6191 #endif
6192 /* poll any events */
6193 /* XXX: separate device handlers from system ones */
6194 nfds = -1;
6195 FD_ZERO(&rfds);
6196 FD_ZERO(&wfds);
6197 FD_ZERO(&xfds);
6198 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6199 if (ioh->deleted)
6200 continue;
6201 if (ioh->fd_read &&
6202 (!ioh->fd_read_poll ||
6203 ioh->fd_read_poll(ioh->opaque) != 0)) {
6204 FD_SET(ioh->fd, &rfds);
6205 if (ioh->fd > nfds)
6206 nfds = ioh->fd;
6208 if (ioh->fd_write) {
6209 FD_SET(ioh->fd, &wfds);
6210 if (ioh->fd > nfds)
6211 nfds = ioh->fd;
6215 tv.tv_sec = 0;
6216 #ifdef _WIN32
6217 tv.tv_usec = 0;
6218 #else
6219 tv.tv_usec = timeout * 1000;
6220 #endif
6221 #if defined(CONFIG_SLIRP)
6222 if (slirp_inited) {
6223 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6225 #endif
6226 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6227 if (ret > 0) {
6228 IOHandlerRecord **pioh;
6230 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6231 if (ioh->deleted)
6232 continue;
6233 if (FD_ISSET(ioh->fd, &rfds)) {
6234 ioh->fd_read(ioh->opaque);
6236 if (FD_ISSET(ioh->fd, &wfds)) {
6237 ioh->fd_write(ioh->opaque);
6241 /* remove deleted IO handlers */
6242 pioh = &first_io_handler;
6243 while (*pioh) {
6244 ioh = *pioh;
6245 if (ioh->deleted) {
6246 *pioh = ioh->next;
6247 qemu_free(ioh);
6248 } else
6249 pioh = &ioh->next;
6252 #if defined(CONFIG_SLIRP)
6253 if (slirp_inited) {
6254 if (ret < 0) {
6255 FD_ZERO(&rfds);
6256 FD_ZERO(&wfds);
6257 FD_ZERO(&xfds);
6259 slirp_select_poll(&rfds, &wfds, &xfds);
6261 #endif
6262 qemu_aio_poll();
6263 qemu_bh_poll();
6265 if (vm_running) {
6266 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6267 qemu_get_clock(vm_clock));
6268 /* run dma transfers, if any */
6269 DMA_run();
6272 /* real time timers */
6273 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6274 qemu_get_clock(rt_clock));
6277 static CPUState *cur_cpu;
6279 int main_loop(void)
6281 int ret, timeout;
6282 #ifdef CONFIG_PROFILER
6283 int64_t ti;
6284 #endif
6285 CPUState *env;
6287 cur_cpu = first_cpu;
6288 for(;;) {
6289 if (vm_running) {
6291 env = cur_cpu;
6292 for(;;) {
6293 /* get next cpu */
6294 env = env->next_cpu;
6295 if (!env)
6296 env = first_cpu;
6297 #ifdef CONFIG_PROFILER
6298 ti = profile_getclock();
6299 #endif
6300 ret = cpu_exec(env);
6301 #ifdef CONFIG_PROFILER
6302 qemu_time += profile_getclock() - ti;
6303 #endif
6304 if (ret == EXCP_HLT) {
6305 /* Give the next CPU a chance to run. */
6306 cur_cpu = env;
6307 continue;
6309 if (ret != EXCP_HALTED)
6310 break;
6311 /* all CPUs are halted ? */
6312 if (env == cur_cpu)
6313 break;
6315 cur_cpu = env;
6317 if (shutdown_requested) {
6318 ret = EXCP_INTERRUPT;
6319 break;
6321 if (reset_requested) {
6322 reset_requested = 0;
6323 qemu_system_reset();
6324 ret = EXCP_INTERRUPT;
6326 if (powerdown_requested) {
6327 powerdown_requested = 0;
6328 qemu_system_powerdown();
6329 ret = EXCP_INTERRUPT;
6331 if (ret == EXCP_DEBUG) {
6332 vm_stop(EXCP_DEBUG);
6334 /* If all cpus are halted then wait until the next IRQ */
6335 /* XXX: use timeout computed from timers */
6336 if (ret == EXCP_HALTED)
6337 timeout = 10;
6338 else
6339 timeout = 0;
6340 } else {
6341 timeout = 10;
6343 #ifdef CONFIG_PROFILER
6344 ti = profile_getclock();
6345 #endif
6346 main_loop_wait(timeout);
6347 #ifdef CONFIG_PROFILER
6348 dev_time += profile_getclock() - ti;
6349 #endif
6351 cpu_disable_ticks();
6352 return ret;
6355 void help(void)
6357 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6358 "usage: %s [options] [disk_image]\n"
6359 "\n"
6360 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6361 "\n"
6362 "Standard options:\n"
6363 "-M machine select emulated machine (-M ? for list)\n"
6364 "-cpu cpu select CPU (-cpu ? for list)\n"
6365 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6366 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6367 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6368 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6369 "-sd file use 'file' as SecureDigital card image\n"
6370 "-pflash file use 'file' as a parallel flash image\n"
6371 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6372 "-snapshot write to temporary files instead of disk image files\n"
6373 #ifdef CONFIG_SDL
6374 "-no-frame open SDL window without a frame and window decorations\n"
6375 "-no-quit disable SDL window close capability\n"
6376 #endif
6377 #ifdef TARGET_I386
6378 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6379 #endif
6380 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6381 "-smp n set the number of CPUs to 'n' [default=1]\n"
6382 "-nographic disable graphical output and redirect serial I/Os to console\n"
6383 #ifndef _WIN32
6384 "-k language use keyboard layout (for example \"fr\" for French)\n"
6385 #endif
6386 #ifdef HAS_AUDIO
6387 "-audio-help print list of audio drivers and their options\n"
6388 "-soundhw c1,... enable audio support\n"
6389 " and only specified sound cards (comma separated list)\n"
6390 " use -soundhw ? to get the list of supported cards\n"
6391 " use -soundhw all to enable all of them\n"
6392 #endif
6393 "-localtime set the real time clock to local time [default=utc]\n"
6394 "-full-screen start in full screen\n"
6395 #ifdef TARGET_I386
6396 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6397 #endif
6398 "-usb enable the USB driver (will be the default soon)\n"
6399 "-usbdevice name add the host or guest USB device 'name'\n"
6400 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6401 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6402 #endif
6403 "-name string set the name of the guest\n"
6404 "\n"
6405 "Network options:\n"
6406 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6407 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6408 #ifdef CONFIG_SLIRP
6409 "-net user[,vlan=n][,hostname=host]\n"
6410 " connect the user mode network stack to VLAN 'n' and send\n"
6411 " hostname 'host' to DHCP clients\n"
6412 #endif
6413 #ifdef _WIN32
6414 "-net tap[,vlan=n],ifname=name\n"
6415 " connect the host TAP network interface to VLAN 'n'\n"
6416 #else
6417 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6418 " connect the host TAP network interface to VLAN 'n' and use\n"
6419 " the network script 'file' (default=%s);\n"
6420 " use 'script=no' to disable script execution;\n"
6421 " use 'fd=h' to connect to an already opened TAP interface\n"
6422 #endif
6423 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6424 " connect the vlan 'n' to another VLAN using a socket connection\n"
6425 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6426 " connect the vlan 'n' to multicast maddr and port\n"
6427 "-net none use it alone to have zero network devices; if no -net option\n"
6428 " is provided, the default is '-net nic -net user'\n"
6429 "\n"
6430 #ifdef CONFIG_SLIRP
6431 "-tftp dir allow tftp access to files in dir [-net user]\n"
6432 "-bootp file advertise file in BOOTP replies\n"
6433 #ifndef _WIN32
6434 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6435 #endif
6436 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6437 " redirect TCP or UDP connections from host to guest [-net user]\n"
6438 #endif
6439 "\n"
6440 "Linux boot specific:\n"
6441 "-kernel bzImage use 'bzImage' as kernel image\n"
6442 "-append cmdline use 'cmdline' as kernel command line\n"
6443 "-initrd file use 'file' as initial ram disk\n"
6444 "\n"
6445 "Debug/Expert options:\n"
6446 "-monitor dev redirect the monitor to char device 'dev'\n"
6447 "-serial dev redirect the serial port to char device 'dev'\n"
6448 "-parallel dev redirect the parallel port to char device 'dev'\n"
6449 "-pidfile file Write PID to 'file'\n"
6450 "-S freeze CPU at startup (use 'c' to start execution)\n"
6451 "-s wait gdb connection to port\n"
6452 "-p port set gdb connection port [default=%s]\n"
6453 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6454 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6455 " translation (t=none or lba) (usually qemu can guess them)\n"
6456 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6457 #ifdef USE_KQEMU
6458 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6459 "-no-kqemu disable KQEMU kernel module usage\n"
6460 #endif
6461 #ifdef USE_CODE_COPY
6462 "-no-code-copy disable code copy acceleration\n"
6463 #endif
6464 #ifdef TARGET_I386
6465 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6466 " (default is CL-GD5446 PCI VGA)\n"
6467 "-no-acpi disable ACPI\n"
6468 #endif
6469 "-no-reboot exit instead of rebooting\n"
6470 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6471 "-vnc display start a VNC server on display\n"
6472 #ifndef _WIN32
6473 "-daemonize daemonize QEMU after initializing\n"
6474 #endif
6475 "-option-rom rom load a file, rom, into the option ROM space\n"
6476 "\n"
6477 "During emulation, the following keys are useful:\n"
6478 "ctrl-alt-f toggle full screen\n"
6479 "ctrl-alt-n switch to virtual console 'n'\n"
6480 "ctrl-alt toggle mouse and keyboard grab\n"
6481 "\n"
6482 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6484 "qemu",
6485 DEFAULT_RAM_SIZE,
6486 #ifndef _WIN32
6487 DEFAULT_NETWORK_SCRIPT,
6488 #endif
6489 DEFAULT_GDBSTUB_PORT,
6490 "/tmp/qemu.log");
6491 exit(1);
6494 #define HAS_ARG 0x0001
6496 enum {
6497 QEMU_OPTION_h,
6499 QEMU_OPTION_M,
6500 QEMU_OPTION_cpu,
6501 QEMU_OPTION_fda,
6502 QEMU_OPTION_fdb,
6503 QEMU_OPTION_hda,
6504 QEMU_OPTION_hdb,
6505 QEMU_OPTION_hdc,
6506 QEMU_OPTION_hdd,
6507 QEMU_OPTION_cdrom,
6508 QEMU_OPTION_sd,
6509 QEMU_OPTION_pflash,
6510 QEMU_OPTION_boot,
6511 QEMU_OPTION_snapshot,
6512 #ifdef TARGET_I386
6513 QEMU_OPTION_no_fd_bootchk,
6514 #endif
6515 QEMU_OPTION_m,
6516 QEMU_OPTION_nographic,
6517 #ifdef HAS_AUDIO
6518 QEMU_OPTION_audio_help,
6519 QEMU_OPTION_soundhw,
6520 #endif
6522 QEMU_OPTION_net,
6523 QEMU_OPTION_tftp,
6524 QEMU_OPTION_bootp,
6525 QEMU_OPTION_smb,
6526 QEMU_OPTION_redir,
6528 QEMU_OPTION_kernel,
6529 QEMU_OPTION_append,
6530 QEMU_OPTION_initrd,
6532 QEMU_OPTION_S,
6533 QEMU_OPTION_s,
6534 QEMU_OPTION_p,
6535 QEMU_OPTION_d,
6536 QEMU_OPTION_hdachs,
6537 QEMU_OPTION_L,
6538 QEMU_OPTION_no_code_copy,
6539 QEMU_OPTION_k,
6540 QEMU_OPTION_localtime,
6541 QEMU_OPTION_cirrusvga,
6542 QEMU_OPTION_vmsvga,
6543 QEMU_OPTION_g,
6544 QEMU_OPTION_std_vga,
6545 QEMU_OPTION_echr,
6546 QEMU_OPTION_monitor,
6547 QEMU_OPTION_serial,
6548 QEMU_OPTION_parallel,
6549 QEMU_OPTION_loadvm,
6550 QEMU_OPTION_full_screen,
6551 QEMU_OPTION_no_frame,
6552 QEMU_OPTION_no_quit,
6553 QEMU_OPTION_pidfile,
6554 QEMU_OPTION_no_kqemu,
6555 QEMU_OPTION_kernel_kqemu,
6556 QEMU_OPTION_win2k_hack,
6557 QEMU_OPTION_usb,
6558 QEMU_OPTION_usbdevice,
6559 QEMU_OPTION_smp,
6560 QEMU_OPTION_vnc,
6561 QEMU_OPTION_no_acpi,
6562 QEMU_OPTION_no_reboot,
6563 QEMU_OPTION_daemonize,
6564 QEMU_OPTION_option_rom,
6565 QEMU_OPTION_semihosting,
6566 QEMU_OPTION_name,
6569 typedef struct QEMUOption {
6570 const char *name;
6571 int flags;
6572 int index;
6573 } QEMUOption;
6575 const QEMUOption qemu_options[] = {
6576 { "h", 0, QEMU_OPTION_h },
6577 { "help", 0, QEMU_OPTION_h },
6579 { "M", HAS_ARG, QEMU_OPTION_M },
6580 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6581 { "fda", HAS_ARG, QEMU_OPTION_fda },
6582 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6583 { "hda", HAS_ARG, QEMU_OPTION_hda },
6584 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6585 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6586 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6587 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6588 { "sd", HAS_ARG, QEMU_OPTION_sd },
6589 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6590 { "boot", HAS_ARG, QEMU_OPTION_boot },
6591 { "snapshot", 0, QEMU_OPTION_snapshot },
6592 #ifdef TARGET_I386
6593 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6594 #endif
6595 { "m", HAS_ARG, QEMU_OPTION_m },
6596 { "nographic", 0, QEMU_OPTION_nographic },
6597 { "k", HAS_ARG, QEMU_OPTION_k },
6598 #ifdef HAS_AUDIO
6599 { "audio-help", 0, QEMU_OPTION_audio_help },
6600 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6601 #endif
6603 { "net", HAS_ARG, QEMU_OPTION_net},
6604 #ifdef CONFIG_SLIRP
6605 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6606 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6607 #ifndef _WIN32
6608 { "smb", HAS_ARG, QEMU_OPTION_smb },
6609 #endif
6610 { "redir", HAS_ARG, QEMU_OPTION_redir },
6611 #endif
6613 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6614 { "append", HAS_ARG, QEMU_OPTION_append },
6615 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6617 { "S", 0, QEMU_OPTION_S },
6618 { "s", 0, QEMU_OPTION_s },
6619 { "p", HAS_ARG, QEMU_OPTION_p },
6620 { "d", HAS_ARG, QEMU_OPTION_d },
6621 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6622 { "L", HAS_ARG, QEMU_OPTION_L },
6623 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6624 #ifdef USE_KQEMU
6625 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6626 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6627 #endif
6628 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6629 { "g", 1, QEMU_OPTION_g },
6630 #endif
6631 { "localtime", 0, QEMU_OPTION_localtime },
6632 { "std-vga", 0, QEMU_OPTION_std_vga },
6633 { "echr", 1, QEMU_OPTION_echr },
6634 { "monitor", 1, QEMU_OPTION_monitor },
6635 { "serial", 1, QEMU_OPTION_serial },
6636 { "parallel", 1, QEMU_OPTION_parallel },
6637 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6638 { "full-screen", 0, QEMU_OPTION_full_screen },
6639 #ifdef CONFIG_SDL
6640 { "no-frame", 0, QEMU_OPTION_no_frame },
6641 { "no-quit", 0, QEMU_OPTION_no_quit },
6642 #endif
6643 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6644 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6645 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6646 { "smp", HAS_ARG, QEMU_OPTION_smp },
6647 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6649 /* temporary options */
6650 { "usb", 0, QEMU_OPTION_usb },
6651 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6652 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6653 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6654 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6655 { "daemonize", 0, QEMU_OPTION_daemonize },
6656 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6657 #if defined(TARGET_ARM)
6658 { "semihosting", 0, QEMU_OPTION_semihosting },
6659 #endif
6660 { "name", HAS_ARG, QEMU_OPTION_name },
6661 { NULL },
6664 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6666 /* this stack is only used during signal handling */
6667 #define SIGNAL_STACK_SIZE 32768
6669 static uint8_t *signal_stack;
6671 #endif
6673 /* password input */
6675 static BlockDriverState *get_bdrv(int index)
6677 BlockDriverState *bs;
6679 if (index < 4) {
6680 bs = bs_table[index];
6681 } else if (index < 6) {
6682 bs = fd_table[index - 4];
6683 } else {
6684 bs = NULL;
6686 return bs;
6689 static void read_passwords(void)
6691 BlockDriverState *bs;
6692 int i, j;
6693 char password[256];
6695 for(i = 0; i < 6; i++) {
6696 bs = get_bdrv(i);
6697 if (bs && bdrv_is_encrypted(bs)) {
6698 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6699 for(j = 0; j < 3; j++) {
6700 monitor_readline("Password: ",
6701 1, password, sizeof(password));
6702 if (bdrv_set_key(bs, password) == 0)
6703 break;
6704 term_printf("invalid password\n");
6710 /* XXX: currently we cannot use simultaneously different CPUs */
6711 void register_machines(void)
6713 #if defined(TARGET_I386)
6714 qemu_register_machine(&pc_machine);
6715 qemu_register_machine(&isapc_machine);
6716 #elif defined(TARGET_PPC)
6717 qemu_register_machine(&heathrow_machine);
6718 qemu_register_machine(&core99_machine);
6719 qemu_register_machine(&prep_machine);
6720 qemu_register_machine(&ref405ep_machine);
6721 qemu_register_machine(&taihu_machine);
6722 #elif defined(TARGET_MIPS)
6723 qemu_register_machine(&mips_machine);
6724 qemu_register_machine(&mips_malta_machine);
6725 qemu_register_machine(&mips_pica61_machine);
6726 #elif defined(TARGET_SPARC)
6727 #ifdef TARGET_SPARC64
6728 qemu_register_machine(&sun4u_machine);
6729 #else
6730 qemu_register_machine(&ss5_machine);
6731 qemu_register_machine(&ss10_machine);
6732 #endif
6733 #elif defined(TARGET_ARM)
6734 qemu_register_machine(&integratorcp_machine);
6735 qemu_register_machine(&versatilepb_machine);
6736 qemu_register_machine(&versatileab_machine);
6737 qemu_register_machine(&realview_machine);
6738 #elif defined(TARGET_SH4)
6739 qemu_register_machine(&shix_machine);
6740 #elif defined(TARGET_ALPHA)
6741 /* XXX: TODO */
6742 #else
6743 #error unsupported CPU
6744 #endif
6747 #ifdef HAS_AUDIO
6748 struct soundhw soundhw[] = {
6749 #ifdef TARGET_I386
6751 "pcspk",
6752 "PC speaker",
6755 { .init_isa = pcspk_audio_init }
6757 #endif
6759 "sb16",
6760 "Creative Sound Blaster 16",
6763 { .init_isa = SB16_init }
6766 #ifdef CONFIG_ADLIB
6768 "adlib",
6769 #ifdef HAS_YMF262
6770 "Yamaha YMF262 (OPL3)",
6771 #else
6772 "Yamaha YM3812 (OPL2)",
6773 #endif
6776 { .init_isa = Adlib_init }
6778 #endif
6780 #ifdef CONFIG_GUS
6782 "gus",
6783 "Gravis Ultrasound GF1",
6786 { .init_isa = GUS_init }
6788 #endif
6791 "es1370",
6792 "ENSONIQ AudioPCI ES1370",
6795 { .init_pci = es1370_init }
6798 { NULL, NULL, 0, 0, { NULL } }
6801 static void select_soundhw (const char *optarg)
6803 struct soundhw *c;
6805 if (*optarg == '?') {
6806 show_valid_cards:
6808 printf ("Valid sound card names (comma separated):\n");
6809 for (c = soundhw; c->name; ++c) {
6810 printf ("%-11s %s\n", c->name, c->descr);
6812 printf ("\n-soundhw all will enable all of the above\n");
6813 exit (*optarg != '?');
6815 else {
6816 size_t l;
6817 const char *p;
6818 char *e;
6819 int bad_card = 0;
6821 if (!strcmp (optarg, "all")) {
6822 for (c = soundhw; c->name; ++c) {
6823 c->enabled = 1;
6825 return;
6828 p = optarg;
6829 while (*p) {
6830 e = strchr (p, ',');
6831 l = !e ? strlen (p) : (size_t) (e - p);
6833 for (c = soundhw; c->name; ++c) {
6834 if (!strncmp (c->name, p, l)) {
6835 c->enabled = 1;
6836 break;
6840 if (!c->name) {
6841 if (l > 80) {
6842 fprintf (stderr,
6843 "Unknown sound card name (too big to show)\n");
6845 else {
6846 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6847 (int) l, p);
6849 bad_card = 1;
6851 p += l + (e != NULL);
6854 if (bad_card)
6855 goto show_valid_cards;
6858 #endif
6860 #ifdef _WIN32
6861 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6863 exit(STATUS_CONTROL_C_EXIT);
6864 return TRUE;
6866 #endif
6868 #define MAX_NET_CLIENTS 32
6870 int main(int argc, char **argv)
6872 #ifdef CONFIG_GDBSTUB
6873 int use_gdbstub;
6874 const char *gdbstub_port;
6875 #endif
6876 int i, cdrom_index, pflash_index;
6877 int snapshot, linux_boot;
6878 const char *initrd_filename;
6879 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6880 const char *pflash_filename[MAX_PFLASH];
6881 const char *sd_filename;
6882 const char *kernel_filename, *kernel_cmdline;
6883 DisplayState *ds = &display_state;
6884 int cyls, heads, secs, translation;
6885 char net_clients[MAX_NET_CLIENTS][256];
6886 int nb_net_clients;
6887 int optind;
6888 const char *r, *optarg;
6889 CharDriverState *monitor_hd;
6890 char monitor_device[128];
6891 char serial_devices[MAX_SERIAL_PORTS][128];
6892 int serial_device_index;
6893 char parallel_devices[MAX_PARALLEL_PORTS][128];
6894 int parallel_device_index;
6895 const char *loadvm = NULL;
6896 QEMUMachine *machine;
6897 const char *cpu_model;
6898 char usb_devices[MAX_USB_CMDLINE][128];
6899 int usb_devices_index;
6900 int fds[2];
6901 const char *pid_file = NULL;
6903 LIST_INIT (&vm_change_state_head);
6904 #ifndef _WIN32
6906 struct sigaction act;
6907 sigfillset(&act.sa_mask);
6908 act.sa_flags = 0;
6909 act.sa_handler = SIG_IGN;
6910 sigaction(SIGPIPE, &act, NULL);
6912 #else
6913 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6914 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6915 QEMU to run on a single CPU */
6917 HANDLE h;
6918 DWORD mask, smask;
6919 int i;
6920 h = GetCurrentProcess();
6921 if (GetProcessAffinityMask(h, &mask, &smask)) {
6922 for(i = 0; i < 32; i++) {
6923 if (mask & (1 << i))
6924 break;
6926 if (i != 32) {
6927 mask = 1 << i;
6928 SetProcessAffinityMask(h, mask);
6932 #endif
6934 register_machines();
6935 machine = first_machine;
6936 cpu_model = NULL;
6937 initrd_filename = NULL;
6938 for(i = 0; i < MAX_FD; i++)
6939 fd_filename[i] = NULL;
6940 for(i = 0; i < MAX_DISKS; i++)
6941 hd_filename[i] = NULL;
6942 for(i = 0; i < MAX_PFLASH; i++)
6943 pflash_filename[i] = NULL;
6944 pflash_index = 0;
6945 sd_filename = NULL;
6946 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6947 vga_ram_size = VGA_RAM_SIZE;
6948 #ifdef CONFIG_GDBSTUB
6949 use_gdbstub = 0;
6950 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6951 #endif
6952 snapshot = 0;
6953 nographic = 0;
6954 kernel_filename = NULL;
6955 kernel_cmdline = "";
6956 #ifdef TARGET_PPC
6957 cdrom_index = 1;
6958 #else
6959 cdrom_index = 2;
6960 #endif
6961 cyls = heads = secs = 0;
6962 translation = BIOS_ATA_TRANSLATION_AUTO;
6963 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6965 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6966 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6967 serial_devices[i][0] = '\0';
6968 serial_device_index = 0;
6970 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6971 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6972 parallel_devices[i][0] = '\0';
6973 parallel_device_index = 0;
6975 usb_devices_index = 0;
6977 nb_net_clients = 0;
6979 nb_nics = 0;
6980 /* default mac address of the first network interface */
6982 optind = 1;
6983 for(;;) {
6984 if (optind >= argc)
6985 break;
6986 r = argv[optind];
6987 if (r[0] != '-') {
6988 hd_filename[0] = argv[optind++];
6989 } else {
6990 const QEMUOption *popt;
6992 optind++;
6993 /* Treat --foo the same as -foo. */
6994 if (r[1] == '-')
6995 r++;
6996 popt = qemu_options;
6997 for(;;) {
6998 if (!popt->name) {
6999 fprintf(stderr, "%s: invalid option -- '%s'\n",
7000 argv[0], r);
7001 exit(1);
7003 if (!strcmp(popt->name, r + 1))
7004 break;
7005 popt++;
7007 if (popt->flags & HAS_ARG) {
7008 if (optind >= argc) {
7009 fprintf(stderr, "%s: option '%s' requires an argument\n",
7010 argv[0], r);
7011 exit(1);
7013 optarg = argv[optind++];
7014 } else {
7015 optarg = NULL;
7018 switch(popt->index) {
7019 case QEMU_OPTION_M:
7020 machine = find_machine(optarg);
7021 if (!machine) {
7022 QEMUMachine *m;
7023 printf("Supported machines are:\n");
7024 for(m = first_machine; m != NULL; m = m->next) {
7025 printf("%-10s %s%s\n",
7026 m->name, m->desc,
7027 m == first_machine ? " (default)" : "");
7029 exit(1);
7031 break;
7032 case QEMU_OPTION_cpu:
7033 /* hw initialization will check this */
7034 if (optarg[0] == '?') {
7035 #if defined(TARGET_PPC)
7036 ppc_cpu_list(stdout, &fprintf);
7037 #elif defined(TARGET_ARM)
7038 arm_cpu_list();
7039 #elif defined(TARGET_MIPS)
7040 mips_cpu_list(stdout, &fprintf);
7041 #elif defined(TARGET_SPARC)
7042 sparc_cpu_list(stdout, &fprintf);
7043 #endif
7044 exit(1);
7045 } else {
7046 cpu_model = optarg;
7048 break;
7049 case QEMU_OPTION_initrd:
7050 initrd_filename = optarg;
7051 break;
7052 case QEMU_OPTION_hda:
7053 case QEMU_OPTION_hdb:
7054 case QEMU_OPTION_hdc:
7055 case QEMU_OPTION_hdd:
7057 int hd_index;
7058 hd_index = popt->index - QEMU_OPTION_hda;
7059 hd_filename[hd_index] = optarg;
7060 if (hd_index == cdrom_index)
7061 cdrom_index = -1;
7063 break;
7064 case QEMU_OPTION_sd:
7065 sd_filename = optarg;
7066 break;
7067 case QEMU_OPTION_pflash:
7068 if (pflash_index >= MAX_PFLASH) {
7069 fprintf(stderr, "qemu: too many parallel flash images\n");
7070 exit(1);
7072 pflash_filename[pflash_index++] = optarg;
7073 break;
7074 case QEMU_OPTION_snapshot:
7075 snapshot = 1;
7076 break;
7077 case QEMU_OPTION_hdachs:
7079 const char *p;
7080 p = optarg;
7081 cyls = strtol(p, (char **)&p, 0);
7082 if (cyls < 1 || cyls > 16383)
7083 goto chs_fail;
7084 if (*p != ',')
7085 goto chs_fail;
7086 p++;
7087 heads = strtol(p, (char **)&p, 0);
7088 if (heads < 1 || heads > 16)
7089 goto chs_fail;
7090 if (*p != ',')
7091 goto chs_fail;
7092 p++;
7093 secs = strtol(p, (char **)&p, 0);
7094 if (secs < 1 || secs > 63)
7095 goto chs_fail;
7096 if (*p == ',') {
7097 p++;
7098 if (!strcmp(p, "none"))
7099 translation = BIOS_ATA_TRANSLATION_NONE;
7100 else if (!strcmp(p, "lba"))
7101 translation = BIOS_ATA_TRANSLATION_LBA;
7102 else if (!strcmp(p, "auto"))
7103 translation = BIOS_ATA_TRANSLATION_AUTO;
7104 else
7105 goto chs_fail;
7106 } else if (*p != '\0') {
7107 chs_fail:
7108 fprintf(stderr, "qemu: invalid physical CHS format\n");
7109 exit(1);
7112 break;
7113 case QEMU_OPTION_nographic:
7114 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7115 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7116 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7117 nographic = 1;
7118 break;
7119 case QEMU_OPTION_kernel:
7120 kernel_filename = optarg;
7121 break;
7122 case QEMU_OPTION_append:
7123 kernel_cmdline = optarg;
7124 break;
7125 case QEMU_OPTION_cdrom:
7126 if (cdrom_index >= 0) {
7127 hd_filename[cdrom_index] = optarg;
7129 break;
7130 case QEMU_OPTION_boot:
7131 boot_device = optarg[0];
7132 if (boot_device != 'a' &&
7133 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7134 // Network boot
7135 boot_device != 'n' &&
7136 #endif
7137 boot_device != 'c' && boot_device != 'd') {
7138 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7139 exit(1);
7141 break;
7142 case QEMU_OPTION_fda:
7143 fd_filename[0] = optarg;
7144 break;
7145 case QEMU_OPTION_fdb:
7146 fd_filename[1] = optarg;
7147 break;
7148 #ifdef TARGET_I386
7149 case QEMU_OPTION_no_fd_bootchk:
7150 fd_bootchk = 0;
7151 break;
7152 #endif
7153 case QEMU_OPTION_no_code_copy:
7154 code_copy_enabled = 0;
7155 break;
7156 case QEMU_OPTION_net:
7157 if (nb_net_clients >= MAX_NET_CLIENTS) {
7158 fprintf(stderr, "qemu: too many network clients\n");
7159 exit(1);
7161 pstrcpy(net_clients[nb_net_clients],
7162 sizeof(net_clients[0]),
7163 optarg);
7164 nb_net_clients++;
7165 break;
7166 #ifdef CONFIG_SLIRP
7167 case QEMU_OPTION_tftp:
7168 tftp_prefix = optarg;
7169 break;
7170 case QEMU_OPTION_bootp:
7171 bootp_filename = optarg;
7172 break;
7173 #ifndef _WIN32
7174 case QEMU_OPTION_smb:
7175 net_slirp_smb(optarg);
7176 break;
7177 #endif
7178 case QEMU_OPTION_redir:
7179 net_slirp_redir(optarg);
7180 break;
7181 #endif
7182 #ifdef HAS_AUDIO
7183 case QEMU_OPTION_audio_help:
7184 AUD_help ();
7185 exit (0);
7186 break;
7187 case QEMU_OPTION_soundhw:
7188 select_soundhw (optarg);
7189 break;
7190 #endif
7191 case QEMU_OPTION_h:
7192 help();
7193 break;
7194 case QEMU_OPTION_m:
7195 ram_size = atoi(optarg) * 1024 * 1024;
7196 if (ram_size <= 0)
7197 help();
7198 if (ram_size > PHYS_RAM_MAX_SIZE) {
7199 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7200 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7201 exit(1);
7203 break;
7204 case QEMU_OPTION_d:
7206 int mask;
7207 CPULogItem *item;
7209 mask = cpu_str_to_log_mask(optarg);
7210 if (!mask) {
7211 printf("Log items (comma separated):\n");
7212 for(item = cpu_log_items; item->mask != 0; item++) {
7213 printf("%-10s %s\n", item->name, item->help);
7215 exit(1);
7217 cpu_set_log(mask);
7219 break;
7220 #ifdef CONFIG_GDBSTUB
7221 case QEMU_OPTION_s:
7222 use_gdbstub = 1;
7223 break;
7224 case QEMU_OPTION_p:
7225 gdbstub_port = optarg;
7226 break;
7227 #endif
7228 case QEMU_OPTION_L:
7229 bios_dir = optarg;
7230 break;
7231 case QEMU_OPTION_S:
7232 autostart = 0;
7233 break;
7234 case QEMU_OPTION_k:
7235 keyboard_layout = optarg;
7236 break;
7237 case QEMU_OPTION_localtime:
7238 rtc_utc = 0;
7239 break;
7240 case QEMU_OPTION_cirrusvga:
7241 cirrus_vga_enabled = 1;
7242 vmsvga_enabled = 0;
7243 break;
7244 case QEMU_OPTION_vmsvga:
7245 cirrus_vga_enabled = 0;
7246 vmsvga_enabled = 1;
7247 break;
7248 case QEMU_OPTION_std_vga:
7249 cirrus_vga_enabled = 0;
7250 vmsvga_enabled = 0;
7251 break;
7252 case QEMU_OPTION_g:
7254 const char *p;
7255 int w, h, depth;
7256 p = optarg;
7257 w = strtol(p, (char **)&p, 10);
7258 if (w <= 0) {
7259 graphic_error:
7260 fprintf(stderr, "qemu: invalid resolution or depth\n");
7261 exit(1);
7263 if (*p != 'x')
7264 goto graphic_error;
7265 p++;
7266 h = strtol(p, (char **)&p, 10);
7267 if (h <= 0)
7268 goto graphic_error;
7269 if (*p == 'x') {
7270 p++;
7271 depth = strtol(p, (char **)&p, 10);
7272 if (depth != 8 && depth != 15 && depth != 16 &&
7273 depth != 24 && depth != 32)
7274 goto graphic_error;
7275 } else if (*p == '\0') {
7276 depth = graphic_depth;
7277 } else {
7278 goto graphic_error;
7281 graphic_width = w;
7282 graphic_height = h;
7283 graphic_depth = depth;
7285 break;
7286 case QEMU_OPTION_echr:
7288 char *r;
7289 term_escape_char = strtol(optarg, &r, 0);
7290 if (r == optarg)
7291 printf("Bad argument to echr\n");
7292 break;
7294 case QEMU_OPTION_monitor:
7295 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7296 break;
7297 case QEMU_OPTION_serial:
7298 if (serial_device_index >= MAX_SERIAL_PORTS) {
7299 fprintf(stderr, "qemu: too many serial ports\n");
7300 exit(1);
7302 pstrcpy(serial_devices[serial_device_index],
7303 sizeof(serial_devices[0]), optarg);
7304 serial_device_index++;
7305 break;
7306 case QEMU_OPTION_parallel:
7307 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7308 fprintf(stderr, "qemu: too many parallel ports\n");
7309 exit(1);
7311 pstrcpy(parallel_devices[parallel_device_index],
7312 sizeof(parallel_devices[0]), optarg);
7313 parallel_device_index++;
7314 break;
7315 case QEMU_OPTION_loadvm:
7316 loadvm = optarg;
7317 break;
7318 case QEMU_OPTION_full_screen:
7319 full_screen = 1;
7320 break;
7321 #ifdef CONFIG_SDL
7322 case QEMU_OPTION_no_frame:
7323 no_frame = 1;
7324 break;
7325 case QEMU_OPTION_no_quit:
7326 no_quit = 1;
7327 break;
7328 #endif
7329 case QEMU_OPTION_pidfile:
7330 pid_file = optarg;
7331 break;
7332 #ifdef TARGET_I386
7333 case QEMU_OPTION_win2k_hack:
7334 win2k_install_hack = 1;
7335 break;
7336 #endif
7337 #ifdef USE_KQEMU
7338 case QEMU_OPTION_no_kqemu:
7339 kqemu_allowed = 0;
7340 break;
7341 case QEMU_OPTION_kernel_kqemu:
7342 kqemu_allowed = 2;
7343 break;
7344 #endif
7345 case QEMU_OPTION_usb:
7346 usb_enabled = 1;
7347 break;
7348 case QEMU_OPTION_usbdevice:
7349 usb_enabled = 1;
7350 if (usb_devices_index >= MAX_USB_CMDLINE) {
7351 fprintf(stderr, "Too many USB devices\n");
7352 exit(1);
7354 pstrcpy(usb_devices[usb_devices_index],
7355 sizeof(usb_devices[usb_devices_index]),
7356 optarg);
7357 usb_devices_index++;
7358 break;
7359 case QEMU_OPTION_smp:
7360 smp_cpus = atoi(optarg);
7361 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7362 fprintf(stderr, "Invalid number of CPUs\n");
7363 exit(1);
7365 break;
7366 case QEMU_OPTION_vnc:
7367 vnc_display = optarg;
7368 break;
7369 case QEMU_OPTION_no_acpi:
7370 acpi_enabled = 0;
7371 break;
7372 case QEMU_OPTION_no_reboot:
7373 no_reboot = 1;
7374 break;
7375 case QEMU_OPTION_daemonize:
7376 daemonize = 1;
7377 break;
7378 case QEMU_OPTION_option_rom:
7379 if (nb_option_roms >= MAX_OPTION_ROMS) {
7380 fprintf(stderr, "Too many option ROMs\n");
7381 exit(1);
7383 option_rom[nb_option_roms] = optarg;
7384 nb_option_roms++;
7385 break;
7386 case QEMU_OPTION_semihosting:
7387 semihosting_enabled = 1;
7388 break;
7389 case QEMU_OPTION_name:
7390 qemu_name = optarg;
7391 break;
7396 #ifndef _WIN32
7397 if (daemonize && !nographic && vnc_display == NULL) {
7398 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7399 daemonize = 0;
7402 if (daemonize) {
7403 pid_t pid;
7405 if (pipe(fds) == -1)
7406 exit(1);
7408 pid = fork();
7409 if (pid > 0) {
7410 uint8_t status;
7411 ssize_t len;
7413 close(fds[1]);
7415 again:
7416 len = read(fds[0], &status, 1);
7417 if (len == -1 && (errno == EINTR))
7418 goto again;
7420 if (len != 1)
7421 exit(1);
7422 else if (status == 1) {
7423 fprintf(stderr, "Could not acquire pidfile\n");
7424 exit(1);
7425 } else
7426 exit(0);
7427 } else if (pid < 0)
7428 exit(1);
7430 setsid();
7432 pid = fork();
7433 if (pid > 0)
7434 exit(0);
7435 else if (pid < 0)
7436 exit(1);
7438 umask(027);
7439 chdir("/");
7441 signal(SIGTSTP, SIG_IGN);
7442 signal(SIGTTOU, SIG_IGN);
7443 signal(SIGTTIN, SIG_IGN);
7445 #endif
7447 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7448 if (daemonize) {
7449 uint8_t status = 1;
7450 write(fds[1], &status, 1);
7451 } else
7452 fprintf(stderr, "Could not acquire pid file\n");
7453 exit(1);
7456 #ifdef USE_KQEMU
7457 if (smp_cpus > 1)
7458 kqemu_allowed = 0;
7459 #endif
7460 linux_boot = (kernel_filename != NULL);
7462 if (!linux_boot &&
7463 boot_device != 'n' &&
7464 hd_filename[0] == '\0' &&
7465 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7466 fd_filename[0] == '\0')
7467 help();
7469 /* boot to floppy or the default cd if no hard disk defined yet */
7470 if (hd_filename[0] == '\0' && boot_device == 'c') {
7471 if (fd_filename[0] != '\0')
7472 boot_device = 'a';
7473 else
7474 boot_device = 'd';
7477 setvbuf(stdout, NULL, _IOLBF, 0);
7479 init_timers();
7480 init_timer_alarm();
7481 qemu_aio_init();
7483 #ifdef _WIN32
7484 socket_init();
7485 #endif
7487 /* init network clients */
7488 if (nb_net_clients == 0) {
7489 /* if no clients, we use a default config */
7490 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7491 "nic");
7492 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7493 "user");
7494 nb_net_clients = 2;
7497 for(i = 0;i < nb_net_clients; i++) {
7498 if (net_client_init(net_clients[i]) < 0)
7499 exit(1);
7502 #ifdef TARGET_I386
7503 if (boot_device == 'n') {
7504 for (i = 0; i < nb_nics; i++) {
7505 const char *model = nd_table[i].model;
7506 char buf[1024];
7507 if (model == NULL)
7508 model = "ne2k_pci";
7509 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7510 if (get_image_size(buf) > 0) {
7511 option_rom[nb_option_roms] = strdup(buf);
7512 nb_option_roms++;
7513 break;
7516 if (i == nb_nics) {
7517 fprintf(stderr, "No valid PXE rom found for network device\n");
7518 exit(1);
7520 boot_device = 'c'; /* to prevent confusion by the BIOS */
7522 #endif
7524 /* init the memory */
7525 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7527 phys_ram_base = qemu_vmalloc(phys_ram_size);
7528 if (!phys_ram_base) {
7529 fprintf(stderr, "Could not allocate physical memory\n");
7530 exit(1);
7533 /* we always create the cdrom drive, even if no disk is there */
7534 bdrv_init();
7535 if (cdrom_index >= 0) {
7536 bs_table[cdrom_index] = bdrv_new("cdrom");
7537 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7540 /* open the virtual block devices */
7541 for(i = 0; i < MAX_DISKS; i++) {
7542 if (hd_filename[i]) {
7543 if (!bs_table[i]) {
7544 char buf[64];
7545 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7546 bs_table[i] = bdrv_new(buf);
7548 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7549 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7550 hd_filename[i]);
7551 exit(1);
7553 if (i == 0 && cyls != 0) {
7554 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7555 bdrv_set_translation_hint(bs_table[i], translation);
7560 /* we always create at least one floppy disk */
7561 fd_table[0] = bdrv_new("fda");
7562 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7564 for(i = 0; i < MAX_FD; i++) {
7565 if (fd_filename[i]) {
7566 if (!fd_table[i]) {
7567 char buf[64];
7568 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7569 fd_table[i] = bdrv_new(buf);
7570 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7572 if (fd_filename[i][0] != '\0') {
7573 if (bdrv_open(fd_table[i], fd_filename[i],
7574 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7575 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7576 fd_filename[i]);
7577 exit(1);
7583 /* Open the virtual parallel flash bloc devices */
7584 for(i = 0; i < MAX_PFLASH; i++) {
7585 if (pflash_filename[i]) {
7586 if (!pflash_table[i]) {
7587 char buf[64];
7588 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7589 pflash_table[i] = bdrv_new(buf);
7591 if (bdrv_open(pflash_table[i], pflash_filename[i],
7592 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7593 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7594 pflash_filename[i]);
7595 exit(1);
7600 sd_bdrv = bdrv_new ("sd");
7601 /* FIXME: This isn't really a floppy, but it's a reasonable
7602 approximation. */
7603 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7604 if (sd_filename) {
7605 if (bdrv_open(sd_bdrv, sd_filename,
7606 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7607 fprintf(stderr, "qemu: could not open SD card image %s\n",
7608 sd_filename);
7612 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7613 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7615 init_ioports();
7617 /* terminal init */
7618 if (nographic) {
7619 dumb_display_init(ds);
7620 } else if (vnc_display != NULL) {
7621 vnc_display_init(ds, vnc_display);
7622 } else {
7623 #if defined(CONFIG_SDL)
7624 sdl_display_init(ds, full_screen, no_frame);
7625 #elif defined(CONFIG_COCOA)
7626 cocoa_display_init(ds, full_screen);
7627 #else
7628 dumb_display_init(ds);
7629 #endif
7632 /* Maintain compatibility with multiple stdio monitors */
7633 if (!strcmp(monitor_device,"stdio")) {
7634 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7635 if (!strcmp(serial_devices[i],"mon:stdio")) {
7636 monitor_device[0] = '\0';
7637 break;
7638 } else if (!strcmp(serial_devices[i],"stdio")) {
7639 monitor_device[0] = '\0';
7640 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7641 break;
7645 if (monitor_device[0] != '\0') {
7646 monitor_hd = qemu_chr_open(monitor_device);
7647 if (!monitor_hd) {
7648 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7649 exit(1);
7651 monitor_init(monitor_hd, !nographic);
7654 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7655 const char *devname = serial_devices[i];
7656 if (devname[0] != '\0' && strcmp(devname, "none")) {
7657 serial_hds[i] = qemu_chr_open(devname);
7658 if (!serial_hds[i]) {
7659 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7660 devname);
7661 exit(1);
7663 if (!strcmp(devname, "vc"))
7664 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7668 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7669 const char *devname = parallel_devices[i];
7670 if (devname[0] != '\0' && strcmp(devname, "none")) {
7671 parallel_hds[i] = qemu_chr_open(devname);
7672 if (!parallel_hds[i]) {
7673 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7674 devname);
7675 exit(1);
7677 if (!strcmp(devname, "vc"))
7678 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7682 machine->init(ram_size, vga_ram_size, boot_device,
7683 ds, fd_filename, snapshot,
7684 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7686 /* init USB devices */
7687 if (usb_enabled) {
7688 for(i = 0; i < usb_devices_index; i++) {
7689 if (usb_device_add(usb_devices[i]) < 0) {
7690 fprintf(stderr, "Warning: could not add USB device %s\n",
7691 usb_devices[i]);
7696 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7697 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7699 #ifdef CONFIG_GDBSTUB
7700 if (use_gdbstub) {
7701 /* XXX: use standard host:port notation and modify options
7702 accordingly. */
7703 if (gdbserver_start(gdbstub_port) < 0) {
7704 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
7705 gdbstub_port);
7706 exit(1);
7708 } else
7709 #endif
7710 if (loadvm)
7711 do_loadvm(loadvm);
7714 /* XXX: simplify init */
7715 read_passwords();
7716 if (autostart) {
7717 vm_start();
7721 if (daemonize) {
7722 uint8_t status = 0;
7723 ssize_t len;
7724 int fd;
7726 again1:
7727 len = write(fds[1], &status, 1);
7728 if (len == -1 && (errno == EINTR))
7729 goto again1;
7731 if (len != 1)
7732 exit(1);
7734 fd = open("/dev/null", O_RDWR);
7735 if (fd == -1)
7736 exit(1);
7738 dup2(fd, 0);
7739 dup2(fd, 1);
7740 dup2(fd, 2);
7742 close(fd);
7745 main_loop();
7746 quit_timers();
7747 return 0;