Rename variables and rearrange code to please gcc -Wshadow checks
[qemu/qemu_0_9_1_stable.git] / vl.c
blob172b5ab155a7e9748b7a2204298d15acb6a48c97
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 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
51 #include <freebsd/stdlib.h>
52 #else
53 #ifndef __sun__
54 #include <linux/if.h>
55 #include <linux/if_tun.h>
56 #include <pty.h>
57 #include <malloc.h>
58 #include <linux/rtc.h>
59 #include <linux/ppdev.h>
60 #include <linux/parport.h>
61 #else
62 #include <sys/stat.h>
63 #include <sys/ethernet.h>
64 #include <sys/sockio.h>
65 #include <arpa/inet.h>
66 #include <netinet/arp.h>
67 #include <netinet/in.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip_icmp.h> // must come after ip.h
71 #include <netinet/udp.h>
72 #include <netinet/tcp.h>
73 #include <net/if.h>
74 #include <syslog.h>
75 #include <stropts.h>
76 #endif
77 #endif
78 #endif
80 #if defined(CONFIG_SLIRP)
81 #include "libslirp.h"
82 #endif
84 #ifdef _WIN32
85 #include <malloc.h>
86 #include <sys/timeb.h>
87 #include <windows.h>
88 #define getopt_long_only getopt_long
89 #define memalign(align, size) malloc(size)
90 #endif
92 #include "qemu_socket.h"
94 #ifdef CONFIG_SDL
95 #ifdef __APPLE__
96 #include <SDL/SDL.h>
97 #endif
98 #endif /* CONFIG_SDL */
100 #ifdef CONFIG_COCOA
101 #undef main
102 #define main qemu_main
103 #endif /* CONFIG_COCOA */
105 #include "disas.h"
107 #include "exec-all.h"
109 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
110 #ifdef __sun__
111 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
112 #else
113 #define SMBD_COMMAND "/usr/sbin/smbd"
114 #endif
116 //#define DEBUG_UNUSED_IOPORT
117 //#define DEBUG_IOPORT
119 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
121 #ifdef TARGET_PPC
122 #define DEFAULT_RAM_SIZE 144
123 #else
124 #define DEFAULT_RAM_SIZE 128
125 #endif
126 /* in ms */
127 #define GUI_REFRESH_INTERVAL 30
129 /* Max number of USB devices that can be specified on the commandline. */
130 #define MAX_USB_CMDLINE 8
132 /* XXX: use a two level table to limit memory usage */
133 #define MAX_IOPORTS 65536
135 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
136 char phys_ram_file[1024];
137 void *ioport_opaque[MAX_IOPORTS];
138 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
139 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
140 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
141 to store the VM snapshots */
142 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
143 BlockDriverState *pflash_table[MAX_PFLASH];
144 BlockDriverState *sd_bdrv;
145 BlockDriverState *mtd_bdrv;
146 /* point to the block driver where the snapshots are managed */
147 BlockDriverState *bs_snapshots;
148 int vga_ram_size;
149 static DisplayState display_state;
150 int nographic;
151 const char* keyboard_layout = NULL;
152 int64_t ticks_per_sec;
153 int boot_device = 'c';
154 int ram_size;
155 int pit_min_timer_count = 0;
156 int nb_nics;
157 NICInfo nd_table[MAX_NICS];
158 int vm_running;
159 int rtc_utc = 1;
160 int cirrus_vga_enabled = 1;
161 int vmsvga_enabled = 0;
162 #ifdef TARGET_SPARC
163 int graphic_width = 1024;
164 int graphic_height = 768;
165 int graphic_depth = 8;
166 #else
167 int graphic_width = 800;
168 int graphic_height = 600;
169 int graphic_depth = 15;
170 #endif
171 int full_screen = 0;
172 int no_frame = 0;
173 int no_quit = 0;
174 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
175 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
176 #ifdef TARGET_I386
177 int win2k_install_hack = 0;
178 #endif
179 int usb_enabled = 0;
180 static VLANState *first_vlan;
181 int smp_cpus = 1;
182 const char *vnc_display;
183 #if defined(TARGET_SPARC)
184 #define MAX_CPUS 16
185 #elif defined(TARGET_I386)
186 #define MAX_CPUS 255
187 #else
188 #define MAX_CPUS 1
189 #endif
190 int acpi_enabled = 1;
191 int fd_bootchk = 1;
192 int no_reboot = 0;
193 int cursor_hide = 1;
194 int graphic_rotate = 0;
195 int daemonize = 0;
196 const char *option_rom[MAX_OPTION_ROMS];
197 int nb_option_roms;
198 int semihosting_enabled = 0;
199 int autostart = 1;
200 const char *qemu_name;
201 int alt_grab = 0;
202 #ifdef TARGET_SPARC
203 unsigned int nb_prom_envs = 0;
204 const char *prom_envs[MAX_PROM_ENVS];
205 #endif
207 /***********************************************************/
208 /* x86 ISA bus support */
210 target_phys_addr_t isa_mem_base = 0;
211 PicState2 *isa_pic;
213 uint32_t default_ioport_readb(void *opaque, uint32_t address)
215 #ifdef DEBUG_UNUSED_IOPORT
216 fprintf(stderr, "unused inb: port=0x%04x\n", address);
217 #endif
218 return 0xff;
221 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
223 #ifdef DEBUG_UNUSED_IOPORT
224 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
225 #endif
228 /* default is to make two byte accesses */
229 uint32_t default_ioport_readw(void *opaque, uint32_t address)
231 uint32_t data;
232 data = ioport_read_table[0][address](ioport_opaque[address], address);
233 address = (address + 1) & (MAX_IOPORTS - 1);
234 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
235 return data;
238 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
240 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
241 address = (address + 1) & (MAX_IOPORTS - 1);
242 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
245 uint32_t default_ioport_readl(void *opaque, uint32_t address)
247 #ifdef DEBUG_UNUSED_IOPORT
248 fprintf(stderr, "unused inl: port=0x%04x\n", address);
249 #endif
250 return 0xffffffff;
253 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
255 #ifdef DEBUG_UNUSED_IOPORT
256 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
257 #endif
260 void init_ioports(void)
262 int i;
264 for(i = 0; i < MAX_IOPORTS; i++) {
265 ioport_read_table[0][i] = default_ioport_readb;
266 ioport_write_table[0][i] = default_ioport_writeb;
267 ioport_read_table[1][i] = default_ioport_readw;
268 ioport_write_table[1][i] = default_ioport_writew;
269 ioport_read_table[2][i] = default_ioport_readl;
270 ioport_write_table[2][i] = default_ioport_writel;
274 /* size is the word size in byte */
275 int register_ioport_read(int start, int length, int size,
276 IOPortReadFunc *func, void *opaque)
278 int i, bsize;
280 if (size == 1) {
281 bsize = 0;
282 } else if (size == 2) {
283 bsize = 1;
284 } else if (size == 4) {
285 bsize = 2;
286 } else {
287 hw_error("register_ioport_read: invalid size");
288 return -1;
290 for(i = start; i < start + length; i += size) {
291 ioport_read_table[bsize][i] = func;
292 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
293 hw_error("register_ioport_read: invalid opaque");
294 ioport_opaque[i] = opaque;
296 return 0;
299 /* size is the word size in byte */
300 int register_ioport_write(int start, int length, int size,
301 IOPortWriteFunc *func, void *opaque)
303 int i, bsize;
305 if (size == 1) {
306 bsize = 0;
307 } else if (size == 2) {
308 bsize = 1;
309 } else if (size == 4) {
310 bsize = 2;
311 } else {
312 hw_error("register_ioport_write: invalid size");
313 return -1;
315 for(i = start; i < start + length; i += size) {
316 ioport_write_table[bsize][i] = func;
317 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
318 hw_error("register_ioport_write: invalid opaque");
319 ioport_opaque[i] = opaque;
321 return 0;
324 void isa_unassign_ioport(int start, int length)
326 int i;
328 for(i = start; i < start + length; i++) {
329 ioport_read_table[0][i] = default_ioport_readb;
330 ioport_read_table[1][i] = default_ioport_readw;
331 ioport_read_table[2][i] = default_ioport_readl;
333 ioport_write_table[0][i] = default_ioport_writeb;
334 ioport_write_table[1][i] = default_ioport_writew;
335 ioport_write_table[2][i] = default_ioport_writel;
339 /***********************************************************/
341 void cpu_outb(CPUState *env, int addr, int val)
343 #ifdef DEBUG_IOPORT
344 if (loglevel & CPU_LOG_IOPORT)
345 fprintf(logfile, "outb: %04x %02x\n", addr, val);
346 #endif
347 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
348 #ifdef USE_KQEMU
349 if (env)
350 env->last_io_time = cpu_get_time_fast();
351 #endif
354 void cpu_outw(CPUState *env, int addr, int val)
356 #ifdef DEBUG_IOPORT
357 if (loglevel & CPU_LOG_IOPORT)
358 fprintf(logfile, "outw: %04x %04x\n", addr, val);
359 #endif
360 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
361 #ifdef USE_KQEMU
362 if (env)
363 env->last_io_time = cpu_get_time_fast();
364 #endif
367 void cpu_outl(CPUState *env, int addr, int val)
369 #ifdef DEBUG_IOPORT
370 if (loglevel & CPU_LOG_IOPORT)
371 fprintf(logfile, "outl: %04x %08x\n", addr, val);
372 #endif
373 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
374 #ifdef USE_KQEMU
375 if (env)
376 env->last_io_time = cpu_get_time_fast();
377 #endif
380 int cpu_inb(CPUState *env, int addr)
382 int val;
383 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
384 #ifdef DEBUG_IOPORT
385 if (loglevel & CPU_LOG_IOPORT)
386 fprintf(logfile, "inb : %04x %02x\n", addr, val);
387 #endif
388 #ifdef USE_KQEMU
389 if (env)
390 env->last_io_time = cpu_get_time_fast();
391 #endif
392 return val;
395 int cpu_inw(CPUState *env, int addr)
397 int val;
398 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
399 #ifdef DEBUG_IOPORT
400 if (loglevel & CPU_LOG_IOPORT)
401 fprintf(logfile, "inw : %04x %04x\n", addr, val);
402 #endif
403 #ifdef USE_KQEMU
404 if (env)
405 env->last_io_time = cpu_get_time_fast();
406 #endif
407 return val;
410 int cpu_inl(CPUState *env, int addr)
412 int val;
413 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
414 #ifdef DEBUG_IOPORT
415 if (loglevel & CPU_LOG_IOPORT)
416 fprintf(logfile, "inl : %04x %08x\n", addr, val);
417 #endif
418 #ifdef USE_KQEMU
419 if (env)
420 env->last_io_time = cpu_get_time_fast();
421 #endif
422 return val;
425 /***********************************************************/
426 void hw_error(const char *fmt, ...)
428 va_list ap;
429 CPUState *env;
431 va_start(ap, fmt);
432 fprintf(stderr, "qemu: hardware error: ");
433 vfprintf(stderr, fmt, ap);
434 fprintf(stderr, "\n");
435 for(env = first_cpu; env != NULL; env = env->next_cpu) {
436 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
437 #ifdef TARGET_I386
438 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
439 #else
440 cpu_dump_state(env, stderr, fprintf, 0);
441 #endif
443 va_end(ap);
444 abort();
447 /***********************************************************/
448 /* keyboard/mouse */
450 static QEMUPutKBDEvent *qemu_put_kbd_event;
451 static void *qemu_put_kbd_event_opaque;
452 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
453 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
455 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
457 qemu_put_kbd_event_opaque = opaque;
458 qemu_put_kbd_event = func;
461 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
462 void *opaque, int absolute,
463 const char *name)
465 QEMUPutMouseEntry *s, *cursor;
467 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
468 if (!s)
469 return NULL;
471 s->qemu_put_mouse_event = func;
472 s->qemu_put_mouse_event_opaque = opaque;
473 s->qemu_put_mouse_event_absolute = absolute;
474 s->qemu_put_mouse_event_name = qemu_strdup(name);
475 s->next = NULL;
477 if (!qemu_put_mouse_event_head) {
478 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
479 return s;
482 cursor = qemu_put_mouse_event_head;
483 while (cursor->next != NULL)
484 cursor = cursor->next;
486 cursor->next = s;
487 qemu_put_mouse_event_current = s;
489 return s;
492 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
494 QEMUPutMouseEntry *prev = NULL, *cursor;
496 if (!qemu_put_mouse_event_head || entry == NULL)
497 return;
499 cursor = qemu_put_mouse_event_head;
500 while (cursor != NULL && cursor != entry) {
501 prev = cursor;
502 cursor = cursor->next;
505 if (cursor == NULL) // does not exist or list empty
506 return;
507 else if (prev == NULL) { // entry is head
508 qemu_put_mouse_event_head = cursor->next;
509 if (qemu_put_mouse_event_current == entry)
510 qemu_put_mouse_event_current = cursor->next;
511 qemu_free(entry->qemu_put_mouse_event_name);
512 qemu_free(entry);
513 return;
516 prev->next = entry->next;
518 if (qemu_put_mouse_event_current == entry)
519 qemu_put_mouse_event_current = prev;
521 qemu_free(entry->qemu_put_mouse_event_name);
522 qemu_free(entry);
525 void kbd_put_keycode(int keycode)
527 if (qemu_put_kbd_event) {
528 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
532 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
534 QEMUPutMouseEvent *mouse_event;
535 void *mouse_event_opaque;
536 int width;
538 if (!qemu_put_mouse_event_current) {
539 return;
542 mouse_event =
543 qemu_put_mouse_event_current->qemu_put_mouse_event;
544 mouse_event_opaque =
545 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
547 if (mouse_event) {
548 if (graphic_rotate) {
549 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
550 width = 0x7fff;
551 else
552 width = graphic_width;
553 mouse_event(mouse_event_opaque,
554 width - dy, dx, dz, buttons_state);
555 } else
556 mouse_event(mouse_event_opaque,
557 dx, dy, dz, buttons_state);
561 int kbd_mouse_is_absolute(void)
563 if (!qemu_put_mouse_event_current)
564 return 0;
566 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
569 void do_info_mice(void)
571 QEMUPutMouseEntry *cursor;
572 int index = 0;
574 if (!qemu_put_mouse_event_head) {
575 term_printf("No mouse devices connected\n");
576 return;
579 term_printf("Mouse devices available:\n");
580 cursor = qemu_put_mouse_event_head;
581 while (cursor != NULL) {
582 term_printf("%c Mouse #%d: %s\n",
583 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
584 index, cursor->qemu_put_mouse_event_name);
585 index++;
586 cursor = cursor->next;
590 void do_mouse_set(int index)
592 QEMUPutMouseEntry *cursor;
593 int i = 0;
595 if (!qemu_put_mouse_event_head) {
596 term_printf("No mouse devices connected\n");
597 return;
600 cursor = qemu_put_mouse_event_head;
601 while (cursor != NULL && index != i) {
602 i++;
603 cursor = cursor->next;
606 if (cursor != NULL)
607 qemu_put_mouse_event_current = cursor;
608 else
609 term_printf("Mouse at given index not found\n");
612 /* compute with 96 bit intermediate result: (a*b)/c */
613 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
615 union {
616 uint64_t ll;
617 struct {
618 #ifdef WORDS_BIGENDIAN
619 uint32_t high, low;
620 #else
621 uint32_t low, high;
622 #endif
623 } l;
624 } u, res;
625 uint64_t rl, rh;
627 u.ll = a;
628 rl = (uint64_t)u.l.low * (uint64_t)b;
629 rh = (uint64_t)u.l.high * (uint64_t)b;
630 rh += (rl >> 32);
631 res.l.high = rh / c;
632 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
633 return res.ll;
636 /***********************************************************/
637 /* real time host monotonic timer */
639 #define QEMU_TIMER_BASE 1000000000LL
641 #ifdef WIN32
643 static int64_t clock_freq;
645 static void init_get_clock(void)
647 LARGE_INTEGER freq;
648 int ret;
649 ret = QueryPerformanceFrequency(&freq);
650 if (ret == 0) {
651 fprintf(stderr, "Could not calibrate ticks\n");
652 exit(1);
654 clock_freq = freq.QuadPart;
657 static int64_t get_clock(void)
659 LARGE_INTEGER ti;
660 QueryPerformanceCounter(&ti);
661 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
664 #else
666 static int use_rt_clock;
668 static void init_get_clock(void)
670 use_rt_clock = 0;
671 #if defined(__linux__)
673 struct timespec ts;
674 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
675 use_rt_clock = 1;
678 #endif
681 static int64_t get_clock(void)
683 #if defined(__linux__)
684 if (use_rt_clock) {
685 struct timespec ts;
686 clock_gettime(CLOCK_MONOTONIC, &ts);
687 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
688 } else
689 #endif
691 /* XXX: using gettimeofday leads to problems if the date
692 changes, so it should be avoided. */
693 struct timeval tv;
694 gettimeofday(&tv, NULL);
695 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
699 #endif
701 /***********************************************************/
702 /* guest cycle counter */
704 static int64_t cpu_ticks_prev;
705 static int64_t cpu_ticks_offset;
706 static int64_t cpu_clock_offset;
707 static int cpu_ticks_enabled;
709 /* return the host CPU cycle counter and handle stop/restart */
710 int64_t cpu_get_ticks(void)
712 if (!cpu_ticks_enabled) {
713 return cpu_ticks_offset;
714 } else {
715 int64_t ticks;
716 ticks = cpu_get_real_ticks();
717 if (cpu_ticks_prev > ticks) {
718 /* Note: non increasing ticks may happen if the host uses
719 software suspend */
720 cpu_ticks_offset += cpu_ticks_prev - ticks;
722 cpu_ticks_prev = ticks;
723 return ticks + cpu_ticks_offset;
727 /* return the host CPU monotonic timer and handle stop/restart */
728 static int64_t cpu_get_clock(void)
730 int64_t ti;
731 if (!cpu_ticks_enabled) {
732 return cpu_clock_offset;
733 } else {
734 ti = get_clock();
735 return ti + cpu_clock_offset;
739 /* enable cpu_get_ticks() */
740 void cpu_enable_ticks(void)
742 if (!cpu_ticks_enabled) {
743 cpu_ticks_offset -= cpu_get_real_ticks();
744 cpu_clock_offset -= get_clock();
745 cpu_ticks_enabled = 1;
749 /* disable cpu_get_ticks() : the clock is stopped. You must not call
750 cpu_get_ticks() after that. */
751 void cpu_disable_ticks(void)
753 if (cpu_ticks_enabled) {
754 cpu_ticks_offset = cpu_get_ticks();
755 cpu_clock_offset = cpu_get_clock();
756 cpu_ticks_enabled = 0;
760 /***********************************************************/
761 /* timers */
763 #define QEMU_TIMER_REALTIME 0
764 #define QEMU_TIMER_VIRTUAL 1
766 struct QEMUClock {
767 int type;
768 /* XXX: add frequency */
771 struct QEMUTimer {
772 QEMUClock *clock;
773 int64_t expire_time;
774 QEMUTimerCB *cb;
775 void *opaque;
776 struct QEMUTimer *next;
779 QEMUClock *rt_clock;
780 QEMUClock *vm_clock;
782 static QEMUTimer *active_timers[2];
783 #ifdef _WIN32
784 static MMRESULT timerID;
785 static HANDLE host_alarm = NULL;
786 static unsigned int period = 1;
787 #else
788 /* frequency of the times() clock tick */
789 static int timer_freq;
790 #endif
792 QEMUClock *qemu_new_clock(int type)
794 QEMUClock *clock;
795 clock = qemu_mallocz(sizeof(QEMUClock));
796 if (!clock)
797 return NULL;
798 clock->type = type;
799 return clock;
802 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
804 QEMUTimer *ts;
806 ts = qemu_mallocz(sizeof(QEMUTimer));
807 ts->clock = clock;
808 ts->cb = cb;
809 ts->opaque = opaque;
810 return ts;
813 void qemu_free_timer(QEMUTimer *ts)
815 qemu_free(ts);
818 /* stop a timer, but do not dealloc it */
819 void qemu_del_timer(QEMUTimer *ts)
821 QEMUTimer **pt, *t;
823 /* NOTE: this code must be signal safe because
824 qemu_timer_expired() can be called from a signal. */
825 pt = &active_timers[ts->clock->type];
826 for(;;) {
827 t = *pt;
828 if (!t)
829 break;
830 if (t == ts) {
831 *pt = t->next;
832 break;
834 pt = &t->next;
838 /* modify the current timer so that it will be fired when current_time
839 >= expire_time. The corresponding callback will be called. */
840 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
842 QEMUTimer **pt, *t;
844 qemu_del_timer(ts);
846 /* add the timer in the sorted list */
847 /* NOTE: this code must be signal safe because
848 qemu_timer_expired() can be called from a signal. */
849 pt = &active_timers[ts->clock->type];
850 for(;;) {
851 t = *pt;
852 if (!t)
853 break;
854 if (t->expire_time > expire_time)
855 break;
856 pt = &t->next;
858 ts->expire_time = expire_time;
859 ts->next = *pt;
860 *pt = ts;
863 int qemu_timer_pending(QEMUTimer *ts)
865 QEMUTimer *t;
866 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
867 if (t == ts)
868 return 1;
870 return 0;
873 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
875 if (!timer_head)
876 return 0;
877 return (timer_head->expire_time <= current_time);
880 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
882 QEMUTimer *ts;
884 for(;;) {
885 ts = *ptimer_head;
886 if (!ts || ts->expire_time > current_time)
887 break;
888 /* remove timer from the list before calling the callback */
889 *ptimer_head = ts->next;
890 ts->next = NULL;
892 /* run the callback (the timer list can be modified) */
893 ts->cb(ts->opaque);
897 int64_t qemu_get_clock(QEMUClock *clock)
899 switch(clock->type) {
900 case QEMU_TIMER_REALTIME:
901 return get_clock() / 1000000;
902 default:
903 case QEMU_TIMER_VIRTUAL:
904 return cpu_get_clock();
908 static void init_timers(void)
910 init_get_clock();
911 ticks_per_sec = QEMU_TIMER_BASE;
912 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
913 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
916 /* save a timer */
917 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
919 uint64_t expire_time;
921 if (qemu_timer_pending(ts)) {
922 expire_time = ts->expire_time;
923 } else {
924 expire_time = -1;
926 qemu_put_be64(f, expire_time);
929 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
931 uint64_t expire_time;
933 expire_time = qemu_get_be64(f);
934 if (expire_time != -1) {
935 qemu_mod_timer(ts, expire_time);
936 } else {
937 qemu_del_timer(ts);
941 static void timer_save(QEMUFile *f, void *opaque)
943 if (cpu_ticks_enabled) {
944 hw_error("cannot save state if virtual timers are running");
946 qemu_put_be64s(f, &cpu_ticks_offset);
947 qemu_put_be64s(f, &ticks_per_sec);
948 qemu_put_be64s(f, &cpu_clock_offset);
951 static int timer_load(QEMUFile *f, void *opaque, int version_id)
953 if (version_id != 1 && version_id != 2)
954 return -EINVAL;
955 if (cpu_ticks_enabled) {
956 return -EINVAL;
958 qemu_get_be64s(f, &cpu_ticks_offset);
959 qemu_get_be64s(f, &ticks_per_sec);
960 if (version_id == 2) {
961 qemu_get_be64s(f, &cpu_clock_offset);
963 return 0;
966 #ifdef _WIN32
967 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
968 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
969 #else
970 static void host_alarm_handler(int host_signum)
971 #endif
973 #if 0
974 #define DISP_FREQ 1000
976 static int64_t delta_min = INT64_MAX;
977 static int64_t delta_max, delta_cum, last_clock, delta, ti;
978 static int count;
979 ti = qemu_get_clock(vm_clock);
980 if (last_clock != 0) {
981 delta = ti - last_clock;
982 if (delta < delta_min)
983 delta_min = delta;
984 if (delta > delta_max)
985 delta_max = delta;
986 delta_cum += delta;
987 if (++count == DISP_FREQ) {
988 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
989 muldiv64(delta_min, 1000000, ticks_per_sec),
990 muldiv64(delta_max, 1000000, ticks_per_sec),
991 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
992 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
993 count = 0;
994 delta_min = INT64_MAX;
995 delta_max = 0;
996 delta_cum = 0;
999 last_clock = ti;
1001 #endif
1002 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1003 qemu_get_clock(vm_clock)) ||
1004 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1005 qemu_get_clock(rt_clock))) {
1006 #ifdef _WIN32
1007 SetEvent(host_alarm);
1008 #endif
1009 CPUState *env = cpu_single_env;
1010 if (env) {
1011 /* stop the currently executing cpu because a timer occured */
1012 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1013 #ifdef USE_KQEMU
1014 if (env->kqemu_enabled) {
1015 kqemu_cpu_interrupt(env);
1017 #endif
1022 #ifndef _WIN32
1024 #if defined(__linux__)
1026 #define RTC_FREQ 1024
1028 static int rtc_fd;
1030 static int start_rtc_timer(void)
1032 rtc_fd = open("/dev/rtc", O_RDONLY);
1033 if (rtc_fd < 0)
1034 return -1;
1035 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1036 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1037 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1038 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1039 goto fail;
1041 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1042 fail:
1043 close(rtc_fd);
1044 return -1;
1046 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1047 return 0;
1050 #else
1052 static int start_rtc_timer(void)
1054 return -1;
1057 #endif /* !defined(__linux__) */
1059 #endif /* !defined(_WIN32) */
1061 static void init_timer_alarm(void)
1063 #ifdef _WIN32
1065 int count=0;
1066 TIMECAPS tc;
1068 ZeroMemory(&tc, sizeof(TIMECAPS));
1069 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1070 if (period < tc.wPeriodMin)
1071 period = tc.wPeriodMin;
1072 timeBeginPeriod(period);
1073 timerID = timeSetEvent(1, // interval (ms)
1074 period, // resolution
1075 host_alarm_handler, // function
1076 (DWORD)&count, // user parameter
1077 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1078 if( !timerID ) {
1079 perror("failed timer alarm");
1080 exit(1);
1082 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1083 if (!host_alarm) {
1084 perror("failed CreateEvent");
1085 exit(1);
1087 qemu_add_wait_object(host_alarm, NULL, NULL);
1089 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1090 #else
1092 struct sigaction act;
1093 struct itimerval itv;
1095 /* get times() syscall frequency */
1096 timer_freq = sysconf(_SC_CLK_TCK);
1098 /* timer signal */
1099 sigfillset(&act.sa_mask);
1100 act.sa_flags = 0;
1101 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1102 act.sa_flags |= SA_ONSTACK;
1103 #endif
1104 act.sa_handler = host_alarm_handler;
1105 sigaction(SIGALRM, &act, NULL);
1107 itv.it_interval.tv_sec = 0;
1108 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1109 itv.it_value.tv_sec = 0;
1110 itv.it_value.tv_usec = 10 * 1000;
1111 setitimer(ITIMER_REAL, &itv, NULL);
1112 /* we probe the tick duration of the kernel to inform the user if
1113 the emulated kernel requested a too high timer frequency */
1114 getitimer(ITIMER_REAL, &itv);
1116 #if defined(__linux__)
1117 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1118 have timers with 1 ms resolution. The correct solution will
1119 be to use the POSIX real time timers available in recent
1120 2.6 kernels */
1121 if (itv.it_interval.tv_usec > 1000 || 1) {
1122 /* try to use /dev/rtc to have a faster timer */
1123 if (start_rtc_timer() < 0)
1124 goto use_itimer;
1125 /* disable itimer */
1126 itv.it_interval.tv_sec = 0;
1127 itv.it_interval.tv_usec = 0;
1128 itv.it_value.tv_sec = 0;
1129 itv.it_value.tv_usec = 0;
1130 setitimer(ITIMER_REAL, &itv, NULL);
1132 /* use the RTC */
1133 sigaction(SIGIO, &act, NULL);
1134 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1135 fcntl(rtc_fd, F_SETOWN, getpid());
1136 } else
1137 #endif /* defined(__linux__) */
1139 use_itimer:
1140 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1141 PIT_FREQ) / 1000000;
1144 #endif
1147 void quit_timers(void)
1149 #ifdef _WIN32
1150 timeKillEvent(timerID);
1151 timeEndPeriod(period);
1152 if (host_alarm) {
1153 CloseHandle(host_alarm);
1154 host_alarm = NULL;
1156 #endif
1159 /***********************************************************/
1160 /* character device */
1162 static void qemu_chr_event(CharDriverState *s, int event)
1164 if (!s->chr_event)
1165 return;
1166 s->chr_event(s->handler_opaque, event);
1169 static void qemu_chr_reset_bh(void *opaque)
1171 CharDriverState *s = opaque;
1172 qemu_chr_event(s, CHR_EVENT_RESET);
1173 qemu_bh_delete(s->bh);
1174 s->bh = NULL;
1177 void qemu_chr_reset(CharDriverState *s)
1179 if (s->bh == NULL) {
1180 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1181 qemu_bh_schedule(s->bh);
1185 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1187 return s->chr_write(s, buf, len);
1190 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1192 if (!s->chr_ioctl)
1193 return -ENOTSUP;
1194 return s->chr_ioctl(s, cmd, arg);
1197 int qemu_chr_can_read(CharDriverState *s)
1199 if (!s->chr_can_read)
1200 return 0;
1201 return s->chr_can_read(s->handler_opaque);
1204 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1206 s->chr_read(s->handler_opaque, buf, len);
1210 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1212 char buf[4096];
1213 va_list ap;
1214 va_start(ap, fmt);
1215 vsnprintf(buf, sizeof(buf), fmt, ap);
1216 qemu_chr_write(s, buf, strlen(buf));
1217 va_end(ap);
1220 void qemu_chr_send_event(CharDriverState *s, int event)
1222 if (s->chr_send_event)
1223 s->chr_send_event(s, event);
1226 void qemu_chr_add_handlers(CharDriverState *s,
1227 IOCanRWHandler *fd_can_read,
1228 IOReadHandler *fd_read,
1229 IOEventHandler *fd_event,
1230 void *opaque)
1232 s->chr_can_read = fd_can_read;
1233 s->chr_read = fd_read;
1234 s->chr_event = fd_event;
1235 s->handler_opaque = opaque;
1236 if (s->chr_update_read_handler)
1237 s->chr_update_read_handler(s);
1240 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1242 return len;
1245 static CharDriverState *qemu_chr_open_null(void)
1247 CharDriverState *chr;
1249 chr = qemu_mallocz(sizeof(CharDriverState));
1250 if (!chr)
1251 return NULL;
1252 chr->chr_write = null_chr_write;
1253 return chr;
1256 /* MUX driver for serial I/O splitting */
1257 static int term_timestamps;
1258 static int64_t term_timestamps_start;
1259 #define MAX_MUX 4
1260 typedef struct {
1261 IOCanRWHandler *chr_can_read[MAX_MUX];
1262 IOReadHandler *chr_read[MAX_MUX];
1263 IOEventHandler *chr_event[MAX_MUX];
1264 void *ext_opaque[MAX_MUX];
1265 CharDriverState *drv;
1266 int mux_cnt;
1267 int term_got_escape;
1268 int max_size;
1269 } MuxDriver;
1272 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1274 MuxDriver *d = chr->opaque;
1275 int ret;
1276 if (!term_timestamps) {
1277 ret = d->drv->chr_write(d->drv, buf, len);
1278 } else {
1279 int i;
1281 ret = 0;
1282 for(i = 0; i < len; i++) {
1283 ret += d->drv->chr_write(d->drv, buf+i, 1);
1284 if (buf[i] == '\n') {
1285 char buf1[64];
1286 int64_t ti;
1287 int secs;
1289 ti = get_clock();
1290 if (term_timestamps_start == -1)
1291 term_timestamps_start = ti;
1292 ti -= term_timestamps_start;
1293 secs = ti / 1000000000;
1294 snprintf(buf1, sizeof(buf1),
1295 "[%02d:%02d:%02d.%03d] ",
1296 secs / 3600,
1297 (secs / 60) % 60,
1298 secs % 60,
1299 (int)((ti / 1000000) % 1000));
1300 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1304 return ret;
1307 static char *mux_help[] = {
1308 "% h print this help\n\r",
1309 "% x exit emulator\n\r",
1310 "% s save disk data back to file (if -snapshot)\n\r",
1311 "% t toggle console timestamps\n\r"
1312 "% b send break (magic sysrq)\n\r",
1313 "% c switch between console and monitor\n\r",
1314 "% % sends %\n\r",
1315 NULL
1318 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1319 static void mux_print_help(CharDriverState *chr)
1321 int i, j;
1322 char ebuf[15] = "Escape-Char";
1323 char cbuf[50] = "\n\r";
1325 if (term_escape_char > 0 && term_escape_char < 26) {
1326 sprintf(cbuf,"\n\r");
1327 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1328 } else {
1329 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1331 chr->chr_write(chr, cbuf, strlen(cbuf));
1332 for (i = 0; mux_help[i] != NULL; i++) {
1333 for (j=0; mux_help[i][j] != '\0'; j++) {
1334 if (mux_help[i][j] == '%')
1335 chr->chr_write(chr, ebuf, strlen(ebuf));
1336 else
1337 chr->chr_write(chr, &mux_help[i][j], 1);
1342 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1344 if (d->term_got_escape) {
1345 d->term_got_escape = 0;
1346 if (ch == term_escape_char)
1347 goto send_char;
1348 switch(ch) {
1349 case '?':
1350 case 'h':
1351 mux_print_help(chr);
1352 break;
1353 case 'x':
1355 char *term = "QEMU: Terminated\n\r";
1356 chr->chr_write(chr,term,strlen(term));
1357 exit(0);
1358 break;
1360 case 's':
1362 int i;
1363 for (i = 0; i < MAX_DISKS; i++) {
1364 if (bs_table[i])
1365 bdrv_commit(bs_table[i]);
1367 if (mtd_bdrv)
1368 bdrv_commit(mtd_bdrv);
1370 break;
1371 case 'b':
1372 qemu_chr_event(chr, CHR_EVENT_BREAK);
1373 break;
1374 case 'c':
1375 /* Switch to the next registered device */
1376 chr->focus++;
1377 if (chr->focus >= d->mux_cnt)
1378 chr->focus = 0;
1379 break;
1380 case 't':
1381 term_timestamps = !term_timestamps;
1382 term_timestamps_start = -1;
1383 break;
1385 } else if (ch == term_escape_char) {
1386 d->term_got_escape = 1;
1387 } else {
1388 send_char:
1389 return 1;
1391 return 0;
1394 static int mux_chr_can_read(void *opaque)
1396 CharDriverState *chr = opaque;
1397 MuxDriver *d = chr->opaque;
1398 if (d->chr_can_read[chr->focus])
1399 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1400 return 0;
1403 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1405 CharDriverState *chr = opaque;
1406 MuxDriver *d = chr->opaque;
1407 int i;
1408 for(i = 0; i < size; i++)
1409 if (mux_proc_byte(chr, d, buf[i]))
1410 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1413 static void mux_chr_event(void *opaque, int event)
1415 CharDriverState *chr = opaque;
1416 MuxDriver *d = chr->opaque;
1417 int i;
1419 /* Send the event to all registered listeners */
1420 for (i = 0; i < d->mux_cnt; i++)
1421 if (d->chr_event[i])
1422 d->chr_event[i](d->ext_opaque[i], event);
1425 static void mux_chr_update_read_handler(CharDriverState *chr)
1427 MuxDriver *d = chr->opaque;
1429 if (d->mux_cnt >= MAX_MUX) {
1430 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1431 return;
1433 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1434 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1435 d->chr_read[d->mux_cnt] = chr->chr_read;
1436 d->chr_event[d->mux_cnt] = chr->chr_event;
1437 /* Fix up the real driver with mux routines */
1438 if (d->mux_cnt == 0) {
1439 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1440 mux_chr_event, chr);
1442 chr->focus = d->mux_cnt;
1443 d->mux_cnt++;
1446 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1448 CharDriverState *chr;
1449 MuxDriver *d;
1451 chr = qemu_mallocz(sizeof(CharDriverState));
1452 if (!chr)
1453 return NULL;
1454 d = qemu_mallocz(sizeof(MuxDriver));
1455 if (!d) {
1456 free(chr);
1457 return NULL;
1460 chr->opaque = d;
1461 d->drv = drv;
1462 chr->focus = -1;
1463 chr->chr_write = mux_chr_write;
1464 chr->chr_update_read_handler = mux_chr_update_read_handler;
1465 return chr;
1469 #ifdef _WIN32
1471 static void socket_cleanup(void)
1473 WSACleanup();
1476 static int socket_init(void)
1478 WSADATA Data;
1479 int ret, err;
1481 ret = WSAStartup(MAKEWORD(2,2), &Data);
1482 if (ret != 0) {
1483 err = WSAGetLastError();
1484 fprintf(stderr, "WSAStartup: %d\n", err);
1485 return -1;
1487 atexit(socket_cleanup);
1488 return 0;
1491 static int send_all(int fd, const uint8_t *buf, int len1)
1493 int ret, len;
1495 len = len1;
1496 while (len > 0) {
1497 ret = send(fd, buf, len, 0);
1498 if (ret < 0) {
1499 int errno;
1500 errno = WSAGetLastError();
1501 if (errno != WSAEWOULDBLOCK) {
1502 return -1;
1504 } else if (ret == 0) {
1505 break;
1506 } else {
1507 buf += ret;
1508 len -= ret;
1511 return len1 - len;
1514 void socket_set_nonblock(int fd)
1516 unsigned long opt = 1;
1517 ioctlsocket(fd, FIONBIO, &opt);
1520 #else
1522 static int unix_write(int fd, const uint8_t *buf, int len1)
1524 int ret, len;
1526 len = len1;
1527 while (len > 0) {
1528 ret = write(fd, buf, len);
1529 if (ret < 0) {
1530 if (errno != EINTR && errno != EAGAIN)
1531 return -1;
1532 } else if (ret == 0) {
1533 break;
1534 } else {
1535 buf += ret;
1536 len -= ret;
1539 return len1 - len;
1542 static inline int send_all(int fd, const uint8_t *buf, int len1)
1544 return unix_write(fd, buf, len1);
1547 void socket_set_nonblock(int fd)
1549 fcntl(fd, F_SETFL, O_NONBLOCK);
1551 #endif /* !_WIN32 */
1553 #ifndef _WIN32
1555 typedef struct {
1556 int fd_in, fd_out;
1557 int max_size;
1558 } FDCharDriver;
1560 #define STDIO_MAX_CLIENTS 1
1561 static int stdio_nb_clients = 0;
1563 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1565 FDCharDriver *s = chr->opaque;
1566 return unix_write(s->fd_out, buf, len);
1569 static int fd_chr_read_poll(void *opaque)
1571 CharDriverState *chr = opaque;
1572 FDCharDriver *s = chr->opaque;
1574 s->max_size = qemu_chr_can_read(chr);
1575 return s->max_size;
1578 static void fd_chr_read(void *opaque)
1580 CharDriverState *chr = opaque;
1581 FDCharDriver *s = chr->opaque;
1582 int size, len;
1583 uint8_t buf[1024];
1585 len = sizeof(buf);
1586 if (len > s->max_size)
1587 len = s->max_size;
1588 if (len == 0)
1589 return;
1590 size = read(s->fd_in, buf, len);
1591 if (size == 0) {
1592 /* FD has been closed. Remove it from the active list. */
1593 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1594 return;
1596 if (size > 0) {
1597 qemu_chr_read(chr, buf, size);
1601 static void fd_chr_update_read_handler(CharDriverState *chr)
1603 FDCharDriver *s = chr->opaque;
1605 if (s->fd_in >= 0) {
1606 if (nographic && s->fd_in == 0) {
1607 } else {
1608 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1609 fd_chr_read, NULL, chr);
1614 /* open a character device to a unix fd */
1615 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1617 CharDriverState *chr;
1618 FDCharDriver *s;
1620 chr = qemu_mallocz(sizeof(CharDriverState));
1621 if (!chr)
1622 return NULL;
1623 s = qemu_mallocz(sizeof(FDCharDriver));
1624 if (!s) {
1625 free(chr);
1626 return NULL;
1628 s->fd_in = fd_in;
1629 s->fd_out = fd_out;
1630 chr->opaque = s;
1631 chr->chr_write = fd_chr_write;
1632 chr->chr_update_read_handler = fd_chr_update_read_handler;
1634 qemu_chr_reset(chr);
1636 return chr;
1639 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1641 int fd_out;
1643 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1644 if (fd_out < 0)
1645 return NULL;
1646 return qemu_chr_open_fd(-1, fd_out);
1649 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1651 int fd_in, fd_out;
1652 char filename_in[256], filename_out[256];
1654 snprintf(filename_in, 256, "%s.in", filename);
1655 snprintf(filename_out, 256, "%s.out", filename);
1656 fd_in = open(filename_in, O_RDWR | O_BINARY);
1657 fd_out = open(filename_out, O_RDWR | O_BINARY);
1658 if (fd_in < 0 || fd_out < 0) {
1659 if (fd_in >= 0)
1660 close(fd_in);
1661 if (fd_out >= 0)
1662 close(fd_out);
1663 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1664 if (fd_in < 0)
1665 return NULL;
1667 return qemu_chr_open_fd(fd_in, fd_out);
1671 /* for STDIO, we handle the case where several clients use it
1672 (nographic mode) */
1674 #define TERM_FIFO_MAX_SIZE 1
1676 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1677 static int term_fifo_size;
1679 static int stdio_read_poll(void *opaque)
1681 CharDriverState *chr = opaque;
1683 /* try to flush the queue if needed */
1684 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1685 qemu_chr_read(chr, term_fifo, 1);
1686 term_fifo_size = 0;
1688 /* see if we can absorb more chars */
1689 if (term_fifo_size == 0)
1690 return 1;
1691 else
1692 return 0;
1695 static void stdio_read(void *opaque)
1697 int size;
1698 uint8_t buf[1];
1699 CharDriverState *chr = opaque;
1701 size = read(0, buf, 1);
1702 if (size == 0) {
1703 /* stdin has been closed. Remove it from the active list. */
1704 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1705 return;
1707 if (size > 0) {
1708 if (qemu_chr_can_read(chr) > 0) {
1709 qemu_chr_read(chr, buf, 1);
1710 } else if (term_fifo_size == 0) {
1711 term_fifo[term_fifo_size++] = buf[0];
1716 /* init terminal so that we can grab keys */
1717 static struct termios oldtty;
1718 static int old_fd0_flags;
1720 static void term_exit(void)
1722 tcsetattr (0, TCSANOW, &oldtty);
1723 fcntl(0, F_SETFL, old_fd0_flags);
1726 static void term_init(void)
1728 struct termios tty;
1730 tcgetattr (0, &tty);
1731 oldtty = tty;
1732 old_fd0_flags = fcntl(0, F_GETFL);
1734 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1735 |INLCR|IGNCR|ICRNL|IXON);
1736 tty.c_oflag |= OPOST;
1737 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1738 /* if graphical mode, we allow Ctrl-C handling */
1739 if (nographic)
1740 tty.c_lflag &= ~ISIG;
1741 tty.c_cflag &= ~(CSIZE|PARENB);
1742 tty.c_cflag |= CS8;
1743 tty.c_cc[VMIN] = 1;
1744 tty.c_cc[VTIME] = 0;
1746 tcsetattr (0, TCSANOW, &tty);
1748 atexit(term_exit);
1750 fcntl(0, F_SETFL, O_NONBLOCK);
1753 static CharDriverState *qemu_chr_open_stdio(void)
1755 CharDriverState *chr;
1757 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1758 return NULL;
1759 chr = qemu_chr_open_fd(0, 1);
1760 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1761 stdio_nb_clients++;
1762 term_init();
1764 return chr;
1767 #if defined(__linux__) || defined(__sun__)
1768 static CharDriverState *qemu_chr_open_pty(void)
1770 struct termios tty;
1771 char slave_name[1024];
1772 int master_fd, slave_fd;
1774 #if defined(__linux__)
1775 /* Not satisfying */
1776 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1777 return NULL;
1779 #endif
1781 /* Disabling local echo and line-buffered output */
1782 tcgetattr (master_fd, &tty);
1783 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1784 tty.c_cc[VMIN] = 1;
1785 tty.c_cc[VTIME] = 0;
1786 tcsetattr (master_fd, TCSAFLUSH, &tty);
1788 fprintf(stderr, "char device redirected to %s\n", slave_name);
1789 return qemu_chr_open_fd(master_fd, master_fd);
1792 static void tty_serial_init(int fd, int speed,
1793 int parity, int data_bits, int stop_bits)
1795 struct termios tty;
1796 speed_t spd;
1798 #if 0
1799 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1800 speed, parity, data_bits, stop_bits);
1801 #endif
1802 tcgetattr (fd, &tty);
1804 switch(speed) {
1805 case 50:
1806 spd = B50;
1807 break;
1808 case 75:
1809 spd = B75;
1810 break;
1811 case 300:
1812 spd = B300;
1813 break;
1814 case 600:
1815 spd = B600;
1816 break;
1817 case 1200:
1818 spd = B1200;
1819 break;
1820 case 2400:
1821 spd = B2400;
1822 break;
1823 case 4800:
1824 spd = B4800;
1825 break;
1826 case 9600:
1827 spd = B9600;
1828 break;
1829 case 19200:
1830 spd = B19200;
1831 break;
1832 case 38400:
1833 spd = B38400;
1834 break;
1835 case 57600:
1836 spd = B57600;
1837 break;
1838 default:
1839 case 115200:
1840 spd = B115200;
1841 break;
1844 cfsetispeed(&tty, spd);
1845 cfsetospeed(&tty, spd);
1847 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1848 |INLCR|IGNCR|ICRNL|IXON);
1849 tty.c_oflag |= OPOST;
1850 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1851 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1852 switch(data_bits) {
1853 default:
1854 case 8:
1855 tty.c_cflag |= CS8;
1856 break;
1857 case 7:
1858 tty.c_cflag |= CS7;
1859 break;
1860 case 6:
1861 tty.c_cflag |= CS6;
1862 break;
1863 case 5:
1864 tty.c_cflag |= CS5;
1865 break;
1867 switch(parity) {
1868 default:
1869 case 'N':
1870 break;
1871 case 'E':
1872 tty.c_cflag |= PARENB;
1873 break;
1874 case 'O':
1875 tty.c_cflag |= PARENB | PARODD;
1876 break;
1878 if (stop_bits == 2)
1879 tty.c_cflag |= CSTOPB;
1881 tcsetattr (fd, TCSANOW, &tty);
1884 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1886 FDCharDriver *s = chr->opaque;
1888 switch(cmd) {
1889 case CHR_IOCTL_SERIAL_SET_PARAMS:
1891 QEMUSerialSetParams *ssp = arg;
1892 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1893 ssp->data_bits, ssp->stop_bits);
1895 break;
1896 case CHR_IOCTL_SERIAL_SET_BREAK:
1898 int enable = *(int *)arg;
1899 if (enable)
1900 tcsendbreak(s->fd_in, 1);
1902 break;
1903 default:
1904 return -ENOTSUP;
1906 return 0;
1909 static CharDriverState *qemu_chr_open_tty(const char *filename)
1911 CharDriverState *chr;
1912 int fd;
1914 fd = open(filename, O_RDWR | O_NONBLOCK);
1915 if (fd < 0)
1916 return NULL;
1917 fcntl(fd, F_SETFL, O_NONBLOCK);
1918 tty_serial_init(fd, 115200, 'N', 8, 1);
1919 chr = qemu_chr_open_fd(fd, fd);
1920 if (!chr)
1921 return NULL;
1922 chr->chr_ioctl = tty_serial_ioctl;
1923 qemu_chr_reset(chr);
1924 return chr;
1926 #else /* ! __linux__ && ! __sun__ */
1927 static CharDriverState *qemu_chr_open_pty(void)
1929 return NULL;
1931 #endif /* __linux__ || __sun__ */
1933 #if defined(__linux__)
1934 typedef struct {
1935 int fd;
1936 int mode;
1937 } ParallelCharDriver;
1939 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1941 if (s->mode != mode) {
1942 int m = mode;
1943 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1944 return 0;
1945 s->mode = mode;
1947 return 1;
1950 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1952 ParallelCharDriver *drv = chr->opaque;
1953 int fd = drv->fd;
1954 uint8_t b;
1956 switch(cmd) {
1957 case CHR_IOCTL_PP_READ_DATA:
1958 if (ioctl(fd, PPRDATA, &b) < 0)
1959 return -ENOTSUP;
1960 *(uint8_t *)arg = b;
1961 break;
1962 case CHR_IOCTL_PP_WRITE_DATA:
1963 b = *(uint8_t *)arg;
1964 if (ioctl(fd, PPWDATA, &b) < 0)
1965 return -ENOTSUP;
1966 break;
1967 case CHR_IOCTL_PP_READ_CONTROL:
1968 if (ioctl(fd, PPRCONTROL, &b) < 0)
1969 return -ENOTSUP;
1970 /* Linux gives only the lowest bits, and no way to know data
1971 direction! For better compatibility set the fixed upper
1972 bits. */
1973 *(uint8_t *)arg = b | 0xc0;
1974 break;
1975 case CHR_IOCTL_PP_WRITE_CONTROL:
1976 b = *(uint8_t *)arg;
1977 if (ioctl(fd, PPWCONTROL, &b) < 0)
1978 return -ENOTSUP;
1979 break;
1980 case CHR_IOCTL_PP_READ_STATUS:
1981 if (ioctl(fd, PPRSTATUS, &b) < 0)
1982 return -ENOTSUP;
1983 *(uint8_t *)arg = b;
1984 break;
1985 case CHR_IOCTL_PP_EPP_READ_ADDR:
1986 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1987 struct ParallelIOArg *parg = arg;
1988 int n = read(fd, parg->buffer, parg->count);
1989 if (n != parg->count) {
1990 return -EIO;
1993 break;
1994 case CHR_IOCTL_PP_EPP_READ:
1995 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1996 struct ParallelIOArg *parg = arg;
1997 int n = read(fd, parg->buffer, parg->count);
1998 if (n != parg->count) {
1999 return -EIO;
2002 break;
2003 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2004 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2005 struct ParallelIOArg *parg = arg;
2006 int n = write(fd, parg->buffer, parg->count);
2007 if (n != parg->count) {
2008 return -EIO;
2011 break;
2012 case CHR_IOCTL_PP_EPP_WRITE:
2013 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2014 struct ParallelIOArg *parg = arg;
2015 int n = write(fd, parg->buffer, parg->count);
2016 if (n != parg->count) {
2017 return -EIO;
2020 break;
2021 default:
2022 return -ENOTSUP;
2024 return 0;
2027 static void pp_close(CharDriverState *chr)
2029 ParallelCharDriver *drv = chr->opaque;
2030 int fd = drv->fd;
2032 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2033 ioctl(fd, PPRELEASE);
2034 close(fd);
2035 qemu_free(drv);
2038 static CharDriverState *qemu_chr_open_pp(const char *filename)
2040 CharDriverState *chr;
2041 ParallelCharDriver *drv;
2042 int fd;
2044 fd = open(filename, O_RDWR);
2045 if (fd < 0)
2046 return NULL;
2048 if (ioctl(fd, PPCLAIM) < 0) {
2049 close(fd);
2050 return NULL;
2053 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2054 if (!drv) {
2055 close(fd);
2056 return NULL;
2058 drv->fd = fd;
2059 drv->mode = IEEE1284_MODE_COMPAT;
2061 chr = qemu_mallocz(sizeof(CharDriverState));
2062 if (!chr) {
2063 qemu_free(drv);
2064 close(fd);
2065 return NULL;
2067 chr->chr_write = null_chr_write;
2068 chr->chr_ioctl = pp_ioctl;
2069 chr->chr_close = pp_close;
2070 chr->opaque = drv;
2072 qemu_chr_reset(chr);
2074 return chr;
2076 #endif /* __linux__ */
2078 #else /* _WIN32 */
2080 typedef struct {
2081 int max_size;
2082 HANDLE hcom, hrecv, hsend;
2083 OVERLAPPED orecv, osend;
2084 BOOL fpipe;
2085 DWORD len;
2086 } WinCharState;
2088 #define NSENDBUF 2048
2089 #define NRECVBUF 2048
2090 #define MAXCONNECT 1
2091 #define NTIMEOUT 5000
2093 static int win_chr_poll(void *opaque);
2094 static int win_chr_pipe_poll(void *opaque);
2096 static void win_chr_close(CharDriverState *chr)
2098 WinCharState *s = chr->opaque;
2100 if (s->hsend) {
2101 CloseHandle(s->hsend);
2102 s->hsend = NULL;
2104 if (s->hrecv) {
2105 CloseHandle(s->hrecv);
2106 s->hrecv = NULL;
2108 if (s->hcom) {
2109 CloseHandle(s->hcom);
2110 s->hcom = NULL;
2112 if (s->fpipe)
2113 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2114 else
2115 qemu_del_polling_cb(win_chr_poll, chr);
2118 static int win_chr_init(CharDriverState *chr, const char *filename)
2120 WinCharState *s = chr->opaque;
2121 COMMCONFIG comcfg;
2122 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2123 COMSTAT comstat;
2124 DWORD size;
2125 DWORD err;
2127 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2128 if (!s->hsend) {
2129 fprintf(stderr, "Failed CreateEvent\n");
2130 goto fail;
2132 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2133 if (!s->hrecv) {
2134 fprintf(stderr, "Failed CreateEvent\n");
2135 goto fail;
2138 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2139 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2140 if (s->hcom == INVALID_HANDLE_VALUE) {
2141 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2142 s->hcom = NULL;
2143 goto fail;
2146 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2147 fprintf(stderr, "Failed SetupComm\n");
2148 goto fail;
2151 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2152 size = sizeof(COMMCONFIG);
2153 GetDefaultCommConfig(filename, &comcfg, &size);
2154 comcfg.dcb.DCBlength = sizeof(DCB);
2155 CommConfigDialog(filename, NULL, &comcfg);
2157 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2158 fprintf(stderr, "Failed SetCommState\n");
2159 goto fail;
2162 if (!SetCommMask(s->hcom, EV_ERR)) {
2163 fprintf(stderr, "Failed SetCommMask\n");
2164 goto fail;
2167 cto.ReadIntervalTimeout = MAXDWORD;
2168 if (!SetCommTimeouts(s->hcom, &cto)) {
2169 fprintf(stderr, "Failed SetCommTimeouts\n");
2170 goto fail;
2173 if (!ClearCommError(s->hcom, &err, &comstat)) {
2174 fprintf(stderr, "Failed ClearCommError\n");
2175 goto fail;
2177 qemu_add_polling_cb(win_chr_poll, chr);
2178 return 0;
2180 fail:
2181 win_chr_close(chr);
2182 return -1;
2185 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2187 WinCharState *s = chr->opaque;
2188 DWORD len, ret, size, err;
2190 len = len1;
2191 ZeroMemory(&s->osend, sizeof(s->osend));
2192 s->osend.hEvent = s->hsend;
2193 while (len > 0) {
2194 if (s->hsend)
2195 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2196 else
2197 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2198 if (!ret) {
2199 err = GetLastError();
2200 if (err == ERROR_IO_PENDING) {
2201 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2202 if (ret) {
2203 buf += size;
2204 len -= size;
2205 } else {
2206 break;
2208 } else {
2209 break;
2211 } else {
2212 buf += size;
2213 len -= size;
2216 return len1 - len;
2219 static int win_chr_read_poll(CharDriverState *chr)
2221 WinCharState *s = chr->opaque;
2223 s->max_size = qemu_chr_can_read(chr);
2224 return s->max_size;
2227 static void win_chr_readfile(CharDriverState *chr)
2229 WinCharState *s = chr->opaque;
2230 int ret, err;
2231 uint8_t buf[1024];
2232 DWORD size;
2234 ZeroMemory(&s->orecv, sizeof(s->orecv));
2235 s->orecv.hEvent = s->hrecv;
2236 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2237 if (!ret) {
2238 err = GetLastError();
2239 if (err == ERROR_IO_PENDING) {
2240 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2244 if (size > 0) {
2245 qemu_chr_read(chr, buf, size);
2249 static void win_chr_read(CharDriverState *chr)
2251 WinCharState *s = chr->opaque;
2253 if (s->len > s->max_size)
2254 s->len = s->max_size;
2255 if (s->len == 0)
2256 return;
2258 win_chr_readfile(chr);
2261 static int win_chr_poll(void *opaque)
2263 CharDriverState *chr = opaque;
2264 WinCharState *s = chr->opaque;
2265 COMSTAT status;
2266 DWORD comerr;
2268 ClearCommError(s->hcom, &comerr, &status);
2269 if (status.cbInQue > 0) {
2270 s->len = status.cbInQue;
2271 win_chr_read_poll(chr);
2272 win_chr_read(chr);
2273 return 1;
2275 return 0;
2278 static CharDriverState *qemu_chr_open_win(const char *filename)
2280 CharDriverState *chr;
2281 WinCharState *s;
2283 chr = qemu_mallocz(sizeof(CharDriverState));
2284 if (!chr)
2285 return NULL;
2286 s = qemu_mallocz(sizeof(WinCharState));
2287 if (!s) {
2288 free(chr);
2289 return NULL;
2291 chr->opaque = s;
2292 chr->chr_write = win_chr_write;
2293 chr->chr_close = win_chr_close;
2295 if (win_chr_init(chr, filename) < 0) {
2296 free(s);
2297 free(chr);
2298 return NULL;
2300 qemu_chr_reset(chr);
2301 return chr;
2304 static int win_chr_pipe_poll(void *opaque)
2306 CharDriverState *chr = opaque;
2307 WinCharState *s = chr->opaque;
2308 DWORD size;
2310 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2311 if (size > 0) {
2312 s->len = size;
2313 win_chr_read_poll(chr);
2314 win_chr_read(chr);
2315 return 1;
2317 return 0;
2320 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2322 WinCharState *s = chr->opaque;
2323 OVERLAPPED ov;
2324 int ret;
2325 DWORD size;
2326 char openname[256];
2328 s->fpipe = TRUE;
2330 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2331 if (!s->hsend) {
2332 fprintf(stderr, "Failed CreateEvent\n");
2333 goto fail;
2335 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2336 if (!s->hrecv) {
2337 fprintf(stderr, "Failed CreateEvent\n");
2338 goto fail;
2341 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2342 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2343 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2344 PIPE_WAIT,
2345 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2346 if (s->hcom == INVALID_HANDLE_VALUE) {
2347 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2348 s->hcom = NULL;
2349 goto fail;
2352 ZeroMemory(&ov, sizeof(ov));
2353 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2354 ret = ConnectNamedPipe(s->hcom, &ov);
2355 if (ret) {
2356 fprintf(stderr, "Failed ConnectNamedPipe\n");
2357 goto fail;
2360 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2361 if (!ret) {
2362 fprintf(stderr, "Failed GetOverlappedResult\n");
2363 if (ov.hEvent) {
2364 CloseHandle(ov.hEvent);
2365 ov.hEvent = NULL;
2367 goto fail;
2370 if (ov.hEvent) {
2371 CloseHandle(ov.hEvent);
2372 ov.hEvent = NULL;
2374 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2375 return 0;
2377 fail:
2378 win_chr_close(chr);
2379 return -1;
2383 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2385 CharDriverState *chr;
2386 WinCharState *s;
2388 chr = qemu_mallocz(sizeof(CharDriverState));
2389 if (!chr)
2390 return NULL;
2391 s = qemu_mallocz(sizeof(WinCharState));
2392 if (!s) {
2393 free(chr);
2394 return NULL;
2396 chr->opaque = s;
2397 chr->chr_write = win_chr_write;
2398 chr->chr_close = win_chr_close;
2400 if (win_chr_pipe_init(chr, filename) < 0) {
2401 free(s);
2402 free(chr);
2403 return NULL;
2405 qemu_chr_reset(chr);
2406 return chr;
2409 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2411 CharDriverState *chr;
2412 WinCharState *s;
2414 chr = qemu_mallocz(sizeof(CharDriverState));
2415 if (!chr)
2416 return NULL;
2417 s = qemu_mallocz(sizeof(WinCharState));
2418 if (!s) {
2419 free(chr);
2420 return NULL;
2422 s->hcom = fd_out;
2423 chr->opaque = s;
2424 chr->chr_write = win_chr_write;
2425 qemu_chr_reset(chr);
2426 return chr;
2429 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2431 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2434 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2436 HANDLE fd_out;
2438 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2439 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2440 if (fd_out == INVALID_HANDLE_VALUE)
2441 return NULL;
2443 return qemu_chr_open_win_file(fd_out);
2445 #endif /* !_WIN32 */
2447 /***********************************************************/
2448 /* UDP Net console */
2450 typedef struct {
2451 int fd;
2452 struct sockaddr_in daddr;
2453 char buf[1024];
2454 int bufcnt;
2455 int bufptr;
2456 int max_size;
2457 } NetCharDriver;
2459 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2461 NetCharDriver *s = chr->opaque;
2463 return sendto(s->fd, buf, len, 0,
2464 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2467 static int udp_chr_read_poll(void *opaque)
2469 CharDriverState *chr = opaque;
2470 NetCharDriver *s = chr->opaque;
2472 s->max_size = qemu_chr_can_read(chr);
2474 /* If there were any stray characters in the queue process them
2475 * first
2477 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2478 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2479 s->bufptr++;
2480 s->max_size = qemu_chr_can_read(chr);
2482 return s->max_size;
2485 static void udp_chr_read(void *opaque)
2487 CharDriverState *chr = opaque;
2488 NetCharDriver *s = chr->opaque;
2490 if (s->max_size == 0)
2491 return;
2492 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2493 s->bufptr = s->bufcnt;
2494 if (s->bufcnt <= 0)
2495 return;
2497 s->bufptr = 0;
2498 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2499 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2500 s->bufptr++;
2501 s->max_size = qemu_chr_can_read(chr);
2505 static void udp_chr_update_read_handler(CharDriverState *chr)
2507 NetCharDriver *s = chr->opaque;
2509 if (s->fd >= 0) {
2510 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2511 udp_chr_read, NULL, chr);
2515 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2516 #ifndef _WIN32
2517 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2518 #endif
2519 int parse_host_src_port(struct sockaddr_in *haddr,
2520 struct sockaddr_in *saddr,
2521 const char *str);
2523 static CharDriverState *qemu_chr_open_udp(const char *def)
2525 CharDriverState *chr = NULL;
2526 NetCharDriver *s = NULL;
2527 int fd = -1;
2528 struct sockaddr_in saddr;
2530 chr = qemu_mallocz(sizeof(CharDriverState));
2531 if (!chr)
2532 goto return_err;
2533 s = qemu_mallocz(sizeof(NetCharDriver));
2534 if (!s)
2535 goto return_err;
2537 fd = socket(PF_INET, SOCK_DGRAM, 0);
2538 if (fd < 0) {
2539 perror("socket(PF_INET, SOCK_DGRAM)");
2540 goto return_err;
2543 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2544 printf("Could not parse: %s\n", def);
2545 goto return_err;
2548 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2550 perror("bind");
2551 goto return_err;
2554 s->fd = fd;
2555 s->bufcnt = 0;
2556 s->bufptr = 0;
2557 chr->opaque = s;
2558 chr->chr_write = udp_chr_write;
2559 chr->chr_update_read_handler = udp_chr_update_read_handler;
2560 return chr;
2562 return_err:
2563 if (chr)
2564 free(chr);
2565 if (s)
2566 free(s);
2567 if (fd >= 0)
2568 closesocket(fd);
2569 return NULL;
2572 /***********************************************************/
2573 /* TCP Net console */
2575 typedef struct {
2576 int fd, listen_fd;
2577 int connected;
2578 int max_size;
2579 int do_telnetopt;
2580 int do_nodelay;
2581 int is_unix;
2582 } TCPCharDriver;
2584 static void tcp_chr_accept(void *opaque);
2586 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2588 TCPCharDriver *s = chr->opaque;
2589 if (s->connected) {
2590 return send_all(s->fd, buf, len);
2591 } else {
2592 /* XXX: indicate an error ? */
2593 return len;
2597 static int tcp_chr_read_poll(void *opaque)
2599 CharDriverState *chr = opaque;
2600 TCPCharDriver *s = chr->opaque;
2601 if (!s->connected)
2602 return 0;
2603 s->max_size = qemu_chr_can_read(chr);
2604 return s->max_size;
2607 #define IAC 255
2608 #define IAC_BREAK 243
2609 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2610 TCPCharDriver *s,
2611 char *buf, int *size)
2613 /* Handle any telnet client's basic IAC options to satisfy char by
2614 * char mode with no echo. All IAC options will be removed from
2615 * the buf and the do_telnetopt variable will be used to track the
2616 * state of the width of the IAC information.
2618 * IAC commands come in sets of 3 bytes with the exception of the
2619 * "IAC BREAK" command and the double IAC.
2622 int i;
2623 int j = 0;
2625 for (i = 0; i < *size; i++) {
2626 if (s->do_telnetopt > 1) {
2627 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2628 /* Double IAC means send an IAC */
2629 if (j != i)
2630 buf[j] = buf[i];
2631 j++;
2632 s->do_telnetopt = 1;
2633 } else {
2634 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2635 /* Handle IAC break commands by sending a serial break */
2636 qemu_chr_event(chr, CHR_EVENT_BREAK);
2637 s->do_telnetopt++;
2639 s->do_telnetopt++;
2641 if (s->do_telnetopt >= 4) {
2642 s->do_telnetopt = 1;
2644 } else {
2645 if ((unsigned char)buf[i] == IAC) {
2646 s->do_telnetopt = 2;
2647 } else {
2648 if (j != i)
2649 buf[j] = buf[i];
2650 j++;
2654 *size = j;
2657 static void tcp_chr_read(void *opaque)
2659 CharDriverState *chr = opaque;
2660 TCPCharDriver *s = chr->opaque;
2661 uint8_t buf[1024];
2662 int len, size;
2664 if (!s->connected || s->max_size <= 0)
2665 return;
2666 len = sizeof(buf);
2667 if (len > s->max_size)
2668 len = s->max_size;
2669 size = recv(s->fd, buf, len, 0);
2670 if (size == 0) {
2671 /* connection closed */
2672 s->connected = 0;
2673 if (s->listen_fd >= 0) {
2674 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2676 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2677 closesocket(s->fd);
2678 s->fd = -1;
2679 } else if (size > 0) {
2680 if (s->do_telnetopt)
2681 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2682 if (size > 0)
2683 qemu_chr_read(chr, buf, size);
2687 static void tcp_chr_connect(void *opaque)
2689 CharDriverState *chr = opaque;
2690 TCPCharDriver *s = chr->opaque;
2692 s->connected = 1;
2693 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2694 tcp_chr_read, NULL, chr);
2695 qemu_chr_reset(chr);
2698 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2699 static void tcp_chr_telnet_init(int fd)
2701 char buf[3];
2702 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2703 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2704 send(fd, (char *)buf, 3, 0);
2705 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2706 send(fd, (char *)buf, 3, 0);
2707 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2708 send(fd, (char *)buf, 3, 0);
2709 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2710 send(fd, (char *)buf, 3, 0);
2713 static void socket_set_nodelay(int fd)
2715 int val = 1;
2716 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2719 static void tcp_chr_accept(void *opaque)
2721 CharDriverState *chr = opaque;
2722 TCPCharDriver *s = chr->opaque;
2723 struct sockaddr_in saddr;
2724 #ifndef _WIN32
2725 struct sockaddr_un uaddr;
2726 #endif
2727 struct sockaddr *addr;
2728 socklen_t len;
2729 int fd;
2731 for(;;) {
2732 #ifndef _WIN32
2733 if (s->is_unix) {
2734 len = sizeof(uaddr);
2735 addr = (struct sockaddr *)&uaddr;
2736 } else
2737 #endif
2739 len = sizeof(saddr);
2740 addr = (struct sockaddr *)&saddr;
2742 fd = accept(s->listen_fd, addr, &len);
2743 if (fd < 0 && errno != EINTR) {
2744 return;
2745 } else if (fd >= 0) {
2746 if (s->do_telnetopt)
2747 tcp_chr_telnet_init(fd);
2748 break;
2751 socket_set_nonblock(fd);
2752 if (s->do_nodelay)
2753 socket_set_nodelay(fd);
2754 s->fd = fd;
2755 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2756 tcp_chr_connect(chr);
2759 static void tcp_chr_close(CharDriverState *chr)
2761 TCPCharDriver *s = chr->opaque;
2762 if (s->fd >= 0)
2763 closesocket(s->fd);
2764 if (s->listen_fd >= 0)
2765 closesocket(s->listen_fd);
2766 qemu_free(s);
2769 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2770 int is_telnet,
2771 int is_unix)
2773 CharDriverState *chr = NULL;
2774 TCPCharDriver *s = NULL;
2775 int fd = -1, ret, err, val;
2776 int is_listen = 0;
2777 int is_waitconnect = 1;
2778 int do_nodelay = 0;
2779 const char *ptr;
2780 struct sockaddr_in saddr;
2781 #ifndef _WIN32
2782 struct sockaddr_un uaddr;
2783 #endif
2784 struct sockaddr *addr;
2785 socklen_t addrlen;
2787 #ifndef _WIN32
2788 if (is_unix) {
2789 addr = (struct sockaddr *)&uaddr;
2790 addrlen = sizeof(uaddr);
2791 if (parse_unix_path(&uaddr, host_str) < 0)
2792 goto fail;
2793 } else
2794 #endif
2796 addr = (struct sockaddr *)&saddr;
2797 addrlen = sizeof(saddr);
2798 if (parse_host_port(&saddr, host_str) < 0)
2799 goto fail;
2802 ptr = host_str;
2803 while((ptr = strchr(ptr,','))) {
2804 ptr++;
2805 if (!strncmp(ptr,"server",6)) {
2806 is_listen = 1;
2807 } else if (!strncmp(ptr,"nowait",6)) {
2808 is_waitconnect = 0;
2809 } else if (!strncmp(ptr,"nodelay",6)) {
2810 do_nodelay = 1;
2811 } else {
2812 printf("Unknown option: %s\n", ptr);
2813 goto fail;
2816 if (!is_listen)
2817 is_waitconnect = 0;
2819 chr = qemu_mallocz(sizeof(CharDriverState));
2820 if (!chr)
2821 goto fail;
2822 s = qemu_mallocz(sizeof(TCPCharDriver));
2823 if (!s)
2824 goto fail;
2826 #ifndef _WIN32
2827 if (is_unix)
2828 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2829 else
2830 #endif
2831 fd = socket(PF_INET, SOCK_STREAM, 0);
2833 if (fd < 0)
2834 goto fail;
2836 if (!is_waitconnect)
2837 socket_set_nonblock(fd);
2839 s->connected = 0;
2840 s->fd = -1;
2841 s->listen_fd = -1;
2842 s->is_unix = is_unix;
2843 s->do_nodelay = do_nodelay && !is_unix;
2845 chr->opaque = s;
2846 chr->chr_write = tcp_chr_write;
2847 chr->chr_close = tcp_chr_close;
2849 if (is_listen) {
2850 /* allow fast reuse */
2851 #ifndef _WIN32
2852 if (is_unix) {
2853 char path[109];
2854 strncpy(path, uaddr.sun_path, 108);
2855 path[108] = 0;
2856 unlink(path);
2857 } else
2858 #endif
2860 val = 1;
2861 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2864 ret = bind(fd, addr, addrlen);
2865 if (ret < 0)
2866 goto fail;
2868 ret = listen(fd, 0);
2869 if (ret < 0)
2870 goto fail;
2872 s->listen_fd = fd;
2873 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2874 if (is_telnet)
2875 s->do_telnetopt = 1;
2876 } else {
2877 for(;;) {
2878 ret = connect(fd, addr, addrlen);
2879 if (ret < 0) {
2880 err = socket_error();
2881 if (err == EINTR || err == EWOULDBLOCK) {
2882 } else if (err == EINPROGRESS) {
2883 break;
2884 #ifdef _WIN32
2885 } else if (err == WSAEALREADY) {
2886 break;
2887 #endif
2888 } else {
2889 goto fail;
2891 } else {
2892 s->connected = 1;
2893 break;
2896 s->fd = fd;
2897 socket_set_nodelay(fd);
2898 if (s->connected)
2899 tcp_chr_connect(chr);
2900 else
2901 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2904 if (is_listen && is_waitconnect) {
2905 printf("QEMU waiting for connection on: %s\n", host_str);
2906 tcp_chr_accept(chr);
2907 socket_set_nonblock(s->listen_fd);
2910 return chr;
2911 fail:
2912 if (fd >= 0)
2913 closesocket(fd);
2914 qemu_free(s);
2915 qemu_free(chr);
2916 return NULL;
2919 CharDriverState *qemu_chr_open(const char *filename)
2921 const char *p;
2923 if (!strcmp(filename, "vc")) {
2924 return text_console_init(&display_state);
2925 } else if (!strcmp(filename, "null")) {
2926 return qemu_chr_open_null();
2927 } else
2928 if (strstart(filename, "tcp:", &p)) {
2929 return qemu_chr_open_tcp(p, 0, 0);
2930 } else
2931 if (strstart(filename, "telnet:", &p)) {
2932 return qemu_chr_open_tcp(p, 1, 0);
2933 } else
2934 if (strstart(filename, "udp:", &p)) {
2935 return qemu_chr_open_udp(p);
2936 } else
2937 if (strstart(filename, "mon:", &p)) {
2938 CharDriverState *drv = qemu_chr_open(p);
2939 if (drv) {
2940 drv = qemu_chr_open_mux(drv);
2941 monitor_init(drv, !nographic);
2942 return drv;
2944 printf("Unable to open driver: %s\n", p);
2945 return 0;
2946 } else
2947 #ifndef _WIN32
2948 if (strstart(filename, "unix:", &p)) {
2949 return qemu_chr_open_tcp(p, 0, 1);
2950 } else if (strstart(filename, "file:", &p)) {
2951 return qemu_chr_open_file_out(p);
2952 } else if (strstart(filename, "pipe:", &p)) {
2953 return qemu_chr_open_pipe(p);
2954 } else if (!strcmp(filename, "pty")) {
2955 return qemu_chr_open_pty();
2956 } else if (!strcmp(filename, "stdio")) {
2957 return qemu_chr_open_stdio();
2958 } else
2959 #if defined(__linux__)
2960 if (strstart(filename, "/dev/parport", NULL)) {
2961 return qemu_chr_open_pp(filename);
2962 } else
2963 #endif
2964 if (strstart(filename, "/dev/", NULL)) {
2965 return qemu_chr_open_tty(filename);
2966 } else
2967 #else /* !_WIN32 */
2968 if (strstart(filename, "COM", NULL)) {
2969 return qemu_chr_open_win(filename);
2970 } else
2971 if (strstart(filename, "pipe:", &p)) {
2972 return qemu_chr_open_win_pipe(p);
2973 } else
2974 if (strstart(filename, "con:", NULL)) {
2975 return qemu_chr_open_win_con(filename);
2976 } else
2977 if (strstart(filename, "file:", &p)) {
2978 return qemu_chr_open_win_file_out(p);
2980 #endif
2982 return NULL;
2986 void qemu_chr_close(CharDriverState *chr)
2988 if (chr->chr_close)
2989 chr->chr_close(chr);
2992 /***********************************************************/
2993 /* network device redirectors */
2995 void hex_dump(FILE *f, const uint8_t *buf, int size)
2997 int len, i, j, c;
2999 for(i=0;i<size;i+=16) {
3000 len = size - i;
3001 if (len > 16)
3002 len = 16;
3003 fprintf(f, "%08x ", i);
3004 for(j=0;j<16;j++) {
3005 if (j < len)
3006 fprintf(f, " %02x", buf[i+j]);
3007 else
3008 fprintf(f, " ");
3010 fprintf(f, " ");
3011 for(j=0;j<len;j++) {
3012 c = buf[i+j];
3013 if (c < ' ' || c > '~')
3014 c = '.';
3015 fprintf(f, "%c", c);
3017 fprintf(f, "\n");
3021 static int parse_macaddr(uint8_t *macaddr, const char *p)
3023 int i;
3024 for(i = 0; i < 6; i++) {
3025 macaddr[i] = strtol(p, (char **)&p, 16);
3026 if (i == 5) {
3027 if (*p != '\0')
3028 return -1;
3029 } else {
3030 if (*p != ':')
3031 return -1;
3032 p++;
3035 return 0;
3038 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3040 const char *p, *p1;
3041 int len;
3042 p = *pp;
3043 p1 = strchr(p, sep);
3044 if (!p1)
3045 return -1;
3046 len = p1 - p;
3047 p1++;
3048 if (buf_size > 0) {
3049 if (len > buf_size - 1)
3050 len = buf_size - 1;
3051 memcpy(buf, p, len);
3052 buf[len] = '\0';
3054 *pp = p1;
3055 return 0;
3058 int parse_host_src_port(struct sockaddr_in *haddr,
3059 struct sockaddr_in *saddr,
3060 const char *input_str)
3062 char *str = strdup(input_str);
3063 char *host_str = str;
3064 char *src_str;
3065 char *ptr;
3068 * Chop off any extra arguments at the end of the string which
3069 * would start with a comma, then fill in the src port information
3070 * if it was provided else use the "any address" and "any port".
3072 if ((ptr = strchr(str,',')))
3073 *ptr = '\0';
3075 if ((src_str = strchr(input_str,'@'))) {
3076 *src_str = '\0';
3077 src_str++;
3080 if (parse_host_port(haddr, host_str) < 0)
3081 goto fail;
3083 if (!src_str || *src_str == '\0')
3084 src_str = ":0";
3086 if (parse_host_port(saddr, src_str) < 0)
3087 goto fail;
3089 free(str);
3090 return(0);
3092 fail:
3093 free(str);
3094 return -1;
3097 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3099 char buf[512];
3100 struct hostent *he;
3101 const char *p, *r;
3102 int port;
3104 p = str;
3105 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3106 return -1;
3107 saddr->sin_family = AF_INET;
3108 if (buf[0] == '\0') {
3109 saddr->sin_addr.s_addr = 0;
3110 } else {
3111 if (isdigit(buf[0])) {
3112 if (!inet_aton(buf, &saddr->sin_addr))
3113 return -1;
3114 } else {
3115 if ((he = gethostbyname(buf)) == NULL)
3116 return - 1;
3117 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3120 port = strtol(p, (char **)&r, 0);
3121 if (r == p)
3122 return -1;
3123 saddr->sin_port = htons(port);
3124 return 0;
3127 #ifndef _WIN32
3128 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3130 const char *p;
3131 int len;
3133 len = MIN(108, strlen(str));
3134 p = strchr(str, ',');
3135 if (p)
3136 len = MIN(len, p - str);
3138 memset(uaddr, 0, sizeof(*uaddr));
3140 uaddr->sun_family = AF_UNIX;
3141 memcpy(uaddr->sun_path, str, len);
3143 return 0;
3145 #endif
3147 /* find or alloc a new VLAN */
3148 VLANState *qemu_find_vlan(int id)
3150 VLANState **pvlan, *vlan;
3151 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3152 if (vlan->id == id)
3153 return vlan;
3155 vlan = qemu_mallocz(sizeof(VLANState));
3156 if (!vlan)
3157 return NULL;
3158 vlan->id = id;
3159 vlan->next = NULL;
3160 pvlan = &first_vlan;
3161 while (*pvlan != NULL)
3162 pvlan = &(*pvlan)->next;
3163 *pvlan = vlan;
3164 return vlan;
3167 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3168 IOReadHandler *fd_read,
3169 IOCanRWHandler *fd_can_read,
3170 void *opaque)
3172 VLANClientState *vc, **pvc;
3173 vc = qemu_mallocz(sizeof(VLANClientState));
3174 if (!vc)
3175 return NULL;
3176 vc->fd_read = fd_read;
3177 vc->fd_can_read = fd_can_read;
3178 vc->opaque = opaque;
3179 vc->vlan = vlan;
3181 vc->next = NULL;
3182 pvc = &vlan->first_client;
3183 while (*pvc != NULL)
3184 pvc = &(*pvc)->next;
3185 *pvc = vc;
3186 return vc;
3189 int qemu_can_send_packet(VLANClientState *vc1)
3191 VLANState *vlan = vc1->vlan;
3192 VLANClientState *vc;
3194 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3195 if (vc != vc1) {
3196 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3197 return 0;
3200 return 1;
3203 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3205 VLANState *vlan = vc1->vlan;
3206 VLANClientState *vc;
3208 #if 0
3209 printf("vlan %d send:\n", vlan->id);
3210 hex_dump(stdout, buf, size);
3211 #endif
3212 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3213 if (vc != vc1) {
3214 vc->fd_read(vc->opaque, buf, size);
3219 #if defined(CONFIG_SLIRP)
3221 /* slirp network adapter */
3223 static int slirp_inited;
3224 static VLANClientState *slirp_vc;
3226 int slirp_can_output(void)
3228 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3231 void slirp_output(const uint8_t *pkt, int pkt_len)
3233 #if 0
3234 printf("slirp output:\n");
3235 hex_dump(stdout, pkt, pkt_len);
3236 #endif
3237 if (!slirp_vc)
3238 return;
3239 qemu_send_packet(slirp_vc, pkt, pkt_len);
3242 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3244 #if 0
3245 printf("slirp input:\n");
3246 hex_dump(stdout, buf, size);
3247 #endif
3248 slirp_input(buf, size);
3251 static int net_slirp_init(VLANState *vlan)
3253 if (!slirp_inited) {
3254 slirp_inited = 1;
3255 slirp_init();
3257 slirp_vc = qemu_new_vlan_client(vlan,
3258 slirp_receive, NULL, NULL);
3259 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3260 return 0;
3263 static void net_slirp_redir(const char *redir_str)
3265 int is_udp;
3266 char buf[256], *r;
3267 const char *p;
3268 struct in_addr guest_addr;
3269 int host_port, guest_port;
3271 if (!slirp_inited) {
3272 slirp_inited = 1;
3273 slirp_init();
3276 p = redir_str;
3277 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3278 goto fail;
3279 if (!strcmp(buf, "tcp")) {
3280 is_udp = 0;
3281 } else if (!strcmp(buf, "udp")) {
3282 is_udp = 1;
3283 } else {
3284 goto fail;
3287 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3288 goto fail;
3289 host_port = strtol(buf, &r, 0);
3290 if (r == buf)
3291 goto fail;
3293 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3294 goto fail;
3295 if (buf[0] == '\0') {
3296 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3298 if (!inet_aton(buf, &guest_addr))
3299 goto fail;
3301 guest_port = strtol(p, &r, 0);
3302 if (r == p)
3303 goto fail;
3305 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3306 fprintf(stderr, "qemu: could not set up redirection\n");
3307 exit(1);
3309 return;
3310 fail:
3311 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3312 exit(1);
3315 #ifndef _WIN32
3317 char smb_dir[1024];
3319 static void smb_exit(void)
3321 DIR *d;
3322 struct dirent *de;
3323 char filename[1024];
3325 /* erase all the files in the directory */
3326 d = opendir(smb_dir);
3327 for(;;) {
3328 de = readdir(d);
3329 if (!de)
3330 break;
3331 if (strcmp(de->d_name, ".") != 0 &&
3332 strcmp(de->d_name, "..") != 0) {
3333 snprintf(filename, sizeof(filename), "%s/%s",
3334 smb_dir, de->d_name);
3335 unlink(filename);
3338 closedir(d);
3339 rmdir(smb_dir);
3342 /* automatic user mode samba server configuration */
3343 void net_slirp_smb(const char *exported_dir)
3345 char smb_conf[1024];
3346 char smb_cmdline[1024];
3347 FILE *f;
3349 if (!slirp_inited) {
3350 slirp_inited = 1;
3351 slirp_init();
3354 /* XXX: better tmp dir construction */
3355 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3356 if (mkdir(smb_dir, 0700) < 0) {
3357 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3358 exit(1);
3360 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3362 f = fopen(smb_conf, "w");
3363 if (!f) {
3364 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3365 exit(1);
3367 fprintf(f,
3368 "[global]\n"
3369 "private dir=%s\n"
3370 "smb ports=0\n"
3371 "socket address=127.0.0.1\n"
3372 "pid directory=%s\n"
3373 "lock directory=%s\n"
3374 "log file=%s/log.smbd\n"
3375 "smb passwd file=%s/smbpasswd\n"
3376 "security = share\n"
3377 "[qemu]\n"
3378 "path=%s\n"
3379 "read only=no\n"
3380 "guest ok=yes\n",
3381 smb_dir,
3382 smb_dir,
3383 smb_dir,
3384 smb_dir,
3385 smb_dir,
3386 exported_dir
3388 fclose(f);
3389 atexit(smb_exit);
3391 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3392 SMBD_COMMAND, smb_conf);
3394 slirp_add_exec(0, smb_cmdline, 4, 139);
3397 #endif /* !defined(_WIN32) */
3399 #endif /* CONFIG_SLIRP */
3401 #if !defined(_WIN32)
3403 typedef struct TAPState {
3404 VLANClientState *vc;
3405 int fd;
3406 } TAPState;
3408 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3410 TAPState *s = opaque;
3411 int ret;
3412 for(;;) {
3413 ret = write(s->fd, buf, size);
3414 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3415 } else {
3416 break;
3421 static void tap_send(void *opaque)
3423 TAPState *s = opaque;
3424 uint8_t buf[4096];
3425 int size;
3427 #ifdef __sun__
3428 struct strbuf sbuf;
3429 int f = 0;
3430 sbuf.maxlen = sizeof(buf);
3431 sbuf.buf = buf;
3432 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3433 #else
3434 size = read(s->fd, buf, sizeof(buf));
3435 #endif
3436 if (size > 0) {
3437 qemu_send_packet(s->vc, buf, size);
3441 /* fd support */
3443 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3445 TAPState *s;
3447 s = qemu_mallocz(sizeof(TAPState));
3448 if (!s)
3449 return NULL;
3450 s->fd = fd;
3451 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3452 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3453 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3454 return s;
3457 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3458 static int tap_open(char *ifname, int ifname_size)
3460 int fd;
3461 char *dev;
3462 struct stat s;
3464 fd = open("/dev/tap", O_RDWR);
3465 if (fd < 0) {
3466 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3467 return -1;
3470 fstat(fd, &s);
3471 dev = devname(s.st_rdev, S_IFCHR);
3472 pstrcpy(ifname, ifname_size, dev);
3474 fcntl(fd, F_SETFL, O_NONBLOCK);
3475 return fd;
3477 #elif defined(__sun__)
3478 #define TUNNEWPPA (('T'<<16) | 0x0001)
3480 * Allocate TAP device, returns opened fd.
3481 * Stores dev name in the first arg(must be large enough).
3483 int tap_alloc(char *dev)
3485 int tap_fd, if_fd, ppa = -1;
3486 static int ip_fd = 0;
3487 char *ptr;
3489 static int arp_fd = 0;
3490 int ip_muxid, arp_muxid;
3491 struct strioctl strioc_if, strioc_ppa;
3492 int link_type = I_PLINK;;
3493 struct lifreq ifr;
3494 char actual_name[32] = "";
3496 memset(&ifr, 0x0, sizeof(ifr));
3498 if( *dev ){
3499 ptr = dev;
3500 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3501 ppa = atoi(ptr);
3504 /* Check if IP device was opened */
3505 if( ip_fd )
3506 close(ip_fd);
3508 if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3509 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3510 return -1;
3513 if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3514 syslog(LOG_ERR, "Can't open /dev/tap");
3515 return -1;
3518 /* Assign a new PPA and get its unit number. */
3519 strioc_ppa.ic_cmd = TUNNEWPPA;
3520 strioc_ppa.ic_timout = 0;
3521 strioc_ppa.ic_len = sizeof(ppa);
3522 strioc_ppa.ic_dp = (char *)&ppa;
3523 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3524 syslog (LOG_ERR, "Can't assign new interface");
3526 if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3527 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3528 return -1;
3530 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3531 syslog(LOG_ERR, "Can't push IP module");
3532 return -1;
3535 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3536 syslog(LOG_ERR, "Can't get flags\n");
3538 snprintf (actual_name, 32, "tap%d", ppa);
3539 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3541 ifr.lifr_ppa = ppa;
3542 /* Assign ppa according to the unit number returned by tun device */
3544 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3545 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3546 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3547 syslog (LOG_ERR, "Can't get flags\n");
3548 /* Push arp module to if_fd */
3549 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3550 syslog (LOG_ERR, "Can't push ARP module (2)");
3552 /* Push arp module to ip_fd */
3553 if (ioctl (ip_fd, I_POP, NULL) < 0)
3554 syslog (LOG_ERR, "I_POP failed\n");
3555 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3556 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3557 /* Open arp_fd */
3558 if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3559 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3561 /* Set ifname to arp */
3562 strioc_if.ic_cmd = SIOCSLIFNAME;
3563 strioc_if.ic_timout = 0;
3564 strioc_if.ic_len = sizeof(ifr);
3565 strioc_if.ic_dp = (char *)&ifr;
3566 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3567 syslog (LOG_ERR, "Can't set ifname to arp\n");
3570 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3571 syslog(LOG_ERR, "Can't link TAP device to IP");
3572 return -1;
3575 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3576 syslog (LOG_ERR, "Can't link TAP device to ARP");
3578 close (if_fd);
3580 memset(&ifr, 0x0, sizeof(ifr));
3581 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3582 ifr.lifr_ip_muxid = ip_muxid;
3583 ifr.lifr_arp_muxid = arp_muxid;
3585 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3587 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3588 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3589 syslog (LOG_ERR, "Can't set multiplexor id");
3592 sprintf(dev, "tap%d", ppa);
3593 return tap_fd;
3596 static int tap_open(char *ifname, int ifname_size)
3598 char dev[10]="";
3599 int fd;
3600 if( (fd = tap_alloc(dev)) < 0 ){
3601 fprintf(stderr, "Cannot allocate TAP device\n");
3602 return -1;
3604 pstrcpy(ifname, ifname_size, dev);
3605 fcntl(fd, F_SETFL, O_NONBLOCK);
3606 return fd;
3608 #else
3609 static int tap_open(char *ifname, int ifname_size)
3611 struct ifreq ifr;
3612 int fd, ret;
3614 fd = open("/dev/net/tun", O_RDWR);
3615 if (fd < 0) {
3616 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3617 return -1;
3619 memset(&ifr, 0, sizeof(ifr));
3620 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3621 if (ifname[0] != '\0')
3622 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3623 else
3624 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3625 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3626 if (ret != 0) {
3627 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3628 close(fd);
3629 return -1;
3631 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3632 fcntl(fd, F_SETFL, O_NONBLOCK);
3633 return fd;
3635 #endif
3637 static int net_tap_init(VLANState *vlan, const char *ifname1,
3638 const char *setup_script)
3640 TAPState *s;
3641 int pid, status, fd;
3642 char *args[3];
3643 char **parg;
3644 char ifname[128];
3646 if (ifname1 != NULL)
3647 pstrcpy(ifname, sizeof(ifname), ifname1);
3648 else
3649 ifname[0] = '\0';
3650 fd = tap_open(ifname, sizeof(ifname));
3651 if (fd < 0)
3652 return -1;
3654 if (!setup_script || !strcmp(setup_script, "no"))
3655 setup_script = "";
3656 if (setup_script[0] != '\0') {
3657 /* try to launch network init script */
3658 pid = fork();
3659 if (pid >= 0) {
3660 if (pid == 0) {
3661 int open_max = sysconf (_SC_OPEN_MAX), i;
3662 for (i = 0; i < open_max; i++)
3663 if (i != STDIN_FILENO &&
3664 i != STDOUT_FILENO &&
3665 i != STDERR_FILENO &&
3666 i != fd)
3667 close(i);
3669 parg = args;
3670 *parg++ = (char *)setup_script;
3671 *parg++ = ifname;
3672 *parg++ = NULL;
3673 execv(setup_script, args);
3674 _exit(1);
3676 while (waitpid(pid, &status, 0) != pid);
3677 if (!WIFEXITED(status) ||
3678 WEXITSTATUS(status) != 0) {
3679 fprintf(stderr, "%s: could not launch network script\n",
3680 setup_script);
3681 return -1;
3685 s = net_tap_fd_init(vlan, fd);
3686 if (!s)
3687 return -1;
3688 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3689 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3690 return 0;
3693 #endif /* !_WIN32 */
3695 /* network connection */
3696 typedef struct NetSocketState {
3697 VLANClientState *vc;
3698 int fd;
3699 int state; /* 0 = getting length, 1 = getting data */
3700 int index;
3701 int packet_len;
3702 uint8_t buf[4096];
3703 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3704 } NetSocketState;
3706 typedef struct NetSocketListenState {
3707 VLANState *vlan;
3708 int fd;
3709 } NetSocketListenState;
3711 /* XXX: we consider we can send the whole packet without blocking */
3712 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3714 NetSocketState *s = opaque;
3715 uint32_t len;
3716 len = htonl(size);
3718 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3719 send_all(s->fd, buf, size);
3722 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3724 NetSocketState *s = opaque;
3725 sendto(s->fd, buf, size, 0,
3726 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3729 static void net_socket_send(void *opaque)
3731 NetSocketState *s = opaque;
3732 int l, size, err;
3733 uint8_t buf1[4096];
3734 const uint8_t *buf;
3736 size = recv(s->fd, buf1, sizeof(buf1), 0);
3737 if (size < 0) {
3738 err = socket_error();
3739 if (err != EWOULDBLOCK)
3740 goto eoc;
3741 } else if (size == 0) {
3742 /* end of connection */
3743 eoc:
3744 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3745 closesocket(s->fd);
3746 return;
3748 buf = buf1;
3749 while (size > 0) {
3750 /* reassemble a packet from the network */
3751 switch(s->state) {
3752 case 0:
3753 l = 4 - s->index;
3754 if (l > size)
3755 l = size;
3756 memcpy(s->buf + s->index, buf, l);
3757 buf += l;
3758 size -= l;
3759 s->index += l;
3760 if (s->index == 4) {
3761 /* got length */
3762 s->packet_len = ntohl(*(uint32_t *)s->buf);
3763 s->index = 0;
3764 s->state = 1;
3766 break;
3767 case 1:
3768 l = s->packet_len - s->index;
3769 if (l > size)
3770 l = size;
3771 memcpy(s->buf + s->index, buf, l);
3772 s->index += l;
3773 buf += l;
3774 size -= l;
3775 if (s->index >= s->packet_len) {
3776 qemu_send_packet(s->vc, s->buf, s->packet_len);
3777 s->index = 0;
3778 s->state = 0;
3780 break;
3785 static void net_socket_send_dgram(void *opaque)
3787 NetSocketState *s = opaque;
3788 int size;
3790 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3791 if (size < 0)
3792 return;
3793 if (size == 0) {
3794 /* end of connection */
3795 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3796 return;
3798 qemu_send_packet(s->vc, s->buf, size);
3801 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3803 struct ip_mreq imr;
3804 int fd;
3805 int val, ret;
3806 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3807 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3808 inet_ntoa(mcastaddr->sin_addr),
3809 (int)ntohl(mcastaddr->sin_addr.s_addr));
3810 return -1;
3813 fd = socket(PF_INET, SOCK_DGRAM, 0);
3814 if (fd < 0) {
3815 perror("socket(PF_INET, SOCK_DGRAM)");
3816 return -1;
3819 val = 1;
3820 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3821 (const char *)&val, sizeof(val));
3822 if (ret < 0) {
3823 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3824 goto fail;
3827 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3828 if (ret < 0) {
3829 perror("bind");
3830 goto fail;
3833 /* Add host to multicast group */
3834 imr.imr_multiaddr = mcastaddr->sin_addr;
3835 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3837 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3838 (const char *)&imr, sizeof(struct ip_mreq));
3839 if (ret < 0) {
3840 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3841 goto fail;
3844 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3845 val = 1;
3846 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3847 (const char *)&val, sizeof(val));
3848 if (ret < 0) {
3849 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3850 goto fail;
3853 socket_set_nonblock(fd);
3854 return fd;
3855 fail:
3856 if (fd >= 0)
3857 closesocket(fd);
3858 return -1;
3861 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3862 int is_connected)
3864 struct sockaddr_in saddr;
3865 int newfd;
3866 socklen_t saddr_len;
3867 NetSocketState *s;
3869 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3870 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3871 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3874 if (is_connected) {
3875 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3876 /* must be bound */
3877 if (saddr.sin_addr.s_addr==0) {
3878 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3879 fd);
3880 return NULL;
3882 /* clone dgram socket */
3883 newfd = net_socket_mcast_create(&saddr);
3884 if (newfd < 0) {
3885 /* error already reported by net_socket_mcast_create() */
3886 close(fd);
3887 return NULL;
3889 /* clone newfd to fd, close newfd */
3890 dup2(newfd, fd);
3891 close(newfd);
3893 } else {
3894 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3895 fd, strerror(errno));
3896 return NULL;
3900 s = qemu_mallocz(sizeof(NetSocketState));
3901 if (!s)
3902 return NULL;
3903 s->fd = fd;
3905 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3906 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3908 /* mcast: save bound address as dst */
3909 if (is_connected) s->dgram_dst=saddr;
3911 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3912 "socket: fd=%d (%s mcast=%s:%d)",
3913 fd, is_connected? "cloned" : "",
3914 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3915 return s;
3918 static void net_socket_connect(void *opaque)
3920 NetSocketState *s = opaque;
3921 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3924 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3925 int is_connected)
3927 NetSocketState *s;
3928 s = qemu_mallocz(sizeof(NetSocketState));
3929 if (!s)
3930 return NULL;
3931 s->fd = fd;
3932 s->vc = qemu_new_vlan_client(vlan,
3933 net_socket_receive, NULL, s);
3934 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3935 "socket: fd=%d", fd);
3936 if (is_connected) {
3937 net_socket_connect(s);
3938 } else {
3939 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3941 return s;
3944 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3945 int is_connected)
3947 int so_type=-1, optlen=sizeof(so_type);
3949 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3950 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3951 return NULL;
3953 switch(so_type) {
3954 case SOCK_DGRAM:
3955 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3956 case SOCK_STREAM:
3957 return net_socket_fd_init_stream(vlan, fd, is_connected);
3958 default:
3959 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3960 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3961 return net_socket_fd_init_stream(vlan, fd, is_connected);
3963 return NULL;
3966 static void net_socket_accept(void *opaque)
3968 NetSocketListenState *s = opaque;
3969 NetSocketState *s1;
3970 struct sockaddr_in saddr;
3971 socklen_t len;
3972 int fd;
3974 for(;;) {
3975 len = sizeof(saddr);
3976 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3977 if (fd < 0 && errno != EINTR) {
3978 return;
3979 } else if (fd >= 0) {
3980 break;
3983 s1 = net_socket_fd_init(s->vlan, fd, 1);
3984 if (!s1) {
3985 closesocket(fd);
3986 } else {
3987 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3988 "socket: connection from %s:%d",
3989 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3993 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3995 NetSocketListenState *s;
3996 int fd, val, ret;
3997 struct sockaddr_in saddr;
3999 if (parse_host_port(&saddr, host_str) < 0)
4000 return -1;
4002 s = qemu_mallocz(sizeof(NetSocketListenState));
4003 if (!s)
4004 return -1;
4006 fd = socket(PF_INET, SOCK_STREAM, 0);
4007 if (fd < 0) {
4008 perror("socket");
4009 return -1;
4011 socket_set_nonblock(fd);
4013 /* allow fast reuse */
4014 val = 1;
4015 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4017 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4018 if (ret < 0) {
4019 perror("bind");
4020 return -1;
4022 ret = listen(fd, 0);
4023 if (ret < 0) {
4024 perror("listen");
4025 return -1;
4027 s->vlan = vlan;
4028 s->fd = fd;
4029 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4030 return 0;
4033 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4035 NetSocketState *s;
4036 int fd, connected, ret, err;
4037 struct sockaddr_in saddr;
4039 if (parse_host_port(&saddr, host_str) < 0)
4040 return -1;
4042 fd = socket(PF_INET, SOCK_STREAM, 0);
4043 if (fd < 0) {
4044 perror("socket");
4045 return -1;
4047 socket_set_nonblock(fd);
4049 connected = 0;
4050 for(;;) {
4051 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4052 if (ret < 0) {
4053 err = socket_error();
4054 if (err == EINTR || err == EWOULDBLOCK) {
4055 } else if (err == EINPROGRESS) {
4056 break;
4057 #ifdef _WIN32
4058 } else if (err == WSAEALREADY) {
4059 break;
4060 #endif
4061 } else {
4062 perror("connect");
4063 closesocket(fd);
4064 return -1;
4066 } else {
4067 connected = 1;
4068 break;
4071 s = net_socket_fd_init(vlan, fd, connected);
4072 if (!s)
4073 return -1;
4074 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4075 "socket: connect to %s:%d",
4076 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4077 return 0;
4080 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4082 NetSocketState *s;
4083 int fd;
4084 struct sockaddr_in saddr;
4086 if (parse_host_port(&saddr, host_str) < 0)
4087 return -1;
4090 fd = net_socket_mcast_create(&saddr);
4091 if (fd < 0)
4092 return -1;
4094 s = net_socket_fd_init(vlan, fd, 0);
4095 if (!s)
4096 return -1;
4098 s->dgram_dst = saddr;
4100 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4101 "socket: mcast=%s:%d",
4102 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4103 return 0;
4107 static int get_param_value(char *buf, int buf_size,
4108 const char *tag, const char *str)
4110 const char *p;
4111 char *q;
4112 char option[128];
4114 p = str;
4115 for(;;) {
4116 q = option;
4117 while (*p != '\0' && *p != '=') {
4118 if ((q - option) < sizeof(option) - 1)
4119 *q++ = *p;
4120 p++;
4122 *q = '\0';
4123 if (*p != '=')
4124 break;
4125 p++;
4126 if (!strcmp(tag, option)) {
4127 q = buf;
4128 while (*p != '\0' && *p != ',') {
4129 if ((q - buf) < buf_size - 1)
4130 *q++ = *p;
4131 p++;
4133 *q = '\0';
4134 return q - buf;
4135 } else {
4136 while (*p != '\0' && *p != ',') {
4137 p++;
4140 if (*p != ',')
4141 break;
4142 p++;
4144 return 0;
4147 static int net_client_init(const char *str)
4149 const char *p;
4150 char *q;
4151 char device[64];
4152 char buf[1024];
4153 int vlan_id, ret;
4154 VLANState *vlan;
4156 p = str;
4157 q = device;
4158 while (*p != '\0' && *p != ',') {
4159 if ((q - device) < sizeof(device) - 1)
4160 *q++ = *p;
4161 p++;
4163 *q = '\0';
4164 if (*p == ',')
4165 p++;
4166 vlan_id = 0;
4167 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4168 vlan_id = strtol(buf, NULL, 0);
4170 vlan = qemu_find_vlan(vlan_id);
4171 if (!vlan) {
4172 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4173 return -1;
4175 if (!strcmp(device, "nic")) {
4176 NICInfo *nd;
4177 uint8_t *macaddr;
4179 if (nb_nics >= MAX_NICS) {
4180 fprintf(stderr, "Too Many NICs\n");
4181 return -1;
4183 nd = &nd_table[nb_nics];
4184 macaddr = nd->macaddr;
4185 macaddr[0] = 0x52;
4186 macaddr[1] = 0x54;
4187 macaddr[2] = 0x00;
4188 macaddr[3] = 0x12;
4189 macaddr[4] = 0x34;
4190 macaddr[5] = 0x56 + nb_nics;
4192 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4193 if (parse_macaddr(macaddr, buf) < 0) {
4194 fprintf(stderr, "invalid syntax for ethernet address\n");
4195 return -1;
4198 if (get_param_value(buf, sizeof(buf), "model", p)) {
4199 nd->model = strdup(buf);
4201 nd->vlan = vlan;
4202 nb_nics++;
4203 vlan->nb_guest_devs++;
4204 ret = 0;
4205 } else
4206 if (!strcmp(device, "none")) {
4207 /* does nothing. It is needed to signal that no network cards
4208 are wanted */
4209 ret = 0;
4210 } else
4211 #ifdef CONFIG_SLIRP
4212 if (!strcmp(device, "user")) {
4213 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4214 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4216 vlan->nb_host_devs++;
4217 ret = net_slirp_init(vlan);
4218 } else
4219 #endif
4220 #ifdef _WIN32
4221 if (!strcmp(device, "tap")) {
4222 char ifname[64];
4223 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4224 fprintf(stderr, "tap: no interface name\n");
4225 return -1;
4227 vlan->nb_host_devs++;
4228 ret = tap_win32_init(vlan, ifname);
4229 } else
4230 #else
4231 if (!strcmp(device, "tap")) {
4232 char ifname[64];
4233 char setup_script[1024];
4234 int fd;
4235 vlan->nb_host_devs++;
4236 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4237 fd = strtol(buf, NULL, 0);
4238 ret = -1;
4239 if (net_tap_fd_init(vlan, fd))
4240 ret = 0;
4241 } else {
4242 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4243 ifname[0] = '\0';
4245 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4246 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4248 ret = net_tap_init(vlan, ifname, setup_script);
4250 } else
4251 #endif
4252 if (!strcmp(device, "socket")) {
4253 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4254 int fd;
4255 fd = strtol(buf, NULL, 0);
4256 ret = -1;
4257 if (net_socket_fd_init(vlan, fd, 1))
4258 ret = 0;
4259 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4260 ret = net_socket_listen_init(vlan, buf);
4261 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4262 ret = net_socket_connect_init(vlan, buf);
4263 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4264 ret = net_socket_mcast_init(vlan, buf);
4265 } else {
4266 fprintf(stderr, "Unknown socket options: %s\n", p);
4267 return -1;
4269 vlan->nb_host_devs++;
4270 } else
4272 fprintf(stderr, "Unknown network device: %s\n", device);
4273 return -1;
4275 if (ret < 0) {
4276 fprintf(stderr, "Could not initialize device '%s'\n", device);
4279 return ret;
4282 void do_info_network(void)
4284 VLANState *vlan;
4285 VLANClientState *vc;
4287 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4288 term_printf("VLAN %d devices:\n", vlan->id);
4289 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4290 term_printf(" %s\n", vc->info_str);
4294 /***********************************************************/
4295 /* USB devices */
4297 static USBPort *used_usb_ports;
4298 static USBPort *free_usb_ports;
4300 /* ??? Maybe change this to register a hub to keep track of the topology. */
4301 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4302 usb_attachfn attach)
4304 port->opaque = opaque;
4305 port->index = index;
4306 port->attach = attach;
4307 port->next = free_usb_ports;
4308 free_usb_ports = port;
4311 static int usb_device_add(const char *devname)
4313 const char *p;
4314 USBDevice *dev;
4315 USBPort *port;
4317 if (!free_usb_ports)
4318 return -1;
4320 if (strstart(devname, "host:", &p)) {
4321 dev = usb_host_device_open(p);
4322 } else if (!strcmp(devname, "mouse")) {
4323 dev = usb_mouse_init();
4324 } else if (!strcmp(devname, "tablet")) {
4325 dev = usb_tablet_init();
4326 } else if (!strcmp(devname, "keyboard")) {
4327 dev = usb_keyboard_init();
4328 } else if (strstart(devname, "disk:", &p)) {
4329 dev = usb_msd_init(p);
4330 } else if (!strcmp(devname, "wacom-tablet")) {
4331 dev = usb_wacom_init();
4332 } else {
4333 return -1;
4335 if (!dev)
4336 return -1;
4338 /* Find a USB port to add the device to. */
4339 port = free_usb_ports;
4340 if (!port->next) {
4341 USBDevice *hub;
4343 /* Create a new hub and chain it on. */
4344 free_usb_ports = NULL;
4345 port->next = used_usb_ports;
4346 used_usb_ports = port;
4348 hub = usb_hub_init(VM_USB_HUB_SIZE);
4349 usb_attach(port, hub);
4350 port = free_usb_ports;
4353 free_usb_ports = port->next;
4354 port->next = used_usb_ports;
4355 used_usb_ports = port;
4356 usb_attach(port, dev);
4357 return 0;
4360 static int usb_device_del(const char *devname)
4362 USBPort *port;
4363 USBPort **lastp;
4364 USBDevice *dev;
4365 int bus_num, addr;
4366 const char *p;
4368 if (!used_usb_ports)
4369 return -1;
4371 p = strchr(devname, '.');
4372 if (!p)
4373 return -1;
4374 bus_num = strtoul(devname, NULL, 0);
4375 addr = strtoul(p + 1, NULL, 0);
4376 if (bus_num != 0)
4377 return -1;
4379 lastp = &used_usb_ports;
4380 port = used_usb_ports;
4381 while (port && port->dev->addr != addr) {
4382 lastp = &port->next;
4383 port = port->next;
4386 if (!port)
4387 return -1;
4389 dev = port->dev;
4390 *lastp = port->next;
4391 usb_attach(port, NULL);
4392 dev->handle_destroy(dev);
4393 port->next = free_usb_ports;
4394 free_usb_ports = port;
4395 return 0;
4398 void do_usb_add(const char *devname)
4400 int ret;
4401 ret = usb_device_add(devname);
4402 if (ret < 0)
4403 term_printf("Could not add USB device '%s'\n", devname);
4406 void do_usb_del(const char *devname)
4408 int ret;
4409 ret = usb_device_del(devname);
4410 if (ret < 0)
4411 term_printf("Could not remove USB device '%s'\n", devname);
4414 void usb_info(void)
4416 USBDevice *dev;
4417 USBPort *port;
4418 const char *speed_str;
4420 if (!usb_enabled) {
4421 term_printf("USB support not enabled\n");
4422 return;
4425 for (port = used_usb_ports; port; port = port->next) {
4426 dev = port->dev;
4427 if (!dev)
4428 continue;
4429 switch(dev->speed) {
4430 case USB_SPEED_LOW:
4431 speed_str = "1.5";
4432 break;
4433 case USB_SPEED_FULL:
4434 speed_str = "12";
4435 break;
4436 case USB_SPEED_HIGH:
4437 speed_str = "480";
4438 break;
4439 default:
4440 speed_str = "?";
4441 break;
4443 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4444 0, dev->addr, speed_str, dev->devname);
4448 /***********************************************************/
4449 /* PCMCIA/Cardbus */
4451 static struct pcmcia_socket_entry_s {
4452 struct pcmcia_socket_s *socket;
4453 struct pcmcia_socket_entry_s *next;
4454 } *pcmcia_sockets = 0;
4456 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4458 struct pcmcia_socket_entry_s *entry;
4460 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4461 entry->socket = socket;
4462 entry->next = pcmcia_sockets;
4463 pcmcia_sockets = entry;
4466 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4468 struct pcmcia_socket_entry_s *entry, **ptr;
4470 ptr = &pcmcia_sockets;
4471 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4472 if (entry->socket == socket) {
4473 *ptr = entry->next;
4474 qemu_free(entry);
4478 void pcmcia_info(void)
4480 struct pcmcia_socket_entry_s *iter;
4481 if (!pcmcia_sockets)
4482 term_printf("No PCMCIA sockets\n");
4484 for (iter = pcmcia_sockets; iter; iter = iter->next)
4485 term_printf("%s: %s\n", iter->socket->slot_string,
4486 iter->socket->attached ? iter->socket->card_string :
4487 "Empty");
4490 /***********************************************************/
4491 /* dumb display */
4493 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4497 static void dumb_resize(DisplayState *ds, int w, int h)
4501 static void dumb_refresh(DisplayState *ds)
4503 #if defined(CONFIG_SDL)
4504 vga_hw_update();
4505 #endif
4508 static void dumb_display_init(DisplayState *ds)
4510 ds->data = NULL;
4511 ds->linesize = 0;
4512 ds->depth = 0;
4513 ds->dpy_update = dumb_update;
4514 ds->dpy_resize = dumb_resize;
4515 ds->dpy_refresh = dumb_refresh;
4518 /***********************************************************/
4519 /* I/O handling */
4521 #define MAX_IO_HANDLERS 64
4523 typedef struct IOHandlerRecord {
4524 int fd;
4525 IOCanRWHandler *fd_read_poll;
4526 IOHandler *fd_read;
4527 IOHandler *fd_write;
4528 int deleted;
4529 void *opaque;
4530 /* temporary data */
4531 struct pollfd *ufd;
4532 struct IOHandlerRecord *next;
4533 } IOHandlerRecord;
4535 static IOHandlerRecord *first_io_handler;
4537 /* XXX: fd_read_poll should be suppressed, but an API change is
4538 necessary in the character devices to suppress fd_can_read(). */
4539 int qemu_set_fd_handler2(int fd,
4540 IOCanRWHandler *fd_read_poll,
4541 IOHandler *fd_read,
4542 IOHandler *fd_write,
4543 void *opaque)
4545 IOHandlerRecord **pioh, *ioh;
4547 if (!fd_read && !fd_write) {
4548 pioh = &first_io_handler;
4549 for(;;) {
4550 ioh = *pioh;
4551 if (ioh == NULL)
4552 break;
4553 if (ioh->fd == fd) {
4554 ioh->deleted = 1;
4555 break;
4557 pioh = &ioh->next;
4559 } else {
4560 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4561 if (ioh->fd == fd)
4562 goto found;
4564 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4565 if (!ioh)
4566 return -1;
4567 ioh->next = first_io_handler;
4568 first_io_handler = ioh;
4569 found:
4570 ioh->fd = fd;
4571 ioh->fd_read_poll = fd_read_poll;
4572 ioh->fd_read = fd_read;
4573 ioh->fd_write = fd_write;
4574 ioh->opaque = opaque;
4575 ioh->deleted = 0;
4577 return 0;
4580 int qemu_set_fd_handler(int fd,
4581 IOHandler *fd_read,
4582 IOHandler *fd_write,
4583 void *opaque)
4585 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4588 /***********************************************************/
4589 /* Polling handling */
4591 typedef struct PollingEntry {
4592 PollingFunc *func;
4593 void *opaque;
4594 struct PollingEntry *next;
4595 } PollingEntry;
4597 static PollingEntry *first_polling_entry;
4599 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4601 PollingEntry **ppe, *pe;
4602 pe = qemu_mallocz(sizeof(PollingEntry));
4603 if (!pe)
4604 return -1;
4605 pe->func = func;
4606 pe->opaque = opaque;
4607 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4608 *ppe = pe;
4609 return 0;
4612 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4614 PollingEntry **ppe, *pe;
4615 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4616 pe = *ppe;
4617 if (pe->func == func && pe->opaque == opaque) {
4618 *ppe = pe->next;
4619 qemu_free(pe);
4620 break;
4625 #ifdef _WIN32
4626 /***********************************************************/
4627 /* Wait objects support */
4628 typedef struct WaitObjects {
4629 int num;
4630 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4631 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4632 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4633 } WaitObjects;
4635 static WaitObjects wait_objects = {0};
4637 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4639 WaitObjects *w = &wait_objects;
4641 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4642 return -1;
4643 w->events[w->num] = handle;
4644 w->func[w->num] = func;
4645 w->opaque[w->num] = opaque;
4646 w->num++;
4647 return 0;
4650 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4652 int i, found;
4653 WaitObjects *w = &wait_objects;
4655 found = 0;
4656 for (i = 0; i < w->num; i++) {
4657 if (w->events[i] == handle)
4658 found = 1;
4659 if (found) {
4660 w->events[i] = w->events[i + 1];
4661 w->func[i] = w->func[i + 1];
4662 w->opaque[i] = w->opaque[i + 1];
4665 if (found)
4666 w->num--;
4668 #endif
4670 /***********************************************************/
4671 /* savevm/loadvm support */
4673 #define IO_BUF_SIZE 32768
4675 struct QEMUFile {
4676 FILE *outfile;
4677 BlockDriverState *bs;
4678 int is_file;
4679 int is_writable;
4680 int64_t base_offset;
4681 int64_t buf_offset; /* start of buffer when writing, end of buffer
4682 when reading */
4683 int buf_index;
4684 int buf_size; /* 0 when writing */
4685 uint8_t buf[IO_BUF_SIZE];
4688 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4690 QEMUFile *f;
4692 f = qemu_mallocz(sizeof(QEMUFile));
4693 if (!f)
4694 return NULL;
4695 if (!strcmp(mode, "wb")) {
4696 f->is_writable = 1;
4697 } else if (!strcmp(mode, "rb")) {
4698 f->is_writable = 0;
4699 } else {
4700 goto fail;
4702 f->outfile = fopen(filename, mode);
4703 if (!f->outfile)
4704 goto fail;
4705 f->is_file = 1;
4706 return f;
4707 fail:
4708 if (f->outfile)
4709 fclose(f->outfile);
4710 qemu_free(f);
4711 return NULL;
4714 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4716 QEMUFile *f;
4718 f = qemu_mallocz(sizeof(QEMUFile));
4719 if (!f)
4720 return NULL;
4721 f->is_file = 0;
4722 f->bs = bs;
4723 f->is_writable = is_writable;
4724 f->base_offset = offset;
4725 return f;
4728 void qemu_fflush(QEMUFile *f)
4730 if (!f->is_writable)
4731 return;
4732 if (f->buf_index > 0) {
4733 if (f->is_file) {
4734 fseek(f->outfile, f->buf_offset, SEEK_SET);
4735 fwrite(f->buf, 1, f->buf_index, f->outfile);
4736 } else {
4737 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4738 f->buf, f->buf_index);
4740 f->buf_offset += f->buf_index;
4741 f->buf_index = 0;
4745 static void qemu_fill_buffer(QEMUFile *f)
4747 int len;
4749 if (f->is_writable)
4750 return;
4751 if (f->is_file) {
4752 fseek(f->outfile, f->buf_offset, SEEK_SET);
4753 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4754 if (len < 0)
4755 len = 0;
4756 } else {
4757 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4758 f->buf, IO_BUF_SIZE);
4759 if (len < 0)
4760 len = 0;
4762 f->buf_index = 0;
4763 f->buf_size = len;
4764 f->buf_offset += len;
4767 void qemu_fclose(QEMUFile *f)
4769 if (f->is_writable)
4770 qemu_fflush(f);
4771 if (f->is_file) {
4772 fclose(f->outfile);
4774 qemu_free(f);
4777 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4779 int l;
4780 while (size > 0) {
4781 l = IO_BUF_SIZE - f->buf_index;
4782 if (l > size)
4783 l = size;
4784 memcpy(f->buf + f->buf_index, buf, l);
4785 f->buf_index += l;
4786 buf += l;
4787 size -= l;
4788 if (f->buf_index >= IO_BUF_SIZE)
4789 qemu_fflush(f);
4793 void qemu_put_byte(QEMUFile *f, int v)
4795 f->buf[f->buf_index++] = v;
4796 if (f->buf_index >= IO_BUF_SIZE)
4797 qemu_fflush(f);
4800 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4802 int size, l;
4804 size = size1;
4805 while (size > 0) {
4806 l = f->buf_size - f->buf_index;
4807 if (l == 0) {
4808 qemu_fill_buffer(f);
4809 l = f->buf_size - f->buf_index;
4810 if (l == 0)
4811 break;
4813 if (l > size)
4814 l = size;
4815 memcpy(buf, f->buf + f->buf_index, l);
4816 f->buf_index += l;
4817 buf += l;
4818 size -= l;
4820 return size1 - size;
4823 int qemu_get_byte(QEMUFile *f)
4825 if (f->buf_index >= f->buf_size) {
4826 qemu_fill_buffer(f);
4827 if (f->buf_index >= f->buf_size)
4828 return 0;
4830 return f->buf[f->buf_index++];
4833 int64_t qemu_ftell(QEMUFile *f)
4835 return f->buf_offset - f->buf_size + f->buf_index;
4838 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4840 if (whence == SEEK_SET) {
4841 /* nothing to do */
4842 } else if (whence == SEEK_CUR) {
4843 pos += qemu_ftell(f);
4844 } else {
4845 /* SEEK_END not supported */
4846 return -1;
4848 if (f->is_writable) {
4849 qemu_fflush(f);
4850 f->buf_offset = pos;
4851 } else {
4852 f->buf_offset = pos;
4853 f->buf_index = 0;
4854 f->buf_size = 0;
4856 return pos;
4859 void qemu_put_be16(QEMUFile *f, unsigned int v)
4861 qemu_put_byte(f, v >> 8);
4862 qemu_put_byte(f, v);
4865 void qemu_put_be32(QEMUFile *f, unsigned int v)
4867 qemu_put_byte(f, v >> 24);
4868 qemu_put_byte(f, v >> 16);
4869 qemu_put_byte(f, v >> 8);
4870 qemu_put_byte(f, v);
4873 void qemu_put_be64(QEMUFile *f, uint64_t v)
4875 qemu_put_be32(f, v >> 32);
4876 qemu_put_be32(f, v);
4879 unsigned int qemu_get_be16(QEMUFile *f)
4881 unsigned int v;
4882 v = qemu_get_byte(f) << 8;
4883 v |= qemu_get_byte(f);
4884 return v;
4887 unsigned int qemu_get_be32(QEMUFile *f)
4889 unsigned int v;
4890 v = qemu_get_byte(f) << 24;
4891 v |= qemu_get_byte(f) << 16;
4892 v |= qemu_get_byte(f) << 8;
4893 v |= qemu_get_byte(f);
4894 return v;
4897 uint64_t qemu_get_be64(QEMUFile *f)
4899 uint64_t v;
4900 v = (uint64_t)qemu_get_be32(f) << 32;
4901 v |= qemu_get_be32(f);
4902 return v;
4905 typedef struct SaveStateEntry {
4906 char idstr[256];
4907 int instance_id;
4908 int version_id;
4909 SaveStateHandler *save_state;
4910 LoadStateHandler *load_state;
4911 void *opaque;
4912 struct SaveStateEntry *next;
4913 } SaveStateEntry;
4915 static SaveStateEntry *first_se;
4917 int register_savevm(const char *idstr,
4918 int instance_id,
4919 int version_id,
4920 SaveStateHandler *save_state,
4921 LoadStateHandler *load_state,
4922 void *opaque)
4924 SaveStateEntry *se, **pse;
4926 se = qemu_malloc(sizeof(SaveStateEntry));
4927 if (!se)
4928 return -1;
4929 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4930 se->instance_id = instance_id;
4931 se->version_id = version_id;
4932 se->save_state = save_state;
4933 se->load_state = load_state;
4934 se->opaque = opaque;
4935 se->next = NULL;
4937 /* add at the end of list */
4938 pse = &first_se;
4939 while (*pse != NULL)
4940 pse = &(*pse)->next;
4941 *pse = se;
4942 return 0;
4945 #define QEMU_VM_FILE_MAGIC 0x5145564d
4946 #define QEMU_VM_FILE_VERSION 0x00000002
4948 int qemu_savevm_state(QEMUFile *f)
4950 SaveStateEntry *se;
4951 int len, ret;
4952 int64_t cur_pos, len_pos, total_len_pos;
4954 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4955 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4956 total_len_pos = qemu_ftell(f);
4957 qemu_put_be64(f, 0); /* total size */
4959 for(se = first_se; se != NULL; se = se->next) {
4960 /* ID string */
4961 len = strlen(se->idstr);
4962 qemu_put_byte(f, len);
4963 qemu_put_buffer(f, se->idstr, len);
4965 qemu_put_be32(f, se->instance_id);
4966 qemu_put_be32(f, se->version_id);
4968 /* record size: filled later */
4969 len_pos = qemu_ftell(f);
4970 qemu_put_be32(f, 0);
4972 se->save_state(f, se->opaque);
4974 /* fill record size */
4975 cur_pos = qemu_ftell(f);
4976 len = cur_pos - len_pos - 4;
4977 qemu_fseek(f, len_pos, SEEK_SET);
4978 qemu_put_be32(f, len);
4979 qemu_fseek(f, cur_pos, SEEK_SET);
4981 cur_pos = qemu_ftell(f);
4982 qemu_fseek(f, total_len_pos, SEEK_SET);
4983 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4984 qemu_fseek(f, cur_pos, SEEK_SET);
4986 ret = 0;
4987 return ret;
4990 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4992 SaveStateEntry *se;
4994 for(se = first_se; se != NULL; se = se->next) {
4995 if (!strcmp(se->idstr, idstr) &&
4996 instance_id == se->instance_id)
4997 return se;
4999 return NULL;
5002 int qemu_loadvm_state(QEMUFile *f)
5004 SaveStateEntry *se;
5005 int len, ret, instance_id, record_len, version_id;
5006 int64_t total_len, end_pos, cur_pos;
5007 unsigned int v;
5008 char idstr[256];
5010 v = qemu_get_be32(f);
5011 if (v != QEMU_VM_FILE_MAGIC)
5012 goto fail;
5013 v = qemu_get_be32(f);
5014 if (v != QEMU_VM_FILE_VERSION) {
5015 fail:
5016 ret = -1;
5017 goto the_end;
5019 total_len = qemu_get_be64(f);
5020 end_pos = total_len + qemu_ftell(f);
5021 for(;;) {
5022 if (qemu_ftell(f) >= end_pos)
5023 break;
5024 len = qemu_get_byte(f);
5025 qemu_get_buffer(f, idstr, len);
5026 idstr[len] = '\0';
5027 instance_id = qemu_get_be32(f);
5028 version_id = qemu_get_be32(f);
5029 record_len = qemu_get_be32(f);
5030 #if 0
5031 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5032 idstr, instance_id, version_id, record_len);
5033 #endif
5034 cur_pos = qemu_ftell(f);
5035 se = find_se(idstr, instance_id);
5036 if (!se) {
5037 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5038 instance_id, idstr);
5039 } else {
5040 ret = se->load_state(f, se->opaque, version_id);
5041 if (ret < 0) {
5042 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5043 instance_id, idstr);
5046 /* always seek to exact end of record */
5047 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5049 ret = 0;
5050 the_end:
5051 return ret;
5054 /* device can contain snapshots */
5055 static int bdrv_can_snapshot(BlockDriverState *bs)
5057 return (bs &&
5058 !bdrv_is_removable(bs) &&
5059 !bdrv_is_read_only(bs));
5062 /* device must be snapshots in order to have a reliable snapshot */
5063 static int bdrv_has_snapshot(BlockDriverState *bs)
5065 return (bs &&
5066 !bdrv_is_removable(bs) &&
5067 !bdrv_is_read_only(bs));
5070 static BlockDriverState *get_bs_snapshots(void)
5072 BlockDriverState *bs;
5073 int i;
5075 if (bs_snapshots)
5076 return bs_snapshots;
5077 for(i = 0; i <= MAX_DISKS; i++) {
5078 bs = bs_table[i];
5079 if (bdrv_can_snapshot(bs))
5080 goto ok;
5082 return NULL;
5084 bs_snapshots = bs;
5085 return bs;
5088 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5089 const char *name)
5091 QEMUSnapshotInfo *sn_tab, *sn;
5092 int nb_sns, i, ret;
5094 ret = -ENOENT;
5095 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5096 if (nb_sns < 0)
5097 return ret;
5098 for(i = 0; i < nb_sns; i++) {
5099 sn = &sn_tab[i];
5100 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5101 *sn_info = *sn;
5102 ret = 0;
5103 break;
5106 qemu_free(sn_tab);
5107 return ret;
5110 void do_savevm(const char *name)
5112 BlockDriverState *bs, *bs1;
5113 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5114 int must_delete, ret, i;
5115 BlockDriverInfo bdi1, *bdi = &bdi1;
5116 QEMUFile *f;
5117 int saved_vm_running;
5118 #ifdef _WIN32
5119 struct _timeb tb;
5120 #else
5121 struct timeval tv;
5122 #endif
5124 bs = get_bs_snapshots();
5125 if (!bs) {
5126 term_printf("No block device can accept snapshots\n");
5127 return;
5130 /* ??? Should this occur after vm_stop? */
5131 qemu_aio_flush();
5133 saved_vm_running = vm_running;
5134 vm_stop(0);
5136 must_delete = 0;
5137 if (name) {
5138 ret = bdrv_snapshot_find(bs, old_sn, name);
5139 if (ret >= 0) {
5140 must_delete = 1;
5143 memset(sn, 0, sizeof(*sn));
5144 if (must_delete) {
5145 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5146 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5147 } else {
5148 if (name)
5149 pstrcpy(sn->name, sizeof(sn->name), name);
5152 /* fill auxiliary fields */
5153 #ifdef _WIN32
5154 _ftime(&tb);
5155 sn->date_sec = tb.time;
5156 sn->date_nsec = tb.millitm * 1000000;
5157 #else
5158 gettimeofday(&tv, NULL);
5159 sn->date_sec = tv.tv_sec;
5160 sn->date_nsec = tv.tv_usec * 1000;
5161 #endif
5162 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5164 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5165 term_printf("Device %s does not support VM state snapshots\n",
5166 bdrv_get_device_name(bs));
5167 goto the_end;
5170 /* save the VM state */
5171 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5172 if (!f) {
5173 term_printf("Could not open VM state file\n");
5174 goto the_end;
5176 ret = qemu_savevm_state(f);
5177 sn->vm_state_size = qemu_ftell(f);
5178 qemu_fclose(f);
5179 if (ret < 0) {
5180 term_printf("Error %d while writing VM\n", ret);
5181 goto the_end;
5184 /* create the snapshots */
5186 for(i = 0; i < MAX_DISKS; i++) {
5187 bs1 = bs_table[i];
5188 if (bdrv_has_snapshot(bs1)) {
5189 if (must_delete) {
5190 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5191 if (ret < 0) {
5192 term_printf("Error while deleting snapshot on '%s'\n",
5193 bdrv_get_device_name(bs1));
5196 ret = bdrv_snapshot_create(bs1, sn);
5197 if (ret < 0) {
5198 term_printf("Error while creating snapshot on '%s'\n",
5199 bdrv_get_device_name(bs1));
5204 the_end:
5205 if (saved_vm_running)
5206 vm_start();
5209 void do_loadvm(const char *name)
5211 BlockDriverState *bs, *bs1;
5212 BlockDriverInfo bdi1, *bdi = &bdi1;
5213 QEMUFile *f;
5214 int i, ret;
5215 int saved_vm_running;
5217 bs = get_bs_snapshots();
5218 if (!bs) {
5219 term_printf("No block device supports snapshots\n");
5220 return;
5223 /* Flush all IO requests so they don't interfere with the new state. */
5224 qemu_aio_flush();
5226 saved_vm_running = vm_running;
5227 vm_stop(0);
5229 for(i = 0; i <= MAX_DISKS; i++) {
5230 bs1 = bs_table[i];
5231 if (bdrv_has_snapshot(bs1)) {
5232 ret = bdrv_snapshot_goto(bs1, name);
5233 if (ret < 0) {
5234 if (bs != bs1)
5235 term_printf("Warning: ");
5236 switch(ret) {
5237 case -ENOTSUP:
5238 term_printf("Snapshots not supported on device '%s'\n",
5239 bdrv_get_device_name(bs1));
5240 break;
5241 case -ENOENT:
5242 term_printf("Could not find snapshot '%s' on device '%s'\n",
5243 name, bdrv_get_device_name(bs1));
5244 break;
5245 default:
5246 term_printf("Error %d while activating snapshot on '%s'\n",
5247 ret, bdrv_get_device_name(bs1));
5248 break;
5250 /* fatal on snapshot block device */
5251 if (bs == bs1)
5252 goto the_end;
5257 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5258 term_printf("Device %s does not support VM state snapshots\n",
5259 bdrv_get_device_name(bs));
5260 return;
5263 /* restore the VM state */
5264 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5265 if (!f) {
5266 term_printf("Could not open VM state file\n");
5267 goto the_end;
5269 ret = qemu_loadvm_state(f);
5270 qemu_fclose(f);
5271 if (ret < 0) {
5272 term_printf("Error %d while loading VM state\n", ret);
5274 the_end:
5275 if (saved_vm_running)
5276 vm_start();
5279 void do_delvm(const char *name)
5281 BlockDriverState *bs, *bs1;
5282 int i, ret;
5284 bs = get_bs_snapshots();
5285 if (!bs) {
5286 term_printf("No block device supports snapshots\n");
5287 return;
5290 for(i = 0; i <= MAX_DISKS; i++) {
5291 bs1 = bs_table[i];
5292 if (bdrv_has_snapshot(bs1)) {
5293 ret = bdrv_snapshot_delete(bs1, name);
5294 if (ret < 0) {
5295 if (ret == -ENOTSUP)
5296 term_printf("Snapshots not supported on device '%s'\n",
5297 bdrv_get_device_name(bs1));
5298 else
5299 term_printf("Error %d while deleting snapshot on '%s'\n",
5300 ret, bdrv_get_device_name(bs1));
5306 void do_info_snapshots(void)
5308 BlockDriverState *bs, *bs1;
5309 QEMUSnapshotInfo *sn_tab, *sn;
5310 int nb_sns, i;
5311 char buf[256];
5313 bs = get_bs_snapshots();
5314 if (!bs) {
5315 term_printf("No available block device supports snapshots\n");
5316 return;
5318 term_printf("Snapshot devices:");
5319 for(i = 0; i <= MAX_DISKS; i++) {
5320 bs1 = bs_table[i];
5321 if (bdrv_has_snapshot(bs1)) {
5322 if (bs == bs1)
5323 term_printf(" %s", bdrv_get_device_name(bs1));
5326 term_printf("\n");
5328 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5329 if (nb_sns < 0) {
5330 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5331 return;
5333 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5334 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5335 for(i = 0; i < nb_sns; i++) {
5336 sn = &sn_tab[i];
5337 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5339 qemu_free(sn_tab);
5342 /***********************************************************/
5343 /* cpu save/restore */
5345 #if defined(TARGET_I386)
5347 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5349 qemu_put_be32(f, dt->selector);
5350 qemu_put_betl(f, dt->base);
5351 qemu_put_be32(f, dt->limit);
5352 qemu_put_be32(f, dt->flags);
5355 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5357 dt->selector = qemu_get_be32(f);
5358 dt->base = qemu_get_betl(f);
5359 dt->limit = qemu_get_be32(f);
5360 dt->flags = qemu_get_be32(f);
5363 void cpu_save(QEMUFile *f, void *opaque)
5365 CPUState *env = opaque;
5366 uint16_t fptag, fpus, fpuc, fpregs_format;
5367 uint32_t hflags;
5368 int i;
5370 for(i = 0; i < CPU_NB_REGS; i++)
5371 qemu_put_betls(f, &env->regs[i]);
5372 qemu_put_betls(f, &env->eip);
5373 qemu_put_betls(f, &env->eflags);
5374 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5375 qemu_put_be32s(f, &hflags);
5377 /* FPU */
5378 fpuc = env->fpuc;
5379 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5380 fptag = 0;
5381 for(i = 0; i < 8; i++) {
5382 fptag |= ((!env->fptags[i]) << i);
5385 qemu_put_be16s(f, &fpuc);
5386 qemu_put_be16s(f, &fpus);
5387 qemu_put_be16s(f, &fptag);
5389 #ifdef USE_X86LDOUBLE
5390 fpregs_format = 0;
5391 #else
5392 fpregs_format = 1;
5393 #endif
5394 qemu_put_be16s(f, &fpregs_format);
5396 for(i = 0; i < 8; i++) {
5397 #ifdef USE_X86LDOUBLE
5399 uint64_t mant;
5400 uint16_t exp;
5401 /* we save the real CPU data (in case of MMX usage only 'mant'
5402 contains the MMX register */
5403 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5404 qemu_put_be64(f, mant);
5405 qemu_put_be16(f, exp);
5407 #else
5408 /* if we use doubles for float emulation, we save the doubles to
5409 avoid losing information in case of MMX usage. It can give
5410 problems if the image is restored on a CPU where long
5411 doubles are used instead. */
5412 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5413 #endif
5416 for(i = 0; i < 6; i++)
5417 cpu_put_seg(f, &env->segs[i]);
5418 cpu_put_seg(f, &env->ldt);
5419 cpu_put_seg(f, &env->tr);
5420 cpu_put_seg(f, &env->gdt);
5421 cpu_put_seg(f, &env->idt);
5423 qemu_put_be32s(f, &env->sysenter_cs);
5424 qemu_put_be32s(f, &env->sysenter_esp);
5425 qemu_put_be32s(f, &env->sysenter_eip);
5427 qemu_put_betls(f, &env->cr[0]);
5428 qemu_put_betls(f, &env->cr[2]);
5429 qemu_put_betls(f, &env->cr[3]);
5430 qemu_put_betls(f, &env->cr[4]);
5432 for(i = 0; i < 8; i++)
5433 qemu_put_betls(f, &env->dr[i]);
5435 /* MMU */
5436 qemu_put_be32s(f, &env->a20_mask);
5438 /* XMM */
5439 qemu_put_be32s(f, &env->mxcsr);
5440 for(i = 0; i < CPU_NB_REGS; i++) {
5441 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5442 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5445 #ifdef TARGET_X86_64
5446 qemu_put_be64s(f, &env->efer);
5447 qemu_put_be64s(f, &env->star);
5448 qemu_put_be64s(f, &env->lstar);
5449 qemu_put_be64s(f, &env->cstar);
5450 qemu_put_be64s(f, &env->fmask);
5451 qemu_put_be64s(f, &env->kernelgsbase);
5452 #endif
5453 qemu_put_be32s(f, &env->smbase);
5456 #ifdef USE_X86LDOUBLE
5457 /* XXX: add that in a FPU generic layer */
5458 union x86_longdouble {
5459 uint64_t mant;
5460 uint16_t exp;
5463 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5464 #define EXPBIAS1 1023
5465 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5466 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5468 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5470 int e;
5471 /* mantissa */
5472 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5473 /* exponent + sign */
5474 e = EXPD1(temp) - EXPBIAS1 + 16383;
5475 e |= SIGND1(temp) >> 16;
5476 p->exp = e;
5478 #endif
5480 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5482 CPUState *env = opaque;
5483 int i, guess_mmx;
5484 uint32_t hflags;
5485 uint16_t fpus, fpuc, fptag, fpregs_format;
5487 if (version_id != 3 && version_id != 4)
5488 return -EINVAL;
5489 for(i = 0; i < CPU_NB_REGS; i++)
5490 qemu_get_betls(f, &env->regs[i]);
5491 qemu_get_betls(f, &env->eip);
5492 qemu_get_betls(f, &env->eflags);
5493 qemu_get_be32s(f, &hflags);
5495 qemu_get_be16s(f, &fpuc);
5496 qemu_get_be16s(f, &fpus);
5497 qemu_get_be16s(f, &fptag);
5498 qemu_get_be16s(f, &fpregs_format);
5500 /* NOTE: we cannot always restore the FPU state if the image come
5501 from a host with a different 'USE_X86LDOUBLE' define. We guess
5502 if we are in an MMX state to restore correctly in that case. */
5503 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5504 for(i = 0; i < 8; i++) {
5505 uint64_t mant;
5506 uint16_t exp;
5508 switch(fpregs_format) {
5509 case 0:
5510 mant = qemu_get_be64(f);
5511 exp = qemu_get_be16(f);
5512 #ifdef USE_X86LDOUBLE
5513 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5514 #else
5515 /* difficult case */
5516 if (guess_mmx)
5517 env->fpregs[i].mmx.MMX_Q(0) = mant;
5518 else
5519 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5520 #endif
5521 break;
5522 case 1:
5523 mant = qemu_get_be64(f);
5524 #ifdef USE_X86LDOUBLE
5526 union x86_longdouble *p;
5527 /* difficult case */
5528 p = (void *)&env->fpregs[i];
5529 if (guess_mmx) {
5530 p->mant = mant;
5531 p->exp = 0xffff;
5532 } else {
5533 fp64_to_fp80(p, mant);
5536 #else
5537 env->fpregs[i].mmx.MMX_Q(0) = mant;
5538 #endif
5539 break;
5540 default:
5541 return -EINVAL;
5545 env->fpuc = fpuc;
5546 /* XXX: restore FPU round state */
5547 env->fpstt = (fpus >> 11) & 7;
5548 env->fpus = fpus & ~0x3800;
5549 fptag ^= 0xff;
5550 for(i = 0; i < 8; i++) {
5551 env->fptags[i] = (fptag >> i) & 1;
5554 for(i = 0; i < 6; i++)
5555 cpu_get_seg(f, &env->segs[i]);
5556 cpu_get_seg(f, &env->ldt);
5557 cpu_get_seg(f, &env->tr);
5558 cpu_get_seg(f, &env->gdt);
5559 cpu_get_seg(f, &env->idt);
5561 qemu_get_be32s(f, &env->sysenter_cs);
5562 qemu_get_be32s(f, &env->sysenter_esp);
5563 qemu_get_be32s(f, &env->sysenter_eip);
5565 qemu_get_betls(f, &env->cr[0]);
5566 qemu_get_betls(f, &env->cr[2]);
5567 qemu_get_betls(f, &env->cr[3]);
5568 qemu_get_betls(f, &env->cr[4]);
5570 for(i = 0; i < 8; i++)
5571 qemu_get_betls(f, &env->dr[i]);
5573 /* MMU */
5574 qemu_get_be32s(f, &env->a20_mask);
5576 qemu_get_be32s(f, &env->mxcsr);
5577 for(i = 0; i < CPU_NB_REGS; i++) {
5578 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5579 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5582 #ifdef TARGET_X86_64
5583 qemu_get_be64s(f, &env->efer);
5584 qemu_get_be64s(f, &env->star);
5585 qemu_get_be64s(f, &env->lstar);
5586 qemu_get_be64s(f, &env->cstar);
5587 qemu_get_be64s(f, &env->fmask);
5588 qemu_get_be64s(f, &env->kernelgsbase);
5589 #endif
5590 if (version_id >= 4)
5591 qemu_get_be32s(f, &env->smbase);
5593 /* XXX: compute hflags from scratch, except for CPL and IIF */
5594 env->hflags = hflags;
5595 tlb_flush(env, 1);
5596 return 0;
5599 #elif defined(TARGET_PPC)
5600 void cpu_save(QEMUFile *f, void *opaque)
5604 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5606 return 0;
5609 #elif defined(TARGET_MIPS)
5610 void cpu_save(QEMUFile *f, void *opaque)
5614 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5616 return 0;
5619 #elif defined(TARGET_SPARC)
5620 void cpu_save(QEMUFile *f, void *opaque)
5622 CPUState *env = opaque;
5623 int i;
5624 uint32_t tmp;
5626 for(i = 0; i < 8; i++)
5627 qemu_put_betls(f, &env->gregs[i]);
5628 for(i = 0; i < NWINDOWS * 16; i++)
5629 qemu_put_betls(f, &env->regbase[i]);
5631 /* FPU */
5632 for(i = 0; i < TARGET_FPREGS; i++) {
5633 union {
5634 float32 f;
5635 uint32_t i;
5636 } u;
5637 u.f = env->fpr[i];
5638 qemu_put_be32(f, u.i);
5641 qemu_put_betls(f, &env->pc);
5642 qemu_put_betls(f, &env->npc);
5643 qemu_put_betls(f, &env->y);
5644 tmp = GET_PSR(env);
5645 qemu_put_be32(f, tmp);
5646 qemu_put_betls(f, &env->fsr);
5647 qemu_put_betls(f, &env->tbr);
5648 #ifndef TARGET_SPARC64
5649 qemu_put_be32s(f, &env->wim);
5650 /* MMU */
5651 for(i = 0; i < 16; i++)
5652 qemu_put_be32s(f, &env->mmuregs[i]);
5653 #endif
5656 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5658 CPUState *env = opaque;
5659 int i;
5660 uint32_t tmp;
5662 for(i = 0; i < 8; i++)
5663 qemu_get_betls(f, &env->gregs[i]);
5664 for(i = 0; i < NWINDOWS * 16; i++)
5665 qemu_get_betls(f, &env->regbase[i]);
5667 /* FPU */
5668 for(i = 0; i < TARGET_FPREGS; i++) {
5669 union {
5670 float32 f;
5671 uint32_t i;
5672 } u;
5673 u.i = qemu_get_be32(f);
5674 env->fpr[i] = u.f;
5677 qemu_get_betls(f, &env->pc);
5678 qemu_get_betls(f, &env->npc);
5679 qemu_get_betls(f, &env->y);
5680 tmp = qemu_get_be32(f);
5681 env->cwp = 0; /* needed to ensure that the wrapping registers are
5682 correctly updated */
5683 PUT_PSR(env, tmp);
5684 qemu_get_betls(f, &env->fsr);
5685 qemu_get_betls(f, &env->tbr);
5686 #ifndef TARGET_SPARC64
5687 qemu_get_be32s(f, &env->wim);
5688 /* MMU */
5689 for(i = 0; i < 16; i++)
5690 qemu_get_be32s(f, &env->mmuregs[i]);
5691 #endif
5692 tlb_flush(env, 1);
5693 return 0;
5696 #elif defined(TARGET_ARM)
5698 void cpu_save(QEMUFile *f, void *opaque)
5700 int i;
5701 CPUARMState *env = (CPUARMState *)opaque;
5703 for (i = 0; i < 16; i++) {
5704 qemu_put_be32(f, env->regs[i]);
5706 qemu_put_be32(f, cpsr_read(env));
5707 qemu_put_be32(f, env->spsr);
5708 for (i = 0; i < 6; i++) {
5709 qemu_put_be32(f, env->banked_spsr[i]);
5710 qemu_put_be32(f, env->banked_r13[i]);
5711 qemu_put_be32(f, env->banked_r14[i]);
5713 for (i = 0; i < 5; i++) {
5714 qemu_put_be32(f, env->usr_regs[i]);
5715 qemu_put_be32(f, env->fiq_regs[i]);
5717 qemu_put_be32(f, env->cp15.c0_cpuid);
5718 qemu_put_be32(f, env->cp15.c0_cachetype);
5719 qemu_put_be32(f, env->cp15.c1_sys);
5720 qemu_put_be32(f, env->cp15.c1_coproc);
5721 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
5722 qemu_put_be32(f, env->cp15.c2_base);
5723 qemu_put_be32(f, env->cp15.c2_data);
5724 qemu_put_be32(f, env->cp15.c2_insn);
5725 qemu_put_be32(f, env->cp15.c3);
5726 qemu_put_be32(f, env->cp15.c5_insn);
5727 qemu_put_be32(f, env->cp15.c5_data);
5728 for (i = 0; i < 8; i++) {
5729 qemu_put_be32(f, env->cp15.c6_region[i]);
5731 qemu_put_be32(f, env->cp15.c6_insn);
5732 qemu_put_be32(f, env->cp15.c6_data);
5733 qemu_put_be32(f, env->cp15.c9_insn);
5734 qemu_put_be32(f, env->cp15.c9_data);
5735 qemu_put_be32(f, env->cp15.c13_fcse);
5736 qemu_put_be32(f, env->cp15.c13_context);
5737 qemu_put_be32(f, env->cp15.c15_cpar);
5739 qemu_put_be32(f, env->features);
5741 if (arm_feature(env, ARM_FEATURE_VFP)) {
5742 for (i = 0; i < 16; i++) {
5743 CPU_DoubleU u;
5744 u.d = env->vfp.regs[i];
5745 qemu_put_be32(f, u.l.upper);
5746 qemu_put_be32(f, u.l.lower);
5748 for (i = 0; i < 16; i++) {
5749 qemu_put_be32(f, env->vfp.xregs[i]);
5752 /* TODO: Should use proper FPSCR access functions. */
5753 qemu_put_be32(f, env->vfp.vec_len);
5754 qemu_put_be32(f, env->vfp.vec_stride);
5757 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5758 for (i = 0; i < 16; i++) {
5759 qemu_put_be64(f, env->iwmmxt.regs[i]);
5761 for (i = 0; i < 16; i++) {
5762 qemu_put_be32(f, env->iwmmxt.cregs[i]);
5767 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5769 CPUARMState *env = (CPUARMState *)opaque;
5770 int i;
5772 if (version_id != 0)
5773 return -EINVAL;
5775 for (i = 0; i < 16; i++) {
5776 env->regs[i] = qemu_get_be32(f);
5778 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
5779 env->spsr = qemu_get_be32(f);
5780 for (i = 0; i < 6; i++) {
5781 env->banked_spsr[i] = qemu_get_be32(f);
5782 env->banked_r13[i] = qemu_get_be32(f);
5783 env->banked_r14[i] = qemu_get_be32(f);
5785 for (i = 0; i < 5; i++) {
5786 env->usr_regs[i] = qemu_get_be32(f);
5787 env->fiq_regs[i] = qemu_get_be32(f);
5789 env->cp15.c0_cpuid = qemu_get_be32(f);
5790 env->cp15.c0_cachetype = qemu_get_be32(f);
5791 env->cp15.c1_sys = qemu_get_be32(f);
5792 env->cp15.c1_coproc = qemu_get_be32(f);
5793 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
5794 env->cp15.c2_base = qemu_get_be32(f);
5795 env->cp15.c2_data = qemu_get_be32(f);
5796 env->cp15.c2_insn = qemu_get_be32(f);
5797 env->cp15.c3 = qemu_get_be32(f);
5798 env->cp15.c5_insn = qemu_get_be32(f);
5799 env->cp15.c5_data = qemu_get_be32(f);
5800 for (i = 0; i < 8; i++) {
5801 env->cp15.c6_region[i] = qemu_get_be32(f);
5803 env->cp15.c6_insn = qemu_get_be32(f);
5804 env->cp15.c6_data = qemu_get_be32(f);
5805 env->cp15.c9_insn = qemu_get_be32(f);
5806 env->cp15.c9_data = qemu_get_be32(f);
5807 env->cp15.c13_fcse = qemu_get_be32(f);
5808 env->cp15.c13_context = qemu_get_be32(f);
5809 env->cp15.c15_cpar = qemu_get_be32(f);
5811 env->features = qemu_get_be32(f);
5813 if (arm_feature(env, ARM_FEATURE_VFP)) {
5814 for (i = 0; i < 16; i++) {
5815 CPU_DoubleU u;
5816 u.l.upper = qemu_get_be32(f);
5817 u.l.lower = qemu_get_be32(f);
5818 env->vfp.regs[i] = u.d;
5820 for (i = 0; i < 16; i++) {
5821 env->vfp.xregs[i] = qemu_get_be32(f);
5824 /* TODO: Should use proper FPSCR access functions. */
5825 env->vfp.vec_len = qemu_get_be32(f);
5826 env->vfp.vec_stride = qemu_get_be32(f);
5829 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5830 for (i = 0; i < 16; i++) {
5831 env->iwmmxt.regs[i] = qemu_get_be64(f);
5833 for (i = 0; i < 16; i++) {
5834 env->iwmmxt.cregs[i] = qemu_get_be32(f);
5838 return 0;
5841 #else
5843 #warning No CPU save/restore functions
5845 #endif
5847 /***********************************************************/
5848 /* ram save/restore */
5850 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5852 int v;
5854 v = qemu_get_byte(f);
5855 switch(v) {
5856 case 0:
5857 if (qemu_get_buffer(f, buf, len) != len)
5858 return -EIO;
5859 break;
5860 case 1:
5861 v = qemu_get_byte(f);
5862 memset(buf, v, len);
5863 break;
5864 default:
5865 return -EINVAL;
5867 return 0;
5870 static int ram_load_v1(QEMUFile *f, void *opaque)
5872 int i, ret;
5874 if (qemu_get_be32(f) != phys_ram_size)
5875 return -EINVAL;
5876 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5877 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5878 if (ret)
5879 return ret;
5881 return 0;
5884 #define BDRV_HASH_BLOCK_SIZE 1024
5885 #define IOBUF_SIZE 4096
5886 #define RAM_CBLOCK_MAGIC 0xfabe
5888 typedef struct RamCompressState {
5889 z_stream zstream;
5890 QEMUFile *f;
5891 uint8_t buf[IOBUF_SIZE];
5892 } RamCompressState;
5894 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5896 int ret;
5897 memset(s, 0, sizeof(*s));
5898 s->f = f;
5899 ret = deflateInit2(&s->zstream, 1,
5900 Z_DEFLATED, 15,
5901 9, Z_DEFAULT_STRATEGY);
5902 if (ret != Z_OK)
5903 return -1;
5904 s->zstream.avail_out = IOBUF_SIZE;
5905 s->zstream.next_out = s->buf;
5906 return 0;
5909 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5911 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5912 qemu_put_be16(s->f, len);
5913 qemu_put_buffer(s->f, buf, len);
5916 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5918 int ret;
5920 s->zstream.avail_in = len;
5921 s->zstream.next_in = (uint8_t *)buf;
5922 while (s->zstream.avail_in > 0) {
5923 ret = deflate(&s->zstream, Z_NO_FLUSH);
5924 if (ret != Z_OK)
5925 return -1;
5926 if (s->zstream.avail_out == 0) {
5927 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5928 s->zstream.avail_out = IOBUF_SIZE;
5929 s->zstream.next_out = s->buf;
5932 return 0;
5935 static void ram_compress_close(RamCompressState *s)
5937 int len, ret;
5939 /* compress last bytes */
5940 for(;;) {
5941 ret = deflate(&s->zstream, Z_FINISH);
5942 if (ret == Z_OK || ret == Z_STREAM_END) {
5943 len = IOBUF_SIZE - s->zstream.avail_out;
5944 if (len > 0) {
5945 ram_put_cblock(s, s->buf, len);
5947 s->zstream.avail_out = IOBUF_SIZE;
5948 s->zstream.next_out = s->buf;
5949 if (ret == Z_STREAM_END)
5950 break;
5951 } else {
5952 goto fail;
5955 fail:
5956 deflateEnd(&s->zstream);
5959 typedef struct RamDecompressState {
5960 z_stream zstream;
5961 QEMUFile *f;
5962 uint8_t buf[IOBUF_SIZE];
5963 } RamDecompressState;
5965 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5967 int ret;
5968 memset(s, 0, sizeof(*s));
5969 s->f = f;
5970 ret = inflateInit(&s->zstream);
5971 if (ret != Z_OK)
5972 return -1;
5973 return 0;
5976 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5978 int ret, clen;
5980 s->zstream.avail_out = len;
5981 s->zstream.next_out = buf;
5982 while (s->zstream.avail_out > 0) {
5983 if (s->zstream.avail_in == 0) {
5984 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5985 return -1;
5986 clen = qemu_get_be16(s->f);
5987 if (clen > IOBUF_SIZE)
5988 return -1;
5989 qemu_get_buffer(s->f, s->buf, clen);
5990 s->zstream.avail_in = clen;
5991 s->zstream.next_in = s->buf;
5993 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5994 if (ret != Z_OK && ret != Z_STREAM_END) {
5995 return -1;
5998 return 0;
6001 static void ram_decompress_close(RamDecompressState *s)
6003 inflateEnd(&s->zstream);
6006 static void ram_save(QEMUFile *f, void *opaque)
6008 int i;
6009 RamCompressState s1, *s = &s1;
6010 uint8_t buf[10];
6012 qemu_put_be32(f, phys_ram_size);
6013 if (ram_compress_open(s, f) < 0)
6014 return;
6015 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6016 #if 0
6017 if (tight_savevm_enabled) {
6018 int64_t sector_num;
6019 int j;
6021 /* find if the memory block is available on a virtual
6022 block device */
6023 sector_num = -1;
6024 for(j = 0; j < MAX_DISKS; j++) {
6025 if (bs_table[j]) {
6026 sector_num = bdrv_hash_find(bs_table[j],
6027 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6028 if (sector_num >= 0)
6029 break;
6032 if (j == MAX_DISKS)
6033 goto normal_compress;
6034 buf[0] = 1;
6035 buf[1] = j;
6036 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6037 ram_compress_buf(s, buf, 10);
6038 } else
6039 #endif
6041 // normal_compress:
6042 buf[0] = 0;
6043 ram_compress_buf(s, buf, 1);
6044 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6047 ram_compress_close(s);
6050 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6052 RamDecompressState s1, *s = &s1;
6053 uint8_t buf[10];
6054 int i;
6056 if (version_id == 1)
6057 return ram_load_v1(f, opaque);
6058 if (version_id != 2)
6059 return -EINVAL;
6060 if (qemu_get_be32(f) != phys_ram_size)
6061 return -EINVAL;
6062 if (ram_decompress_open(s, f) < 0)
6063 return -EINVAL;
6064 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6065 if (ram_decompress_buf(s, buf, 1) < 0) {
6066 fprintf(stderr, "Error while reading ram block header\n");
6067 goto error;
6069 if (buf[0] == 0) {
6070 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6071 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6072 goto error;
6074 } else
6075 #if 0
6076 if (buf[0] == 1) {
6077 int bs_index;
6078 int64_t sector_num;
6080 ram_decompress_buf(s, buf + 1, 9);
6081 bs_index = buf[1];
6082 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6083 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6084 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6085 goto error;
6087 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6088 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6089 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6090 bs_index, sector_num);
6091 goto error;
6093 } else
6094 #endif
6096 error:
6097 printf("Error block header\n");
6098 return -EINVAL;
6101 ram_decompress_close(s);
6102 return 0;
6105 /***********************************************************/
6106 /* bottom halves (can be seen as timers which expire ASAP) */
6108 struct QEMUBH {
6109 QEMUBHFunc *cb;
6110 void *opaque;
6111 int scheduled;
6112 QEMUBH *next;
6115 static QEMUBH *first_bh = NULL;
6117 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6119 QEMUBH *bh;
6120 bh = qemu_mallocz(sizeof(QEMUBH));
6121 if (!bh)
6122 return NULL;
6123 bh->cb = cb;
6124 bh->opaque = opaque;
6125 return bh;
6128 int qemu_bh_poll(void)
6130 QEMUBH *bh, **pbh;
6131 int ret;
6133 ret = 0;
6134 for(;;) {
6135 pbh = &first_bh;
6136 bh = *pbh;
6137 if (!bh)
6138 break;
6139 ret = 1;
6140 *pbh = bh->next;
6141 bh->scheduled = 0;
6142 bh->cb(bh->opaque);
6144 return ret;
6147 void qemu_bh_schedule(QEMUBH *bh)
6149 CPUState *env = cpu_single_env;
6150 if (bh->scheduled)
6151 return;
6152 bh->scheduled = 1;
6153 bh->next = first_bh;
6154 first_bh = bh;
6156 /* stop the currently executing CPU to execute the BH ASAP */
6157 if (env) {
6158 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6162 void qemu_bh_cancel(QEMUBH *bh)
6164 QEMUBH **pbh;
6165 if (bh->scheduled) {
6166 pbh = &first_bh;
6167 while (*pbh != bh)
6168 pbh = &(*pbh)->next;
6169 *pbh = bh->next;
6170 bh->scheduled = 0;
6174 void qemu_bh_delete(QEMUBH *bh)
6176 qemu_bh_cancel(bh);
6177 qemu_free(bh);
6180 /***********************************************************/
6181 /* machine registration */
6183 QEMUMachine *first_machine = NULL;
6185 int qemu_register_machine(QEMUMachine *m)
6187 QEMUMachine **pm;
6188 pm = &first_machine;
6189 while (*pm != NULL)
6190 pm = &(*pm)->next;
6191 m->next = NULL;
6192 *pm = m;
6193 return 0;
6196 QEMUMachine *find_machine(const char *name)
6198 QEMUMachine *m;
6200 for(m = first_machine; m != NULL; m = m->next) {
6201 if (!strcmp(m->name, name))
6202 return m;
6204 return NULL;
6207 /***********************************************************/
6208 /* main execution loop */
6210 void gui_update(void *opaque)
6212 DisplayState *ds = opaque;
6213 ds->dpy_refresh(ds);
6214 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6217 struct vm_change_state_entry {
6218 VMChangeStateHandler *cb;
6219 void *opaque;
6220 LIST_ENTRY (vm_change_state_entry) entries;
6223 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6225 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6226 void *opaque)
6228 VMChangeStateEntry *e;
6230 e = qemu_mallocz(sizeof (*e));
6231 if (!e)
6232 return NULL;
6234 e->cb = cb;
6235 e->opaque = opaque;
6236 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6237 return e;
6240 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6242 LIST_REMOVE (e, entries);
6243 qemu_free (e);
6246 static void vm_state_notify(int running)
6248 VMChangeStateEntry *e;
6250 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6251 e->cb(e->opaque, running);
6255 /* XXX: support several handlers */
6256 static VMStopHandler *vm_stop_cb;
6257 static void *vm_stop_opaque;
6259 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6261 vm_stop_cb = cb;
6262 vm_stop_opaque = opaque;
6263 return 0;
6266 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6268 vm_stop_cb = NULL;
6271 void vm_start(void)
6273 if (!vm_running) {
6274 cpu_enable_ticks();
6275 vm_running = 1;
6276 vm_state_notify(1);
6280 void vm_stop(int reason)
6282 if (vm_running) {
6283 cpu_disable_ticks();
6284 vm_running = 0;
6285 if (reason != 0) {
6286 if (vm_stop_cb) {
6287 vm_stop_cb(vm_stop_opaque, reason);
6290 vm_state_notify(0);
6294 /* reset/shutdown handler */
6296 typedef struct QEMUResetEntry {
6297 QEMUResetHandler *func;
6298 void *opaque;
6299 struct QEMUResetEntry *next;
6300 } QEMUResetEntry;
6302 static QEMUResetEntry *first_reset_entry;
6303 static int reset_requested;
6304 static int shutdown_requested;
6305 static int powerdown_requested;
6307 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6309 QEMUResetEntry **pre, *re;
6311 pre = &first_reset_entry;
6312 while (*pre != NULL)
6313 pre = &(*pre)->next;
6314 re = qemu_mallocz(sizeof(QEMUResetEntry));
6315 re->func = func;
6316 re->opaque = opaque;
6317 re->next = NULL;
6318 *pre = re;
6321 static void qemu_system_reset(void)
6323 QEMUResetEntry *re;
6325 /* reset all devices */
6326 for(re = first_reset_entry; re != NULL; re = re->next) {
6327 re->func(re->opaque);
6331 void qemu_system_reset_request(void)
6333 if (no_reboot) {
6334 shutdown_requested = 1;
6335 } else {
6336 reset_requested = 1;
6338 if (cpu_single_env)
6339 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6342 void qemu_system_shutdown_request(void)
6344 shutdown_requested = 1;
6345 if (cpu_single_env)
6346 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6349 void qemu_system_powerdown_request(void)
6351 powerdown_requested = 1;
6352 if (cpu_single_env)
6353 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6356 void main_loop_wait(int timeout)
6358 IOHandlerRecord *ioh;
6359 fd_set rfds, wfds, xfds;
6360 int ret, nfds;
6361 #ifdef _WIN32
6362 int ret2, i;
6363 #endif
6364 struct timeval tv;
6365 PollingEntry *pe;
6368 /* XXX: need to suppress polling by better using win32 events */
6369 ret = 0;
6370 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6371 ret |= pe->func(pe->opaque);
6373 #ifdef _WIN32
6374 if (ret == 0) {
6375 int err;
6376 WaitObjects *w = &wait_objects;
6378 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6379 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6380 if (w->func[ret - WAIT_OBJECT_0])
6381 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6383 /* Check for additional signaled events */
6384 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6386 /* Check if event is signaled */
6387 ret2 = WaitForSingleObject(w->events[i], 0);
6388 if(ret2 == WAIT_OBJECT_0) {
6389 if (w->func[i])
6390 w->func[i](w->opaque[i]);
6391 } else if (ret2 == WAIT_TIMEOUT) {
6392 } else {
6393 err = GetLastError();
6394 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6397 } else if (ret == WAIT_TIMEOUT) {
6398 } else {
6399 err = GetLastError();
6400 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6403 #endif
6404 /* poll any events */
6405 /* XXX: separate device handlers from system ones */
6406 nfds = -1;
6407 FD_ZERO(&rfds);
6408 FD_ZERO(&wfds);
6409 FD_ZERO(&xfds);
6410 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6411 if (ioh->deleted)
6412 continue;
6413 if (ioh->fd_read &&
6414 (!ioh->fd_read_poll ||
6415 ioh->fd_read_poll(ioh->opaque) != 0)) {
6416 FD_SET(ioh->fd, &rfds);
6417 if (ioh->fd > nfds)
6418 nfds = ioh->fd;
6420 if (ioh->fd_write) {
6421 FD_SET(ioh->fd, &wfds);
6422 if (ioh->fd > nfds)
6423 nfds = ioh->fd;
6427 tv.tv_sec = 0;
6428 #ifdef _WIN32
6429 tv.tv_usec = 0;
6430 #else
6431 tv.tv_usec = timeout * 1000;
6432 #endif
6433 #if defined(CONFIG_SLIRP)
6434 if (slirp_inited) {
6435 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6437 #endif
6438 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6439 if (ret > 0) {
6440 IOHandlerRecord **pioh;
6442 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6443 if (ioh->deleted)
6444 continue;
6445 if (FD_ISSET(ioh->fd, &rfds)) {
6446 ioh->fd_read(ioh->opaque);
6448 if (FD_ISSET(ioh->fd, &wfds)) {
6449 ioh->fd_write(ioh->opaque);
6453 /* remove deleted IO handlers */
6454 pioh = &first_io_handler;
6455 while (*pioh) {
6456 ioh = *pioh;
6457 if (ioh->deleted) {
6458 *pioh = ioh->next;
6459 qemu_free(ioh);
6460 } else
6461 pioh = &ioh->next;
6464 #if defined(CONFIG_SLIRP)
6465 if (slirp_inited) {
6466 if (ret < 0) {
6467 FD_ZERO(&rfds);
6468 FD_ZERO(&wfds);
6469 FD_ZERO(&xfds);
6471 slirp_select_poll(&rfds, &wfds, &xfds);
6473 #endif
6474 qemu_aio_poll();
6476 if (vm_running) {
6477 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6478 qemu_get_clock(vm_clock));
6479 /* run dma transfers, if any */
6480 DMA_run();
6483 /* real time timers */
6484 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6485 qemu_get_clock(rt_clock));
6487 /* Check bottom-halves last in case any of the earlier events triggered
6488 them. */
6489 qemu_bh_poll();
6493 static CPUState *cur_cpu;
6495 int main_loop(void)
6497 int ret, timeout;
6498 #ifdef CONFIG_PROFILER
6499 int64_t ti;
6500 #endif
6501 CPUState *env;
6503 cur_cpu = first_cpu;
6504 for(;;) {
6505 if (vm_running) {
6507 env = cur_cpu;
6508 for(;;) {
6509 /* get next cpu */
6510 env = env->next_cpu;
6511 if (!env)
6512 env = first_cpu;
6513 #ifdef CONFIG_PROFILER
6514 ti = profile_getclock();
6515 #endif
6516 ret = cpu_exec(env);
6517 #ifdef CONFIG_PROFILER
6518 qemu_time += profile_getclock() - ti;
6519 #endif
6520 if (ret == EXCP_HLT) {
6521 /* Give the next CPU a chance to run. */
6522 cur_cpu = env;
6523 continue;
6525 if (ret != EXCP_HALTED)
6526 break;
6527 /* all CPUs are halted ? */
6528 if (env == cur_cpu)
6529 break;
6531 cur_cpu = env;
6533 if (shutdown_requested) {
6534 ret = EXCP_INTERRUPT;
6535 break;
6537 if (reset_requested) {
6538 reset_requested = 0;
6539 qemu_system_reset();
6540 ret = EXCP_INTERRUPT;
6542 if (powerdown_requested) {
6543 powerdown_requested = 0;
6544 qemu_system_powerdown();
6545 ret = EXCP_INTERRUPT;
6547 if (ret == EXCP_DEBUG) {
6548 vm_stop(EXCP_DEBUG);
6550 /* If all cpus are halted then wait until the next IRQ */
6551 /* XXX: use timeout computed from timers */
6552 if (ret == EXCP_HALTED)
6553 timeout = 10;
6554 else
6555 timeout = 0;
6556 } else {
6557 timeout = 10;
6559 #ifdef CONFIG_PROFILER
6560 ti = profile_getclock();
6561 #endif
6562 main_loop_wait(timeout);
6563 #ifdef CONFIG_PROFILER
6564 dev_time += profile_getclock() - ti;
6565 #endif
6567 cpu_disable_ticks();
6568 return ret;
6571 void help(void)
6573 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6574 "usage: %s [options] [disk_image]\n"
6575 "\n"
6576 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6577 "\n"
6578 "Standard options:\n"
6579 "-M machine select emulated machine (-M ? for list)\n"
6580 "-cpu cpu select CPU (-cpu ? for list)\n"
6581 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6582 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6583 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6584 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6585 "-mtdblock file use 'file' as on-board Flash memory image\n"
6586 "-sd file use 'file' as SecureDigital card image\n"
6587 "-pflash file use 'file' as a parallel flash image\n"
6588 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6589 "-snapshot write to temporary files instead of disk image files\n"
6590 #ifdef CONFIG_SDL
6591 "-no-frame open SDL window without a frame and window decorations\n"
6592 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
6593 "-no-quit disable SDL window close capability\n"
6594 #endif
6595 #ifdef TARGET_I386
6596 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6597 #endif
6598 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6599 "-smp n set the number of CPUs to 'n' [default=1]\n"
6600 "-nographic disable graphical output and redirect serial I/Os to console\n"
6601 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6602 #ifndef _WIN32
6603 "-k language use keyboard layout (for example \"fr\" for French)\n"
6604 #endif
6605 #ifdef HAS_AUDIO
6606 "-audio-help print list of audio drivers and their options\n"
6607 "-soundhw c1,... enable audio support\n"
6608 " and only specified sound cards (comma separated list)\n"
6609 " use -soundhw ? to get the list of supported cards\n"
6610 " use -soundhw all to enable all of them\n"
6611 #endif
6612 "-localtime set the real time clock to local time [default=utc]\n"
6613 "-full-screen start in full screen\n"
6614 #ifdef TARGET_I386
6615 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6616 #endif
6617 "-usb enable the USB driver (will be the default soon)\n"
6618 "-usbdevice name add the host or guest USB device 'name'\n"
6619 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6620 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6621 #endif
6622 "-name string set the name of the guest\n"
6623 "\n"
6624 "Network options:\n"
6625 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6626 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6627 #ifdef CONFIG_SLIRP
6628 "-net user[,vlan=n][,hostname=host]\n"
6629 " connect the user mode network stack to VLAN 'n' and send\n"
6630 " hostname 'host' to DHCP clients\n"
6631 #endif
6632 #ifdef _WIN32
6633 "-net tap[,vlan=n],ifname=name\n"
6634 " connect the host TAP network interface to VLAN 'n'\n"
6635 #else
6636 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6637 " connect the host TAP network interface to VLAN 'n' and use\n"
6638 " the network script 'file' (default=%s);\n"
6639 " use 'script=no' to disable script execution;\n"
6640 " use 'fd=h' to connect to an already opened TAP interface\n"
6641 #endif
6642 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6643 " connect the vlan 'n' to another VLAN using a socket connection\n"
6644 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6645 " connect the vlan 'n' to multicast maddr and port\n"
6646 "-net none use it alone to have zero network devices; if no -net option\n"
6647 " is provided, the default is '-net nic -net user'\n"
6648 "\n"
6649 #ifdef CONFIG_SLIRP
6650 "-tftp dir allow tftp access to files in dir [-net user]\n"
6651 "-bootp file advertise file in BOOTP replies\n"
6652 #ifndef _WIN32
6653 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6654 #endif
6655 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6656 " redirect TCP or UDP connections from host to guest [-net user]\n"
6657 #endif
6658 "\n"
6659 "Linux boot specific:\n"
6660 "-kernel bzImage use 'bzImage' as kernel image\n"
6661 "-append cmdline use 'cmdline' as kernel command line\n"
6662 "-initrd file use 'file' as initial ram disk\n"
6663 "\n"
6664 "Debug/Expert options:\n"
6665 "-monitor dev redirect the monitor to char device 'dev'\n"
6666 "-serial dev redirect the serial port to char device 'dev'\n"
6667 "-parallel dev redirect the parallel port to char device 'dev'\n"
6668 "-pidfile file Write PID to 'file'\n"
6669 "-S freeze CPU at startup (use 'c' to start execution)\n"
6670 "-s wait gdb connection to port\n"
6671 "-p port set gdb connection port [default=%s]\n"
6672 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6673 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6674 " translation (t=none or lba) (usually qemu can guess them)\n"
6675 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6676 #ifdef USE_KQEMU
6677 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6678 "-no-kqemu disable KQEMU kernel module usage\n"
6679 #endif
6680 #ifdef USE_CODE_COPY
6681 "-no-code-copy disable code copy acceleration\n"
6682 #endif
6683 #ifdef TARGET_I386
6684 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6685 " (default is CL-GD5446 PCI VGA)\n"
6686 "-no-acpi disable ACPI\n"
6687 #endif
6688 "-no-reboot exit instead of rebooting\n"
6689 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6690 "-vnc display start a VNC server on display\n"
6691 #ifndef _WIN32
6692 "-daemonize daemonize QEMU after initializing\n"
6693 #endif
6694 "-option-rom rom load a file, rom, into the option ROM space\n"
6695 #ifdef TARGET_SPARC
6696 "-prom-env variable=value set OpenBIOS nvram variables\n"
6697 #endif
6698 "\n"
6699 "During emulation, the following keys are useful:\n"
6700 "ctrl-alt-f toggle full screen\n"
6701 "ctrl-alt-n switch to virtual console 'n'\n"
6702 "ctrl-alt toggle mouse and keyboard grab\n"
6703 "\n"
6704 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6706 "qemu",
6707 DEFAULT_RAM_SIZE,
6708 #ifndef _WIN32
6709 DEFAULT_NETWORK_SCRIPT,
6710 #endif
6711 DEFAULT_GDBSTUB_PORT,
6712 "/tmp/qemu.log");
6713 exit(strcmp(optarg, "?"));
6716 #define HAS_ARG 0x0001
6718 enum {
6719 QEMU_OPTION_h,
6721 QEMU_OPTION_M,
6722 QEMU_OPTION_cpu,
6723 QEMU_OPTION_fda,
6724 QEMU_OPTION_fdb,
6725 QEMU_OPTION_hda,
6726 QEMU_OPTION_hdb,
6727 QEMU_OPTION_hdc,
6728 QEMU_OPTION_hdd,
6729 QEMU_OPTION_cdrom,
6730 QEMU_OPTION_mtdblock,
6731 QEMU_OPTION_sd,
6732 QEMU_OPTION_pflash,
6733 QEMU_OPTION_boot,
6734 QEMU_OPTION_snapshot,
6735 #ifdef TARGET_I386
6736 QEMU_OPTION_no_fd_bootchk,
6737 #endif
6738 QEMU_OPTION_m,
6739 QEMU_OPTION_nographic,
6740 QEMU_OPTION_portrait,
6741 #ifdef HAS_AUDIO
6742 QEMU_OPTION_audio_help,
6743 QEMU_OPTION_soundhw,
6744 #endif
6746 QEMU_OPTION_net,
6747 QEMU_OPTION_tftp,
6748 QEMU_OPTION_bootp,
6749 QEMU_OPTION_smb,
6750 QEMU_OPTION_redir,
6752 QEMU_OPTION_kernel,
6753 QEMU_OPTION_append,
6754 QEMU_OPTION_initrd,
6756 QEMU_OPTION_S,
6757 QEMU_OPTION_s,
6758 QEMU_OPTION_p,
6759 QEMU_OPTION_d,
6760 QEMU_OPTION_hdachs,
6761 QEMU_OPTION_L,
6762 QEMU_OPTION_no_code_copy,
6763 QEMU_OPTION_k,
6764 QEMU_OPTION_localtime,
6765 QEMU_OPTION_cirrusvga,
6766 QEMU_OPTION_vmsvga,
6767 QEMU_OPTION_g,
6768 QEMU_OPTION_std_vga,
6769 QEMU_OPTION_echr,
6770 QEMU_OPTION_monitor,
6771 QEMU_OPTION_serial,
6772 QEMU_OPTION_parallel,
6773 QEMU_OPTION_loadvm,
6774 QEMU_OPTION_full_screen,
6775 QEMU_OPTION_no_frame,
6776 QEMU_OPTION_alt_grab,
6777 QEMU_OPTION_no_quit,
6778 QEMU_OPTION_pidfile,
6779 QEMU_OPTION_no_kqemu,
6780 QEMU_OPTION_kernel_kqemu,
6781 QEMU_OPTION_win2k_hack,
6782 QEMU_OPTION_usb,
6783 QEMU_OPTION_usbdevice,
6784 QEMU_OPTION_smp,
6785 QEMU_OPTION_vnc,
6786 QEMU_OPTION_no_acpi,
6787 QEMU_OPTION_no_reboot,
6788 QEMU_OPTION_show_cursor,
6789 QEMU_OPTION_daemonize,
6790 QEMU_OPTION_option_rom,
6791 QEMU_OPTION_semihosting,
6792 QEMU_OPTION_name,
6793 QEMU_OPTION_prom_env,
6796 typedef struct QEMUOption {
6797 const char *name;
6798 int flags;
6799 int index;
6800 } QEMUOption;
6802 const QEMUOption qemu_options[] = {
6803 { "h", 0, QEMU_OPTION_h },
6804 { "help", 0, QEMU_OPTION_h },
6806 { "M", HAS_ARG, QEMU_OPTION_M },
6807 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6808 { "fda", HAS_ARG, QEMU_OPTION_fda },
6809 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6810 { "hda", HAS_ARG, QEMU_OPTION_hda },
6811 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6812 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6813 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6814 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6815 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6816 { "sd", HAS_ARG, QEMU_OPTION_sd },
6817 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6818 { "boot", HAS_ARG, QEMU_OPTION_boot },
6819 { "snapshot", 0, QEMU_OPTION_snapshot },
6820 #ifdef TARGET_I386
6821 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6822 #endif
6823 { "m", HAS_ARG, QEMU_OPTION_m },
6824 { "nographic", 0, QEMU_OPTION_nographic },
6825 { "portrait", 0, QEMU_OPTION_portrait },
6826 { "k", HAS_ARG, QEMU_OPTION_k },
6827 #ifdef HAS_AUDIO
6828 { "audio-help", 0, QEMU_OPTION_audio_help },
6829 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6830 #endif
6832 { "net", HAS_ARG, QEMU_OPTION_net},
6833 #ifdef CONFIG_SLIRP
6834 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6835 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6836 #ifndef _WIN32
6837 { "smb", HAS_ARG, QEMU_OPTION_smb },
6838 #endif
6839 { "redir", HAS_ARG, QEMU_OPTION_redir },
6840 #endif
6842 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6843 { "append", HAS_ARG, QEMU_OPTION_append },
6844 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6846 { "S", 0, QEMU_OPTION_S },
6847 { "s", 0, QEMU_OPTION_s },
6848 { "p", HAS_ARG, QEMU_OPTION_p },
6849 { "d", HAS_ARG, QEMU_OPTION_d },
6850 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6851 { "L", HAS_ARG, QEMU_OPTION_L },
6852 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6853 #ifdef USE_KQEMU
6854 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6855 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6856 #endif
6857 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6858 { "g", 1, QEMU_OPTION_g },
6859 #endif
6860 { "localtime", 0, QEMU_OPTION_localtime },
6861 { "std-vga", 0, QEMU_OPTION_std_vga },
6862 { "echr", HAS_ARG, QEMU_OPTION_echr },
6863 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
6864 { "serial", HAS_ARG, QEMU_OPTION_serial },
6865 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
6866 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6867 { "full-screen", 0, QEMU_OPTION_full_screen },
6868 #ifdef CONFIG_SDL
6869 { "no-frame", 0, QEMU_OPTION_no_frame },
6870 { "alt-grab", 0, QEMU_OPTION_alt_grab },
6871 { "no-quit", 0, QEMU_OPTION_no_quit },
6872 #endif
6873 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6874 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6875 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6876 { "smp", HAS_ARG, QEMU_OPTION_smp },
6877 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6879 /* temporary options */
6880 { "usb", 0, QEMU_OPTION_usb },
6881 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6882 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6883 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6884 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6885 { "show-cursor", 0, QEMU_OPTION_show_cursor },
6886 { "daemonize", 0, QEMU_OPTION_daemonize },
6887 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6888 #if defined(TARGET_ARM) || defined(TARGET_M68K)
6889 { "semihosting", 0, QEMU_OPTION_semihosting },
6890 #endif
6891 { "name", HAS_ARG, QEMU_OPTION_name },
6892 #if defined(TARGET_SPARC)
6893 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
6894 #endif
6895 { NULL },
6898 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6900 /* this stack is only used during signal handling */
6901 #define SIGNAL_STACK_SIZE 32768
6903 static uint8_t *signal_stack;
6905 #endif
6907 /* password input */
6909 int qemu_key_check(BlockDriverState *bs, const char *name)
6911 char password[256];
6912 int i;
6914 if (!bdrv_is_encrypted(bs))
6915 return 0;
6917 term_printf("%s is encrypted.\n", name);
6918 for(i = 0; i < 3; i++) {
6919 monitor_readline("Password: ", 1, password, sizeof(password));
6920 if (bdrv_set_key(bs, password) == 0)
6921 return 0;
6922 term_printf("invalid password\n");
6924 return -EPERM;
6927 static BlockDriverState *get_bdrv(int index)
6929 BlockDriverState *bs;
6931 if (index < 4) {
6932 bs = bs_table[index];
6933 } else if (index < 6) {
6934 bs = fd_table[index - 4];
6935 } else {
6936 bs = NULL;
6938 return bs;
6941 static void read_passwords(void)
6943 BlockDriverState *bs;
6944 int i;
6946 for(i = 0; i < 6; i++) {
6947 bs = get_bdrv(i);
6948 if (bs)
6949 qemu_key_check(bs, bdrv_get_device_name(bs));
6953 /* XXX: currently we cannot use simultaneously different CPUs */
6954 void register_machines(void)
6956 #if defined(TARGET_I386)
6957 qemu_register_machine(&pc_machine);
6958 qemu_register_machine(&isapc_machine);
6959 #elif defined(TARGET_PPC)
6960 qemu_register_machine(&heathrow_machine);
6961 qemu_register_machine(&core99_machine);
6962 qemu_register_machine(&prep_machine);
6963 qemu_register_machine(&ref405ep_machine);
6964 qemu_register_machine(&taihu_machine);
6965 #elif defined(TARGET_MIPS)
6966 qemu_register_machine(&mips_machine);
6967 qemu_register_machine(&mips_malta_machine);
6968 qemu_register_machine(&mips_pica61_machine);
6969 #elif defined(TARGET_SPARC)
6970 #ifdef TARGET_SPARC64
6971 qemu_register_machine(&sun4u_machine);
6972 #else
6973 qemu_register_machine(&ss5_machine);
6974 qemu_register_machine(&ss10_machine);
6975 #endif
6976 #elif defined(TARGET_ARM)
6977 qemu_register_machine(&integratorcp_machine);
6978 qemu_register_machine(&versatilepb_machine);
6979 qemu_register_machine(&versatileab_machine);
6980 qemu_register_machine(&realview_machine);
6981 qemu_register_machine(&akitapda_machine);
6982 qemu_register_machine(&spitzpda_machine);
6983 qemu_register_machine(&borzoipda_machine);
6984 qemu_register_machine(&terrierpda_machine);
6985 #elif defined(TARGET_SH4)
6986 qemu_register_machine(&shix_machine);
6987 #elif defined(TARGET_ALPHA)
6988 /* XXX: TODO */
6989 #elif defined(TARGET_M68K)
6990 qemu_register_machine(&mcf5208evb_machine);
6991 qemu_register_machine(&an5206_machine);
6992 #else
6993 #error unsupported CPU
6994 #endif
6997 #ifdef HAS_AUDIO
6998 struct soundhw soundhw[] = {
6999 #ifdef HAS_AUDIO_CHOICE
7000 #ifdef TARGET_I386
7002 "pcspk",
7003 "PC speaker",
7006 { .init_isa = pcspk_audio_init }
7008 #endif
7010 "sb16",
7011 "Creative Sound Blaster 16",
7014 { .init_isa = SB16_init }
7017 #ifdef CONFIG_ADLIB
7019 "adlib",
7020 #ifdef HAS_YMF262
7021 "Yamaha YMF262 (OPL3)",
7022 #else
7023 "Yamaha YM3812 (OPL2)",
7024 #endif
7027 { .init_isa = Adlib_init }
7029 #endif
7031 #ifdef CONFIG_GUS
7033 "gus",
7034 "Gravis Ultrasound GF1",
7037 { .init_isa = GUS_init }
7039 #endif
7042 "es1370",
7043 "ENSONIQ AudioPCI ES1370",
7046 { .init_pci = es1370_init }
7048 #endif
7050 { NULL, NULL, 0, 0, { NULL } }
7053 static void select_soundhw (const char *optarg)
7055 struct soundhw *c;
7057 if (*optarg == '?') {
7058 show_valid_cards:
7060 printf ("Valid sound card names (comma separated):\n");
7061 for (c = soundhw; c->name; ++c) {
7062 printf ("%-11s %s\n", c->name, c->descr);
7064 printf ("\n-soundhw all will enable all of the above\n");
7065 exit (*optarg != '?');
7067 else {
7068 size_t l;
7069 const char *p;
7070 char *e;
7071 int bad_card = 0;
7073 if (!strcmp (optarg, "all")) {
7074 for (c = soundhw; c->name; ++c) {
7075 c->enabled = 1;
7077 return;
7080 p = optarg;
7081 while (*p) {
7082 e = strchr (p, ',');
7083 l = !e ? strlen (p) : (size_t) (e - p);
7085 for (c = soundhw; c->name; ++c) {
7086 if (!strncmp (c->name, p, l)) {
7087 c->enabled = 1;
7088 break;
7092 if (!c->name) {
7093 if (l > 80) {
7094 fprintf (stderr,
7095 "Unknown sound card name (too big to show)\n");
7097 else {
7098 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7099 (int) l, p);
7101 bad_card = 1;
7103 p += l + (e != NULL);
7106 if (bad_card)
7107 goto show_valid_cards;
7110 #endif
7112 #ifdef _WIN32
7113 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7115 exit(STATUS_CONTROL_C_EXIT);
7116 return TRUE;
7118 #endif
7120 #define MAX_NET_CLIENTS 32
7122 int main(int argc, char **argv)
7124 #ifdef CONFIG_GDBSTUB
7125 int use_gdbstub;
7126 const char *gdbstub_port;
7127 #endif
7128 int i, cdrom_index, pflash_index;
7129 int snapshot, linux_boot;
7130 const char *initrd_filename;
7131 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7132 const char *pflash_filename[MAX_PFLASH];
7133 const char *sd_filename;
7134 const char *mtd_filename;
7135 const char *kernel_filename, *kernel_cmdline;
7136 DisplayState *ds = &display_state;
7137 int cyls, heads, secs, translation;
7138 char net_clients[MAX_NET_CLIENTS][256];
7139 int nb_net_clients;
7140 int optind;
7141 const char *r, *optarg;
7142 CharDriverState *monitor_hd;
7143 char monitor_device[128];
7144 char serial_devices[MAX_SERIAL_PORTS][128];
7145 int serial_device_index;
7146 char parallel_devices[MAX_PARALLEL_PORTS][128];
7147 int parallel_device_index;
7148 const char *loadvm = NULL;
7149 QEMUMachine *machine;
7150 const char *cpu_model;
7151 char usb_devices[MAX_USB_CMDLINE][128];
7152 int usb_devices_index;
7153 int fds[2];
7154 const char *pid_file = NULL;
7155 VLANState *vlan;
7157 LIST_INIT (&vm_change_state_head);
7158 #ifndef _WIN32
7160 struct sigaction act;
7161 sigfillset(&act.sa_mask);
7162 act.sa_flags = 0;
7163 act.sa_handler = SIG_IGN;
7164 sigaction(SIGPIPE, &act, NULL);
7166 #else
7167 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7168 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7169 QEMU to run on a single CPU */
7171 HANDLE h;
7172 DWORD mask, smask;
7173 int i;
7174 h = GetCurrentProcess();
7175 if (GetProcessAffinityMask(h, &mask, &smask)) {
7176 for(i = 0; i < 32; i++) {
7177 if (mask & (1 << i))
7178 break;
7180 if (i != 32) {
7181 mask = 1 << i;
7182 SetProcessAffinityMask(h, mask);
7186 #endif
7188 register_machines();
7189 machine = first_machine;
7190 cpu_model = NULL;
7191 initrd_filename = NULL;
7192 for(i = 0; i < MAX_FD; i++)
7193 fd_filename[i] = NULL;
7194 for(i = 0; i < MAX_DISKS; i++)
7195 hd_filename[i] = NULL;
7196 for(i = 0; i < MAX_PFLASH; i++)
7197 pflash_filename[i] = NULL;
7198 pflash_index = 0;
7199 sd_filename = NULL;
7200 mtd_filename = NULL;
7201 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7202 vga_ram_size = VGA_RAM_SIZE;
7203 #ifdef CONFIG_GDBSTUB
7204 use_gdbstub = 0;
7205 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7206 #endif
7207 snapshot = 0;
7208 nographic = 0;
7209 kernel_filename = NULL;
7210 kernel_cmdline = "";
7211 #ifdef TARGET_PPC
7212 cdrom_index = 1;
7213 #else
7214 cdrom_index = 2;
7215 #endif
7216 cyls = heads = secs = 0;
7217 translation = BIOS_ATA_TRANSLATION_AUTO;
7218 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7220 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7221 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7222 serial_devices[i][0] = '\0';
7223 serial_device_index = 0;
7225 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7226 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7227 parallel_devices[i][0] = '\0';
7228 parallel_device_index = 0;
7230 usb_devices_index = 0;
7232 nb_net_clients = 0;
7234 nb_nics = 0;
7235 /* default mac address of the first network interface */
7237 optind = 1;
7238 for(;;) {
7239 if (optind >= argc)
7240 break;
7241 r = argv[optind];
7242 if (r[0] != '-') {
7243 hd_filename[0] = argv[optind++];
7244 } else {
7245 const QEMUOption *popt;
7247 optind++;
7248 /* Treat --foo the same as -foo. */
7249 if (r[1] == '-')
7250 r++;
7251 popt = qemu_options;
7252 for(;;) {
7253 if (!popt->name) {
7254 fprintf(stderr, "%s: invalid option -- '%s'\n",
7255 argv[0], r);
7256 exit(1);
7258 if (!strcmp(popt->name, r + 1))
7259 break;
7260 popt++;
7262 if (popt->flags & HAS_ARG) {
7263 if (optind >= argc) {
7264 fprintf(stderr, "%s: option '%s' requires an argument\n",
7265 argv[0], r);
7266 exit(1);
7268 optarg = argv[optind++];
7269 } else {
7270 optarg = NULL;
7273 switch(popt->index) {
7274 case QEMU_OPTION_M:
7275 machine = find_machine(optarg);
7276 if (!machine) {
7277 QEMUMachine *m;
7278 printf("Supported machines are:\n");
7279 for(m = first_machine; m != NULL; m = m->next) {
7280 printf("%-10s %s%s\n",
7281 m->name, m->desc,
7282 m == first_machine ? " (default)" : "");
7284 exit(1);
7286 break;
7287 case QEMU_OPTION_cpu:
7288 /* hw initialization will check this */
7289 if (optarg[0] == '?') {
7290 #if defined(TARGET_PPC)
7291 ppc_cpu_list(stdout, &fprintf);
7292 #elif defined(TARGET_ARM)
7293 arm_cpu_list();
7294 #elif defined(TARGET_MIPS)
7295 mips_cpu_list(stdout, &fprintf);
7296 #elif defined(TARGET_SPARC)
7297 sparc_cpu_list(stdout, &fprintf);
7298 #endif
7299 exit(1);
7300 } else {
7301 cpu_model = optarg;
7303 break;
7304 case QEMU_OPTION_initrd:
7305 initrd_filename = optarg;
7306 break;
7307 case QEMU_OPTION_hda:
7308 case QEMU_OPTION_hdb:
7309 case QEMU_OPTION_hdc:
7310 case QEMU_OPTION_hdd:
7312 int hd_index;
7313 hd_index = popt->index - QEMU_OPTION_hda;
7314 hd_filename[hd_index] = optarg;
7315 if (hd_index == cdrom_index)
7316 cdrom_index = -1;
7318 break;
7319 case QEMU_OPTION_mtdblock:
7320 mtd_filename = optarg;
7321 break;
7322 case QEMU_OPTION_sd:
7323 sd_filename = optarg;
7324 break;
7325 case QEMU_OPTION_pflash:
7326 if (pflash_index >= MAX_PFLASH) {
7327 fprintf(stderr, "qemu: too many parallel flash images\n");
7328 exit(1);
7330 pflash_filename[pflash_index++] = optarg;
7331 break;
7332 case QEMU_OPTION_snapshot:
7333 snapshot = 1;
7334 break;
7335 case QEMU_OPTION_hdachs:
7337 const char *p;
7338 p = optarg;
7339 cyls = strtol(p, (char **)&p, 0);
7340 if (cyls < 1 || cyls > 16383)
7341 goto chs_fail;
7342 if (*p != ',')
7343 goto chs_fail;
7344 p++;
7345 heads = strtol(p, (char **)&p, 0);
7346 if (heads < 1 || heads > 16)
7347 goto chs_fail;
7348 if (*p != ',')
7349 goto chs_fail;
7350 p++;
7351 secs = strtol(p, (char **)&p, 0);
7352 if (secs < 1 || secs > 63)
7353 goto chs_fail;
7354 if (*p == ',') {
7355 p++;
7356 if (!strcmp(p, "none"))
7357 translation = BIOS_ATA_TRANSLATION_NONE;
7358 else if (!strcmp(p, "lba"))
7359 translation = BIOS_ATA_TRANSLATION_LBA;
7360 else if (!strcmp(p, "auto"))
7361 translation = BIOS_ATA_TRANSLATION_AUTO;
7362 else
7363 goto chs_fail;
7364 } else if (*p != '\0') {
7365 chs_fail:
7366 fprintf(stderr, "qemu: invalid physical CHS format\n");
7367 exit(1);
7370 break;
7371 case QEMU_OPTION_nographic:
7372 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7373 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7374 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7375 nographic = 1;
7376 break;
7377 case QEMU_OPTION_portrait:
7378 graphic_rotate = 1;
7379 break;
7380 case QEMU_OPTION_kernel:
7381 kernel_filename = optarg;
7382 break;
7383 case QEMU_OPTION_append:
7384 kernel_cmdline = optarg;
7385 break;
7386 case QEMU_OPTION_cdrom:
7387 if (cdrom_index >= 0) {
7388 hd_filename[cdrom_index] = optarg;
7390 break;
7391 case QEMU_OPTION_boot:
7392 boot_device = optarg[0];
7393 if (boot_device != 'a' &&
7394 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7395 // Network boot
7396 boot_device != 'n' &&
7397 #endif
7398 boot_device != 'c' && boot_device != 'd') {
7399 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7400 exit(1);
7402 break;
7403 case QEMU_OPTION_fda:
7404 fd_filename[0] = optarg;
7405 break;
7406 case QEMU_OPTION_fdb:
7407 fd_filename[1] = optarg;
7408 break;
7409 #ifdef TARGET_I386
7410 case QEMU_OPTION_no_fd_bootchk:
7411 fd_bootchk = 0;
7412 break;
7413 #endif
7414 case QEMU_OPTION_no_code_copy:
7415 code_copy_enabled = 0;
7416 break;
7417 case QEMU_OPTION_net:
7418 if (nb_net_clients >= MAX_NET_CLIENTS) {
7419 fprintf(stderr, "qemu: too many network clients\n");
7420 exit(1);
7422 pstrcpy(net_clients[nb_net_clients],
7423 sizeof(net_clients[0]),
7424 optarg);
7425 nb_net_clients++;
7426 break;
7427 #ifdef CONFIG_SLIRP
7428 case QEMU_OPTION_tftp:
7429 tftp_prefix = optarg;
7430 break;
7431 case QEMU_OPTION_bootp:
7432 bootp_filename = optarg;
7433 break;
7434 #ifndef _WIN32
7435 case QEMU_OPTION_smb:
7436 net_slirp_smb(optarg);
7437 break;
7438 #endif
7439 case QEMU_OPTION_redir:
7440 net_slirp_redir(optarg);
7441 break;
7442 #endif
7443 #ifdef HAS_AUDIO
7444 case QEMU_OPTION_audio_help:
7445 AUD_help ();
7446 exit (0);
7447 break;
7448 case QEMU_OPTION_soundhw:
7449 select_soundhw (optarg);
7450 break;
7451 #endif
7452 case QEMU_OPTION_h:
7453 help();
7454 break;
7455 case QEMU_OPTION_m:
7456 ram_size = atoi(optarg) * 1024 * 1024;
7457 if (ram_size <= 0)
7458 help();
7459 if (ram_size > PHYS_RAM_MAX_SIZE) {
7460 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7461 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7462 exit(1);
7464 break;
7465 case QEMU_OPTION_d:
7467 int mask;
7468 CPULogItem *item;
7470 mask = cpu_str_to_log_mask(optarg);
7471 if (!mask) {
7472 printf("Log items (comma separated):\n");
7473 for(item = cpu_log_items; item->mask != 0; item++) {
7474 printf("%-10s %s\n", item->name, item->help);
7476 exit(1);
7478 cpu_set_log(mask);
7480 break;
7481 #ifdef CONFIG_GDBSTUB
7482 case QEMU_OPTION_s:
7483 use_gdbstub = 1;
7484 break;
7485 case QEMU_OPTION_p:
7486 gdbstub_port = optarg;
7487 break;
7488 #endif
7489 case QEMU_OPTION_L:
7490 bios_dir = optarg;
7491 break;
7492 case QEMU_OPTION_S:
7493 autostart = 0;
7494 break;
7495 case QEMU_OPTION_k:
7496 keyboard_layout = optarg;
7497 break;
7498 case QEMU_OPTION_localtime:
7499 rtc_utc = 0;
7500 break;
7501 case QEMU_OPTION_cirrusvga:
7502 cirrus_vga_enabled = 1;
7503 vmsvga_enabled = 0;
7504 break;
7505 case QEMU_OPTION_vmsvga:
7506 cirrus_vga_enabled = 0;
7507 vmsvga_enabled = 1;
7508 break;
7509 case QEMU_OPTION_std_vga:
7510 cirrus_vga_enabled = 0;
7511 vmsvga_enabled = 0;
7512 break;
7513 case QEMU_OPTION_g:
7515 const char *p;
7516 int w, h, depth;
7517 p = optarg;
7518 w = strtol(p, (char **)&p, 10);
7519 if (w <= 0) {
7520 graphic_error:
7521 fprintf(stderr, "qemu: invalid resolution or depth\n");
7522 exit(1);
7524 if (*p != 'x')
7525 goto graphic_error;
7526 p++;
7527 h = strtol(p, (char **)&p, 10);
7528 if (h <= 0)
7529 goto graphic_error;
7530 if (*p == 'x') {
7531 p++;
7532 depth = strtol(p, (char **)&p, 10);
7533 if (depth != 8 && depth != 15 && depth != 16 &&
7534 depth != 24 && depth != 32)
7535 goto graphic_error;
7536 } else if (*p == '\0') {
7537 depth = graphic_depth;
7538 } else {
7539 goto graphic_error;
7542 graphic_width = w;
7543 graphic_height = h;
7544 graphic_depth = depth;
7546 break;
7547 case QEMU_OPTION_echr:
7549 char *r;
7550 term_escape_char = strtol(optarg, &r, 0);
7551 if (r == optarg)
7552 printf("Bad argument to echr\n");
7553 break;
7555 case QEMU_OPTION_monitor:
7556 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7557 break;
7558 case QEMU_OPTION_serial:
7559 if (serial_device_index >= MAX_SERIAL_PORTS) {
7560 fprintf(stderr, "qemu: too many serial ports\n");
7561 exit(1);
7563 pstrcpy(serial_devices[serial_device_index],
7564 sizeof(serial_devices[0]), optarg);
7565 serial_device_index++;
7566 break;
7567 case QEMU_OPTION_parallel:
7568 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7569 fprintf(stderr, "qemu: too many parallel ports\n");
7570 exit(1);
7572 pstrcpy(parallel_devices[parallel_device_index],
7573 sizeof(parallel_devices[0]), optarg);
7574 parallel_device_index++;
7575 break;
7576 case QEMU_OPTION_loadvm:
7577 loadvm = optarg;
7578 break;
7579 case QEMU_OPTION_full_screen:
7580 full_screen = 1;
7581 break;
7582 #ifdef CONFIG_SDL
7583 case QEMU_OPTION_no_frame:
7584 no_frame = 1;
7585 break;
7586 case QEMU_OPTION_alt_grab:
7587 alt_grab = 1;
7588 break;
7589 case QEMU_OPTION_no_quit:
7590 no_quit = 1;
7591 break;
7592 #endif
7593 case QEMU_OPTION_pidfile:
7594 pid_file = optarg;
7595 break;
7596 #ifdef TARGET_I386
7597 case QEMU_OPTION_win2k_hack:
7598 win2k_install_hack = 1;
7599 break;
7600 #endif
7601 #ifdef USE_KQEMU
7602 case QEMU_OPTION_no_kqemu:
7603 kqemu_allowed = 0;
7604 break;
7605 case QEMU_OPTION_kernel_kqemu:
7606 kqemu_allowed = 2;
7607 break;
7608 #endif
7609 case QEMU_OPTION_usb:
7610 usb_enabled = 1;
7611 break;
7612 case QEMU_OPTION_usbdevice:
7613 usb_enabled = 1;
7614 if (usb_devices_index >= MAX_USB_CMDLINE) {
7615 fprintf(stderr, "Too many USB devices\n");
7616 exit(1);
7618 pstrcpy(usb_devices[usb_devices_index],
7619 sizeof(usb_devices[usb_devices_index]),
7620 optarg);
7621 usb_devices_index++;
7622 break;
7623 case QEMU_OPTION_smp:
7624 smp_cpus = atoi(optarg);
7625 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7626 fprintf(stderr, "Invalid number of CPUs\n");
7627 exit(1);
7629 break;
7630 case QEMU_OPTION_vnc:
7631 vnc_display = optarg;
7632 break;
7633 case QEMU_OPTION_no_acpi:
7634 acpi_enabled = 0;
7635 break;
7636 case QEMU_OPTION_no_reboot:
7637 no_reboot = 1;
7638 break;
7639 case QEMU_OPTION_show_cursor:
7640 cursor_hide = 0;
7641 break;
7642 case QEMU_OPTION_daemonize:
7643 daemonize = 1;
7644 break;
7645 case QEMU_OPTION_option_rom:
7646 if (nb_option_roms >= MAX_OPTION_ROMS) {
7647 fprintf(stderr, "Too many option ROMs\n");
7648 exit(1);
7650 option_rom[nb_option_roms] = optarg;
7651 nb_option_roms++;
7652 break;
7653 case QEMU_OPTION_semihosting:
7654 semihosting_enabled = 1;
7655 break;
7656 case QEMU_OPTION_name:
7657 qemu_name = optarg;
7658 break;
7659 #ifdef TARGET_SPARC
7660 case QEMU_OPTION_prom_env:
7661 if (nb_prom_envs >= MAX_PROM_ENVS) {
7662 fprintf(stderr, "Too many prom variables\n");
7663 exit(1);
7665 prom_envs[nb_prom_envs] = optarg;
7666 nb_prom_envs++;
7667 break;
7668 #endif
7673 #ifndef _WIN32
7674 if (daemonize && !nographic && vnc_display == NULL) {
7675 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7676 daemonize = 0;
7679 if (daemonize) {
7680 pid_t pid;
7682 if (pipe(fds) == -1)
7683 exit(1);
7685 pid = fork();
7686 if (pid > 0) {
7687 uint8_t status;
7688 ssize_t len;
7690 close(fds[1]);
7692 again:
7693 len = read(fds[0], &status, 1);
7694 if (len == -1 && (errno == EINTR))
7695 goto again;
7697 if (len != 1)
7698 exit(1);
7699 else if (status == 1) {
7700 fprintf(stderr, "Could not acquire pidfile\n");
7701 exit(1);
7702 } else
7703 exit(0);
7704 } else if (pid < 0)
7705 exit(1);
7707 setsid();
7709 pid = fork();
7710 if (pid > 0)
7711 exit(0);
7712 else if (pid < 0)
7713 exit(1);
7715 umask(027);
7716 chdir("/");
7718 signal(SIGTSTP, SIG_IGN);
7719 signal(SIGTTOU, SIG_IGN);
7720 signal(SIGTTIN, SIG_IGN);
7722 #endif
7724 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7725 if (daemonize) {
7726 uint8_t status = 1;
7727 write(fds[1], &status, 1);
7728 } else
7729 fprintf(stderr, "Could not acquire pid file\n");
7730 exit(1);
7733 #ifdef USE_KQEMU
7734 if (smp_cpus > 1)
7735 kqemu_allowed = 0;
7736 #endif
7737 linux_boot = (kernel_filename != NULL);
7739 if (!linux_boot &&
7740 boot_device != 'n' &&
7741 hd_filename[0] == '\0' &&
7742 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7743 fd_filename[0] == '\0')
7744 help();
7746 /* boot to floppy or the default cd if no hard disk defined yet */
7747 if (hd_filename[0] == '\0' && boot_device == 'c') {
7748 if (fd_filename[0] != '\0')
7749 boot_device = 'a';
7750 else
7751 boot_device = 'd';
7754 setvbuf(stdout, NULL, _IOLBF, 0);
7756 init_timers();
7757 init_timer_alarm();
7758 qemu_aio_init();
7760 #ifdef _WIN32
7761 socket_init();
7762 #endif
7764 /* init network clients */
7765 if (nb_net_clients == 0) {
7766 /* if no clients, we use a default config */
7767 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7768 "nic");
7769 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7770 "user");
7771 nb_net_clients = 2;
7774 for(i = 0;i < nb_net_clients; i++) {
7775 if (net_client_init(net_clients[i]) < 0)
7776 exit(1);
7778 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
7779 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
7780 continue;
7781 if (vlan->nb_guest_devs == 0) {
7782 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
7783 exit(1);
7785 if (vlan->nb_host_devs == 0)
7786 fprintf(stderr,
7787 "Warning: vlan %d is not connected to host network\n",
7788 vlan->id);
7791 #ifdef TARGET_I386
7792 if (boot_device == 'n') {
7793 for (i = 0; i < nb_nics; i++) {
7794 const char *model = nd_table[i].model;
7795 char buf[1024];
7796 if (model == NULL)
7797 model = "ne2k_pci";
7798 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7799 if (get_image_size(buf) > 0) {
7800 option_rom[nb_option_roms] = strdup(buf);
7801 nb_option_roms++;
7802 break;
7805 if (i == nb_nics) {
7806 fprintf(stderr, "No valid PXE rom found for network device\n");
7807 exit(1);
7809 boot_device = 'c'; /* to prevent confusion by the BIOS */
7811 #endif
7813 /* init the memory */
7814 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7816 phys_ram_base = qemu_vmalloc(phys_ram_size);
7817 if (!phys_ram_base) {
7818 fprintf(stderr, "Could not allocate physical memory\n");
7819 exit(1);
7822 /* we always create the cdrom drive, even if no disk is there */
7823 bdrv_init();
7824 if (cdrom_index >= 0) {
7825 bs_table[cdrom_index] = bdrv_new("cdrom");
7826 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7829 /* open the virtual block devices */
7830 for(i = 0; i < MAX_DISKS; i++) {
7831 if (hd_filename[i]) {
7832 if (!bs_table[i]) {
7833 char buf[64];
7834 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7835 bs_table[i] = bdrv_new(buf);
7837 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7838 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7839 hd_filename[i]);
7840 exit(1);
7842 if (i == 0 && cyls != 0) {
7843 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7844 bdrv_set_translation_hint(bs_table[i], translation);
7849 /* we always create at least one floppy disk */
7850 fd_table[0] = bdrv_new("fda");
7851 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7853 for(i = 0; i < MAX_FD; i++) {
7854 if (fd_filename[i]) {
7855 if (!fd_table[i]) {
7856 char buf[64];
7857 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7858 fd_table[i] = bdrv_new(buf);
7859 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7861 if (fd_filename[i][0] != '\0') {
7862 if (bdrv_open(fd_table[i], fd_filename[i],
7863 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7864 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7865 fd_filename[i]);
7866 exit(1);
7872 /* Open the virtual parallel flash block devices */
7873 for(i = 0; i < MAX_PFLASH; i++) {
7874 if (pflash_filename[i]) {
7875 if (!pflash_table[i]) {
7876 char buf[64];
7877 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7878 pflash_table[i] = bdrv_new(buf);
7880 if (bdrv_open(pflash_table[i], pflash_filename[i],
7881 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7882 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7883 pflash_filename[i]);
7884 exit(1);
7889 sd_bdrv = bdrv_new ("sd");
7890 /* FIXME: This isn't really a floppy, but it's a reasonable
7891 approximation. */
7892 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7893 if (sd_filename) {
7894 if (bdrv_open(sd_bdrv, sd_filename,
7895 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7896 fprintf(stderr, "qemu: could not open SD card image %s\n",
7897 sd_filename);
7898 } else
7899 qemu_key_check(sd_bdrv, sd_filename);
7902 if (mtd_filename) {
7903 mtd_bdrv = bdrv_new ("mtd");
7904 if (bdrv_open(mtd_bdrv, mtd_filename,
7905 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
7906 qemu_key_check(mtd_bdrv, mtd_filename)) {
7907 fprintf(stderr, "qemu: could not open Flash image %s\n",
7908 mtd_filename);
7909 bdrv_delete(mtd_bdrv);
7910 mtd_bdrv = 0;
7914 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7915 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7917 init_ioports();
7919 /* terminal init */
7920 memset(&display_state, 0, sizeof(display_state));
7921 if (nographic) {
7922 /* nearly nothing to do */
7923 dumb_display_init(ds);
7924 } else if (vnc_display != NULL) {
7925 vnc_display_init(ds, vnc_display);
7926 } else {
7927 #if defined(CONFIG_SDL)
7928 sdl_display_init(ds, full_screen, no_frame);
7929 #elif defined(CONFIG_COCOA)
7930 cocoa_display_init(ds, full_screen);
7931 #endif
7934 /* Maintain compatibility with multiple stdio monitors */
7935 if (!strcmp(monitor_device,"stdio")) {
7936 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7937 if (!strcmp(serial_devices[i],"mon:stdio")) {
7938 monitor_device[0] = '\0';
7939 break;
7940 } else if (!strcmp(serial_devices[i],"stdio")) {
7941 monitor_device[0] = '\0';
7942 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7943 break;
7947 if (monitor_device[0] != '\0') {
7948 monitor_hd = qemu_chr_open(monitor_device);
7949 if (!monitor_hd) {
7950 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7951 exit(1);
7953 monitor_init(monitor_hd, !nographic);
7956 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7957 const char *devname = serial_devices[i];
7958 if (devname[0] != '\0' && strcmp(devname, "none")) {
7959 serial_hds[i] = qemu_chr_open(devname);
7960 if (!serial_hds[i]) {
7961 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7962 devname);
7963 exit(1);
7965 if (!strcmp(devname, "vc"))
7966 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7970 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7971 const char *devname = parallel_devices[i];
7972 if (devname[0] != '\0' && strcmp(devname, "none")) {
7973 parallel_hds[i] = qemu_chr_open(devname);
7974 if (!parallel_hds[i]) {
7975 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7976 devname);
7977 exit(1);
7979 if (!strcmp(devname, "vc"))
7980 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7984 machine->init(ram_size, vga_ram_size, boot_device,
7985 ds, fd_filename, snapshot,
7986 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7988 /* init USB devices */
7989 if (usb_enabled) {
7990 for(i = 0; i < usb_devices_index; i++) {
7991 if (usb_device_add(usb_devices[i]) < 0) {
7992 fprintf(stderr, "Warning: could not add USB device %s\n",
7993 usb_devices[i]);
7998 if (display_state.dpy_refresh) {
7999 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8000 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8003 #ifdef CONFIG_GDBSTUB
8004 if (use_gdbstub) {
8005 /* XXX: use standard host:port notation and modify options
8006 accordingly. */
8007 if (gdbserver_start(gdbstub_port) < 0) {
8008 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8009 gdbstub_port);
8010 exit(1);
8012 } else
8013 #endif
8014 if (loadvm)
8015 do_loadvm(loadvm);
8018 /* XXX: simplify init */
8019 read_passwords();
8020 if (autostart) {
8021 vm_start();
8025 if (daemonize) {
8026 uint8_t status = 0;
8027 ssize_t len;
8028 int fd;
8030 again1:
8031 len = write(fds[1], &status, 1);
8032 if (len == -1 && (errno == EINTR))
8033 goto again1;
8035 if (len != 1)
8036 exit(1);
8038 fd = open("/dev/null", O_RDWR);
8039 if (fd == -1)
8040 exit(1);
8042 dup2(fd, 0);
8043 dup2(fd, 1);
8044 dup2(fd, 2);
8046 close(fd);
8049 main_loop();
8050 quit_timers();
8051 return 0;