Share more SPR instanciations between all PowerPC 401 incarnations.
[qemu/qemu_0_9_1_stable.git] / vl.c
blob46ce9008d8bd840c6e26ccdf06a27e25ed079cc7
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2007 Fabrice Bellard
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 #include <sys/select.h>
46 #include <arpa/inet.h>
47 #ifdef _BSD
48 #include <sys/stat.h>
49 #ifndef __APPLE__
50 #include <libutil.h>
51 #endif
52 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
53 #include <freebsd/stdlib.h>
54 #else
55 #ifndef __sun__
56 #include <linux/if.h>
57 #include <linux/if_tun.h>
58 #include <pty.h>
59 #include <malloc.h>
60 #include <linux/rtc.h>
62 /* For the benefit of older linux systems which don't supply it,
63 we use a local copy of hpet.h. */
64 /* #include <linux/hpet.h> */
65 #include "hpet.h"
67 #include <linux/ppdev.h>
68 #include <linux/parport.h>
69 #else
70 #include <sys/stat.h>
71 #include <sys/ethernet.h>
72 #include <sys/sockio.h>
73 #include <netinet/arp.h>
74 #include <netinet/in.h>
75 #include <netinet/in_systm.h>
76 #include <netinet/ip.h>
77 #include <netinet/ip_icmp.h> // must come after ip.h
78 #include <netinet/udp.h>
79 #include <netinet/tcp.h>
80 #include <net/if.h>
81 #include <syslog.h>
82 #include <stropts.h>
83 #endif
84 #endif
85 #else
86 #include <winsock2.h>
87 int inet_aton(const char *cp, struct in_addr *ia);
88 #endif
90 #if defined(CONFIG_SLIRP)
91 #include "libslirp.h"
92 #endif
94 #ifdef _WIN32
95 #include <malloc.h>
96 #include <sys/timeb.h>
97 #include <windows.h>
98 #define getopt_long_only getopt_long
99 #define memalign(align, size) malloc(size)
100 #endif
102 #include "qemu_socket.h"
104 #ifdef CONFIG_SDL
105 #ifdef __APPLE__
106 #include <SDL/SDL.h>
107 #endif
108 #endif /* CONFIG_SDL */
110 #ifdef CONFIG_COCOA
111 #undef main
112 #define main qemu_main
113 #endif /* CONFIG_COCOA */
115 #include "disas.h"
117 #include "exec-all.h"
119 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
120 #ifdef __sun__
121 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
122 #else
123 #define SMBD_COMMAND "/usr/sbin/smbd"
124 #endif
126 //#define DEBUG_UNUSED_IOPORT
127 //#define DEBUG_IOPORT
129 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
131 #ifdef TARGET_PPC
132 #define DEFAULT_RAM_SIZE 144
133 #else
134 #define DEFAULT_RAM_SIZE 128
135 #endif
136 /* in ms */
137 #define GUI_REFRESH_INTERVAL 30
139 /* Max number of USB devices that can be specified on the commandline. */
140 #define MAX_USB_CMDLINE 8
142 /* XXX: use a two level table to limit memory usage */
143 #define MAX_IOPORTS 65536
145 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
146 char phys_ram_file[1024];
147 void *ioport_opaque[MAX_IOPORTS];
148 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
149 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
150 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
151 to store the VM snapshots */
152 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
153 BlockDriverState *pflash_table[MAX_PFLASH];
154 BlockDriverState *sd_bdrv;
155 BlockDriverState *mtd_bdrv;
156 /* point to the block driver where the snapshots are managed */
157 BlockDriverState *bs_snapshots;
158 int vga_ram_size;
159 static DisplayState display_state;
160 int nographic;
161 const char* keyboard_layout = NULL;
162 int64_t ticks_per_sec;
163 int boot_device = 'c';
164 int ram_size;
165 int pit_min_timer_count = 0;
166 int nb_nics;
167 NICInfo nd_table[MAX_NICS];
168 int vm_running;
169 int rtc_utc = 1;
170 int cirrus_vga_enabled = 1;
171 int vmsvga_enabled = 0;
172 #ifdef TARGET_SPARC
173 int graphic_width = 1024;
174 int graphic_height = 768;
175 int graphic_depth = 8;
176 #else
177 int graphic_width = 800;
178 int graphic_height = 600;
179 int graphic_depth = 15;
180 #endif
181 int full_screen = 0;
182 int no_frame = 0;
183 int no_quit = 0;
184 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
185 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
186 #ifdef TARGET_I386
187 int win2k_install_hack = 0;
188 #endif
189 int usb_enabled = 0;
190 static VLANState *first_vlan;
191 int smp_cpus = 1;
192 const char *vnc_display;
193 #if defined(TARGET_SPARC)
194 #define MAX_CPUS 16
195 #elif defined(TARGET_I386)
196 #define MAX_CPUS 255
197 #else
198 #define MAX_CPUS 1
199 #endif
200 int acpi_enabled = 1;
201 int fd_bootchk = 1;
202 int no_reboot = 0;
203 int cursor_hide = 1;
204 int graphic_rotate = 0;
205 int daemonize = 0;
206 const char *option_rom[MAX_OPTION_ROMS];
207 int nb_option_roms;
208 int semihosting_enabled = 0;
209 int autostart = 1;
210 #ifdef TARGET_ARM
211 int old_param = 0;
212 #endif
213 const char *qemu_name;
214 int alt_grab = 0;
215 #ifdef TARGET_SPARC
216 unsigned int nb_prom_envs = 0;
217 const char *prom_envs[MAX_PROM_ENVS];
218 #endif
220 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
222 /***********************************************************/
223 /* x86 ISA bus support */
225 target_phys_addr_t isa_mem_base = 0;
226 PicState2 *isa_pic;
228 uint32_t default_ioport_readb(void *opaque, uint32_t address)
230 #ifdef DEBUG_UNUSED_IOPORT
231 fprintf(stderr, "unused inb: port=0x%04x\n", address);
232 #endif
233 return 0xff;
236 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
238 #ifdef DEBUG_UNUSED_IOPORT
239 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
240 #endif
243 /* default is to make two byte accesses */
244 uint32_t default_ioport_readw(void *opaque, uint32_t address)
246 uint32_t data;
247 data = ioport_read_table[0][address](ioport_opaque[address], address);
248 address = (address + 1) & (MAX_IOPORTS - 1);
249 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
250 return data;
253 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
255 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
256 address = (address + 1) & (MAX_IOPORTS - 1);
257 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
260 uint32_t default_ioport_readl(void *opaque, uint32_t address)
262 #ifdef DEBUG_UNUSED_IOPORT
263 fprintf(stderr, "unused inl: port=0x%04x\n", address);
264 #endif
265 return 0xffffffff;
268 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
270 #ifdef DEBUG_UNUSED_IOPORT
271 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
272 #endif
275 void init_ioports(void)
277 int i;
279 for(i = 0; i < MAX_IOPORTS; i++) {
280 ioport_read_table[0][i] = default_ioport_readb;
281 ioport_write_table[0][i] = default_ioport_writeb;
282 ioport_read_table[1][i] = default_ioport_readw;
283 ioport_write_table[1][i] = default_ioport_writew;
284 ioport_read_table[2][i] = default_ioport_readl;
285 ioport_write_table[2][i] = default_ioport_writel;
289 /* size is the word size in byte */
290 int register_ioport_read(int start, int length, int size,
291 IOPortReadFunc *func, void *opaque)
293 int i, bsize;
295 if (size == 1) {
296 bsize = 0;
297 } else if (size == 2) {
298 bsize = 1;
299 } else if (size == 4) {
300 bsize = 2;
301 } else {
302 hw_error("register_ioport_read: invalid size");
303 return -1;
305 for(i = start; i < start + length; i += size) {
306 ioport_read_table[bsize][i] = func;
307 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
308 hw_error("register_ioport_read: invalid opaque");
309 ioport_opaque[i] = opaque;
311 return 0;
314 /* size is the word size in byte */
315 int register_ioport_write(int start, int length, int size,
316 IOPortWriteFunc *func, void *opaque)
318 int i, bsize;
320 if (size == 1) {
321 bsize = 0;
322 } else if (size == 2) {
323 bsize = 1;
324 } else if (size == 4) {
325 bsize = 2;
326 } else {
327 hw_error("register_ioport_write: invalid size");
328 return -1;
330 for(i = start; i < start + length; i += size) {
331 ioport_write_table[bsize][i] = func;
332 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
333 hw_error("register_ioport_write: invalid opaque");
334 ioport_opaque[i] = opaque;
336 return 0;
339 void isa_unassign_ioport(int start, int length)
341 int i;
343 for(i = start; i < start + length; i++) {
344 ioport_read_table[0][i] = default_ioport_readb;
345 ioport_read_table[1][i] = default_ioport_readw;
346 ioport_read_table[2][i] = default_ioport_readl;
348 ioport_write_table[0][i] = default_ioport_writeb;
349 ioport_write_table[1][i] = default_ioport_writew;
350 ioport_write_table[2][i] = default_ioport_writel;
354 /***********************************************************/
356 void cpu_outb(CPUState *env, int addr, int val)
358 #ifdef DEBUG_IOPORT
359 if (loglevel & CPU_LOG_IOPORT)
360 fprintf(logfile, "outb: %04x %02x\n", addr, val);
361 #endif
362 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
363 #ifdef USE_KQEMU
364 if (env)
365 env->last_io_time = cpu_get_time_fast();
366 #endif
369 void cpu_outw(CPUState *env, int addr, int val)
371 #ifdef DEBUG_IOPORT
372 if (loglevel & CPU_LOG_IOPORT)
373 fprintf(logfile, "outw: %04x %04x\n", addr, val);
374 #endif
375 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
376 #ifdef USE_KQEMU
377 if (env)
378 env->last_io_time = cpu_get_time_fast();
379 #endif
382 void cpu_outl(CPUState *env, int addr, int val)
384 #ifdef DEBUG_IOPORT
385 if (loglevel & CPU_LOG_IOPORT)
386 fprintf(logfile, "outl: %04x %08x\n", addr, val);
387 #endif
388 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
389 #ifdef USE_KQEMU
390 if (env)
391 env->last_io_time = cpu_get_time_fast();
392 #endif
395 int cpu_inb(CPUState *env, int addr)
397 int val;
398 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
399 #ifdef DEBUG_IOPORT
400 if (loglevel & CPU_LOG_IOPORT)
401 fprintf(logfile, "inb : %04x %02x\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_inw(CPUState *env, int addr)
412 int val;
413 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
414 #ifdef DEBUG_IOPORT
415 if (loglevel & CPU_LOG_IOPORT)
416 fprintf(logfile, "inw : %04x %04x\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 int cpu_inl(CPUState *env, int addr)
427 int val;
428 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
429 #ifdef DEBUG_IOPORT
430 if (loglevel & CPU_LOG_IOPORT)
431 fprintf(logfile, "inl : %04x %08x\n", addr, val);
432 #endif
433 #ifdef USE_KQEMU
434 if (env)
435 env->last_io_time = cpu_get_time_fast();
436 #endif
437 return val;
440 /***********************************************************/
441 void hw_error(const char *fmt, ...)
443 va_list ap;
444 CPUState *env;
446 va_start(ap, fmt);
447 fprintf(stderr, "qemu: hardware error: ");
448 vfprintf(stderr, fmt, ap);
449 fprintf(stderr, "\n");
450 for(env = first_cpu; env != NULL; env = env->next_cpu) {
451 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
452 #ifdef TARGET_I386
453 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
454 #else
455 cpu_dump_state(env, stderr, fprintf, 0);
456 #endif
458 va_end(ap);
459 abort();
462 /***********************************************************/
463 /* keyboard/mouse */
465 static QEMUPutKBDEvent *qemu_put_kbd_event;
466 static void *qemu_put_kbd_event_opaque;
467 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
468 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
470 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
472 qemu_put_kbd_event_opaque = opaque;
473 qemu_put_kbd_event = func;
476 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
477 void *opaque, int absolute,
478 const char *name)
480 QEMUPutMouseEntry *s, *cursor;
482 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
483 if (!s)
484 return NULL;
486 s->qemu_put_mouse_event = func;
487 s->qemu_put_mouse_event_opaque = opaque;
488 s->qemu_put_mouse_event_absolute = absolute;
489 s->qemu_put_mouse_event_name = qemu_strdup(name);
490 s->next = NULL;
492 if (!qemu_put_mouse_event_head) {
493 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
494 return s;
497 cursor = qemu_put_mouse_event_head;
498 while (cursor->next != NULL)
499 cursor = cursor->next;
501 cursor->next = s;
502 qemu_put_mouse_event_current = s;
504 return s;
507 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
509 QEMUPutMouseEntry *prev = NULL, *cursor;
511 if (!qemu_put_mouse_event_head || entry == NULL)
512 return;
514 cursor = qemu_put_mouse_event_head;
515 while (cursor != NULL && cursor != entry) {
516 prev = cursor;
517 cursor = cursor->next;
520 if (cursor == NULL) // does not exist or list empty
521 return;
522 else if (prev == NULL) { // entry is head
523 qemu_put_mouse_event_head = cursor->next;
524 if (qemu_put_mouse_event_current == entry)
525 qemu_put_mouse_event_current = cursor->next;
526 qemu_free(entry->qemu_put_mouse_event_name);
527 qemu_free(entry);
528 return;
531 prev->next = entry->next;
533 if (qemu_put_mouse_event_current == entry)
534 qemu_put_mouse_event_current = prev;
536 qemu_free(entry->qemu_put_mouse_event_name);
537 qemu_free(entry);
540 void kbd_put_keycode(int keycode)
542 if (qemu_put_kbd_event) {
543 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
547 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
549 QEMUPutMouseEvent *mouse_event;
550 void *mouse_event_opaque;
551 int width;
553 if (!qemu_put_mouse_event_current) {
554 return;
557 mouse_event =
558 qemu_put_mouse_event_current->qemu_put_mouse_event;
559 mouse_event_opaque =
560 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
562 if (mouse_event) {
563 if (graphic_rotate) {
564 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
565 width = 0x7fff;
566 else
567 width = graphic_width;
568 mouse_event(mouse_event_opaque,
569 width - dy, dx, dz, buttons_state);
570 } else
571 mouse_event(mouse_event_opaque,
572 dx, dy, dz, buttons_state);
576 int kbd_mouse_is_absolute(void)
578 if (!qemu_put_mouse_event_current)
579 return 0;
581 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
584 void do_info_mice(void)
586 QEMUPutMouseEntry *cursor;
587 int index = 0;
589 if (!qemu_put_mouse_event_head) {
590 term_printf("No mouse devices connected\n");
591 return;
594 term_printf("Mouse devices available:\n");
595 cursor = qemu_put_mouse_event_head;
596 while (cursor != NULL) {
597 term_printf("%c Mouse #%d: %s\n",
598 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
599 index, cursor->qemu_put_mouse_event_name);
600 index++;
601 cursor = cursor->next;
605 void do_mouse_set(int index)
607 QEMUPutMouseEntry *cursor;
608 int i = 0;
610 if (!qemu_put_mouse_event_head) {
611 term_printf("No mouse devices connected\n");
612 return;
615 cursor = qemu_put_mouse_event_head;
616 while (cursor != NULL && index != i) {
617 i++;
618 cursor = cursor->next;
621 if (cursor != NULL)
622 qemu_put_mouse_event_current = cursor;
623 else
624 term_printf("Mouse at given index not found\n");
627 /* compute with 96 bit intermediate result: (a*b)/c */
628 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
630 union {
631 uint64_t ll;
632 struct {
633 #ifdef WORDS_BIGENDIAN
634 uint32_t high, low;
635 #else
636 uint32_t low, high;
637 #endif
638 } l;
639 } u, res;
640 uint64_t rl, rh;
642 u.ll = a;
643 rl = (uint64_t)u.l.low * (uint64_t)b;
644 rh = (uint64_t)u.l.high * (uint64_t)b;
645 rh += (rl >> 32);
646 res.l.high = rh / c;
647 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
648 return res.ll;
651 /***********************************************************/
652 /* real time host monotonic timer */
654 #define QEMU_TIMER_BASE 1000000000LL
656 #ifdef WIN32
658 static int64_t clock_freq;
660 static void init_get_clock(void)
662 LARGE_INTEGER freq;
663 int ret;
664 ret = QueryPerformanceFrequency(&freq);
665 if (ret == 0) {
666 fprintf(stderr, "Could not calibrate ticks\n");
667 exit(1);
669 clock_freq = freq.QuadPart;
672 static int64_t get_clock(void)
674 LARGE_INTEGER ti;
675 QueryPerformanceCounter(&ti);
676 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
679 #else
681 static int use_rt_clock;
683 static void init_get_clock(void)
685 use_rt_clock = 0;
686 #if defined(__linux__)
688 struct timespec ts;
689 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
690 use_rt_clock = 1;
693 #endif
696 static int64_t get_clock(void)
698 #if defined(__linux__)
699 if (use_rt_clock) {
700 struct timespec ts;
701 clock_gettime(CLOCK_MONOTONIC, &ts);
702 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
703 } else
704 #endif
706 /* XXX: using gettimeofday leads to problems if the date
707 changes, so it should be avoided. */
708 struct timeval tv;
709 gettimeofday(&tv, NULL);
710 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
714 #endif
716 /***********************************************************/
717 /* guest cycle counter */
719 static int64_t cpu_ticks_prev;
720 static int64_t cpu_ticks_offset;
721 static int64_t cpu_clock_offset;
722 static int cpu_ticks_enabled;
724 /* return the host CPU cycle counter and handle stop/restart */
725 int64_t cpu_get_ticks(void)
727 if (!cpu_ticks_enabled) {
728 return cpu_ticks_offset;
729 } else {
730 int64_t ticks;
731 ticks = cpu_get_real_ticks();
732 if (cpu_ticks_prev > ticks) {
733 /* Note: non increasing ticks may happen if the host uses
734 software suspend */
735 cpu_ticks_offset += cpu_ticks_prev - ticks;
737 cpu_ticks_prev = ticks;
738 return ticks + cpu_ticks_offset;
742 /* return the host CPU monotonic timer and handle stop/restart */
743 static int64_t cpu_get_clock(void)
745 int64_t ti;
746 if (!cpu_ticks_enabled) {
747 return cpu_clock_offset;
748 } else {
749 ti = get_clock();
750 return ti + cpu_clock_offset;
754 /* enable cpu_get_ticks() */
755 void cpu_enable_ticks(void)
757 if (!cpu_ticks_enabled) {
758 cpu_ticks_offset -= cpu_get_real_ticks();
759 cpu_clock_offset -= get_clock();
760 cpu_ticks_enabled = 1;
764 /* disable cpu_get_ticks() : the clock is stopped. You must not call
765 cpu_get_ticks() after that. */
766 void cpu_disable_ticks(void)
768 if (cpu_ticks_enabled) {
769 cpu_ticks_offset = cpu_get_ticks();
770 cpu_clock_offset = cpu_get_clock();
771 cpu_ticks_enabled = 0;
775 /***********************************************************/
776 /* timers */
778 #define QEMU_TIMER_REALTIME 0
779 #define QEMU_TIMER_VIRTUAL 1
781 struct QEMUClock {
782 int type;
783 /* XXX: add frequency */
786 struct QEMUTimer {
787 QEMUClock *clock;
788 int64_t expire_time;
789 QEMUTimerCB *cb;
790 void *opaque;
791 struct QEMUTimer *next;
794 struct qemu_alarm_timer {
795 char const *name;
796 unsigned int flags;
798 int (*start)(struct qemu_alarm_timer *t);
799 void (*stop)(struct qemu_alarm_timer *t);
800 void (*rearm)(struct qemu_alarm_timer *t);
801 void *priv;
804 #define ALARM_FLAG_DYNTICKS 0x1
806 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
808 return t->flags & ALARM_FLAG_DYNTICKS;
811 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
813 if (!alarm_has_dynticks(t))
814 return;
816 t->rearm(t);
819 /* TODO: MIN_TIMER_REARM_US should be optimized */
820 #define MIN_TIMER_REARM_US 250
822 static struct qemu_alarm_timer *alarm_timer;
824 #ifdef _WIN32
826 struct qemu_alarm_win32 {
827 MMRESULT timerId;
828 HANDLE host_alarm;
829 unsigned int period;
830 } alarm_win32_data = {0, NULL, -1};
832 static int win32_start_timer(struct qemu_alarm_timer *t);
833 static void win32_stop_timer(struct qemu_alarm_timer *t);
834 static void win32_rearm_timer(struct qemu_alarm_timer *t);
836 #else
838 static int unix_start_timer(struct qemu_alarm_timer *t);
839 static void unix_stop_timer(struct qemu_alarm_timer *t);
841 #ifdef __linux__
843 static int dynticks_start_timer(struct qemu_alarm_timer *t);
844 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
845 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
847 static int hpet_start_timer(struct qemu_alarm_timer *t);
848 static void hpet_stop_timer(struct qemu_alarm_timer *t);
850 static int rtc_start_timer(struct qemu_alarm_timer *t);
851 static void rtc_stop_timer(struct qemu_alarm_timer *t);
853 #endif /* __linux__ */
855 #endif /* _WIN32 */
857 static struct qemu_alarm_timer alarm_timers[] = {
858 #ifndef _WIN32
859 #ifdef __linux__
860 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
861 dynticks_stop_timer, dynticks_rearm_timer, NULL},
862 /* HPET - if available - is preferred */
863 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
864 /* ...otherwise try RTC */
865 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
866 #endif
867 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
868 #else
869 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
870 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
871 {"win32", 0, win32_start_timer,
872 win32_stop_timer, NULL, &alarm_win32_data},
873 #endif
874 {NULL, }
877 static void show_available_alarms()
879 int i;
881 printf("Available alarm timers, in order of precedence:\n");
882 for (i = 0; alarm_timers[i].name; i++)
883 printf("%s\n", alarm_timers[i].name);
886 static void configure_alarms(char const *opt)
888 int i;
889 int cur = 0;
890 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
891 char *arg;
892 char *name;
894 if (!strcmp(opt, "help")) {
895 show_available_alarms();
896 exit(0);
899 arg = strdup(opt);
901 /* Reorder the array */
902 name = strtok(arg, ",");
903 while (name) {
904 struct qemu_alarm_timer tmp;
906 for (i = 0; i < count && alarm_timers[i].name; i++) {
907 if (!strcmp(alarm_timers[i].name, name))
908 break;
911 if (i == count) {
912 fprintf(stderr, "Unknown clock %s\n", name);
913 goto next;
916 if (i < cur)
917 /* Ignore */
918 goto next;
920 /* Swap */
921 tmp = alarm_timers[i];
922 alarm_timers[i] = alarm_timers[cur];
923 alarm_timers[cur] = tmp;
925 cur++;
926 next:
927 name = strtok(NULL, ",");
930 free(arg);
932 if (cur) {
933 /* Disable remaining timers */
934 for (i = cur; i < count; i++)
935 alarm_timers[i].name = NULL;
938 /* debug */
939 show_available_alarms();
942 QEMUClock *rt_clock;
943 QEMUClock *vm_clock;
945 static QEMUTimer *active_timers[2];
947 QEMUClock *qemu_new_clock(int type)
949 QEMUClock *clock;
950 clock = qemu_mallocz(sizeof(QEMUClock));
951 if (!clock)
952 return NULL;
953 clock->type = type;
954 return clock;
957 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
959 QEMUTimer *ts;
961 ts = qemu_mallocz(sizeof(QEMUTimer));
962 ts->clock = clock;
963 ts->cb = cb;
964 ts->opaque = opaque;
965 return ts;
968 void qemu_free_timer(QEMUTimer *ts)
970 qemu_free(ts);
973 /* stop a timer, but do not dealloc it */
974 void qemu_del_timer(QEMUTimer *ts)
976 QEMUTimer **pt, *t;
978 /* NOTE: this code must be signal safe because
979 qemu_timer_expired() can be called from a signal. */
980 pt = &active_timers[ts->clock->type];
981 for(;;) {
982 t = *pt;
983 if (!t)
984 break;
985 if (t == ts) {
986 *pt = t->next;
987 break;
989 pt = &t->next;
992 qemu_rearm_alarm_timer(alarm_timer);
995 /* modify the current timer so that it will be fired when current_time
996 >= expire_time. The corresponding callback will be called. */
997 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
999 QEMUTimer **pt, *t;
1001 qemu_del_timer(ts);
1003 /* add the timer in the sorted list */
1004 /* NOTE: this code must be signal safe because
1005 qemu_timer_expired() can be called from a signal. */
1006 pt = &active_timers[ts->clock->type];
1007 for(;;) {
1008 t = *pt;
1009 if (!t)
1010 break;
1011 if (t->expire_time > expire_time)
1012 break;
1013 pt = &t->next;
1015 ts->expire_time = expire_time;
1016 ts->next = *pt;
1017 *pt = ts;
1020 int qemu_timer_pending(QEMUTimer *ts)
1022 QEMUTimer *t;
1023 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1024 if (t == ts)
1025 return 1;
1027 return 0;
1030 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1032 if (!timer_head)
1033 return 0;
1034 return (timer_head->expire_time <= current_time);
1037 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1039 QEMUTimer *ts;
1041 for(;;) {
1042 ts = *ptimer_head;
1043 if (!ts || ts->expire_time > current_time)
1044 break;
1045 /* remove timer from the list before calling the callback */
1046 *ptimer_head = ts->next;
1047 ts->next = NULL;
1049 /* run the callback (the timer list can be modified) */
1050 ts->cb(ts->opaque);
1052 qemu_rearm_alarm_timer(alarm_timer);
1055 int64_t qemu_get_clock(QEMUClock *clock)
1057 switch(clock->type) {
1058 case QEMU_TIMER_REALTIME:
1059 return get_clock() / 1000000;
1060 default:
1061 case QEMU_TIMER_VIRTUAL:
1062 return cpu_get_clock();
1066 static void init_timers(void)
1068 init_get_clock();
1069 ticks_per_sec = QEMU_TIMER_BASE;
1070 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1071 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1074 /* save a timer */
1075 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1077 uint64_t expire_time;
1079 if (qemu_timer_pending(ts)) {
1080 expire_time = ts->expire_time;
1081 } else {
1082 expire_time = -1;
1084 qemu_put_be64(f, expire_time);
1087 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1089 uint64_t expire_time;
1091 expire_time = qemu_get_be64(f);
1092 if (expire_time != -1) {
1093 qemu_mod_timer(ts, expire_time);
1094 } else {
1095 qemu_del_timer(ts);
1099 static void timer_save(QEMUFile *f, void *opaque)
1101 if (cpu_ticks_enabled) {
1102 hw_error("cannot save state if virtual timers are running");
1104 qemu_put_be64s(f, &cpu_ticks_offset);
1105 qemu_put_be64s(f, &ticks_per_sec);
1106 qemu_put_be64s(f, &cpu_clock_offset);
1109 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1111 if (version_id != 1 && version_id != 2)
1112 return -EINVAL;
1113 if (cpu_ticks_enabled) {
1114 return -EINVAL;
1116 qemu_get_be64s(f, &cpu_ticks_offset);
1117 qemu_get_be64s(f, &ticks_per_sec);
1118 if (version_id == 2) {
1119 qemu_get_be64s(f, &cpu_clock_offset);
1121 return 0;
1124 #ifdef _WIN32
1125 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1126 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1127 #else
1128 static void host_alarm_handler(int host_signum)
1129 #endif
1131 #if 0
1132 #define DISP_FREQ 1000
1134 static int64_t delta_min = INT64_MAX;
1135 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1136 static int count;
1137 ti = qemu_get_clock(vm_clock);
1138 if (last_clock != 0) {
1139 delta = ti - last_clock;
1140 if (delta < delta_min)
1141 delta_min = delta;
1142 if (delta > delta_max)
1143 delta_max = delta;
1144 delta_cum += delta;
1145 if (++count == DISP_FREQ) {
1146 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1147 muldiv64(delta_min, 1000000, ticks_per_sec),
1148 muldiv64(delta_max, 1000000, ticks_per_sec),
1149 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1150 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1151 count = 0;
1152 delta_min = INT64_MAX;
1153 delta_max = 0;
1154 delta_cum = 0;
1157 last_clock = ti;
1159 #endif
1160 if (alarm_has_dynticks(alarm_timer) ||
1161 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1162 qemu_get_clock(vm_clock)) ||
1163 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1164 qemu_get_clock(rt_clock))) {
1165 #ifdef _WIN32
1166 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1167 SetEvent(data->host_alarm);
1168 #endif
1169 CPUState *env = cpu_single_env;
1170 if (env) {
1171 /* stop the currently executing cpu because a timer occured */
1172 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1173 #ifdef USE_KQEMU
1174 if (env->kqemu_enabled) {
1175 kqemu_cpu_interrupt(env);
1177 #endif
1182 static uint64_t qemu_next_deadline(void)
1184 int64_t nearest_delta_us = UINT64_MAX;
1185 int64_t vmdelta_us;
1187 if (active_timers[QEMU_TIMER_REALTIME])
1188 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1189 qemu_get_clock(rt_clock))*1000;
1191 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1192 /* round up */
1193 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1194 qemu_get_clock(vm_clock)+999)/1000;
1195 if (vmdelta_us < nearest_delta_us)
1196 nearest_delta_us = vmdelta_us;
1199 /* Avoid arming the timer to negative, zero, or too low values */
1200 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1201 nearest_delta_us = MIN_TIMER_REARM_US;
1203 return nearest_delta_us;
1206 #ifndef _WIN32
1208 #if defined(__linux__)
1210 #define RTC_FREQ 1024
1212 static void enable_sigio_timer(int fd)
1214 struct sigaction act;
1216 /* timer signal */
1217 sigfillset(&act.sa_mask);
1218 act.sa_flags = 0;
1219 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1220 act.sa_flags |= SA_ONSTACK;
1221 #endif
1222 act.sa_handler = host_alarm_handler;
1224 sigaction(SIGIO, &act, NULL);
1225 fcntl(fd, F_SETFL, O_ASYNC);
1226 fcntl(fd, F_SETOWN, getpid());
1229 static int hpet_start_timer(struct qemu_alarm_timer *t)
1231 struct hpet_info info;
1232 int r, fd;
1234 fd = open("/dev/hpet", O_RDONLY);
1235 if (fd < 0)
1236 return -1;
1238 /* Set frequency */
1239 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1240 if (r < 0) {
1241 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1242 "error, but for better emulation accuracy type:\n"
1243 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1244 goto fail;
1247 /* Check capabilities */
1248 r = ioctl(fd, HPET_INFO, &info);
1249 if (r < 0)
1250 goto fail;
1252 /* Enable periodic mode */
1253 r = ioctl(fd, HPET_EPI, 0);
1254 if (info.hi_flags && (r < 0))
1255 goto fail;
1257 /* Enable interrupt */
1258 r = ioctl(fd, HPET_IE_ON, 0);
1259 if (r < 0)
1260 goto fail;
1262 enable_sigio_timer(fd);
1263 t->priv = (void *)(long)fd;
1265 return 0;
1266 fail:
1267 close(fd);
1268 return -1;
1271 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1273 int fd = (long)t->priv;
1275 close(fd);
1278 static int rtc_start_timer(struct qemu_alarm_timer *t)
1280 int rtc_fd;
1282 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1283 if (rtc_fd < 0)
1284 return -1;
1285 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1286 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1287 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1288 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1289 goto fail;
1291 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1292 fail:
1293 close(rtc_fd);
1294 return -1;
1297 enable_sigio_timer(rtc_fd);
1299 t->priv = (void *)(long)rtc_fd;
1301 return 0;
1304 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1306 int rtc_fd = (long)t->priv;
1308 close(rtc_fd);
1311 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1313 struct sigevent ev;
1314 timer_t host_timer;
1315 struct sigaction act;
1317 sigfillset(&act.sa_mask);
1318 act.sa_flags = 0;
1319 #if defined(TARGET_I386) && defined(USE_CODE_COPY)
1320 act.sa_flags |= SA_ONSTACK;
1321 #endif
1322 act.sa_handler = host_alarm_handler;
1324 sigaction(SIGALRM, &act, NULL);
1326 ev.sigev_value.sival_int = 0;
1327 ev.sigev_notify = SIGEV_SIGNAL;
1328 ev.sigev_signo = SIGALRM;
1330 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1331 perror("timer_create");
1333 /* disable dynticks */
1334 fprintf(stderr, "Dynamic Ticks disabled\n");
1336 return -1;
1339 t->priv = (void *)host_timer;
1341 return 0;
1344 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1346 timer_t host_timer = (timer_t)t->priv;
1348 timer_delete(host_timer);
1351 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1353 timer_t host_timer = (timer_t)t->priv;
1354 struct itimerspec timeout;
1355 int64_t nearest_delta_us = INT64_MAX;
1356 int64_t current_us;
1358 if (!active_timers[QEMU_TIMER_REALTIME] &&
1359 !active_timers[QEMU_TIMER_VIRTUAL])
1360 return;
1362 nearest_delta_us = qemu_next_deadline();
1364 /* check whether a timer is already running */
1365 if (timer_gettime(host_timer, &timeout)) {
1366 perror("gettime");
1367 fprintf(stderr, "Internal timer error: aborting\n");
1368 exit(1);
1370 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1371 if (current_us && current_us <= nearest_delta_us)
1372 return;
1374 timeout.it_interval.tv_sec = 0;
1375 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1376 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1377 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1378 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1379 perror("settime");
1380 fprintf(stderr, "Internal timer error: aborting\n");
1381 exit(1);
1385 #endif /* defined(__linux__) */
1387 static int unix_start_timer(struct qemu_alarm_timer *t)
1389 struct sigaction act;
1390 struct itimerval itv;
1391 int err;
1393 /* timer signal */
1394 sigfillset(&act.sa_mask);
1395 act.sa_flags = 0;
1396 #if defined(TARGET_I386) && defined(USE_CODE_COPY)
1397 act.sa_flags |= SA_ONSTACK;
1398 #endif
1399 act.sa_handler = host_alarm_handler;
1401 sigaction(SIGALRM, &act, NULL);
1403 itv.it_interval.tv_sec = 0;
1404 /* for i386 kernel 2.6 to get 1 ms */
1405 itv.it_interval.tv_usec = 999;
1406 itv.it_value.tv_sec = 0;
1407 itv.it_value.tv_usec = 10 * 1000;
1409 err = setitimer(ITIMER_REAL, &itv, NULL);
1410 if (err)
1411 return -1;
1413 return 0;
1416 static void unix_stop_timer(struct qemu_alarm_timer *t)
1418 struct itimerval itv;
1420 memset(&itv, 0, sizeof(itv));
1421 setitimer(ITIMER_REAL, &itv, NULL);
1424 #endif /* !defined(_WIN32) */
1426 #ifdef _WIN32
1428 static int win32_start_timer(struct qemu_alarm_timer *t)
1430 TIMECAPS tc;
1431 struct qemu_alarm_win32 *data = t->priv;
1432 UINT flags;
1434 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1435 if (!data->host_alarm) {
1436 perror("Failed CreateEvent");
1437 return -1;
1440 memset(&tc, 0, sizeof(tc));
1441 timeGetDevCaps(&tc, sizeof(tc));
1443 if (data->period < tc.wPeriodMin)
1444 data->period = tc.wPeriodMin;
1446 timeBeginPeriod(data->period);
1448 flags = TIME_CALLBACK_FUNCTION;
1449 if (alarm_has_dynticks(t))
1450 flags |= TIME_ONESHOT;
1451 else
1452 flags |= TIME_PERIODIC;
1454 data->timerId = timeSetEvent(1, // interval (ms)
1455 data->period, // resolution
1456 host_alarm_handler, // function
1457 (DWORD)t, // parameter
1458 flags);
1460 if (!data->timerId) {
1461 perror("Failed to initialize win32 alarm timer");
1463 timeEndPeriod(data->period);
1464 CloseHandle(data->host_alarm);
1465 return -1;
1468 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1470 return 0;
1473 static void win32_stop_timer(struct qemu_alarm_timer *t)
1475 struct qemu_alarm_win32 *data = t->priv;
1477 timeKillEvent(data->timerId);
1478 timeEndPeriod(data->period);
1480 CloseHandle(data->host_alarm);
1483 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1485 struct qemu_alarm_win32 *data = t->priv;
1486 uint64_t nearest_delta_us;
1488 if (!active_timers[QEMU_TIMER_REALTIME] &&
1489 !active_timers[QEMU_TIMER_VIRTUAL])
1490 return;
1492 nearest_delta_us = qemu_next_deadline();
1493 nearest_delta_us /= 1000;
1495 timeKillEvent(data->timerId);
1497 data->timerId = timeSetEvent(1,
1498 data->period,
1499 host_alarm_handler,
1500 (DWORD)t,
1501 TIME_ONESHOT | TIME_PERIODIC);
1503 if (!data->timerId) {
1504 perror("Failed to re-arm win32 alarm timer");
1506 timeEndPeriod(data->period);
1507 CloseHandle(data->host_alarm);
1508 exit(1);
1512 #endif /* _WIN32 */
1514 static void init_timer_alarm(void)
1516 struct qemu_alarm_timer *t;
1517 int i, err = -1;
1519 for (i = 0; alarm_timers[i].name; i++) {
1520 t = &alarm_timers[i];
1522 err = t->start(t);
1523 if (!err)
1524 break;
1527 if (err) {
1528 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1529 fprintf(stderr, "Terminating\n");
1530 exit(1);
1533 alarm_timer = t;
1536 void quit_timers(void)
1538 alarm_timer->stop(alarm_timer);
1539 alarm_timer = NULL;
1542 /***********************************************************/
1543 /* character device */
1545 static void qemu_chr_event(CharDriverState *s, int event)
1547 if (!s->chr_event)
1548 return;
1549 s->chr_event(s->handler_opaque, event);
1552 static void qemu_chr_reset_bh(void *opaque)
1554 CharDriverState *s = opaque;
1555 qemu_chr_event(s, CHR_EVENT_RESET);
1556 qemu_bh_delete(s->bh);
1557 s->bh = NULL;
1560 void qemu_chr_reset(CharDriverState *s)
1562 if (s->bh == NULL) {
1563 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1564 qemu_bh_schedule(s->bh);
1568 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1570 return s->chr_write(s, buf, len);
1573 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1575 if (!s->chr_ioctl)
1576 return -ENOTSUP;
1577 return s->chr_ioctl(s, cmd, arg);
1580 int qemu_chr_can_read(CharDriverState *s)
1582 if (!s->chr_can_read)
1583 return 0;
1584 return s->chr_can_read(s->handler_opaque);
1587 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1589 s->chr_read(s->handler_opaque, buf, len);
1593 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1595 char buf[4096];
1596 va_list ap;
1597 va_start(ap, fmt);
1598 vsnprintf(buf, sizeof(buf), fmt, ap);
1599 qemu_chr_write(s, buf, strlen(buf));
1600 va_end(ap);
1603 void qemu_chr_send_event(CharDriverState *s, int event)
1605 if (s->chr_send_event)
1606 s->chr_send_event(s, event);
1609 void qemu_chr_add_handlers(CharDriverState *s,
1610 IOCanRWHandler *fd_can_read,
1611 IOReadHandler *fd_read,
1612 IOEventHandler *fd_event,
1613 void *opaque)
1615 s->chr_can_read = fd_can_read;
1616 s->chr_read = fd_read;
1617 s->chr_event = fd_event;
1618 s->handler_opaque = opaque;
1619 if (s->chr_update_read_handler)
1620 s->chr_update_read_handler(s);
1623 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1625 return len;
1628 static CharDriverState *qemu_chr_open_null(void)
1630 CharDriverState *chr;
1632 chr = qemu_mallocz(sizeof(CharDriverState));
1633 if (!chr)
1634 return NULL;
1635 chr->chr_write = null_chr_write;
1636 return chr;
1639 /* MUX driver for serial I/O splitting */
1640 static int term_timestamps;
1641 static int64_t term_timestamps_start;
1642 #define MAX_MUX 4
1643 typedef struct {
1644 IOCanRWHandler *chr_can_read[MAX_MUX];
1645 IOReadHandler *chr_read[MAX_MUX];
1646 IOEventHandler *chr_event[MAX_MUX];
1647 void *ext_opaque[MAX_MUX];
1648 CharDriverState *drv;
1649 int mux_cnt;
1650 int term_got_escape;
1651 int max_size;
1652 } MuxDriver;
1655 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1657 MuxDriver *d = chr->opaque;
1658 int ret;
1659 if (!term_timestamps) {
1660 ret = d->drv->chr_write(d->drv, buf, len);
1661 } else {
1662 int i;
1664 ret = 0;
1665 for(i = 0; i < len; i++) {
1666 ret += d->drv->chr_write(d->drv, buf+i, 1);
1667 if (buf[i] == '\n') {
1668 char buf1[64];
1669 int64_t ti;
1670 int secs;
1672 ti = get_clock();
1673 if (term_timestamps_start == -1)
1674 term_timestamps_start = ti;
1675 ti -= term_timestamps_start;
1676 secs = ti / 1000000000;
1677 snprintf(buf1, sizeof(buf1),
1678 "[%02d:%02d:%02d.%03d] ",
1679 secs / 3600,
1680 (secs / 60) % 60,
1681 secs % 60,
1682 (int)((ti / 1000000) % 1000));
1683 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1687 return ret;
1690 static char *mux_help[] = {
1691 "% h print this help\n\r",
1692 "% x exit emulator\n\r",
1693 "% s save disk data back to file (if -snapshot)\n\r",
1694 "% t toggle console timestamps\n\r"
1695 "% b send break (magic sysrq)\n\r",
1696 "% c switch between console and monitor\n\r",
1697 "% % sends %\n\r",
1698 NULL
1701 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1702 static void mux_print_help(CharDriverState *chr)
1704 int i, j;
1705 char ebuf[15] = "Escape-Char";
1706 char cbuf[50] = "\n\r";
1708 if (term_escape_char > 0 && term_escape_char < 26) {
1709 sprintf(cbuf,"\n\r");
1710 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1711 } else {
1712 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1714 chr->chr_write(chr, cbuf, strlen(cbuf));
1715 for (i = 0; mux_help[i] != NULL; i++) {
1716 for (j=0; mux_help[i][j] != '\0'; j++) {
1717 if (mux_help[i][j] == '%')
1718 chr->chr_write(chr, ebuf, strlen(ebuf));
1719 else
1720 chr->chr_write(chr, &mux_help[i][j], 1);
1725 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1727 if (d->term_got_escape) {
1728 d->term_got_escape = 0;
1729 if (ch == term_escape_char)
1730 goto send_char;
1731 switch(ch) {
1732 case '?':
1733 case 'h':
1734 mux_print_help(chr);
1735 break;
1736 case 'x':
1738 char *term = "QEMU: Terminated\n\r";
1739 chr->chr_write(chr,term,strlen(term));
1740 exit(0);
1741 break;
1743 case 's':
1745 int i;
1746 for (i = 0; i < MAX_DISKS; i++) {
1747 if (bs_table[i])
1748 bdrv_commit(bs_table[i]);
1750 if (mtd_bdrv)
1751 bdrv_commit(mtd_bdrv);
1753 break;
1754 case 'b':
1755 qemu_chr_event(chr, CHR_EVENT_BREAK);
1756 break;
1757 case 'c':
1758 /* Switch to the next registered device */
1759 chr->focus++;
1760 if (chr->focus >= d->mux_cnt)
1761 chr->focus = 0;
1762 break;
1763 case 't':
1764 term_timestamps = !term_timestamps;
1765 term_timestamps_start = -1;
1766 break;
1768 } else if (ch == term_escape_char) {
1769 d->term_got_escape = 1;
1770 } else {
1771 send_char:
1772 return 1;
1774 return 0;
1777 static int mux_chr_can_read(void *opaque)
1779 CharDriverState *chr = opaque;
1780 MuxDriver *d = chr->opaque;
1781 if (d->chr_can_read[chr->focus])
1782 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1783 return 0;
1786 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1788 CharDriverState *chr = opaque;
1789 MuxDriver *d = chr->opaque;
1790 int i;
1791 for(i = 0; i < size; i++)
1792 if (mux_proc_byte(chr, d, buf[i]))
1793 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1796 static void mux_chr_event(void *opaque, int event)
1798 CharDriverState *chr = opaque;
1799 MuxDriver *d = chr->opaque;
1800 int i;
1802 /* Send the event to all registered listeners */
1803 for (i = 0; i < d->mux_cnt; i++)
1804 if (d->chr_event[i])
1805 d->chr_event[i](d->ext_opaque[i], event);
1808 static void mux_chr_update_read_handler(CharDriverState *chr)
1810 MuxDriver *d = chr->opaque;
1812 if (d->mux_cnt >= MAX_MUX) {
1813 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1814 return;
1816 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1817 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1818 d->chr_read[d->mux_cnt] = chr->chr_read;
1819 d->chr_event[d->mux_cnt] = chr->chr_event;
1820 /* Fix up the real driver with mux routines */
1821 if (d->mux_cnt == 0) {
1822 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1823 mux_chr_event, chr);
1825 chr->focus = d->mux_cnt;
1826 d->mux_cnt++;
1829 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1831 CharDriverState *chr;
1832 MuxDriver *d;
1834 chr = qemu_mallocz(sizeof(CharDriverState));
1835 if (!chr)
1836 return NULL;
1837 d = qemu_mallocz(sizeof(MuxDriver));
1838 if (!d) {
1839 free(chr);
1840 return NULL;
1843 chr->opaque = d;
1844 d->drv = drv;
1845 chr->focus = -1;
1846 chr->chr_write = mux_chr_write;
1847 chr->chr_update_read_handler = mux_chr_update_read_handler;
1848 return chr;
1852 #ifdef _WIN32
1854 static void socket_cleanup(void)
1856 WSACleanup();
1859 static int socket_init(void)
1861 WSADATA Data;
1862 int ret, err;
1864 ret = WSAStartup(MAKEWORD(2,2), &Data);
1865 if (ret != 0) {
1866 err = WSAGetLastError();
1867 fprintf(stderr, "WSAStartup: %d\n", err);
1868 return -1;
1870 atexit(socket_cleanup);
1871 return 0;
1874 static int send_all(int fd, const uint8_t *buf, int len1)
1876 int ret, len;
1878 len = len1;
1879 while (len > 0) {
1880 ret = send(fd, buf, len, 0);
1881 if (ret < 0) {
1882 int errno;
1883 errno = WSAGetLastError();
1884 if (errno != WSAEWOULDBLOCK) {
1885 return -1;
1887 } else if (ret == 0) {
1888 break;
1889 } else {
1890 buf += ret;
1891 len -= ret;
1894 return len1 - len;
1897 void socket_set_nonblock(int fd)
1899 unsigned long opt = 1;
1900 ioctlsocket(fd, FIONBIO, &opt);
1903 #else
1905 static int unix_write(int fd, const uint8_t *buf, int len1)
1907 int ret, len;
1909 len = len1;
1910 while (len > 0) {
1911 ret = write(fd, buf, len);
1912 if (ret < 0) {
1913 if (errno != EINTR && errno != EAGAIN)
1914 return -1;
1915 } else if (ret == 0) {
1916 break;
1917 } else {
1918 buf += ret;
1919 len -= ret;
1922 return len1 - len;
1925 static inline int send_all(int fd, const uint8_t *buf, int len1)
1927 return unix_write(fd, buf, len1);
1930 void socket_set_nonblock(int fd)
1932 fcntl(fd, F_SETFL, O_NONBLOCK);
1934 #endif /* !_WIN32 */
1936 #ifndef _WIN32
1938 typedef struct {
1939 int fd_in, fd_out;
1940 int max_size;
1941 } FDCharDriver;
1943 #define STDIO_MAX_CLIENTS 1
1944 static int stdio_nb_clients = 0;
1946 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1948 FDCharDriver *s = chr->opaque;
1949 return unix_write(s->fd_out, buf, len);
1952 static int fd_chr_read_poll(void *opaque)
1954 CharDriverState *chr = opaque;
1955 FDCharDriver *s = chr->opaque;
1957 s->max_size = qemu_chr_can_read(chr);
1958 return s->max_size;
1961 static void fd_chr_read(void *opaque)
1963 CharDriverState *chr = opaque;
1964 FDCharDriver *s = chr->opaque;
1965 int size, len;
1966 uint8_t buf[1024];
1968 len = sizeof(buf);
1969 if (len > s->max_size)
1970 len = s->max_size;
1971 if (len == 0)
1972 return;
1973 size = read(s->fd_in, buf, len);
1974 if (size == 0) {
1975 /* FD has been closed. Remove it from the active list. */
1976 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1977 return;
1979 if (size > 0) {
1980 qemu_chr_read(chr, buf, size);
1984 static void fd_chr_update_read_handler(CharDriverState *chr)
1986 FDCharDriver *s = chr->opaque;
1988 if (s->fd_in >= 0) {
1989 if (nographic && s->fd_in == 0) {
1990 } else {
1991 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1992 fd_chr_read, NULL, chr);
1997 /* open a character device to a unix fd */
1998 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2000 CharDriverState *chr;
2001 FDCharDriver *s;
2003 chr = qemu_mallocz(sizeof(CharDriverState));
2004 if (!chr)
2005 return NULL;
2006 s = qemu_mallocz(sizeof(FDCharDriver));
2007 if (!s) {
2008 free(chr);
2009 return NULL;
2011 s->fd_in = fd_in;
2012 s->fd_out = fd_out;
2013 chr->opaque = s;
2014 chr->chr_write = fd_chr_write;
2015 chr->chr_update_read_handler = fd_chr_update_read_handler;
2017 qemu_chr_reset(chr);
2019 return chr;
2022 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2024 int fd_out;
2026 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2027 if (fd_out < 0)
2028 return NULL;
2029 return qemu_chr_open_fd(-1, fd_out);
2032 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2034 int fd_in, fd_out;
2035 char filename_in[256], filename_out[256];
2037 snprintf(filename_in, 256, "%s.in", filename);
2038 snprintf(filename_out, 256, "%s.out", filename);
2039 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2040 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2041 if (fd_in < 0 || fd_out < 0) {
2042 if (fd_in >= 0)
2043 close(fd_in);
2044 if (fd_out >= 0)
2045 close(fd_out);
2046 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2047 if (fd_in < 0)
2048 return NULL;
2050 return qemu_chr_open_fd(fd_in, fd_out);
2054 /* for STDIO, we handle the case where several clients use it
2055 (nographic mode) */
2057 #define TERM_FIFO_MAX_SIZE 1
2059 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2060 static int term_fifo_size;
2062 static int stdio_read_poll(void *opaque)
2064 CharDriverState *chr = opaque;
2066 /* try to flush the queue if needed */
2067 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2068 qemu_chr_read(chr, term_fifo, 1);
2069 term_fifo_size = 0;
2071 /* see if we can absorb more chars */
2072 if (term_fifo_size == 0)
2073 return 1;
2074 else
2075 return 0;
2078 static void stdio_read(void *opaque)
2080 int size;
2081 uint8_t buf[1];
2082 CharDriverState *chr = opaque;
2084 size = read(0, buf, 1);
2085 if (size == 0) {
2086 /* stdin has been closed. Remove it from the active list. */
2087 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2088 return;
2090 if (size > 0) {
2091 if (qemu_chr_can_read(chr) > 0) {
2092 qemu_chr_read(chr, buf, 1);
2093 } else if (term_fifo_size == 0) {
2094 term_fifo[term_fifo_size++] = buf[0];
2099 /* init terminal so that we can grab keys */
2100 static struct termios oldtty;
2101 static int old_fd0_flags;
2103 static void term_exit(void)
2105 tcsetattr (0, TCSANOW, &oldtty);
2106 fcntl(0, F_SETFL, old_fd0_flags);
2109 static void term_init(void)
2111 struct termios tty;
2113 tcgetattr (0, &tty);
2114 oldtty = tty;
2115 old_fd0_flags = fcntl(0, F_GETFL);
2117 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2118 |INLCR|IGNCR|ICRNL|IXON);
2119 tty.c_oflag |= OPOST;
2120 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2121 /* if graphical mode, we allow Ctrl-C handling */
2122 if (nographic)
2123 tty.c_lflag &= ~ISIG;
2124 tty.c_cflag &= ~(CSIZE|PARENB);
2125 tty.c_cflag |= CS8;
2126 tty.c_cc[VMIN] = 1;
2127 tty.c_cc[VTIME] = 0;
2129 tcsetattr (0, TCSANOW, &tty);
2131 atexit(term_exit);
2133 fcntl(0, F_SETFL, O_NONBLOCK);
2136 static CharDriverState *qemu_chr_open_stdio(void)
2138 CharDriverState *chr;
2140 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2141 return NULL;
2142 chr = qemu_chr_open_fd(0, 1);
2143 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2144 stdio_nb_clients++;
2145 term_init();
2147 return chr;
2150 #if defined(__linux__) || defined(__sun__)
2151 static CharDriverState *qemu_chr_open_pty(void)
2153 struct termios tty;
2154 char slave_name[1024];
2155 int master_fd, slave_fd;
2157 #if defined(__linux__)
2158 /* Not satisfying */
2159 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2160 return NULL;
2162 #endif
2164 /* Disabling local echo and line-buffered output */
2165 tcgetattr (master_fd, &tty);
2166 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2167 tty.c_cc[VMIN] = 1;
2168 tty.c_cc[VTIME] = 0;
2169 tcsetattr (master_fd, TCSAFLUSH, &tty);
2171 fprintf(stderr, "char device redirected to %s\n", slave_name);
2172 return qemu_chr_open_fd(master_fd, master_fd);
2175 static void tty_serial_init(int fd, int speed,
2176 int parity, int data_bits, int stop_bits)
2178 struct termios tty;
2179 speed_t spd;
2181 #if 0
2182 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2183 speed, parity, data_bits, stop_bits);
2184 #endif
2185 tcgetattr (fd, &tty);
2187 switch(speed) {
2188 case 50:
2189 spd = B50;
2190 break;
2191 case 75:
2192 spd = B75;
2193 break;
2194 case 300:
2195 spd = B300;
2196 break;
2197 case 600:
2198 spd = B600;
2199 break;
2200 case 1200:
2201 spd = B1200;
2202 break;
2203 case 2400:
2204 spd = B2400;
2205 break;
2206 case 4800:
2207 spd = B4800;
2208 break;
2209 case 9600:
2210 spd = B9600;
2211 break;
2212 case 19200:
2213 spd = B19200;
2214 break;
2215 case 38400:
2216 spd = B38400;
2217 break;
2218 case 57600:
2219 spd = B57600;
2220 break;
2221 default:
2222 case 115200:
2223 spd = B115200;
2224 break;
2227 cfsetispeed(&tty, spd);
2228 cfsetospeed(&tty, spd);
2230 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2231 |INLCR|IGNCR|ICRNL|IXON);
2232 tty.c_oflag |= OPOST;
2233 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2234 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2235 switch(data_bits) {
2236 default:
2237 case 8:
2238 tty.c_cflag |= CS8;
2239 break;
2240 case 7:
2241 tty.c_cflag |= CS7;
2242 break;
2243 case 6:
2244 tty.c_cflag |= CS6;
2245 break;
2246 case 5:
2247 tty.c_cflag |= CS5;
2248 break;
2250 switch(parity) {
2251 default:
2252 case 'N':
2253 break;
2254 case 'E':
2255 tty.c_cflag |= PARENB;
2256 break;
2257 case 'O':
2258 tty.c_cflag |= PARENB | PARODD;
2259 break;
2261 if (stop_bits == 2)
2262 tty.c_cflag |= CSTOPB;
2264 tcsetattr (fd, TCSANOW, &tty);
2267 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2269 FDCharDriver *s = chr->opaque;
2271 switch(cmd) {
2272 case CHR_IOCTL_SERIAL_SET_PARAMS:
2274 QEMUSerialSetParams *ssp = arg;
2275 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2276 ssp->data_bits, ssp->stop_bits);
2278 break;
2279 case CHR_IOCTL_SERIAL_SET_BREAK:
2281 int enable = *(int *)arg;
2282 if (enable)
2283 tcsendbreak(s->fd_in, 1);
2285 break;
2286 default:
2287 return -ENOTSUP;
2289 return 0;
2292 static CharDriverState *qemu_chr_open_tty(const char *filename)
2294 CharDriverState *chr;
2295 int fd;
2297 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2298 fcntl(fd, F_SETFL, O_NONBLOCK);
2299 tty_serial_init(fd, 115200, 'N', 8, 1);
2300 chr = qemu_chr_open_fd(fd, fd);
2301 if (!chr) {
2302 close(fd);
2303 return NULL;
2305 chr->chr_ioctl = tty_serial_ioctl;
2306 qemu_chr_reset(chr);
2307 return chr;
2309 #else /* ! __linux__ && ! __sun__ */
2310 static CharDriverState *qemu_chr_open_pty(void)
2312 return NULL;
2314 #endif /* __linux__ || __sun__ */
2316 #if defined(__linux__)
2317 typedef struct {
2318 int fd;
2319 int mode;
2320 } ParallelCharDriver;
2322 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2324 if (s->mode != mode) {
2325 int m = mode;
2326 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2327 return 0;
2328 s->mode = mode;
2330 return 1;
2333 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2335 ParallelCharDriver *drv = chr->opaque;
2336 int fd = drv->fd;
2337 uint8_t b;
2339 switch(cmd) {
2340 case CHR_IOCTL_PP_READ_DATA:
2341 if (ioctl(fd, PPRDATA, &b) < 0)
2342 return -ENOTSUP;
2343 *(uint8_t *)arg = b;
2344 break;
2345 case CHR_IOCTL_PP_WRITE_DATA:
2346 b = *(uint8_t *)arg;
2347 if (ioctl(fd, PPWDATA, &b) < 0)
2348 return -ENOTSUP;
2349 break;
2350 case CHR_IOCTL_PP_READ_CONTROL:
2351 if (ioctl(fd, PPRCONTROL, &b) < 0)
2352 return -ENOTSUP;
2353 /* Linux gives only the lowest bits, and no way to know data
2354 direction! For better compatibility set the fixed upper
2355 bits. */
2356 *(uint8_t *)arg = b | 0xc0;
2357 break;
2358 case CHR_IOCTL_PP_WRITE_CONTROL:
2359 b = *(uint8_t *)arg;
2360 if (ioctl(fd, PPWCONTROL, &b) < 0)
2361 return -ENOTSUP;
2362 break;
2363 case CHR_IOCTL_PP_READ_STATUS:
2364 if (ioctl(fd, PPRSTATUS, &b) < 0)
2365 return -ENOTSUP;
2366 *(uint8_t *)arg = b;
2367 break;
2368 case CHR_IOCTL_PP_EPP_READ_ADDR:
2369 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2370 struct ParallelIOArg *parg = arg;
2371 int n = read(fd, parg->buffer, parg->count);
2372 if (n != parg->count) {
2373 return -EIO;
2376 break;
2377 case CHR_IOCTL_PP_EPP_READ:
2378 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2379 struct ParallelIOArg *parg = arg;
2380 int n = read(fd, parg->buffer, parg->count);
2381 if (n != parg->count) {
2382 return -EIO;
2385 break;
2386 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2387 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2388 struct ParallelIOArg *parg = arg;
2389 int n = write(fd, parg->buffer, parg->count);
2390 if (n != parg->count) {
2391 return -EIO;
2394 break;
2395 case CHR_IOCTL_PP_EPP_WRITE:
2396 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2397 struct ParallelIOArg *parg = arg;
2398 int n = write(fd, parg->buffer, parg->count);
2399 if (n != parg->count) {
2400 return -EIO;
2403 break;
2404 default:
2405 return -ENOTSUP;
2407 return 0;
2410 static void pp_close(CharDriverState *chr)
2412 ParallelCharDriver *drv = chr->opaque;
2413 int fd = drv->fd;
2415 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2416 ioctl(fd, PPRELEASE);
2417 close(fd);
2418 qemu_free(drv);
2421 static CharDriverState *qemu_chr_open_pp(const char *filename)
2423 CharDriverState *chr;
2424 ParallelCharDriver *drv;
2425 int fd;
2427 TFR(fd = open(filename, O_RDWR));
2428 if (fd < 0)
2429 return NULL;
2431 if (ioctl(fd, PPCLAIM) < 0) {
2432 close(fd);
2433 return NULL;
2436 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2437 if (!drv) {
2438 close(fd);
2439 return NULL;
2441 drv->fd = fd;
2442 drv->mode = IEEE1284_MODE_COMPAT;
2444 chr = qemu_mallocz(sizeof(CharDriverState));
2445 if (!chr) {
2446 qemu_free(drv);
2447 close(fd);
2448 return NULL;
2450 chr->chr_write = null_chr_write;
2451 chr->chr_ioctl = pp_ioctl;
2452 chr->chr_close = pp_close;
2453 chr->opaque = drv;
2455 qemu_chr_reset(chr);
2457 return chr;
2459 #endif /* __linux__ */
2461 #else /* _WIN32 */
2463 typedef struct {
2464 int max_size;
2465 HANDLE hcom, hrecv, hsend;
2466 OVERLAPPED orecv, osend;
2467 BOOL fpipe;
2468 DWORD len;
2469 } WinCharState;
2471 #define NSENDBUF 2048
2472 #define NRECVBUF 2048
2473 #define MAXCONNECT 1
2474 #define NTIMEOUT 5000
2476 static int win_chr_poll(void *opaque);
2477 static int win_chr_pipe_poll(void *opaque);
2479 static void win_chr_close(CharDriverState *chr)
2481 WinCharState *s = chr->opaque;
2483 if (s->hsend) {
2484 CloseHandle(s->hsend);
2485 s->hsend = NULL;
2487 if (s->hrecv) {
2488 CloseHandle(s->hrecv);
2489 s->hrecv = NULL;
2491 if (s->hcom) {
2492 CloseHandle(s->hcom);
2493 s->hcom = NULL;
2495 if (s->fpipe)
2496 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2497 else
2498 qemu_del_polling_cb(win_chr_poll, chr);
2501 static int win_chr_init(CharDriverState *chr, const char *filename)
2503 WinCharState *s = chr->opaque;
2504 COMMCONFIG comcfg;
2505 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2506 COMSTAT comstat;
2507 DWORD size;
2508 DWORD err;
2510 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2511 if (!s->hsend) {
2512 fprintf(stderr, "Failed CreateEvent\n");
2513 goto fail;
2515 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2516 if (!s->hrecv) {
2517 fprintf(stderr, "Failed CreateEvent\n");
2518 goto fail;
2521 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2522 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2523 if (s->hcom == INVALID_HANDLE_VALUE) {
2524 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2525 s->hcom = NULL;
2526 goto fail;
2529 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2530 fprintf(stderr, "Failed SetupComm\n");
2531 goto fail;
2534 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2535 size = sizeof(COMMCONFIG);
2536 GetDefaultCommConfig(filename, &comcfg, &size);
2537 comcfg.dcb.DCBlength = sizeof(DCB);
2538 CommConfigDialog(filename, NULL, &comcfg);
2540 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2541 fprintf(stderr, "Failed SetCommState\n");
2542 goto fail;
2545 if (!SetCommMask(s->hcom, EV_ERR)) {
2546 fprintf(stderr, "Failed SetCommMask\n");
2547 goto fail;
2550 cto.ReadIntervalTimeout = MAXDWORD;
2551 if (!SetCommTimeouts(s->hcom, &cto)) {
2552 fprintf(stderr, "Failed SetCommTimeouts\n");
2553 goto fail;
2556 if (!ClearCommError(s->hcom, &err, &comstat)) {
2557 fprintf(stderr, "Failed ClearCommError\n");
2558 goto fail;
2560 qemu_add_polling_cb(win_chr_poll, chr);
2561 return 0;
2563 fail:
2564 win_chr_close(chr);
2565 return -1;
2568 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2570 WinCharState *s = chr->opaque;
2571 DWORD len, ret, size, err;
2573 len = len1;
2574 ZeroMemory(&s->osend, sizeof(s->osend));
2575 s->osend.hEvent = s->hsend;
2576 while (len > 0) {
2577 if (s->hsend)
2578 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2579 else
2580 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2581 if (!ret) {
2582 err = GetLastError();
2583 if (err == ERROR_IO_PENDING) {
2584 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2585 if (ret) {
2586 buf += size;
2587 len -= size;
2588 } else {
2589 break;
2591 } else {
2592 break;
2594 } else {
2595 buf += size;
2596 len -= size;
2599 return len1 - len;
2602 static int win_chr_read_poll(CharDriverState *chr)
2604 WinCharState *s = chr->opaque;
2606 s->max_size = qemu_chr_can_read(chr);
2607 return s->max_size;
2610 static void win_chr_readfile(CharDriverState *chr)
2612 WinCharState *s = chr->opaque;
2613 int ret, err;
2614 uint8_t buf[1024];
2615 DWORD size;
2617 ZeroMemory(&s->orecv, sizeof(s->orecv));
2618 s->orecv.hEvent = s->hrecv;
2619 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2620 if (!ret) {
2621 err = GetLastError();
2622 if (err == ERROR_IO_PENDING) {
2623 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2627 if (size > 0) {
2628 qemu_chr_read(chr, buf, size);
2632 static void win_chr_read(CharDriverState *chr)
2634 WinCharState *s = chr->opaque;
2636 if (s->len > s->max_size)
2637 s->len = s->max_size;
2638 if (s->len == 0)
2639 return;
2641 win_chr_readfile(chr);
2644 static int win_chr_poll(void *opaque)
2646 CharDriverState *chr = opaque;
2647 WinCharState *s = chr->opaque;
2648 COMSTAT status;
2649 DWORD comerr;
2651 ClearCommError(s->hcom, &comerr, &status);
2652 if (status.cbInQue > 0) {
2653 s->len = status.cbInQue;
2654 win_chr_read_poll(chr);
2655 win_chr_read(chr);
2656 return 1;
2658 return 0;
2661 static CharDriverState *qemu_chr_open_win(const char *filename)
2663 CharDriverState *chr;
2664 WinCharState *s;
2666 chr = qemu_mallocz(sizeof(CharDriverState));
2667 if (!chr)
2668 return NULL;
2669 s = qemu_mallocz(sizeof(WinCharState));
2670 if (!s) {
2671 free(chr);
2672 return NULL;
2674 chr->opaque = s;
2675 chr->chr_write = win_chr_write;
2676 chr->chr_close = win_chr_close;
2678 if (win_chr_init(chr, filename) < 0) {
2679 free(s);
2680 free(chr);
2681 return NULL;
2683 qemu_chr_reset(chr);
2684 return chr;
2687 static int win_chr_pipe_poll(void *opaque)
2689 CharDriverState *chr = opaque;
2690 WinCharState *s = chr->opaque;
2691 DWORD size;
2693 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2694 if (size > 0) {
2695 s->len = size;
2696 win_chr_read_poll(chr);
2697 win_chr_read(chr);
2698 return 1;
2700 return 0;
2703 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2705 WinCharState *s = chr->opaque;
2706 OVERLAPPED ov;
2707 int ret;
2708 DWORD size;
2709 char openname[256];
2711 s->fpipe = TRUE;
2713 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2714 if (!s->hsend) {
2715 fprintf(stderr, "Failed CreateEvent\n");
2716 goto fail;
2718 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2719 if (!s->hrecv) {
2720 fprintf(stderr, "Failed CreateEvent\n");
2721 goto fail;
2724 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2725 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2726 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2727 PIPE_WAIT,
2728 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2729 if (s->hcom == INVALID_HANDLE_VALUE) {
2730 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2731 s->hcom = NULL;
2732 goto fail;
2735 ZeroMemory(&ov, sizeof(ov));
2736 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2737 ret = ConnectNamedPipe(s->hcom, &ov);
2738 if (ret) {
2739 fprintf(stderr, "Failed ConnectNamedPipe\n");
2740 goto fail;
2743 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2744 if (!ret) {
2745 fprintf(stderr, "Failed GetOverlappedResult\n");
2746 if (ov.hEvent) {
2747 CloseHandle(ov.hEvent);
2748 ov.hEvent = NULL;
2750 goto fail;
2753 if (ov.hEvent) {
2754 CloseHandle(ov.hEvent);
2755 ov.hEvent = NULL;
2757 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2758 return 0;
2760 fail:
2761 win_chr_close(chr);
2762 return -1;
2766 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2768 CharDriverState *chr;
2769 WinCharState *s;
2771 chr = qemu_mallocz(sizeof(CharDriverState));
2772 if (!chr)
2773 return NULL;
2774 s = qemu_mallocz(sizeof(WinCharState));
2775 if (!s) {
2776 free(chr);
2777 return NULL;
2779 chr->opaque = s;
2780 chr->chr_write = win_chr_write;
2781 chr->chr_close = win_chr_close;
2783 if (win_chr_pipe_init(chr, filename) < 0) {
2784 free(s);
2785 free(chr);
2786 return NULL;
2788 qemu_chr_reset(chr);
2789 return chr;
2792 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2794 CharDriverState *chr;
2795 WinCharState *s;
2797 chr = qemu_mallocz(sizeof(CharDriverState));
2798 if (!chr)
2799 return NULL;
2800 s = qemu_mallocz(sizeof(WinCharState));
2801 if (!s) {
2802 free(chr);
2803 return NULL;
2805 s->hcom = fd_out;
2806 chr->opaque = s;
2807 chr->chr_write = win_chr_write;
2808 qemu_chr_reset(chr);
2809 return chr;
2812 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2814 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2817 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2819 HANDLE fd_out;
2821 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2822 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2823 if (fd_out == INVALID_HANDLE_VALUE)
2824 return NULL;
2826 return qemu_chr_open_win_file(fd_out);
2828 #endif /* !_WIN32 */
2830 /***********************************************************/
2831 /* UDP Net console */
2833 typedef struct {
2834 int fd;
2835 struct sockaddr_in daddr;
2836 char buf[1024];
2837 int bufcnt;
2838 int bufptr;
2839 int max_size;
2840 } NetCharDriver;
2842 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2844 NetCharDriver *s = chr->opaque;
2846 return sendto(s->fd, buf, len, 0,
2847 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2850 static int udp_chr_read_poll(void *opaque)
2852 CharDriverState *chr = opaque;
2853 NetCharDriver *s = chr->opaque;
2855 s->max_size = qemu_chr_can_read(chr);
2857 /* If there were any stray characters in the queue process them
2858 * first
2860 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2861 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2862 s->bufptr++;
2863 s->max_size = qemu_chr_can_read(chr);
2865 return s->max_size;
2868 static void udp_chr_read(void *opaque)
2870 CharDriverState *chr = opaque;
2871 NetCharDriver *s = chr->opaque;
2873 if (s->max_size == 0)
2874 return;
2875 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2876 s->bufptr = s->bufcnt;
2877 if (s->bufcnt <= 0)
2878 return;
2880 s->bufptr = 0;
2881 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2882 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2883 s->bufptr++;
2884 s->max_size = qemu_chr_can_read(chr);
2888 static void udp_chr_update_read_handler(CharDriverState *chr)
2890 NetCharDriver *s = chr->opaque;
2892 if (s->fd >= 0) {
2893 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2894 udp_chr_read, NULL, chr);
2898 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2899 #ifndef _WIN32
2900 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2901 #endif
2902 int parse_host_src_port(struct sockaddr_in *haddr,
2903 struct sockaddr_in *saddr,
2904 const char *str);
2906 static CharDriverState *qemu_chr_open_udp(const char *def)
2908 CharDriverState *chr = NULL;
2909 NetCharDriver *s = NULL;
2910 int fd = -1;
2911 struct sockaddr_in saddr;
2913 chr = qemu_mallocz(sizeof(CharDriverState));
2914 if (!chr)
2915 goto return_err;
2916 s = qemu_mallocz(sizeof(NetCharDriver));
2917 if (!s)
2918 goto return_err;
2920 fd = socket(PF_INET, SOCK_DGRAM, 0);
2921 if (fd < 0) {
2922 perror("socket(PF_INET, SOCK_DGRAM)");
2923 goto return_err;
2926 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2927 printf("Could not parse: %s\n", def);
2928 goto return_err;
2931 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2933 perror("bind");
2934 goto return_err;
2937 s->fd = fd;
2938 s->bufcnt = 0;
2939 s->bufptr = 0;
2940 chr->opaque = s;
2941 chr->chr_write = udp_chr_write;
2942 chr->chr_update_read_handler = udp_chr_update_read_handler;
2943 return chr;
2945 return_err:
2946 if (chr)
2947 free(chr);
2948 if (s)
2949 free(s);
2950 if (fd >= 0)
2951 closesocket(fd);
2952 return NULL;
2955 /***********************************************************/
2956 /* TCP Net console */
2958 typedef struct {
2959 int fd, listen_fd;
2960 int connected;
2961 int max_size;
2962 int do_telnetopt;
2963 int do_nodelay;
2964 int is_unix;
2965 } TCPCharDriver;
2967 static void tcp_chr_accept(void *opaque);
2969 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2971 TCPCharDriver *s = chr->opaque;
2972 if (s->connected) {
2973 return send_all(s->fd, buf, len);
2974 } else {
2975 /* XXX: indicate an error ? */
2976 return len;
2980 static int tcp_chr_read_poll(void *opaque)
2982 CharDriverState *chr = opaque;
2983 TCPCharDriver *s = chr->opaque;
2984 if (!s->connected)
2985 return 0;
2986 s->max_size = qemu_chr_can_read(chr);
2987 return s->max_size;
2990 #define IAC 255
2991 #define IAC_BREAK 243
2992 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2993 TCPCharDriver *s,
2994 char *buf, int *size)
2996 /* Handle any telnet client's basic IAC options to satisfy char by
2997 * char mode with no echo. All IAC options will be removed from
2998 * the buf and the do_telnetopt variable will be used to track the
2999 * state of the width of the IAC information.
3001 * IAC commands come in sets of 3 bytes with the exception of the
3002 * "IAC BREAK" command and the double IAC.
3005 int i;
3006 int j = 0;
3008 for (i = 0; i < *size; i++) {
3009 if (s->do_telnetopt > 1) {
3010 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3011 /* Double IAC means send an IAC */
3012 if (j != i)
3013 buf[j] = buf[i];
3014 j++;
3015 s->do_telnetopt = 1;
3016 } else {
3017 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3018 /* Handle IAC break commands by sending a serial break */
3019 qemu_chr_event(chr, CHR_EVENT_BREAK);
3020 s->do_telnetopt++;
3022 s->do_telnetopt++;
3024 if (s->do_telnetopt >= 4) {
3025 s->do_telnetopt = 1;
3027 } else {
3028 if ((unsigned char)buf[i] == IAC) {
3029 s->do_telnetopt = 2;
3030 } else {
3031 if (j != i)
3032 buf[j] = buf[i];
3033 j++;
3037 *size = j;
3040 static void tcp_chr_read(void *opaque)
3042 CharDriverState *chr = opaque;
3043 TCPCharDriver *s = chr->opaque;
3044 uint8_t buf[1024];
3045 int len, size;
3047 if (!s->connected || s->max_size <= 0)
3048 return;
3049 len = sizeof(buf);
3050 if (len > s->max_size)
3051 len = s->max_size;
3052 size = recv(s->fd, buf, len, 0);
3053 if (size == 0) {
3054 /* connection closed */
3055 s->connected = 0;
3056 if (s->listen_fd >= 0) {
3057 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3059 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3060 closesocket(s->fd);
3061 s->fd = -1;
3062 } else if (size > 0) {
3063 if (s->do_telnetopt)
3064 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3065 if (size > 0)
3066 qemu_chr_read(chr, buf, size);
3070 static void tcp_chr_connect(void *opaque)
3072 CharDriverState *chr = opaque;
3073 TCPCharDriver *s = chr->opaque;
3075 s->connected = 1;
3076 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3077 tcp_chr_read, NULL, chr);
3078 qemu_chr_reset(chr);
3081 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3082 static void tcp_chr_telnet_init(int fd)
3084 char buf[3];
3085 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3086 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3087 send(fd, (char *)buf, 3, 0);
3088 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3089 send(fd, (char *)buf, 3, 0);
3090 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3091 send(fd, (char *)buf, 3, 0);
3092 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3093 send(fd, (char *)buf, 3, 0);
3096 static void socket_set_nodelay(int fd)
3098 int val = 1;
3099 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3102 static void tcp_chr_accept(void *opaque)
3104 CharDriverState *chr = opaque;
3105 TCPCharDriver *s = chr->opaque;
3106 struct sockaddr_in saddr;
3107 #ifndef _WIN32
3108 struct sockaddr_un uaddr;
3109 #endif
3110 struct sockaddr *addr;
3111 socklen_t len;
3112 int fd;
3114 for(;;) {
3115 #ifndef _WIN32
3116 if (s->is_unix) {
3117 len = sizeof(uaddr);
3118 addr = (struct sockaddr *)&uaddr;
3119 } else
3120 #endif
3122 len = sizeof(saddr);
3123 addr = (struct sockaddr *)&saddr;
3125 fd = accept(s->listen_fd, addr, &len);
3126 if (fd < 0 && errno != EINTR) {
3127 return;
3128 } else if (fd >= 0) {
3129 if (s->do_telnetopt)
3130 tcp_chr_telnet_init(fd);
3131 break;
3134 socket_set_nonblock(fd);
3135 if (s->do_nodelay)
3136 socket_set_nodelay(fd);
3137 s->fd = fd;
3138 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3139 tcp_chr_connect(chr);
3142 static void tcp_chr_close(CharDriverState *chr)
3144 TCPCharDriver *s = chr->opaque;
3145 if (s->fd >= 0)
3146 closesocket(s->fd);
3147 if (s->listen_fd >= 0)
3148 closesocket(s->listen_fd);
3149 qemu_free(s);
3152 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3153 int is_telnet,
3154 int is_unix)
3156 CharDriverState *chr = NULL;
3157 TCPCharDriver *s = NULL;
3158 int fd = -1, ret, err, val;
3159 int is_listen = 0;
3160 int is_waitconnect = 1;
3161 int do_nodelay = 0;
3162 const char *ptr;
3163 struct sockaddr_in saddr;
3164 #ifndef _WIN32
3165 struct sockaddr_un uaddr;
3166 #endif
3167 struct sockaddr *addr;
3168 socklen_t addrlen;
3170 #ifndef _WIN32
3171 if (is_unix) {
3172 addr = (struct sockaddr *)&uaddr;
3173 addrlen = sizeof(uaddr);
3174 if (parse_unix_path(&uaddr, host_str) < 0)
3175 goto fail;
3176 } else
3177 #endif
3179 addr = (struct sockaddr *)&saddr;
3180 addrlen = sizeof(saddr);
3181 if (parse_host_port(&saddr, host_str) < 0)
3182 goto fail;
3185 ptr = host_str;
3186 while((ptr = strchr(ptr,','))) {
3187 ptr++;
3188 if (!strncmp(ptr,"server",6)) {
3189 is_listen = 1;
3190 } else if (!strncmp(ptr,"nowait",6)) {
3191 is_waitconnect = 0;
3192 } else if (!strncmp(ptr,"nodelay",6)) {
3193 do_nodelay = 1;
3194 } else {
3195 printf("Unknown option: %s\n", ptr);
3196 goto fail;
3199 if (!is_listen)
3200 is_waitconnect = 0;
3202 chr = qemu_mallocz(sizeof(CharDriverState));
3203 if (!chr)
3204 goto fail;
3205 s = qemu_mallocz(sizeof(TCPCharDriver));
3206 if (!s)
3207 goto fail;
3209 #ifndef _WIN32
3210 if (is_unix)
3211 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3212 else
3213 #endif
3214 fd = socket(PF_INET, SOCK_STREAM, 0);
3216 if (fd < 0)
3217 goto fail;
3219 if (!is_waitconnect)
3220 socket_set_nonblock(fd);
3222 s->connected = 0;
3223 s->fd = -1;
3224 s->listen_fd = -1;
3225 s->is_unix = is_unix;
3226 s->do_nodelay = do_nodelay && !is_unix;
3228 chr->opaque = s;
3229 chr->chr_write = tcp_chr_write;
3230 chr->chr_close = tcp_chr_close;
3232 if (is_listen) {
3233 /* allow fast reuse */
3234 #ifndef _WIN32
3235 if (is_unix) {
3236 char path[109];
3237 strncpy(path, uaddr.sun_path, 108);
3238 path[108] = 0;
3239 unlink(path);
3240 } else
3241 #endif
3243 val = 1;
3244 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3247 ret = bind(fd, addr, addrlen);
3248 if (ret < 0)
3249 goto fail;
3251 ret = listen(fd, 0);
3252 if (ret < 0)
3253 goto fail;
3255 s->listen_fd = fd;
3256 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3257 if (is_telnet)
3258 s->do_telnetopt = 1;
3259 } else {
3260 for(;;) {
3261 ret = connect(fd, addr, addrlen);
3262 if (ret < 0) {
3263 err = socket_error();
3264 if (err == EINTR || err == EWOULDBLOCK) {
3265 } else if (err == EINPROGRESS) {
3266 break;
3267 #ifdef _WIN32
3268 } else if (err == WSAEALREADY) {
3269 break;
3270 #endif
3271 } else {
3272 goto fail;
3274 } else {
3275 s->connected = 1;
3276 break;
3279 s->fd = fd;
3280 socket_set_nodelay(fd);
3281 if (s->connected)
3282 tcp_chr_connect(chr);
3283 else
3284 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3287 if (is_listen && is_waitconnect) {
3288 printf("QEMU waiting for connection on: %s\n", host_str);
3289 tcp_chr_accept(chr);
3290 socket_set_nonblock(s->listen_fd);
3293 return chr;
3294 fail:
3295 if (fd >= 0)
3296 closesocket(fd);
3297 qemu_free(s);
3298 qemu_free(chr);
3299 return NULL;
3302 CharDriverState *qemu_chr_open(const char *filename)
3304 const char *p;
3306 if (!strcmp(filename, "vc")) {
3307 return text_console_init(&display_state, 0);
3308 } else if (strstart(filename, "vc:", &p)) {
3309 return text_console_init(&display_state, p);
3310 } else if (!strcmp(filename, "null")) {
3311 return qemu_chr_open_null();
3312 } else
3313 if (strstart(filename, "tcp:", &p)) {
3314 return qemu_chr_open_tcp(p, 0, 0);
3315 } else
3316 if (strstart(filename, "telnet:", &p)) {
3317 return qemu_chr_open_tcp(p, 1, 0);
3318 } else
3319 if (strstart(filename, "udp:", &p)) {
3320 return qemu_chr_open_udp(p);
3321 } else
3322 if (strstart(filename, "mon:", &p)) {
3323 CharDriverState *drv = qemu_chr_open(p);
3324 if (drv) {
3325 drv = qemu_chr_open_mux(drv);
3326 monitor_init(drv, !nographic);
3327 return drv;
3329 printf("Unable to open driver: %s\n", p);
3330 return 0;
3331 } else
3332 #ifndef _WIN32
3333 if (strstart(filename, "unix:", &p)) {
3334 return qemu_chr_open_tcp(p, 0, 1);
3335 } else if (strstart(filename, "file:", &p)) {
3336 return qemu_chr_open_file_out(p);
3337 } else if (strstart(filename, "pipe:", &p)) {
3338 return qemu_chr_open_pipe(p);
3339 } else if (!strcmp(filename, "pty")) {
3340 return qemu_chr_open_pty();
3341 } else if (!strcmp(filename, "stdio")) {
3342 return qemu_chr_open_stdio();
3343 } else
3344 #if defined(__linux__)
3345 if (strstart(filename, "/dev/parport", NULL)) {
3346 return qemu_chr_open_pp(filename);
3347 } else
3348 #endif
3349 #if defined(__linux__) || defined(__sun__)
3350 if (strstart(filename, "/dev/", NULL)) {
3351 return qemu_chr_open_tty(filename);
3352 } else
3353 #endif
3354 #else /* !_WIN32 */
3355 if (strstart(filename, "COM", NULL)) {
3356 return qemu_chr_open_win(filename);
3357 } else
3358 if (strstart(filename, "pipe:", &p)) {
3359 return qemu_chr_open_win_pipe(p);
3360 } else
3361 if (strstart(filename, "con:", NULL)) {
3362 return qemu_chr_open_win_con(filename);
3363 } else
3364 if (strstart(filename, "file:", &p)) {
3365 return qemu_chr_open_win_file_out(p);
3367 #endif
3369 return NULL;
3373 void qemu_chr_close(CharDriverState *chr)
3375 if (chr->chr_close)
3376 chr->chr_close(chr);
3379 /***********************************************************/
3380 /* network device redirectors */
3382 void hex_dump(FILE *f, const uint8_t *buf, int size)
3384 int len, i, j, c;
3386 for(i=0;i<size;i+=16) {
3387 len = size - i;
3388 if (len > 16)
3389 len = 16;
3390 fprintf(f, "%08x ", i);
3391 for(j=0;j<16;j++) {
3392 if (j < len)
3393 fprintf(f, " %02x", buf[i+j]);
3394 else
3395 fprintf(f, " ");
3397 fprintf(f, " ");
3398 for(j=0;j<len;j++) {
3399 c = buf[i+j];
3400 if (c < ' ' || c > '~')
3401 c = '.';
3402 fprintf(f, "%c", c);
3404 fprintf(f, "\n");
3408 static int parse_macaddr(uint8_t *macaddr, const char *p)
3410 int i;
3411 for(i = 0; i < 6; i++) {
3412 macaddr[i] = strtol(p, (char **)&p, 16);
3413 if (i == 5) {
3414 if (*p != '\0')
3415 return -1;
3416 } else {
3417 if (*p != ':')
3418 return -1;
3419 p++;
3422 return 0;
3425 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3427 const char *p, *p1;
3428 int len;
3429 p = *pp;
3430 p1 = strchr(p, sep);
3431 if (!p1)
3432 return -1;
3433 len = p1 - p;
3434 p1++;
3435 if (buf_size > 0) {
3436 if (len > buf_size - 1)
3437 len = buf_size - 1;
3438 memcpy(buf, p, len);
3439 buf[len] = '\0';
3441 *pp = p1;
3442 return 0;
3445 int parse_host_src_port(struct sockaddr_in *haddr,
3446 struct sockaddr_in *saddr,
3447 const char *input_str)
3449 char *str = strdup(input_str);
3450 char *host_str = str;
3451 char *src_str;
3452 char *ptr;
3455 * Chop off any extra arguments at the end of the string which
3456 * would start with a comma, then fill in the src port information
3457 * if it was provided else use the "any address" and "any port".
3459 if ((ptr = strchr(str,',')))
3460 *ptr = '\0';
3462 if ((src_str = strchr(input_str,'@'))) {
3463 *src_str = '\0';
3464 src_str++;
3467 if (parse_host_port(haddr, host_str) < 0)
3468 goto fail;
3470 if (!src_str || *src_str == '\0')
3471 src_str = ":0";
3473 if (parse_host_port(saddr, src_str) < 0)
3474 goto fail;
3476 free(str);
3477 return(0);
3479 fail:
3480 free(str);
3481 return -1;
3484 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3486 char buf[512];
3487 struct hostent *he;
3488 const char *p, *r;
3489 int port;
3491 p = str;
3492 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3493 return -1;
3494 saddr->sin_family = AF_INET;
3495 if (buf[0] == '\0') {
3496 saddr->sin_addr.s_addr = 0;
3497 } else {
3498 if (isdigit(buf[0])) {
3499 if (!inet_aton(buf, &saddr->sin_addr))
3500 return -1;
3501 } else {
3502 if ((he = gethostbyname(buf)) == NULL)
3503 return - 1;
3504 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3507 port = strtol(p, (char **)&r, 0);
3508 if (r == p)
3509 return -1;
3510 saddr->sin_port = htons(port);
3511 return 0;
3514 #ifndef _WIN32
3515 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3517 const char *p;
3518 int len;
3520 len = MIN(108, strlen(str));
3521 p = strchr(str, ',');
3522 if (p)
3523 len = MIN(len, p - str);
3525 memset(uaddr, 0, sizeof(*uaddr));
3527 uaddr->sun_family = AF_UNIX;
3528 memcpy(uaddr->sun_path, str, len);
3530 return 0;
3532 #endif
3534 /* find or alloc a new VLAN */
3535 VLANState *qemu_find_vlan(int id)
3537 VLANState **pvlan, *vlan;
3538 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3539 if (vlan->id == id)
3540 return vlan;
3542 vlan = qemu_mallocz(sizeof(VLANState));
3543 if (!vlan)
3544 return NULL;
3545 vlan->id = id;
3546 vlan->next = NULL;
3547 pvlan = &first_vlan;
3548 while (*pvlan != NULL)
3549 pvlan = &(*pvlan)->next;
3550 *pvlan = vlan;
3551 return vlan;
3554 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3555 IOReadHandler *fd_read,
3556 IOCanRWHandler *fd_can_read,
3557 void *opaque)
3559 VLANClientState *vc, **pvc;
3560 vc = qemu_mallocz(sizeof(VLANClientState));
3561 if (!vc)
3562 return NULL;
3563 vc->fd_read = fd_read;
3564 vc->fd_can_read = fd_can_read;
3565 vc->opaque = opaque;
3566 vc->vlan = vlan;
3568 vc->next = NULL;
3569 pvc = &vlan->first_client;
3570 while (*pvc != NULL)
3571 pvc = &(*pvc)->next;
3572 *pvc = vc;
3573 return vc;
3576 int qemu_can_send_packet(VLANClientState *vc1)
3578 VLANState *vlan = vc1->vlan;
3579 VLANClientState *vc;
3581 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3582 if (vc != vc1) {
3583 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3584 return 1;
3587 return 0;
3590 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3592 VLANState *vlan = vc1->vlan;
3593 VLANClientState *vc;
3595 #if 0
3596 printf("vlan %d send:\n", vlan->id);
3597 hex_dump(stdout, buf, size);
3598 #endif
3599 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3600 if (vc != vc1) {
3601 vc->fd_read(vc->opaque, buf, size);
3606 #if defined(CONFIG_SLIRP)
3608 /* slirp network adapter */
3610 static int slirp_inited;
3611 static VLANClientState *slirp_vc;
3613 int slirp_can_output(void)
3615 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3618 void slirp_output(const uint8_t *pkt, int pkt_len)
3620 #if 0
3621 printf("slirp output:\n");
3622 hex_dump(stdout, pkt, pkt_len);
3623 #endif
3624 if (!slirp_vc)
3625 return;
3626 qemu_send_packet(slirp_vc, pkt, pkt_len);
3629 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3631 #if 0
3632 printf("slirp input:\n");
3633 hex_dump(stdout, buf, size);
3634 #endif
3635 slirp_input(buf, size);
3638 static int net_slirp_init(VLANState *vlan)
3640 if (!slirp_inited) {
3641 slirp_inited = 1;
3642 slirp_init();
3644 slirp_vc = qemu_new_vlan_client(vlan,
3645 slirp_receive, NULL, NULL);
3646 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3647 return 0;
3650 static void net_slirp_redir(const char *redir_str)
3652 int is_udp;
3653 char buf[256], *r;
3654 const char *p;
3655 struct in_addr guest_addr;
3656 int host_port, guest_port;
3658 if (!slirp_inited) {
3659 slirp_inited = 1;
3660 slirp_init();
3663 p = redir_str;
3664 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3665 goto fail;
3666 if (!strcmp(buf, "tcp")) {
3667 is_udp = 0;
3668 } else if (!strcmp(buf, "udp")) {
3669 is_udp = 1;
3670 } else {
3671 goto fail;
3674 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3675 goto fail;
3676 host_port = strtol(buf, &r, 0);
3677 if (r == buf)
3678 goto fail;
3680 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3681 goto fail;
3682 if (buf[0] == '\0') {
3683 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3685 if (!inet_aton(buf, &guest_addr))
3686 goto fail;
3688 guest_port = strtol(p, &r, 0);
3689 if (r == p)
3690 goto fail;
3692 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3693 fprintf(stderr, "qemu: could not set up redirection\n");
3694 exit(1);
3696 return;
3697 fail:
3698 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3699 exit(1);
3702 #ifndef _WIN32
3704 char smb_dir[1024];
3706 static void smb_exit(void)
3708 DIR *d;
3709 struct dirent *de;
3710 char filename[1024];
3712 /* erase all the files in the directory */
3713 d = opendir(smb_dir);
3714 for(;;) {
3715 de = readdir(d);
3716 if (!de)
3717 break;
3718 if (strcmp(de->d_name, ".") != 0 &&
3719 strcmp(de->d_name, "..") != 0) {
3720 snprintf(filename, sizeof(filename), "%s/%s",
3721 smb_dir, de->d_name);
3722 unlink(filename);
3725 closedir(d);
3726 rmdir(smb_dir);
3729 /* automatic user mode samba server configuration */
3730 void net_slirp_smb(const char *exported_dir)
3732 char smb_conf[1024];
3733 char smb_cmdline[1024];
3734 FILE *f;
3736 if (!slirp_inited) {
3737 slirp_inited = 1;
3738 slirp_init();
3741 /* XXX: better tmp dir construction */
3742 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3743 if (mkdir(smb_dir, 0700) < 0) {
3744 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3745 exit(1);
3747 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3749 f = fopen(smb_conf, "w");
3750 if (!f) {
3751 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3752 exit(1);
3754 fprintf(f,
3755 "[global]\n"
3756 "private dir=%s\n"
3757 "smb ports=0\n"
3758 "socket address=127.0.0.1\n"
3759 "pid directory=%s\n"
3760 "lock directory=%s\n"
3761 "log file=%s/log.smbd\n"
3762 "smb passwd file=%s/smbpasswd\n"
3763 "security = share\n"
3764 "[qemu]\n"
3765 "path=%s\n"
3766 "read only=no\n"
3767 "guest ok=yes\n",
3768 smb_dir,
3769 smb_dir,
3770 smb_dir,
3771 smb_dir,
3772 smb_dir,
3773 exported_dir
3775 fclose(f);
3776 atexit(smb_exit);
3778 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3779 SMBD_COMMAND, smb_conf);
3781 slirp_add_exec(0, smb_cmdline, 4, 139);
3784 #endif /* !defined(_WIN32) */
3786 #endif /* CONFIG_SLIRP */
3788 #if !defined(_WIN32)
3790 typedef struct TAPState {
3791 VLANClientState *vc;
3792 int fd;
3793 } TAPState;
3795 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3797 TAPState *s = opaque;
3798 int ret;
3799 for(;;) {
3800 ret = write(s->fd, buf, size);
3801 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3802 } else {
3803 break;
3808 static void tap_send(void *opaque)
3810 TAPState *s = opaque;
3811 uint8_t buf[4096];
3812 int size;
3814 #ifdef __sun__
3815 struct strbuf sbuf;
3816 int f = 0;
3817 sbuf.maxlen = sizeof(buf);
3818 sbuf.buf = buf;
3819 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3820 #else
3821 size = read(s->fd, buf, sizeof(buf));
3822 #endif
3823 if (size > 0) {
3824 qemu_send_packet(s->vc, buf, size);
3828 /* fd support */
3830 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3832 TAPState *s;
3834 s = qemu_mallocz(sizeof(TAPState));
3835 if (!s)
3836 return NULL;
3837 s->fd = fd;
3838 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3839 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3840 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3841 return s;
3844 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3845 static int tap_open(char *ifname, int ifname_size)
3847 int fd;
3848 char *dev;
3849 struct stat s;
3851 TFR(fd = open("/dev/tap", O_RDWR));
3852 if (fd < 0) {
3853 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3854 return -1;
3857 fstat(fd, &s);
3858 dev = devname(s.st_rdev, S_IFCHR);
3859 pstrcpy(ifname, ifname_size, dev);
3861 fcntl(fd, F_SETFL, O_NONBLOCK);
3862 return fd;
3864 #elif defined(__sun__)
3865 #define TUNNEWPPA (('T'<<16) | 0x0001)
3867 * Allocate TAP device, returns opened fd.
3868 * Stores dev name in the first arg(must be large enough).
3870 int tap_alloc(char *dev)
3872 int tap_fd, if_fd, ppa = -1;
3873 static int ip_fd = 0;
3874 char *ptr;
3876 static int arp_fd = 0;
3877 int ip_muxid, arp_muxid;
3878 struct strioctl strioc_if, strioc_ppa;
3879 int link_type = I_PLINK;;
3880 struct lifreq ifr;
3881 char actual_name[32] = "";
3883 memset(&ifr, 0x0, sizeof(ifr));
3885 if( *dev ){
3886 ptr = dev;
3887 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3888 ppa = atoi(ptr);
3891 /* Check if IP device was opened */
3892 if( ip_fd )
3893 close(ip_fd);
3895 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3896 if (ip_fd < 0) {
3897 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3898 return -1;
3901 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3902 if (tap_fd < 0) {
3903 syslog(LOG_ERR, "Can't open /dev/tap");
3904 return -1;
3907 /* Assign a new PPA and get its unit number. */
3908 strioc_ppa.ic_cmd = TUNNEWPPA;
3909 strioc_ppa.ic_timout = 0;
3910 strioc_ppa.ic_len = sizeof(ppa);
3911 strioc_ppa.ic_dp = (char *)&ppa;
3912 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3913 syslog (LOG_ERR, "Can't assign new interface");
3915 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3916 if (if_fd < 0) {
3917 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3918 return -1;
3920 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3921 syslog(LOG_ERR, "Can't push IP module");
3922 return -1;
3925 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3926 syslog(LOG_ERR, "Can't get flags\n");
3928 snprintf (actual_name, 32, "tap%d", ppa);
3929 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3931 ifr.lifr_ppa = ppa;
3932 /* Assign ppa according to the unit number returned by tun device */
3934 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3935 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3936 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3937 syslog (LOG_ERR, "Can't get flags\n");
3938 /* Push arp module to if_fd */
3939 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3940 syslog (LOG_ERR, "Can't push ARP module (2)");
3942 /* Push arp module to ip_fd */
3943 if (ioctl (ip_fd, I_POP, NULL) < 0)
3944 syslog (LOG_ERR, "I_POP failed\n");
3945 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3946 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3947 /* Open arp_fd */
3948 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3949 if (arp_fd < 0)
3950 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3952 /* Set ifname to arp */
3953 strioc_if.ic_cmd = SIOCSLIFNAME;
3954 strioc_if.ic_timout = 0;
3955 strioc_if.ic_len = sizeof(ifr);
3956 strioc_if.ic_dp = (char *)&ifr;
3957 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3958 syslog (LOG_ERR, "Can't set ifname to arp\n");
3961 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3962 syslog(LOG_ERR, "Can't link TAP device to IP");
3963 return -1;
3966 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3967 syslog (LOG_ERR, "Can't link TAP device to ARP");
3969 close (if_fd);
3971 memset(&ifr, 0x0, sizeof(ifr));
3972 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3973 ifr.lifr_ip_muxid = ip_muxid;
3974 ifr.lifr_arp_muxid = arp_muxid;
3976 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3978 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3979 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3980 syslog (LOG_ERR, "Can't set multiplexor id");
3983 sprintf(dev, "tap%d", ppa);
3984 return tap_fd;
3987 static int tap_open(char *ifname, int ifname_size)
3989 char dev[10]="";
3990 int fd;
3991 if( (fd = tap_alloc(dev)) < 0 ){
3992 fprintf(stderr, "Cannot allocate TAP device\n");
3993 return -1;
3995 pstrcpy(ifname, ifname_size, dev);
3996 fcntl(fd, F_SETFL, O_NONBLOCK);
3997 return fd;
3999 #else
4000 static int tap_open(char *ifname, int ifname_size)
4002 struct ifreq ifr;
4003 int fd, ret;
4005 TFR(fd = open("/dev/net/tun", O_RDWR));
4006 if (fd < 0) {
4007 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4008 return -1;
4010 memset(&ifr, 0, sizeof(ifr));
4011 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4012 if (ifname[0] != '\0')
4013 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4014 else
4015 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4016 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4017 if (ret != 0) {
4018 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4019 close(fd);
4020 return -1;
4022 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4023 fcntl(fd, F_SETFL, O_NONBLOCK);
4024 return fd;
4026 #endif
4028 static int net_tap_init(VLANState *vlan, const char *ifname1,
4029 const char *setup_script)
4031 TAPState *s;
4032 int pid, status, fd;
4033 char *args[3];
4034 char **parg;
4035 char ifname[128];
4037 if (ifname1 != NULL)
4038 pstrcpy(ifname, sizeof(ifname), ifname1);
4039 else
4040 ifname[0] = '\0';
4041 TFR(fd = tap_open(ifname, sizeof(ifname)));
4042 if (fd < 0)
4043 return -1;
4045 if (!setup_script || !strcmp(setup_script, "no"))
4046 setup_script = "";
4047 if (setup_script[0] != '\0') {
4048 /* try to launch network init script */
4049 pid = fork();
4050 if (pid >= 0) {
4051 if (pid == 0) {
4052 int open_max = sysconf (_SC_OPEN_MAX), i;
4053 for (i = 0; i < open_max; i++)
4054 if (i != STDIN_FILENO &&
4055 i != STDOUT_FILENO &&
4056 i != STDERR_FILENO &&
4057 i != fd)
4058 close(i);
4060 parg = args;
4061 *parg++ = (char *)setup_script;
4062 *parg++ = ifname;
4063 *parg++ = NULL;
4064 execv(setup_script, args);
4065 _exit(1);
4067 while (waitpid(pid, &status, 0) != pid);
4068 if (!WIFEXITED(status) ||
4069 WEXITSTATUS(status) != 0) {
4070 fprintf(stderr, "%s: could not launch network script\n",
4071 setup_script);
4072 return -1;
4076 s = net_tap_fd_init(vlan, fd);
4077 if (!s)
4078 return -1;
4079 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4080 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4081 return 0;
4084 #endif /* !_WIN32 */
4086 /* network connection */
4087 typedef struct NetSocketState {
4088 VLANClientState *vc;
4089 int fd;
4090 int state; /* 0 = getting length, 1 = getting data */
4091 int index;
4092 int packet_len;
4093 uint8_t buf[4096];
4094 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4095 } NetSocketState;
4097 typedef struct NetSocketListenState {
4098 VLANState *vlan;
4099 int fd;
4100 } NetSocketListenState;
4102 /* XXX: we consider we can send the whole packet without blocking */
4103 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4105 NetSocketState *s = opaque;
4106 uint32_t len;
4107 len = htonl(size);
4109 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4110 send_all(s->fd, buf, size);
4113 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4115 NetSocketState *s = opaque;
4116 sendto(s->fd, buf, size, 0,
4117 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4120 static void net_socket_send(void *opaque)
4122 NetSocketState *s = opaque;
4123 int l, size, err;
4124 uint8_t buf1[4096];
4125 const uint8_t *buf;
4127 size = recv(s->fd, buf1, sizeof(buf1), 0);
4128 if (size < 0) {
4129 err = socket_error();
4130 if (err != EWOULDBLOCK)
4131 goto eoc;
4132 } else if (size == 0) {
4133 /* end of connection */
4134 eoc:
4135 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4136 closesocket(s->fd);
4137 return;
4139 buf = buf1;
4140 while (size > 0) {
4141 /* reassemble a packet from the network */
4142 switch(s->state) {
4143 case 0:
4144 l = 4 - s->index;
4145 if (l > size)
4146 l = size;
4147 memcpy(s->buf + s->index, buf, l);
4148 buf += l;
4149 size -= l;
4150 s->index += l;
4151 if (s->index == 4) {
4152 /* got length */
4153 s->packet_len = ntohl(*(uint32_t *)s->buf);
4154 s->index = 0;
4155 s->state = 1;
4157 break;
4158 case 1:
4159 l = s->packet_len - s->index;
4160 if (l > size)
4161 l = size;
4162 memcpy(s->buf + s->index, buf, l);
4163 s->index += l;
4164 buf += l;
4165 size -= l;
4166 if (s->index >= s->packet_len) {
4167 qemu_send_packet(s->vc, s->buf, s->packet_len);
4168 s->index = 0;
4169 s->state = 0;
4171 break;
4176 static void net_socket_send_dgram(void *opaque)
4178 NetSocketState *s = opaque;
4179 int size;
4181 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4182 if (size < 0)
4183 return;
4184 if (size == 0) {
4185 /* end of connection */
4186 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4187 return;
4189 qemu_send_packet(s->vc, s->buf, size);
4192 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4194 struct ip_mreq imr;
4195 int fd;
4196 int val, ret;
4197 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4198 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4199 inet_ntoa(mcastaddr->sin_addr),
4200 (int)ntohl(mcastaddr->sin_addr.s_addr));
4201 return -1;
4204 fd = socket(PF_INET, SOCK_DGRAM, 0);
4205 if (fd < 0) {
4206 perror("socket(PF_INET, SOCK_DGRAM)");
4207 return -1;
4210 val = 1;
4211 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4212 (const char *)&val, sizeof(val));
4213 if (ret < 0) {
4214 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4215 goto fail;
4218 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4219 if (ret < 0) {
4220 perror("bind");
4221 goto fail;
4224 /* Add host to multicast group */
4225 imr.imr_multiaddr = mcastaddr->sin_addr;
4226 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4228 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4229 (const char *)&imr, sizeof(struct ip_mreq));
4230 if (ret < 0) {
4231 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4232 goto fail;
4235 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4236 val = 1;
4237 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4238 (const char *)&val, sizeof(val));
4239 if (ret < 0) {
4240 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4241 goto fail;
4244 socket_set_nonblock(fd);
4245 return fd;
4246 fail:
4247 if (fd >= 0)
4248 closesocket(fd);
4249 return -1;
4252 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4253 int is_connected)
4255 struct sockaddr_in saddr;
4256 int newfd;
4257 socklen_t saddr_len;
4258 NetSocketState *s;
4260 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4261 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4262 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4265 if (is_connected) {
4266 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4267 /* must be bound */
4268 if (saddr.sin_addr.s_addr==0) {
4269 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4270 fd);
4271 return NULL;
4273 /* clone dgram socket */
4274 newfd = net_socket_mcast_create(&saddr);
4275 if (newfd < 0) {
4276 /* error already reported by net_socket_mcast_create() */
4277 close(fd);
4278 return NULL;
4280 /* clone newfd to fd, close newfd */
4281 dup2(newfd, fd);
4282 close(newfd);
4284 } else {
4285 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4286 fd, strerror(errno));
4287 return NULL;
4291 s = qemu_mallocz(sizeof(NetSocketState));
4292 if (!s)
4293 return NULL;
4294 s->fd = fd;
4296 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4297 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4299 /* mcast: save bound address as dst */
4300 if (is_connected) s->dgram_dst=saddr;
4302 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4303 "socket: fd=%d (%s mcast=%s:%d)",
4304 fd, is_connected? "cloned" : "",
4305 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4306 return s;
4309 static void net_socket_connect(void *opaque)
4311 NetSocketState *s = opaque;
4312 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4315 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4316 int is_connected)
4318 NetSocketState *s;
4319 s = qemu_mallocz(sizeof(NetSocketState));
4320 if (!s)
4321 return NULL;
4322 s->fd = fd;
4323 s->vc = qemu_new_vlan_client(vlan,
4324 net_socket_receive, NULL, s);
4325 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4326 "socket: fd=%d", fd);
4327 if (is_connected) {
4328 net_socket_connect(s);
4329 } else {
4330 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4332 return s;
4335 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4336 int is_connected)
4338 int so_type=-1, optlen=sizeof(so_type);
4340 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4341 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4342 return NULL;
4344 switch(so_type) {
4345 case SOCK_DGRAM:
4346 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4347 case SOCK_STREAM:
4348 return net_socket_fd_init_stream(vlan, fd, is_connected);
4349 default:
4350 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4351 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4352 return net_socket_fd_init_stream(vlan, fd, is_connected);
4354 return NULL;
4357 static void net_socket_accept(void *opaque)
4359 NetSocketListenState *s = opaque;
4360 NetSocketState *s1;
4361 struct sockaddr_in saddr;
4362 socklen_t len;
4363 int fd;
4365 for(;;) {
4366 len = sizeof(saddr);
4367 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4368 if (fd < 0 && errno != EINTR) {
4369 return;
4370 } else if (fd >= 0) {
4371 break;
4374 s1 = net_socket_fd_init(s->vlan, fd, 1);
4375 if (!s1) {
4376 closesocket(fd);
4377 } else {
4378 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4379 "socket: connection from %s:%d",
4380 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4384 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4386 NetSocketListenState *s;
4387 int fd, val, ret;
4388 struct sockaddr_in saddr;
4390 if (parse_host_port(&saddr, host_str) < 0)
4391 return -1;
4393 s = qemu_mallocz(sizeof(NetSocketListenState));
4394 if (!s)
4395 return -1;
4397 fd = socket(PF_INET, SOCK_STREAM, 0);
4398 if (fd < 0) {
4399 perror("socket");
4400 return -1;
4402 socket_set_nonblock(fd);
4404 /* allow fast reuse */
4405 val = 1;
4406 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4408 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4409 if (ret < 0) {
4410 perror("bind");
4411 return -1;
4413 ret = listen(fd, 0);
4414 if (ret < 0) {
4415 perror("listen");
4416 return -1;
4418 s->vlan = vlan;
4419 s->fd = fd;
4420 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4421 return 0;
4424 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4426 NetSocketState *s;
4427 int fd, connected, ret, err;
4428 struct sockaddr_in saddr;
4430 if (parse_host_port(&saddr, host_str) < 0)
4431 return -1;
4433 fd = socket(PF_INET, SOCK_STREAM, 0);
4434 if (fd < 0) {
4435 perror("socket");
4436 return -1;
4438 socket_set_nonblock(fd);
4440 connected = 0;
4441 for(;;) {
4442 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4443 if (ret < 0) {
4444 err = socket_error();
4445 if (err == EINTR || err == EWOULDBLOCK) {
4446 } else if (err == EINPROGRESS) {
4447 break;
4448 #ifdef _WIN32
4449 } else if (err == WSAEALREADY) {
4450 break;
4451 #endif
4452 } else {
4453 perror("connect");
4454 closesocket(fd);
4455 return -1;
4457 } else {
4458 connected = 1;
4459 break;
4462 s = net_socket_fd_init(vlan, fd, connected);
4463 if (!s)
4464 return -1;
4465 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4466 "socket: connect to %s:%d",
4467 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4468 return 0;
4471 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4473 NetSocketState *s;
4474 int fd;
4475 struct sockaddr_in saddr;
4477 if (parse_host_port(&saddr, host_str) < 0)
4478 return -1;
4481 fd = net_socket_mcast_create(&saddr);
4482 if (fd < 0)
4483 return -1;
4485 s = net_socket_fd_init(vlan, fd, 0);
4486 if (!s)
4487 return -1;
4489 s->dgram_dst = saddr;
4491 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4492 "socket: mcast=%s:%d",
4493 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4494 return 0;
4498 static int get_param_value(char *buf, int buf_size,
4499 const char *tag, const char *str)
4501 const char *p;
4502 char *q;
4503 char option[128];
4505 p = str;
4506 for(;;) {
4507 q = option;
4508 while (*p != '\0' && *p != '=') {
4509 if ((q - option) < sizeof(option) - 1)
4510 *q++ = *p;
4511 p++;
4513 *q = '\0';
4514 if (*p != '=')
4515 break;
4516 p++;
4517 if (!strcmp(tag, option)) {
4518 q = buf;
4519 while (*p != '\0' && *p != ',') {
4520 if ((q - buf) < buf_size - 1)
4521 *q++ = *p;
4522 p++;
4524 *q = '\0';
4525 return q - buf;
4526 } else {
4527 while (*p != '\0' && *p != ',') {
4528 p++;
4531 if (*p != ',')
4532 break;
4533 p++;
4535 return 0;
4538 static int net_client_init(const char *str)
4540 const char *p;
4541 char *q;
4542 char device[64];
4543 char buf[1024];
4544 int vlan_id, ret;
4545 VLANState *vlan;
4547 p = str;
4548 q = device;
4549 while (*p != '\0' && *p != ',') {
4550 if ((q - device) < sizeof(device) - 1)
4551 *q++ = *p;
4552 p++;
4554 *q = '\0';
4555 if (*p == ',')
4556 p++;
4557 vlan_id = 0;
4558 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4559 vlan_id = strtol(buf, NULL, 0);
4561 vlan = qemu_find_vlan(vlan_id);
4562 if (!vlan) {
4563 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4564 return -1;
4566 if (!strcmp(device, "nic")) {
4567 NICInfo *nd;
4568 uint8_t *macaddr;
4570 if (nb_nics >= MAX_NICS) {
4571 fprintf(stderr, "Too Many NICs\n");
4572 return -1;
4574 nd = &nd_table[nb_nics];
4575 macaddr = nd->macaddr;
4576 macaddr[0] = 0x52;
4577 macaddr[1] = 0x54;
4578 macaddr[2] = 0x00;
4579 macaddr[3] = 0x12;
4580 macaddr[4] = 0x34;
4581 macaddr[5] = 0x56 + nb_nics;
4583 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4584 if (parse_macaddr(macaddr, buf) < 0) {
4585 fprintf(stderr, "invalid syntax for ethernet address\n");
4586 return -1;
4589 if (get_param_value(buf, sizeof(buf), "model", p)) {
4590 nd->model = strdup(buf);
4592 nd->vlan = vlan;
4593 nb_nics++;
4594 vlan->nb_guest_devs++;
4595 ret = 0;
4596 } else
4597 if (!strcmp(device, "none")) {
4598 /* does nothing. It is needed to signal that no network cards
4599 are wanted */
4600 ret = 0;
4601 } else
4602 #ifdef CONFIG_SLIRP
4603 if (!strcmp(device, "user")) {
4604 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4605 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4607 vlan->nb_host_devs++;
4608 ret = net_slirp_init(vlan);
4609 } else
4610 #endif
4611 #ifdef _WIN32
4612 if (!strcmp(device, "tap")) {
4613 char ifname[64];
4614 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4615 fprintf(stderr, "tap: no interface name\n");
4616 return -1;
4618 vlan->nb_host_devs++;
4619 ret = tap_win32_init(vlan, ifname);
4620 } else
4621 #else
4622 if (!strcmp(device, "tap")) {
4623 char ifname[64];
4624 char setup_script[1024];
4625 int fd;
4626 vlan->nb_host_devs++;
4627 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4628 fd = strtol(buf, NULL, 0);
4629 ret = -1;
4630 if (net_tap_fd_init(vlan, fd))
4631 ret = 0;
4632 } else {
4633 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4634 ifname[0] = '\0';
4636 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4637 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4639 ret = net_tap_init(vlan, ifname, setup_script);
4641 } else
4642 #endif
4643 if (!strcmp(device, "socket")) {
4644 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4645 int fd;
4646 fd = strtol(buf, NULL, 0);
4647 ret = -1;
4648 if (net_socket_fd_init(vlan, fd, 1))
4649 ret = 0;
4650 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4651 ret = net_socket_listen_init(vlan, buf);
4652 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4653 ret = net_socket_connect_init(vlan, buf);
4654 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4655 ret = net_socket_mcast_init(vlan, buf);
4656 } else {
4657 fprintf(stderr, "Unknown socket options: %s\n", p);
4658 return -1;
4660 vlan->nb_host_devs++;
4661 } else
4663 fprintf(stderr, "Unknown network device: %s\n", device);
4664 return -1;
4666 if (ret < 0) {
4667 fprintf(stderr, "Could not initialize device '%s'\n", device);
4670 return ret;
4673 void do_info_network(void)
4675 VLANState *vlan;
4676 VLANClientState *vc;
4678 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4679 term_printf("VLAN %d devices:\n", vlan->id);
4680 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4681 term_printf(" %s\n", vc->info_str);
4685 /***********************************************************/
4686 /* USB devices */
4688 static USBPort *used_usb_ports;
4689 static USBPort *free_usb_ports;
4691 /* ??? Maybe change this to register a hub to keep track of the topology. */
4692 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4693 usb_attachfn attach)
4695 port->opaque = opaque;
4696 port->index = index;
4697 port->attach = attach;
4698 port->next = free_usb_ports;
4699 free_usb_ports = port;
4702 static int usb_device_add(const char *devname)
4704 const char *p;
4705 USBDevice *dev;
4706 USBPort *port;
4708 if (!free_usb_ports)
4709 return -1;
4711 if (strstart(devname, "host:", &p)) {
4712 dev = usb_host_device_open(p);
4713 } else if (!strcmp(devname, "mouse")) {
4714 dev = usb_mouse_init();
4715 } else if (!strcmp(devname, "tablet")) {
4716 dev = usb_tablet_init();
4717 } else if (!strcmp(devname, "keyboard")) {
4718 dev = usb_keyboard_init();
4719 } else if (strstart(devname, "disk:", &p)) {
4720 dev = usb_msd_init(p);
4721 } else if (!strcmp(devname, "wacom-tablet")) {
4722 dev = usb_wacom_init();
4723 } else {
4724 return -1;
4726 if (!dev)
4727 return -1;
4729 /* Find a USB port to add the device to. */
4730 port = free_usb_ports;
4731 if (!port->next) {
4732 USBDevice *hub;
4734 /* Create a new hub and chain it on. */
4735 free_usb_ports = NULL;
4736 port->next = used_usb_ports;
4737 used_usb_ports = port;
4739 hub = usb_hub_init(VM_USB_HUB_SIZE);
4740 usb_attach(port, hub);
4741 port = free_usb_ports;
4744 free_usb_ports = port->next;
4745 port->next = used_usb_ports;
4746 used_usb_ports = port;
4747 usb_attach(port, dev);
4748 return 0;
4751 static int usb_device_del(const char *devname)
4753 USBPort *port;
4754 USBPort **lastp;
4755 USBDevice *dev;
4756 int bus_num, addr;
4757 const char *p;
4759 if (!used_usb_ports)
4760 return -1;
4762 p = strchr(devname, '.');
4763 if (!p)
4764 return -1;
4765 bus_num = strtoul(devname, NULL, 0);
4766 addr = strtoul(p + 1, NULL, 0);
4767 if (bus_num != 0)
4768 return -1;
4770 lastp = &used_usb_ports;
4771 port = used_usb_ports;
4772 while (port && port->dev->addr != addr) {
4773 lastp = &port->next;
4774 port = port->next;
4777 if (!port)
4778 return -1;
4780 dev = port->dev;
4781 *lastp = port->next;
4782 usb_attach(port, NULL);
4783 dev->handle_destroy(dev);
4784 port->next = free_usb_ports;
4785 free_usb_ports = port;
4786 return 0;
4789 void do_usb_add(const char *devname)
4791 int ret;
4792 ret = usb_device_add(devname);
4793 if (ret < 0)
4794 term_printf("Could not add USB device '%s'\n", devname);
4797 void do_usb_del(const char *devname)
4799 int ret;
4800 ret = usb_device_del(devname);
4801 if (ret < 0)
4802 term_printf("Could not remove USB device '%s'\n", devname);
4805 void usb_info(void)
4807 USBDevice *dev;
4808 USBPort *port;
4809 const char *speed_str;
4811 if (!usb_enabled) {
4812 term_printf("USB support not enabled\n");
4813 return;
4816 for (port = used_usb_ports; port; port = port->next) {
4817 dev = port->dev;
4818 if (!dev)
4819 continue;
4820 switch(dev->speed) {
4821 case USB_SPEED_LOW:
4822 speed_str = "1.5";
4823 break;
4824 case USB_SPEED_FULL:
4825 speed_str = "12";
4826 break;
4827 case USB_SPEED_HIGH:
4828 speed_str = "480";
4829 break;
4830 default:
4831 speed_str = "?";
4832 break;
4834 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4835 0, dev->addr, speed_str, dev->devname);
4839 /***********************************************************/
4840 /* PCMCIA/Cardbus */
4842 static struct pcmcia_socket_entry_s {
4843 struct pcmcia_socket_s *socket;
4844 struct pcmcia_socket_entry_s *next;
4845 } *pcmcia_sockets = 0;
4847 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4849 struct pcmcia_socket_entry_s *entry;
4851 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4852 entry->socket = socket;
4853 entry->next = pcmcia_sockets;
4854 pcmcia_sockets = entry;
4857 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4859 struct pcmcia_socket_entry_s *entry, **ptr;
4861 ptr = &pcmcia_sockets;
4862 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4863 if (entry->socket == socket) {
4864 *ptr = entry->next;
4865 qemu_free(entry);
4869 void pcmcia_info(void)
4871 struct pcmcia_socket_entry_s *iter;
4872 if (!pcmcia_sockets)
4873 term_printf("No PCMCIA sockets\n");
4875 for (iter = pcmcia_sockets; iter; iter = iter->next)
4876 term_printf("%s: %s\n", iter->socket->slot_string,
4877 iter->socket->attached ? iter->socket->card_string :
4878 "Empty");
4881 /***********************************************************/
4882 /* dumb display */
4884 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4888 static void dumb_resize(DisplayState *ds, int w, int h)
4892 static void dumb_refresh(DisplayState *ds)
4894 #if defined(CONFIG_SDL)
4895 vga_hw_update();
4896 #endif
4899 static void dumb_display_init(DisplayState *ds)
4901 ds->data = NULL;
4902 ds->linesize = 0;
4903 ds->depth = 0;
4904 ds->dpy_update = dumb_update;
4905 ds->dpy_resize = dumb_resize;
4906 ds->dpy_refresh = dumb_refresh;
4909 /***********************************************************/
4910 /* I/O handling */
4912 #define MAX_IO_HANDLERS 64
4914 typedef struct IOHandlerRecord {
4915 int fd;
4916 IOCanRWHandler *fd_read_poll;
4917 IOHandler *fd_read;
4918 IOHandler *fd_write;
4919 int deleted;
4920 void *opaque;
4921 /* temporary data */
4922 struct pollfd *ufd;
4923 struct IOHandlerRecord *next;
4924 } IOHandlerRecord;
4926 static IOHandlerRecord *first_io_handler;
4928 /* XXX: fd_read_poll should be suppressed, but an API change is
4929 necessary in the character devices to suppress fd_can_read(). */
4930 int qemu_set_fd_handler2(int fd,
4931 IOCanRWHandler *fd_read_poll,
4932 IOHandler *fd_read,
4933 IOHandler *fd_write,
4934 void *opaque)
4936 IOHandlerRecord **pioh, *ioh;
4938 if (!fd_read && !fd_write) {
4939 pioh = &first_io_handler;
4940 for(;;) {
4941 ioh = *pioh;
4942 if (ioh == NULL)
4943 break;
4944 if (ioh->fd == fd) {
4945 ioh->deleted = 1;
4946 break;
4948 pioh = &ioh->next;
4950 } else {
4951 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4952 if (ioh->fd == fd)
4953 goto found;
4955 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4956 if (!ioh)
4957 return -1;
4958 ioh->next = first_io_handler;
4959 first_io_handler = ioh;
4960 found:
4961 ioh->fd = fd;
4962 ioh->fd_read_poll = fd_read_poll;
4963 ioh->fd_read = fd_read;
4964 ioh->fd_write = fd_write;
4965 ioh->opaque = opaque;
4966 ioh->deleted = 0;
4968 return 0;
4971 int qemu_set_fd_handler(int fd,
4972 IOHandler *fd_read,
4973 IOHandler *fd_write,
4974 void *opaque)
4976 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4979 /***********************************************************/
4980 /* Polling handling */
4982 typedef struct PollingEntry {
4983 PollingFunc *func;
4984 void *opaque;
4985 struct PollingEntry *next;
4986 } PollingEntry;
4988 static PollingEntry *first_polling_entry;
4990 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4992 PollingEntry **ppe, *pe;
4993 pe = qemu_mallocz(sizeof(PollingEntry));
4994 if (!pe)
4995 return -1;
4996 pe->func = func;
4997 pe->opaque = opaque;
4998 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4999 *ppe = pe;
5000 return 0;
5003 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5005 PollingEntry **ppe, *pe;
5006 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5007 pe = *ppe;
5008 if (pe->func == func && pe->opaque == opaque) {
5009 *ppe = pe->next;
5010 qemu_free(pe);
5011 break;
5016 #ifdef _WIN32
5017 /***********************************************************/
5018 /* Wait objects support */
5019 typedef struct WaitObjects {
5020 int num;
5021 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5022 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5023 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5024 } WaitObjects;
5026 static WaitObjects wait_objects = {0};
5028 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5030 WaitObjects *w = &wait_objects;
5032 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5033 return -1;
5034 w->events[w->num] = handle;
5035 w->func[w->num] = func;
5036 w->opaque[w->num] = opaque;
5037 w->num++;
5038 return 0;
5041 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5043 int i, found;
5044 WaitObjects *w = &wait_objects;
5046 found = 0;
5047 for (i = 0; i < w->num; i++) {
5048 if (w->events[i] == handle)
5049 found = 1;
5050 if (found) {
5051 w->events[i] = w->events[i + 1];
5052 w->func[i] = w->func[i + 1];
5053 w->opaque[i] = w->opaque[i + 1];
5056 if (found)
5057 w->num--;
5059 #endif
5061 /***********************************************************/
5062 /* savevm/loadvm support */
5064 #define IO_BUF_SIZE 32768
5066 struct QEMUFile {
5067 FILE *outfile;
5068 BlockDriverState *bs;
5069 int is_file;
5070 int is_writable;
5071 int64_t base_offset;
5072 int64_t buf_offset; /* start of buffer when writing, end of buffer
5073 when reading */
5074 int buf_index;
5075 int buf_size; /* 0 when writing */
5076 uint8_t buf[IO_BUF_SIZE];
5079 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5081 QEMUFile *f;
5083 f = qemu_mallocz(sizeof(QEMUFile));
5084 if (!f)
5085 return NULL;
5086 if (!strcmp(mode, "wb")) {
5087 f->is_writable = 1;
5088 } else if (!strcmp(mode, "rb")) {
5089 f->is_writable = 0;
5090 } else {
5091 goto fail;
5093 f->outfile = fopen(filename, mode);
5094 if (!f->outfile)
5095 goto fail;
5096 f->is_file = 1;
5097 return f;
5098 fail:
5099 if (f->outfile)
5100 fclose(f->outfile);
5101 qemu_free(f);
5102 return NULL;
5105 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5107 QEMUFile *f;
5109 f = qemu_mallocz(sizeof(QEMUFile));
5110 if (!f)
5111 return NULL;
5112 f->is_file = 0;
5113 f->bs = bs;
5114 f->is_writable = is_writable;
5115 f->base_offset = offset;
5116 return f;
5119 void qemu_fflush(QEMUFile *f)
5121 if (!f->is_writable)
5122 return;
5123 if (f->buf_index > 0) {
5124 if (f->is_file) {
5125 fseek(f->outfile, f->buf_offset, SEEK_SET);
5126 fwrite(f->buf, 1, f->buf_index, f->outfile);
5127 } else {
5128 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5129 f->buf, f->buf_index);
5131 f->buf_offset += f->buf_index;
5132 f->buf_index = 0;
5136 static void qemu_fill_buffer(QEMUFile *f)
5138 int len;
5140 if (f->is_writable)
5141 return;
5142 if (f->is_file) {
5143 fseek(f->outfile, f->buf_offset, SEEK_SET);
5144 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5145 if (len < 0)
5146 len = 0;
5147 } else {
5148 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5149 f->buf, IO_BUF_SIZE);
5150 if (len < 0)
5151 len = 0;
5153 f->buf_index = 0;
5154 f->buf_size = len;
5155 f->buf_offset += len;
5158 void qemu_fclose(QEMUFile *f)
5160 if (f->is_writable)
5161 qemu_fflush(f);
5162 if (f->is_file) {
5163 fclose(f->outfile);
5165 qemu_free(f);
5168 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5170 int l;
5171 while (size > 0) {
5172 l = IO_BUF_SIZE - f->buf_index;
5173 if (l > size)
5174 l = size;
5175 memcpy(f->buf + f->buf_index, buf, l);
5176 f->buf_index += l;
5177 buf += l;
5178 size -= l;
5179 if (f->buf_index >= IO_BUF_SIZE)
5180 qemu_fflush(f);
5184 void qemu_put_byte(QEMUFile *f, int v)
5186 f->buf[f->buf_index++] = v;
5187 if (f->buf_index >= IO_BUF_SIZE)
5188 qemu_fflush(f);
5191 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5193 int size, l;
5195 size = size1;
5196 while (size > 0) {
5197 l = f->buf_size - f->buf_index;
5198 if (l == 0) {
5199 qemu_fill_buffer(f);
5200 l = f->buf_size - f->buf_index;
5201 if (l == 0)
5202 break;
5204 if (l > size)
5205 l = size;
5206 memcpy(buf, f->buf + f->buf_index, l);
5207 f->buf_index += l;
5208 buf += l;
5209 size -= l;
5211 return size1 - size;
5214 int qemu_get_byte(QEMUFile *f)
5216 if (f->buf_index >= f->buf_size) {
5217 qemu_fill_buffer(f);
5218 if (f->buf_index >= f->buf_size)
5219 return 0;
5221 return f->buf[f->buf_index++];
5224 int64_t qemu_ftell(QEMUFile *f)
5226 return f->buf_offset - f->buf_size + f->buf_index;
5229 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5231 if (whence == SEEK_SET) {
5232 /* nothing to do */
5233 } else if (whence == SEEK_CUR) {
5234 pos += qemu_ftell(f);
5235 } else {
5236 /* SEEK_END not supported */
5237 return -1;
5239 if (f->is_writable) {
5240 qemu_fflush(f);
5241 f->buf_offset = pos;
5242 } else {
5243 f->buf_offset = pos;
5244 f->buf_index = 0;
5245 f->buf_size = 0;
5247 return pos;
5250 void qemu_put_be16(QEMUFile *f, unsigned int v)
5252 qemu_put_byte(f, v >> 8);
5253 qemu_put_byte(f, v);
5256 void qemu_put_be32(QEMUFile *f, unsigned int v)
5258 qemu_put_byte(f, v >> 24);
5259 qemu_put_byte(f, v >> 16);
5260 qemu_put_byte(f, v >> 8);
5261 qemu_put_byte(f, v);
5264 void qemu_put_be64(QEMUFile *f, uint64_t v)
5266 qemu_put_be32(f, v >> 32);
5267 qemu_put_be32(f, v);
5270 unsigned int qemu_get_be16(QEMUFile *f)
5272 unsigned int v;
5273 v = qemu_get_byte(f) << 8;
5274 v |= qemu_get_byte(f);
5275 return v;
5278 unsigned int qemu_get_be32(QEMUFile *f)
5280 unsigned int v;
5281 v = qemu_get_byte(f) << 24;
5282 v |= qemu_get_byte(f) << 16;
5283 v |= qemu_get_byte(f) << 8;
5284 v |= qemu_get_byte(f);
5285 return v;
5288 uint64_t qemu_get_be64(QEMUFile *f)
5290 uint64_t v;
5291 v = (uint64_t)qemu_get_be32(f) << 32;
5292 v |= qemu_get_be32(f);
5293 return v;
5296 typedef struct SaveStateEntry {
5297 char idstr[256];
5298 int instance_id;
5299 int version_id;
5300 SaveStateHandler *save_state;
5301 LoadStateHandler *load_state;
5302 void *opaque;
5303 struct SaveStateEntry *next;
5304 } SaveStateEntry;
5306 static SaveStateEntry *first_se;
5308 int register_savevm(const char *idstr,
5309 int instance_id,
5310 int version_id,
5311 SaveStateHandler *save_state,
5312 LoadStateHandler *load_state,
5313 void *opaque)
5315 SaveStateEntry *se, **pse;
5317 se = qemu_malloc(sizeof(SaveStateEntry));
5318 if (!se)
5319 return -1;
5320 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5321 se->instance_id = instance_id;
5322 se->version_id = version_id;
5323 se->save_state = save_state;
5324 se->load_state = load_state;
5325 se->opaque = opaque;
5326 se->next = NULL;
5328 /* add at the end of list */
5329 pse = &first_se;
5330 while (*pse != NULL)
5331 pse = &(*pse)->next;
5332 *pse = se;
5333 return 0;
5336 #define QEMU_VM_FILE_MAGIC 0x5145564d
5337 #define QEMU_VM_FILE_VERSION 0x00000002
5339 int qemu_savevm_state(QEMUFile *f)
5341 SaveStateEntry *se;
5342 int len, ret;
5343 int64_t cur_pos, len_pos, total_len_pos;
5345 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5346 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5347 total_len_pos = qemu_ftell(f);
5348 qemu_put_be64(f, 0); /* total size */
5350 for(se = first_se; se != NULL; se = se->next) {
5351 /* ID string */
5352 len = strlen(se->idstr);
5353 qemu_put_byte(f, len);
5354 qemu_put_buffer(f, se->idstr, len);
5356 qemu_put_be32(f, se->instance_id);
5357 qemu_put_be32(f, se->version_id);
5359 /* record size: filled later */
5360 len_pos = qemu_ftell(f);
5361 qemu_put_be32(f, 0);
5363 se->save_state(f, se->opaque);
5365 /* fill record size */
5366 cur_pos = qemu_ftell(f);
5367 len = cur_pos - len_pos - 4;
5368 qemu_fseek(f, len_pos, SEEK_SET);
5369 qemu_put_be32(f, len);
5370 qemu_fseek(f, cur_pos, SEEK_SET);
5372 cur_pos = qemu_ftell(f);
5373 qemu_fseek(f, total_len_pos, SEEK_SET);
5374 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5375 qemu_fseek(f, cur_pos, SEEK_SET);
5377 ret = 0;
5378 return ret;
5381 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5383 SaveStateEntry *se;
5385 for(se = first_se; se != NULL; se = se->next) {
5386 if (!strcmp(se->idstr, idstr) &&
5387 instance_id == se->instance_id)
5388 return se;
5390 return NULL;
5393 int qemu_loadvm_state(QEMUFile *f)
5395 SaveStateEntry *se;
5396 int len, ret, instance_id, record_len, version_id;
5397 int64_t total_len, end_pos, cur_pos;
5398 unsigned int v;
5399 char idstr[256];
5401 v = qemu_get_be32(f);
5402 if (v != QEMU_VM_FILE_MAGIC)
5403 goto fail;
5404 v = qemu_get_be32(f);
5405 if (v != QEMU_VM_FILE_VERSION) {
5406 fail:
5407 ret = -1;
5408 goto the_end;
5410 total_len = qemu_get_be64(f);
5411 end_pos = total_len + qemu_ftell(f);
5412 for(;;) {
5413 if (qemu_ftell(f) >= end_pos)
5414 break;
5415 len = qemu_get_byte(f);
5416 qemu_get_buffer(f, idstr, len);
5417 idstr[len] = '\0';
5418 instance_id = qemu_get_be32(f);
5419 version_id = qemu_get_be32(f);
5420 record_len = qemu_get_be32(f);
5421 #if 0
5422 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5423 idstr, instance_id, version_id, record_len);
5424 #endif
5425 cur_pos = qemu_ftell(f);
5426 se = find_se(idstr, instance_id);
5427 if (!se) {
5428 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5429 instance_id, idstr);
5430 } else {
5431 ret = se->load_state(f, se->opaque, version_id);
5432 if (ret < 0) {
5433 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5434 instance_id, idstr);
5437 /* always seek to exact end of record */
5438 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5440 ret = 0;
5441 the_end:
5442 return ret;
5445 /* device can contain snapshots */
5446 static int bdrv_can_snapshot(BlockDriverState *bs)
5448 return (bs &&
5449 !bdrv_is_removable(bs) &&
5450 !bdrv_is_read_only(bs));
5453 /* device must be snapshots in order to have a reliable snapshot */
5454 static int bdrv_has_snapshot(BlockDriverState *bs)
5456 return (bs &&
5457 !bdrv_is_removable(bs) &&
5458 !bdrv_is_read_only(bs));
5461 static BlockDriverState *get_bs_snapshots(void)
5463 BlockDriverState *bs;
5464 int i;
5466 if (bs_snapshots)
5467 return bs_snapshots;
5468 for(i = 0; i <= MAX_DISKS; i++) {
5469 bs = bs_table[i];
5470 if (bdrv_can_snapshot(bs))
5471 goto ok;
5473 return NULL;
5475 bs_snapshots = bs;
5476 return bs;
5479 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5480 const char *name)
5482 QEMUSnapshotInfo *sn_tab, *sn;
5483 int nb_sns, i, ret;
5485 ret = -ENOENT;
5486 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5487 if (nb_sns < 0)
5488 return ret;
5489 for(i = 0; i < nb_sns; i++) {
5490 sn = &sn_tab[i];
5491 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5492 *sn_info = *sn;
5493 ret = 0;
5494 break;
5497 qemu_free(sn_tab);
5498 return ret;
5501 void do_savevm(const char *name)
5503 BlockDriverState *bs, *bs1;
5504 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5505 int must_delete, ret, i;
5506 BlockDriverInfo bdi1, *bdi = &bdi1;
5507 QEMUFile *f;
5508 int saved_vm_running;
5509 #ifdef _WIN32
5510 struct _timeb tb;
5511 #else
5512 struct timeval tv;
5513 #endif
5515 bs = get_bs_snapshots();
5516 if (!bs) {
5517 term_printf("No block device can accept snapshots\n");
5518 return;
5521 /* ??? Should this occur after vm_stop? */
5522 qemu_aio_flush();
5524 saved_vm_running = vm_running;
5525 vm_stop(0);
5527 must_delete = 0;
5528 if (name) {
5529 ret = bdrv_snapshot_find(bs, old_sn, name);
5530 if (ret >= 0) {
5531 must_delete = 1;
5534 memset(sn, 0, sizeof(*sn));
5535 if (must_delete) {
5536 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5537 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5538 } else {
5539 if (name)
5540 pstrcpy(sn->name, sizeof(sn->name), name);
5543 /* fill auxiliary fields */
5544 #ifdef _WIN32
5545 _ftime(&tb);
5546 sn->date_sec = tb.time;
5547 sn->date_nsec = tb.millitm * 1000000;
5548 #else
5549 gettimeofday(&tv, NULL);
5550 sn->date_sec = tv.tv_sec;
5551 sn->date_nsec = tv.tv_usec * 1000;
5552 #endif
5553 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5555 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5556 term_printf("Device %s does not support VM state snapshots\n",
5557 bdrv_get_device_name(bs));
5558 goto the_end;
5561 /* save the VM state */
5562 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5563 if (!f) {
5564 term_printf("Could not open VM state file\n");
5565 goto the_end;
5567 ret = qemu_savevm_state(f);
5568 sn->vm_state_size = qemu_ftell(f);
5569 qemu_fclose(f);
5570 if (ret < 0) {
5571 term_printf("Error %d while writing VM\n", ret);
5572 goto the_end;
5575 /* create the snapshots */
5577 for(i = 0; i < MAX_DISKS; i++) {
5578 bs1 = bs_table[i];
5579 if (bdrv_has_snapshot(bs1)) {
5580 if (must_delete) {
5581 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5582 if (ret < 0) {
5583 term_printf("Error while deleting snapshot on '%s'\n",
5584 bdrv_get_device_name(bs1));
5587 ret = bdrv_snapshot_create(bs1, sn);
5588 if (ret < 0) {
5589 term_printf("Error while creating snapshot on '%s'\n",
5590 bdrv_get_device_name(bs1));
5595 the_end:
5596 if (saved_vm_running)
5597 vm_start();
5600 void do_loadvm(const char *name)
5602 BlockDriverState *bs, *bs1;
5603 BlockDriverInfo bdi1, *bdi = &bdi1;
5604 QEMUFile *f;
5605 int i, ret;
5606 int saved_vm_running;
5608 bs = get_bs_snapshots();
5609 if (!bs) {
5610 term_printf("No block device supports snapshots\n");
5611 return;
5614 /* Flush all IO requests so they don't interfere with the new state. */
5615 qemu_aio_flush();
5617 saved_vm_running = vm_running;
5618 vm_stop(0);
5620 for(i = 0; i <= MAX_DISKS; i++) {
5621 bs1 = bs_table[i];
5622 if (bdrv_has_snapshot(bs1)) {
5623 ret = bdrv_snapshot_goto(bs1, name);
5624 if (ret < 0) {
5625 if (bs != bs1)
5626 term_printf("Warning: ");
5627 switch(ret) {
5628 case -ENOTSUP:
5629 term_printf("Snapshots not supported on device '%s'\n",
5630 bdrv_get_device_name(bs1));
5631 break;
5632 case -ENOENT:
5633 term_printf("Could not find snapshot '%s' on device '%s'\n",
5634 name, bdrv_get_device_name(bs1));
5635 break;
5636 default:
5637 term_printf("Error %d while activating snapshot on '%s'\n",
5638 ret, bdrv_get_device_name(bs1));
5639 break;
5641 /* fatal on snapshot block device */
5642 if (bs == bs1)
5643 goto the_end;
5648 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5649 term_printf("Device %s does not support VM state snapshots\n",
5650 bdrv_get_device_name(bs));
5651 return;
5654 /* restore the VM state */
5655 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5656 if (!f) {
5657 term_printf("Could not open VM state file\n");
5658 goto the_end;
5660 ret = qemu_loadvm_state(f);
5661 qemu_fclose(f);
5662 if (ret < 0) {
5663 term_printf("Error %d while loading VM state\n", ret);
5665 the_end:
5666 if (saved_vm_running)
5667 vm_start();
5670 void do_delvm(const char *name)
5672 BlockDriverState *bs, *bs1;
5673 int i, ret;
5675 bs = get_bs_snapshots();
5676 if (!bs) {
5677 term_printf("No block device supports snapshots\n");
5678 return;
5681 for(i = 0; i <= MAX_DISKS; i++) {
5682 bs1 = bs_table[i];
5683 if (bdrv_has_snapshot(bs1)) {
5684 ret = bdrv_snapshot_delete(bs1, name);
5685 if (ret < 0) {
5686 if (ret == -ENOTSUP)
5687 term_printf("Snapshots not supported on device '%s'\n",
5688 bdrv_get_device_name(bs1));
5689 else
5690 term_printf("Error %d while deleting snapshot on '%s'\n",
5691 ret, bdrv_get_device_name(bs1));
5697 void do_info_snapshots(void)
5699 BlockDriverState *bs, *bs1;
5700 QEMUSnapshotInfo *sn_tab, *sn;
5701 int nb_sns, i;
5702 char buf[256];
5704 bs = get_bs_snapshots();
5705 if (!bs) {
5706 term_printf("No available block device supports snapshots\n");
5707 return;
5709 term_printf("Snapshot devices:");
5710 for(i = 0; i <= MAX_DISKS; i++) {
5711 bs1 = bs_table[i];
5712 if (bdrv_has_snapshot(bs1)) {
5713 if (bs == bs1)
5714 term_printf(" %s", bdrv_get_device_name(bs1));
5717 term_printf("\n");
5719 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5720 if (nb_sns < 0) {
5721 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5722 return;
5724 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5725 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5726 for(i = 0; i < nb_sns; i++) {
5727 sn = &sn_tab[i];
5728 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5730 qemu_free(sn_tab);
5733 /***********************************************************/
5734 /* cpu save/restore */
5736 #if defined(TARGET_I386)
5738 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5740 qemu_put_be32(f, dt->selector);
5741 qemu_put_betl(f, dt->base);
5742 qemu_put_be32(f, dt->limit);
5743 qemu_put_be32(f, dt->flags);
5746 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5748 dt->selector = qemu_get_be32(f);
5749 dt->base = qemu_get_betl(f);
5750 dt->limit = qemu_get_be32(f);
5751 dt->flags = qemu_get_be32(f);
5754 void cpu_save(QEMUFile *f, void *opaque)
5756 CPUState *env = opaque;
5757 uint16_t fptag, fpus, fpuc, fpregs_format;
5758 uint32_t hflags;
5759 int i;
5761 for(i = 0; i < CPU_NB_REGS; i++)
5762 qemu_put_betls(f, &env->regs[i]);
5763 qemu_put_betls(f, &env->eip);
5764 qemu_put_betls(f, &env->eflags);
5765 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5766 qemu_put_be32s(f, &hflags);
5768 /* FPU */
5769 fpuc = env->fpuc;
5770 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5771 fptag = 0;
5772 for(i = 0; i < 8; i++) {
5773 fptag |= ((!env->fptags[i]) << i);
5776 qemu_put_be16s(f, &fpuc);
5777 qemu_put_be16s(f, &fpus);
5778 qemu_put_be16s(f, &fptag);
5780 #ifdef USE_X86LDOUBLE
5781 fpregs_format = 0;
5782 #else
5783 fpregs_format = 1;
5784 #endif
5785 qemu_put_be16s(f, &fpregs_format);
5787 for(i = 0; i < 8; i++) {
5788 #ifdef USE_X86LDOUBLE
5790 uint64_t mant;
5791 uint16_t exp;
5792 /* we save the real CPU data (in case of MMX usage only 'mant'
5793 contains the MMX register */
5794 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5795 qemu_put_be64(f, mant);
5796 qemu_put_be16(f, exp);
5798 #else
5799 /* if we use doubles for float emulation, we save the doubles to
5800 avoid losing information in case of MMX usage. It can give
5801 problems if the image is restored on a CPU where long
5802 doubles are used instead. */
5803 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5804 #endif
5807 for(i = 0; i < 6; i++)
5808 cpu_put_seg(f, &env->segs[i]);
5809 cpu_put_seg(f, &env->ldt);
5810 cpu_put_seg(f, &env->tr);
5811 cpu_put_seg(f, &env->gdt);
5812 cpu_put_seg(f, &env->idt);
5814 qemu_put_be32s(f, &env->sysenter_cs);
5815 qemu_put_be32s(f, &env->sysenter_esp);
5816 qemu_put_be32s(f, &env->sysenter_eip);
5818 qemu_put_betls(f, &env->cr[0]);
5819 qemu_put_betls(f, &env->cr[2]);
5820 qemu_put_betls(f, &env->cr[3]);
5821 qemu_put_betls(f, &env->cr[4]);
5823 for(i = 0; i < 8; i++)
5824 qemu_put_betls(f, &env->dr[i]);
5826 /* MMU */
5827 qemu_put_be32s(f, &env->a20_mask);
5829 /* XMM */
5830 qemu_put_be32s(f, &env->mxcsr);
5831 for(i = 0; i < CPU_NB_REGS; i++) {
5832 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5833 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5836 #ifdef TARGET_X86_64
5837 qemu_put_be64s(f, &env->efer);
5838 qemu_put_be64s(f, &env->star);
5839 qemu_put_be64s(f, &env->lstar);
5840 qemu_put_be64s(f, &env->cstar);
5841 qemu_put_be64s(f, &env->fmask);
5842 qemu_put_be64s(f, &env->kernelgsbase);
5843 #endif
5844 qemu_put_be32s(f, &env->smbase);
5847 #ifdef USE_X86LDOUBLE
5848 /* XXX: add that in a FPU generic layer */
5849 union x86_longdouble {
5850 uint64_t mant;
5851 uint16_t exp;
5854 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5855 #define EXPBIAS1 1023
5856 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5857 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5859 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5861 int e;
5862 /* mantissa */
5863 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5864 /* exponent + sign */
5865 e = EXPD1(temp) - EXPBIAS1 + 16383;
5866 e |= SIGND1(temp) >> 16;
5867 p->exp = e;
5869 #endif
5871 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5873 CPUState *env = opaque;
5874 int i, guess_mmx;
5875 uint32_t hflags;
5876 uint16_t fpus, fpuc, fptag, fpregs_format;
5878 if (version_id != 3 && version_id != 4)
5879 return -EINVAL;
5880 for(i = 0; i < CPU_NB_REGS; i++)
5881 qemu_get_betls(f, &env->regs[i]);
5882 qemu_get_betls(f, &env->eip);
5883 qemu_get_betls(f, &env->eflags);
5884 qemu_get_be32s(f, &hflags);
5886 qemu_get_be16s(f, &fpuc);
5887 qemu_get_be16s(f, &fpus);
5888 qemu_get_be16s(f, &fptag);
5889 qemu_get_be16s(f, &fpregs_format);
5891 /* NOTE: we cannot always restore the FPU state if the image come
5892 from a host with a different 'USE_X86LDOUBLE' define. We guess
5893 if we are in an MMX state to restore correctly in that case. */
5894 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5895 for(i = 0; i < 8; i++) {
5896 uint64_t mant;
5897 uint16_t exp;
5899 switch(fpregs_format) {
5900 case 0:
5901 mant = qemu_get_be64(f);
5902 exp = qemu_get_be16(f);
5903 #ifdef USE_X86LDOUBLE
5904 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5905 #else
5906 /* difficult case */
5907 if (guess_mmx)
5908 env->fpregs[i].mmx.MMX_Q(0) = mant;
5909 else
5910 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5911 #endif
5912 break;
5913 case 1:
5914 mant = qemu_get_be64(f);
5915 #ifdef USE_X86LDOUBLE
5917 union x86_longdouble *p;
5918 /* difficult case */
5919 p = (void *)&env->fpregs[i];
5920 if (guess_mmx) {
5921 p->mant = mant;
5922 p->exp = 0xffff;
5923 } else {
5924 fp64_to_fp80(p, mant);
5927 #else
5928 env->fpregs[i].mmx.MMX_Q(0) = mant;
5929 #endif
5930 break;
5931 default:
5932 return -EINVAL;
5936 env->fpuc = fpuc;
5937 /* XXX: restore FPU round state */
5938 env->fpstt = (fpus >> 11) & 7;
5939 env->fpus = fpus & ~0x3800;
5940 fptag ^= 0xff;
5941 for(i = 0; i < 8; i++) {
5942 env->fptags[i] = (fptag >> i) & 1;
5945 for(i = 0; i < 6; i++)
5946 cpu_get_seg(f, &env->segs[i]);
5947 cpu_get_seg(f, &env->ldt);
5948 cpu_get_seg(f, &env->tr);
5949 cpu_get_seg(f, &env->gdt);
5950 cpu_get_seg(f, &env->idt);
5952 qemu_get_be32s(f, &env->sysenter_cs);
5953 qemu_get_be32s(f, &env->sysenter_esp);
5954 qemu_get_be32s(f, &env->sysenter_eip);
5956 qemu_get_betls(f, &env->cr[0]);
5957 qemu_get_betls(f, &env->cr[2]);
5958 qemu_get_betls(f, &env->cr[3]);
5959 qemu_get_betls(f, &env->cr[4]);
5961 for(i = 0; i < 8; i++)
5962 qemu_get_betls(f, &env->dr[i]);
5964 /* MMU */
5965 qemu_get_be32s(f, &env->a20_mask);
5967 qemu_get_be32s(f, &env->mxcsr);
5968 for(i = 0; i < CPU_NB_REGS; i++) {
5969 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5970 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5973 #ifdef TARGET_X86_64
5974 qemu_get_be64s(f, &env->efer);
5975 qemu_get_be64s(f, &env->star);
5976 qemu_get_be64s(f, &env->lstar);
5977 qemu_get_be64s(f, &env->cstar);
5978 qemu_get_be64s(f, &env->fmask);
5979 qemu_get_be64s(f, &env->kernelgsbase);
5980 #endif
5981 if (version_id >= 4)
5982 qemu_get_be32s(f, &env->smbase);
5984 /* XXX: compute hflags from scratch, except for CPL and IIF */
5985 env->hflags = hflags;
5986 tlb_flush(env, 1);
5987 return 0;
5990 #elif defined(TARGET_PPC)
5991 void cpu_save(QEMUFile *f, void *opaque)
5995 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5997 return 0;
6000 #elif defined(TARGET_MIPS)
6001 void cpu_save(QEMUFile *f, void *opaque)
6005 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6007 return 0;
6010 #elif defined(TARGET_SPARC)
6011 void cpu_save(QEMUFile *f, void *opaque)
6013 CPUState *env = opaque;
6014 int i;
6015 uint32_t tmp;
6017 for(i = 0; i < 8; i++)
6018 qemu_put_betls(f, &env->gregs[i]);
6019 for(i = 0; i < NWINDOWS * 16; i++)
6020 qemu_put_betls(f, &env->regbase[i]);
6022 /* FPU */
6023 for(i = 0; i < TARGET_FPREGS; i++) {
6024 union {
6025 float32 f;
6026 uint32_t i;
6027 } u;
6028 u.f = env->fpr[i];
6029 qemu_put_be32(f, u.i);
6032 qemu_put_betls(f, &env->pc);
6033 qemu_put_betls(f, &env->npc);
6034 qemu_put_betls(f, &env->y);
6035 tmp = GET_PSR(env);
6036 qemu_put_be32(f, tmp);
6037 qemu_put_betls(f, &env->fsr);
6038 qemu_put_betls(f, &env->tbr);
6039 #ifndef TARGET_SPARC64
6040 qemu_put_be32s(f, &env->wim);
6041 /* MMU */
6042 for(i = 0; i < 16; i++)
6043 qemu_put_be32s(f, &env->mmuregs[i]);
6044 #endif
6047 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6049 CPUState *env = opaque;
6050 int i;
6051 uint32_t tmp;
6053 for(i = 0; i < 8; i++)
6054 qemu_get_betls(f, &env->gregs[i]);
6055 for(i = 0; i < NWINDOWS * 16; i++)
6056 qemu_get_betls(f, &env->regbase[i]);
6058 /* FPU */
6059 for(i = 0; i < TARGET_FPREGS; i++) {
6060 union {
6061 float32 f;
6062 uint32_t i;
6063 } u;
6064 u.i = qemu_get_be32(f);
6065 env->fpr[i] = u.f;
6068 qemu_get_betls(f, &env->pc);
6069 qemu_get_betls(f, &env->npc);
6070 qemu_get_betls(f, &env->y);
6071 tmp = qemu_get_be32(f);
6072 env->cwp = 0; /* needed to ensure that the wrapping registers are
6073 correctly updated */
6074 PUT_PSR(env, tmp);
6075 qemu_get_betls(f, &env->fsr);
6076 qemu_get_betls(f, &env->tbr);
6077 #ifndef TARGET_SPARC64
6078 qemu_get_be32s(f, &env->wim);
6079 /* MMU */
6080 for(i = 0; i < 16; i++)
6081 qemu_get_be32s(f, &env->mmuregs[i]);
6082 #endif
6083 tlb_flush(env, 1);
6084 return 0;
6087 #elif defined(TARGET_ARM)
6089 void cpu_save(QEMUFile *f, void *opaque)
6091 int i;
6092 CPUARMState *env = (CPUARMState *)opaque;
6094 for (i = 0; i < 16; i++) {
6095 qemu_put_be32(f, env->regs[i]);
6097 qemu_put_be32(f, cpsr_read(env));
6098 qemu_put_be32(f, env->spsr);
6099 for (i = 0; i < 6; i++) {
6100 qemu_put_be32(f, env->banked_spsr[i]);
6101 qemu_put_be32(f, env->banked_r13[i]);
6102 qemu_put_be32(f, env->banked_r14[i]);
6104 for (i = 0; i < 5; i++) {
6105 qemu_put_be32(f, env->usr_regs[i]);
6106 qemu_put_be32(f, env->fiq_regs[i]);
6108 qemu_put_be32(f, env->cp15.c0_cpuid);
6109 qemu_put_be32(f, env->cp15.c0_cachetype);
6110 qemu_put_be32(f, env->cp15.c1_sys);
6111 qemu_put_be32(f, env->cp15.c1_coproc);
6112 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6113 qemu_put_be32(f, env->cp15.c2_base);
6114 qemu_put_be32(f, env->cp15.c2_data);
6115 qemu_put_be32(f, env->cp15.c2_insn);
6116 qemu_put_be32(f, env->cp15.c3);
6117 qemu_put_be32(f, env->cp15.c5_insn);
6118 qemu_put_be32(f, env->cp15.c5_data);
6119 for (i = 0; i < 8; i++) {
6120 qemu_put_be32(f, env->cp15.c6_region[i]);
6122 qemu_put_be32(f, env->cp15.c6_insn);
6123 qemu_put_be32(f, env->cp15.c6_data);
6124 qemu_put_be32(f, env->cp15.c9_insn);
6125 qemu_put_be32(f, env->cp15.c9_data);
6126 qemu_put_be32(f, env->cp15.c13_fcse);
6127 qemu_put_be32(f, env->cp15.c13_context);
6128 qemu_put_be32(f, env->cp15.c15_cpar);
6130 qemu_put_be32(f, env->features);
6132 if (arm_feature(env, ARM_FEATURE_VFP)) {
6133 for (i = 0; i < 16; i++) {
6134 CPU_DoubleU u;
6135 u.d = env->vfp.regs[i];
6136 qemu_put_be32(f, u.l.upper);
6137 qemu_put_be32(f, u.l.lower);
6139 for (i = 0; i < 16; i++) {
6140 qemu_put_be32(f, env->vfp.xregs[i]);
6143 /* TODO: Should use proper FPSCR access functions. */
6144 qemu_put_be32(f, env->vfp.vec_len);
6145 qemu_put_be32(f, env->vfp.vec_stride);
6148 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6149 for (i = 0; i < 16; i++) {
6150 qemu_put_be64(f, env->iwmmxt.regs[i]);
6152 for (i = 0; i < 16; i++) {
6153 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6158 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6160 CPUARMState *env = (CPUARMState *)opaque;
6161 int i;
6163 if (version_id != 0)
6164 return -EINVAL;
6166 for (i = 0; i < 16; i++) {
6167 env->regs[i] = qemu_get_be32(f);
6169 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6170 env->spsr = qemu_get_be32(f);
6171 for (i = 0; i < 6; i++) {
6172 env->banked_spsr[i] = qemu_get_be32(f);
6173 env->banked_r13[i] = qemu_get_be32(f);
6174 env->banked_r14[i] = qemu_get_be32(f);
6176 for (i = 0; i < 5; i++) {
6177 env->usr_regs[i] = qemu_get_be32(f);
6178 env->fiq_regs[i] = qemu_get_be32(f);
6180 env->cp15.c0_cpuid = qemu_get_be32(f);
6181 env->cp15.c0_cachetype = qemu_get_be32(f);
6182 env->cp15.c1_sys = qemu_get_be32(f);
6183 env->cp15.c1_coproc = qemu_get_be32(f);
6184 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6185 env->cp15.c2_base = qemu_get_be32(f);
6186 env->cp15.c2_data = qemu_get_be32(f);
6187 env->cp15.c2_insn = qemu_get_be32(f);
6188 env->cp15.c3 = qemu_get_be32(f);
6189 env->cp15.c5_insn = qemu_get_be32(f);
6190 env->cp15.c5_data = qemu_get_be32(f);
6191 for (i = 0; i < 8; i++) {
6192 env->cp15.c6_region[i] = qemu_get_be32(f);
6194 env->cp15.c6_insn = qemu_get_be32(f);
6195 env->cp15.c6_data = qemu_get_be32(f);
6196 env->cp15.c9_insn = qemu_get_be32(f);
6197 env->cp15.c9_data = qemu_get_be32(f);
6198 env->cp15.c13_fcse = qemu_get_be32(f);
6199 env->cp15.c13_context = qemu_get_be32(f);
6200 env->cp15.c15_cpar = qemu_get_be32(f);
6202 env->features = qemu_get_be32(f);
6204 if (arm_feature(env, ARM_FEATURE_VFP)) {
6205 for (i = 0; i < 16; i++) {
6206 CPU_DoubleU u;
6207 u.l.upper = qemu_get_be32(f);
6208 u.l.lower = qemu_get_be32(f);
6209 env->vfp.regs[i] = u.d;
6211 for (i = 0; i < 16; i++) {
6212 env->vfp.xregs[i] = qemu_get_be32(f);
6215 /* TODO: Should use proper FPSCR access functions. */
6216 env->vfp.vec_len = qemu_get_be32(f);
6217 env->vfp.vec_stride = qemu_get_be32(f);
6220 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6221 for (i = 0; i < 16; i++) {
6222 env->iwmmxt.regs[i] = qemu_get_be64(f);
6224 for (i = 0; i < 16; i++) {
6225 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6229 return 0;
6232 #else
6234 #warning No CPU save/restore functions
6236 #endif
6238 /***********************************************************/
6239 /* ram save/restore */
6241 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6243 int v;
6245 v = qemu_get_byte(f);
6246 switch(v) {
6247 case 0:
6248 if (qemu_get_buffer(f, buf, len) != len)
6249 return -EIO;
6250 break;
6251 case 1:
6252 v = qemu_get_byte(f);
6253 memset(buf, v, len);
6254 break;
6255 default:
6256 return -EINVAL;
6258 return 0;
6261 static int ram_load_v1(QEMUFile *f, void *opaque)
6263 int i, ret;
6265 if (qemu_get_be32(f) != phys_ram_size)
6266 return -EINVAL;
6267 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6268 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6269 if (ret)
6270 return ret;
6272 return 0;
6275 #define BDRV_HASH_BLOCK_SIZE 1024
6276 #define IOBUF_SIZE 4096
6277 #define RAM_CBLOCK_MAGIC 0xfabe
6279 typedef struct RamCompressState {
6280 z_stream zstream;
6281 QEMUFile *f;
6282 uint8_t buf[IOBUF_SIZE];
6283 } RamCompressState;
6285 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6287 int ret;
6288 memset(s, 0, sizeof(*s));
6289 s->f = f;
6290 ret = deflateInit2(&s->zstream, 1,
6291 Z_DEFLATED, 15,
6292 9, Z_DEFAULT_STRATEGY);
6293 if (ret != Z_OK)
6294 return -1;
6295 s->zstream.avail_out = IOBUF_SIZE;
6296 s->zstream.next_out = s->buf;
6297 return 0;
6300 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6302 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6303 qemu_put_be16(s->f, len);
6304 qemu_put_buffer(s->f, buf, len);
6307 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6309 int ret;
6311 s->zstream.avail_in = len;
6312 s->zstream.next_in = (uint8_t *)buf;
6313 while (s->zstream.avail_in > 0) {
6314 ret = deflate(&s->zstream, Z_NO_FLUSH);
6315 if (ret != Z_OK)
6316 return -1;
6317 if (s->zstream.avail_out == 0) {
6318 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6319 s->zstream.avail_out = IOBUF_SIZE;
6320 s->zstream.next_out = s->buf;
6323 return 0;
6326 static void ram_compress_close(RamCompressState *s)
6328 int len, ret;
6330 /* compress last bytes */
6331 for(;;) {
6332 ret = deflate(&s->zstream, Z_FINISH);
6333 if (ret == Z_OK || ret == Z_STREAM_END) {
6334 len = IOBUF_SIZE - s->zstream.avail_out;
6335 if (len > 0) {
6336 ram_put_cblock(s, s->buf, len);
6338 s->zstream.avail_out = IOBUF_SIZE;
6339 s->zstream.next_out = s->buf;
6340 if (ret == Z_STREAM_END)
6341 break;
6342 } else {
6343 goto fail;
6346 fail:
6347 deflateEnd(&s->zstream);
6350 typedef struct RamDecompressState {
6351 z_stream zstream;
6352 QEMUFile *f;
6353 uint8_t buf[IOBUF_SIZE];
6354 } RamDecompressState;
6356 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6358 int ret;
6359 memset(s, 0, sizeof(*s));
6360 s->f = f;
6361 ret = inflateInit(&s->zstream);
6362 if (ret != Z_OK)
6363 return -1;
6364 return 0;
6367 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6369 int ret, clen;
6371 s->zstream.avail_out = len;
6372 s->zstream.next_out = buf;
6373 while (s->zstream.avail_out > 0) {
6374 if (s->zstream.avail_in == 0) {
6375 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6376 return -1;
6377 clen = qemu_get_be16(s->f);
6378 if (clen > IOBUF_SIZE)
6379 return -1;
6380 qemu_get_buffer(s->f, s->buf, clen);
6381 s->zstream.avail_in = clen;
6382 s->zstream.next_in = s->buf;
6384 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6385 if (ret != Z_OK && ret != Z_STREAM_END) {
6386 return -1;
6389 return 0;
6392 static void ram_decompress_close(RamDecompressState *s)
6394 inflateEnd(&s->zstream);
6397 static void ram_save(QEMUFile *f, void *opaque)
6399 int i;
6400 RamCompressState s1, *s = &s1;
6401 uint8_t buf[10];
6403 qemu_put_be32(f, phys_ram_size);
6404 if (ram_compress_open(s, f) < 0)
6405 return;
6406 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6407 #if 0
6408 if (tight_savevm_enabled) {
6409 int64_t sector_num;
6410 int j;
6412 /* find if the memory block is available on a virtual
6413 block device */
6414 sector_num = -1;
6415 for(j = 0; j < MAX_DISKS; j++) {
6416 if (bs_table[j]) {
6417 sector_num = bdrv_hash_find(bs_table[j],
6418 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6419 if (sector_num >= 0)
6420 break;
6423 if (j == MAX_DISKS)
6424 goto normal_compress;
6425 buf[0] = 1;
6426 buf[1] = j;
6427 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6428 ram_compress_buf(s, buf, 10);
6429 } else
6430 #endif
6432 // normal_compress:
6433 buf[0] = 0;
6434 ram_compress_buf(s, buf, 1);
6435 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6438 ram_compress_close(s);
6441 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6443 RamDecompressState s1, *s = &s1;
6444 uint8_t buf[10];
6445 int i;
6447 if (version_id == 1)
6448 return ram_load_v1(f, opaque);
6449 if (version_id != 2)
6450 return -EINVAL;
6451 if (qemu_get_be32(f) != phys_ram_size)
6452 return -EINVAL;
6453 if (ram_decompress_open(s, f) < 0)
6454 return -EINVAL;
6455 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6456 if (ram_decompress_buf(s, buf, 1) < 0) {
6457 fprintf(stderr, "Error while reading ram block header\n");
6458 goto error;
6460 if (buf[0] == 0) {
6461 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6462 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6463 goto error;
6465 } else
6466 #if 0
6467 if (buf[0] == 1) {
6468 int bs_index;
6469 int64_t sector_num;
6471 ram_decompress_buf(s, buf + 1, 9);
6472 bs_index = buf[1];
6473 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6474 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6475 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6476 goto error;
6478 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6479 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6480 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6481 bs_index, sector_num);
6482 goto error;
6484 } else
6485 #endif
6487 error:
6488 printf("Error block header\n");
6489 return -EINVAL;
6492 ram_decompress_close(s);
6493 return 0;
6496 /***********************************************************/
6497 /* bottom halves (can be seen as timers which expire ASAP) */
6499 struct QEMUBH {
6500 QEMUBHFunc *cb;
6501 void *opaque;
6502 int scheduled;
6503 QEMUBH *next;
6506 static QEMUBH *first_bh = NULL;
6508 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6510 QEMUBH *bh;
6511 bh = qemu_mallocz(sizeof(QEMUBH));
6512 if (!bh)
6513 return NULL;
6514 bh->cb = cb;
6515 bh->opaque = opaque;
6516 return bh;
6519 int qemu_bh_poll(void)
6521 QEMUBH *bh, **pbh;
6522 int ret;
6524 ret = 0;
6525 for(;;) {
6526 pbh = &first_bh;
6527 bh = *pbh;
6528 if (!bh)
6529 break;
6530 ret = 1;
6531 *pbh = bh->next;
6532 bh->scheduled = 0;
6533 bh->cb(bh->opaque);
6535 return ret;
6538 void qemu_bh_schedule(QEMUBH *bh)
6540 CPUState *env = cpu_single_env;
6541 if (bh->scheduled)
6542 return;
6543 bh->scheduled = 1;
6544 bh->next = first_bh;
6545 first_bh = bh;
6547 /* stop the currently executing CPU to execute the BH ASAP */
6548 if (env) {
6549 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6553 void qemu_bh_cancel(QEMUBH *bh)
6555 QEMUBH **pbh;
6556 if (bh->scheduled) {
6557 pbh = &first_bh;
6558 while (*pbh != bh)
6559 pbh = &(*pbh)->next;
6560 *pbh = bh->next;
6561 bh->scheduled = 0;
6565 void qemu_bh_delete(QEMUBH *bh)
6567 qemu_bh_cancel(bh);
6568 qemu_free(bh);
6571 /***********************************************************/
6572 /* machine registration */
6574 QEMUMachine *first_machine = NULL;
6576 int qemu_register_machine(QEMUMachine *m)
6578 QEMUMachine **pm;
6579 pm = &first_machine;
6580 while (*pm != NULL)
6581 pm = &(*pm)->next;
6582 m->next = NULL;
6583 *pm = m;
6584 return 0;
6587 QEMUMachine *find_machine(const char *name)
6589 QEMUMachine *m;
6591 for(m = first_machine; m != NULL; m = m->next) {
6592 if (!strcmp(m->name, name))
6593 return m;
6595 return NULL;
6598 /***********************************************************/
6599 /* main execution loop */
6601 void gui_update(void *opaque)
6603 DisplayState *ds = opaque;
6604 ds->dpy_refresh(ds);
6605 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6608 struct vm_change_state_entry {
6609 VMChangeStateHandler *cb;
6610 void *opaque;
6611 LIST_ENTRY (vm_change_state_entry) entries;
6614 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6616 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6617 void *opaque)
6619 VMChangeStateEntry *e;
6621 e = qemu_mallocz(sizeof (*e));
6622 if (!e)
6623 return NULL;
6625 e->cb = cb;
6626 e->opaque = opaque;
6627 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6628 return e;
6631 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6633 LIST_REMOVE (e, entries);
6634 qemu_free (e);
6637 static void vm_state_notify(int running)
6639 VMChangeStateEntry *e;
6641 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6642 e->cb(e->opaque, running);
6646 /* XXX: support several handlers */
6647 static VMStopHandler *vm_stop_cb;
6648 static void *vm_stop_opaque;
6650 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6652 vm_stop_cb = cb;
6653 vm_stop_opaque = opaque;
6654 return 0;
6657 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6659 vm_stop_cb = NULL;
6662 void vm_start(void)
6664 if (!vm_running) {
6665 cpu_enable_ticks();
6666 vm_running = 1;
6667 vm_state_notify(1);
6668 qemu_rearm_alarm_timer(alarm_timer);
6672 void vm_stop(int reason)
6674 if (vm_running) {
6675 cpu_disable_ticks();
6676 vm_running = 0;
6677 if (reason != 0) {
6678 if (vm_stop_cb) {
6679 vm_stop_cb(vm_stop_opaque, reason);
6682 vm_state_notify(0);
6686 /* reset/shutdown handler */
6688 typedef struct QEMUResetEntry {
6689 QEMUResetHandler *func;
6690 void *opaque;
6691 struct QEMUResetEntry *next;
6692 } QEMUResetEntry;
6694 static QEMUResetEntry *first_reset_entry;
6695 static int reset_requested;
6696 static int shutdown_requested;
6697 static int powerdown_requested;
6699 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6701 QEMUResetEntry **pre, *re;
6703 pre = &first_reset_entry;
6704 while (*pre != NULL)
6705 pre = &(*pre)->next;
6706 re = qemu_mallocz(sizeof(QEMUResetEntry));
6707 re->func = func;
6708 re->opaque = opaque;
6709 re->next = NULL;
6710 *pre = re;
6713 static void qemu_system_reset(void)
6715 QEMUResetEntry *re;
6717 /* reset all devices */
6718 for(re = first_reset_entry; re != NULL; re = re->next) {
6719 re->func(re->opaque);
6723 void qemu_system_reset_request(void)
6725 if (no_reboot) {
6726 shutdown_requested = 1;
6727 } else {
6728 reset_requested = 1;
6730 if (cpu_single_env)
6731 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6734 void qemu_system_shutdown_request(void)
6736 shutdown_requested = 1;
6737 if (cpu_single_env)
6738 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6741 void qemu_system_powerdown_request(void)
6743 powerdown_requested = 1;
6744 if (cpu_single_env)
6745 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6748 void main_loop_wait(int timeout)
6750 IOHandlerRecord *ioh;
6751 fd_set rfds, wfds, xfds;
6752 int ret, nfds;
6753 #ifdef _WIN32
6754 int ret2, i;
6755 #endif
6756 struct timeval tv;
6757 PollingEntry *pe;
6760 /* XXX: need to suppress polling by better using win32 events */
6761 ret = 0;
6762 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6763 ret |= pe->func(pe->opaque);
6765 #ifdef _WIN32
6766 if (ret == 0) {
6767 int err;
6768 WaitObjects *w = &wait_objects;
6770 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6771 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6772 if (w->func[ret - WAIT_OBJECT_0])
6773 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6775 /* Check for additional signaled events */
6776 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6778 /* Check if event is signaled */
6779 ret2 = WaitForSingleObject(w->events[i], 0);
6780 if(ret2 == WAIT_OBJECT_0) {
6781 if (w->func[i])
6782 w->func[i](w->opaque[i]);
6783 } else if (ret2 == WAIT_TIMEOUT) {
6784 } else {
6785 err = GetLastError();
6786 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6789 } else if (ret == WAIT_TIMEOUT) {
6790 } else {
6791 err = GetLastError();
6792 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6795 #endif
6796 /* poll any events */
6797 /* XXX: separate device handlers from system ones */
6798 nfds = -1;
6799 FD_ZERO(&rfds);
6800 FD_ZERO(&wfds);
6801 FD_ZERO(&xfds);
6802 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6803 if (ioh->deleted)
6804 continue;
6805 if (ioh->fd_read &&
6806 (!ioh->fd_read_poll ||
6807 ioh->fd_read_poll(ioh->opaque) != 0)) {
6808 FD_SET(ioh->fd, &rfds);
6809 if (ioh->fd > nfds)
6810 nfds = ioh->fd;
6812 if (ioh->fd_write) {
6813 FD_SET(ioh->fd, &wfds);
6814 if (ioh->fd > nfds)
6815 nfds = ioh->fd;
6819 tv.tv_sec = 0;
6820 #ifdef _WIN32
6821 tv.tv_usec = 0;
6822 #else
6823 tv.tv_usec = timeout * 1000;
6824 #endif
6825 #if defined(CONFIG_SLIRP)
6826 if (slirp_inited) {
6827 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6829 #endif
6830 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6831 if (ret > 0) {
6832 IOHandlerRecord **pioh;
6834 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6835 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6836 ioh->fd_read(ioh->opaque);
6838 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6839 ioh->fd_write(ioh->opaque);
6843 /* remove deleted IO handlers */
6844 pioh = &first_io_handler;
6845 while (*pioh) {
6846 ioh = *pioh;
6847 if (ioh->deleted) {
6848 *pioh = ioh->next;
6849 qemu_free(ioh);
6850 } else
6851 pioh = &ioh->next;
6854 #if defined(CONFIG_SLIRP)
6855 if (slirp_inited) {
6856 if (ret < 0) {
6857 FD_ZERO(&rfds);
6858 FD_ZERO(&wfds);
6859 FD_ZERO(&xfds);
6861 slirp_select_poll(&rfds, &wfds, &xfds);
6863 #endif
6864 qemu_aio_poll();
6866 if (vm_running) {
6867 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6868 qemu_get_clock(vm_clock));
6869 /* run dma transfers, if any */
6870 DMA_run();
6873 /* real time timers */
6874 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6875 qemu_get_clock(rt_clock));
6877 /* Check bottom-halves last in case any of the earlier events triggered
6878 them. */
6879 qemu_bh_poll();
6883 static CPUState *cur_cpu;
6885 int main_loop(void)
6887 int ret, timeout;
6888 #ifdef CONFIG_PROFILER
6889 int64_t ti;
6890 #endif
6891 CPUState *env;
6893 cur_cpu = first_cpu;
6894 for(;;) {
6895 if (vm_running) {
6897 env = cur_cpu;
6898 for(;;) {
6899 /* get next cpu */
6900 env = env->next_cpu;
6901 if (!env)
6902 env = first_cpu;
6903 #ifdef CONFIG_PROFILER
6904 ti = profile_getclock();
6905 #endif
6906 ret = cpu_exec(env);
6907 #ifdef CONFIG_PROFILER
6908 qemu_time += profile_getclock() - ti;
6909 #endif
6910 if (ret == EXCP_HLT) {
6911 /* Give the next CPU a chance to run. */
6912 cur_cpu = env;
6913 continue;
6915 if (ret != EXCP_HALTED)
6916 break;
6917 /* all CPUs are halted ? */
6918 if (env == cur_cpu)
6919 break;
6921 cur_cpu = env;
6923 if (shutdown_requested) {
6924 ret = EXCP_INTERRUPT;
6925 break;
6927 if (reset_requested) {
6928 reset_requested = 0;
6929 qemu_system_reset();
6930 ret = EXCP_INTERRUPT;
6932 if (powerdown_requested) {
6933 powerdown_requested = 0;
6934 qemu_system_powerdown();
6935 ret = EXCP_INTERRUPT;
6937 if (ret == EXCP_DEBUG) {
6938 vm_stop(EXCP_DEBUG);
6940 /* If all cpus are halted then wait until the next IRQ */
6941 /* XXX: use timeout computed from timers */
6942 if (ret == EXCP_HALTED)
6943 timeout = 10;
6944 else
6945 timeout = 0;
6946 } else {
6947 timeout = 10;
6949 #ifdef CONFIG_PROFILER
6950 ti = profile_getclock();
6951 #endif
6952 main_loop_wait(timeout);
6953 #ifdef CONFIG_PROFILER
6954 dev_time += profile_getclock() - ti;
6955 #endif
6957 cpu_disable_ticks();
6958 return ret;
6961 static void help(int exitcode)
6963 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6964 "usage: %s [options] [disk_image]\n"
6965 "\n"
6966 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6967 "\n"
6968 "Standard options:\n"
6969 "-M machine select emulated machine (-M ? for list)\n"
6970 "-cpu cpu select CPU (-cpu ? for list)\n"
6971 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6972 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6973 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6974 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6975 "-mtdblock file use 'file' as on-board Flash memory image\n"
6976 "-sd file use 'file' as SecureDigital card image\n"
6977 "-pflash file use 'file' as a parallel flash image\n"
6978 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6979 "-snapshot write to temporary files instead of disk image files\n"
6980 #ifdef CONFIG_SDL
6981 "-no-frame open SDL window without a frame and window decorations\n"
6982 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
6983 "-no-quit disable SDL window close capability\n"
6984 #endif
6985 #ifdef TARGET_I386
6986 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6987 #endif
6988 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6989 "-smp n set the number of CPUs to 'n' [default=1]\n"
6990 "-nographic disable graphical output and redirect serial I/Os to console\n"
6991 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6992 #ifndef _WIN32
6993 "-k language use keyboard layout (for example \"fr\" for French)\n"
6994 #endif
6995 #ifdef HAS_AUDIO
6996 "-audio-help print list of audio drivers and their options\n"
6997 "-soundhw c1,... enable audio support\n"
6998 " and only specified sound cards (comma separated list)\n"
6999 " use -soundhw ? to get the list of supported cards\n"
7000 " use -soundhw all to enable all of them\n"
7001 #endif
7002 "-localtime set the real time clock to local time [default=utc]\n"
7003 "-full-screen start in full screen\n"
7004 #ifdef TARGET_I386
7005 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7006 #endif
7007 "-usb enable the USB driver (will be the default soon)\n"
7008 "-usbdevice name add the host or guest USB device 'name'\n"
7009 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7010 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7011 #endif
7012 "-name string set the name of the guest\n"
7013 "\n"
7014 "Network options:\n"
7015 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7016 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7017 #ifdef CONFIG_SLIRP
7018 "-net user[,vlan=n][,hostname=host]\n"
7019 " connect the user mode network stack to VLAN 'n' and send\n"
7020 " hostname 'host' to DHCP clients\n"
7021 #endif
7022 #ifdef _WIN32
7023 "-net tap[,vlan=n],ifname=name\n"
7024 " connect the host TAP network interface to VLAN 'n'\n"
7025 #else
7026 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
7027 " connect the host TAP network interface to VLAN 'n' and use\n"
7028 " the network script 'file' (default=%s);\n"
7029 " use 'script=no' to disable script execution;\n"
7030 " use 'fd=h' to connect to an already opened TAP interface\n"
7031 #endif
7032 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7033 " connect the vlan 'n' to another VLAN using a socket connection\n"
7034 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7035 " connect the vlan 'n' to multicast maddr and port\n"
7036 "-net none use it alone to have zero network devices; if no -net option\n"
7037 " is provided, the default is '-net nic -net user'\n"
7038 "\n"
7039 #ifdef CONFIG_SLIRP
7040 "-tftp dir allow tftp access to files in dir [-net user]\n"
7041 "-bootp file advertise file in BOOTP replies\n"
7042 #ifndef _WIN32
7043 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7044 #endif
7045 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7046 " redirect TCP or UDP connections from host to guest [-net user]\n"
7047 #endif
7048 "\n"
7049 "Linux boot specific:\n"
7050 "-kernel bzImage use 'bzImage' as kernel image\n"
7051 "-append cmdline use 'cmdline' as kernel command line\n"
7052 "-initrd file use 'file' as initial ram disk\n"
7053 "\n"
7054 "Debug/Expert options:\n"
7055 "-monitor dev redirect the monitor to char device 'dev'\n"
7056 "-serial dev redirect the serial port to char device 'dev'\n"
7057 "-parallel dev redirect the parallel port to char device 'dev'\n"
7058 "-pidfile file Write PID to 'file'\n"
7059 "-S freeze CPU at startup (use 'c' to start execution)\n"
7060 "-s wait gdb connection to port\n"
7061 "-p port set gdb connection port [default=%s]\n"
7062 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7063 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7064 " translation (t=none or lba) (usually qemu can guess them)\n"
7065 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7066 #ifdef USE_KQEMU
7067 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7068 "-no-kqemu disable KQEMU kernel module usage\n"
7069 #endif
7070 #ifdef USE_CODE_COPY
7071 "-no-code-copy disable code copy acceleration\n"
7072 #endif
7073 #ifdef TARGET_I386
7074 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7075 " (default is CL-GD5446 PCI VGA)\n"
7076 "-no-acpi disable ACPI\n"
7077 #endif
7078 "-no-reboot exit instead of rebooting\n"
7079 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7080 "-vnc display start a VNC server on display\n"
7081 #ifndef _WIN32
7082 "-daemonize daemonize QEMU after initializing\n"
7083 #endif
7084 "-option-rom rom load a file, rom, into the option ROM space\n"
7085 #ifdef TARGET_SPARC
7086 "-prom-env variable=value set OpenBIOS nvram variables\n"
7087 #endif
7088 "-clock force the use of the given methods for timer alarm.\n"
7089 " To see what timers are available use -clock help\n"
7090 "\n"
7091 "During emulation, the following keys are useful:\n"
7092 "ctrl-alt-f toggle full screen\n"
7093 "ctrl-alt-n switch to virtual console 'n'\n"
7094 "ctrl-alt toggle mouse and keyboard grab\n"
7095 "\n"
7096 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7098 "qemu",
7099 DEFAULT_RAM_SIZE,
7100 #ifndef _WIN32
7101 DEFAULT_NETWORK_SCRIPT,
7102 #endif
7103 DEFAULT_GDBSTUB_PORT,
7104 "/tmp/qemu.log");
7105 exit(exitcode);
7108 #define HAS_ARG 0x0001
7110 enum {
7111 QEMU_OPTION_h,
7113 QEMU_OPTION_M,
7114 QEMU_OPTION_cpu,
7115 QEMU_OPTION_fda,
7116 QEMU_OPTION_fdb,
7117 QEMU_OPTION_hda,
7118 QEMU_OPTION_hdb,
7119 QEMU_OPTION_hdc,
7120 QEMU_OPTION_hdd,
7121 QEMU_OPTION_cdrom,
7122 QEMU_OPTION_mtdblock,
7123 QEMU_OPTION_sd,
7124 QEMU_OPTION_pflash,
7125 QEMU_OPTION_boot,
7126 QEMU_OPTION_snapshot,
7127 #ifdef TARGET_I386
7128 QEMU_OPTION_no_fd_bootchk,
7129 #endif
7130 QEMU_OPTION_m,
7131 QEMU_OPTION_nographic,
7132 QEMU_OPTION_portrait,
7133 #ifdef HAS_AUDIO
7134 QEMU_OPTION_audio_help,
7135 QEMU_OPTION_soundhw,
7136 #endif
7138 QEMU_OPTION_net,
7139 QEMU_OPTION_tftp,
7140 QEMU_OPTION_bootp,
7141 QEMU_OPTION_smb,
7142 QEMU_OPTION_redir,
7144 QEMU_OPTION_kernel,
7145 QEMU_OPTION_append,
7146 QEMU_OPTION_initrd,
7148 QEMU_OPTION_S,
7149 QEMU_OPTION_s,
7150 QEMU_OPTION_p,
7151 QEMU_OPTION_d,
7152 QEMU_OPTION_hdachs,
7153 QEMU_OPTION_L,
7154 QEMU_OPTION_no_code_copy,
7155 QEMU_OPTION_k,
7156 QEMU_OPTION_localtime,
7157 QEMU_OPTION_cirrusvga,
7158 QEMU_OPTION_vmsvga,
7159 QEMU_OPTION_g,
7160 QEMU_OPTION_std_vga,
7161 QEMU_OPTION_echr,
7162 QEMU_OPTION_monitor,
7163 QEMU_OPTION_serial,
7164 QEMU_OPTION_parallel,
7165 QEMU_OPTION_loadvm,
7166 QEMU_OPTION_full_screen,
7167 QEMU_OPTION_no_frame,
7168 QEMU_OPTION_alt_grab,
7169 QEMU_OPTION_no_quit,
7170 QEMU_OPTION_pidfile,
7171 QEMU_OPTION_no_kqemu,
7172 QEMU_OPTION_kernel_kqemu,
7173 QEMU_OPTION_win2k_hack,
7174 QEMU_OPTION_usb,
7175 QEMU_OPTION_usbdevice,
7176 QEMU_OPTION_smp,
7177 QEMU_OPTION_vnc,
7178 QEMU_OPTION_no_acpi,
7179 QEMU_OPTION_no_reboot,
7180 QEMU_OPTION_show_cursor,
7181 QEMU_OPTION_daemonize,
7182 QEMU_OPTION_option_rom,
7183 QEMU_OPTION_semihosting,
7184 QEMU_OPTION_name,
7185 QEMU_OPTION_prom_env,
7186 QEMU_OPTION_old_param,
7187 QEMU_OPTION_clock,
7190 typedef struct QEMUOption {
7191 const char *name;
7192 int flags;
7193 int index;
7194 } QEMUOption;
7196 const QEMUOption qemu_options[] = {
7197 { "h", 0, QEMU_OPTION_h },
7198 { "help", 0, QEMU_OPTION_h },
7200 { "M", HAS_ARG, QEMU_OPTION_M },
7201 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7202 { "fda", HAS_ARG, QEMU_OPTION_fda },
7203 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7204 { "hda", HAS_ARG, QEMU_OPTION_hda },
7205 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7206 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7207 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7208 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7209 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7210 { "sd", HAS_ARG, QEMU_OPTION_sd },
7211 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7212 { "boot", HAS_ARG, QEMU_OPTION_boot },
7213 { "snapshot", 0, QEMU_OPTION_snapshot },
7214 #ifdef TARGET_I386
7215 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7216 #endif
7217 { "m", HAS_ARG, QEMU_OPTION_m },
7218 { "nographic", 0, QEMU_OPTION_nographic },
7219 { "portrait", 0, QEMU_OPTION_portrait },
7220 { "k", HAS_ARG, QEMU_OPTION_k },
7221 #ifdef HAS_AUDIO
7222 { "audio-help", 0, QEMU_OPTION_audio_help },
7223 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7224 #endif
7226 { "net", HAS_ARG, QEMU_OPTION_net},
7227 #ifdef CONFIG_SLIRP
7228 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7229 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7230 #ifndef _WIN32
7231 { "smb", HAS_ARG, QEMU_OPTION_smb },
7232 #endif
7233 { "redir", HAS_ARG, QEMU_OPTION_redir },
7234 #endif
7236 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7237 { "append", HAS_ARG, QEMU_OPTION_append },
7238 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7240 { "S", 0, QEMU_OPTION_S },
7241 { "s", 0, QEMU_OPTION_s },
7242 { "p", HAS_ARG, QEMU_OPTION_p },
7243 { "d", HAS_ARG, QEMU_OPTION_d },
7244 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7245 { "L", HAS_ARG, QEMU_OPTION_L },
7246 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7247 #ifdef USE_KQEMU
7248 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7249 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7250 #endif
7251 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7252 { "g", 1, QEMU_OPTION_g },
7253 #endif
7254 { "localtime", 0, QEMU_OPTION_localtime },
7255 { "std-vga", 0, QEMU_OPTION_std_vga },
7256 { "echr", HAS_ARG, QEMU_OPTION_echr },
7257 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7258 { "serial", HAS_ARG, QEMU_OPTION_serial },
7259 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7260 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7261 { "full-screen", 0, QEMU_OPTION_full_screen },
7262 #ifdef CONFIG_SDL
7263 { "no-frame", 0, QEMU_OPTION_no_frame },
7264 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7265 { "no-quit", 0, QEMU_OPTION_no_quit },
7266 #endif
7267 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7268 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7269 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7270 { "smp", HAS_ARG, QEMU_OPTION_smp },
7271 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7273 /* temporary options */
7274 { "usb", 0, QEMU_OPTION_usb },
7275 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7276 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7277 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7278 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7279 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7280 { "daemonize", 0, QEMU_OPTION_daemonize },
7281 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7282 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7283 { "semihosting", 0, QEMU_OPTION_semihosting },
7284 #endif
7285 { "name", HAS_ARG, QEMU_OPTION_name },
7286 #if defined(TARGET_SPARC)
7287 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7288 #endif
7289 #if defined(TARGET_ARM)
7290 { "old-param", 0, QEMU_OPTION_old_param },
7291 #endif
7292 { "clock", HAS_ARG, QEMU_OPTION_clock },
7293 { NULL },
7296 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
7298 /* this stack is only used during signal handling */
7299 #define SIGNAL_STACK_SIZE 32768
7301 static uint8_t *signal_stack;
7303 #endif
7305 /* password input */
7307 int qemu_key_check(BlockDriverState *bs, const char *name)
7309 char password[256];
7310 int i;
7312 if (!bdrv_is_encrypted(bs))
7313 return 0;
7315 term_printf("%s is encrypted.\n", name);
7316 for(i = 0; i < 3; i++) {
7317 monitor_readline("Password: ", 1, password, sizeof(password));
7318 if (bdrv_set_key(bs, password) == 0)
7319 return 0;
7320 term_printf("invalid password\n");
7322 return -EPERM;
7325 static BlockDriverState *get_bdrv(int index)
7327 BlockDriverState *bs;
7329 if (index < 4) {
7330 bs = bs_table[index];
7331 } else if (index < 6) {
7332 bs = fd_table[index - 4];
7333 } else {
7334 bs = NULL;
7336 return bs;
7339 static void read_passwords(void)
7341 BlockDriverState *bs;
7342 int i;
7344 for(i = 0; i < 6; i++) {
7345 bs = get_bdrv(i);
7346 if (bs)
7347 qemu_key_check(bs, bdrv_get_device_name(bs));
7351 /* XXX: currently we cannot use simultaneously different CPUs */
7352 void register_machines(void)
7354 #if defined(TARGET_I386)
7355 qemu_register_machine(&pc_machine);
7356 qemu_register_machine(&isapc_machine);
7357 #elif defined(TARGET_PPC)
7358 qemu_register_machine(&heathrow_machine);
7359 qemu_register_machine(&core99_machine);
7360 qemu_register_machine(&prep_machine);
7361 qemu_register_machine(&ref405ep_machine);
7362 qemu_register_machine(&taihu_machine);
7363 #elif defined(TARGET_MIPS)
7364 qemu_register_machine(&mips_machine);
7365 qemu_register_machine(&mips_malta_machine);
7366 qemu_register_machine(&mips_pica61_machine);
7367 #elif defined(TARGET_SPARC)
7368 #ifdef TARGET_SPARC64
7369 qemu_register_machine(&sun4u_machine);
7370 #else
7371 qemu_register_machine(&ss5_machine);
7372 qemu_register_machine(&ss10_machine);
7373 #endif
7374 #elif defined(TARGET_ARM)
7375 qemu_register_machine(&integratorcp_machine);
7376 qemu_register_machine(&versatilepb_machine);
7377 qemu_register_machine(&versatileab_machine);
7378 qemu_register_machine(&realview_machine);
7379 qemu_register_machine(&akitapda_machine);
7380 qemu_register_machine(&spitzpda_machine);
7381 qemu_register_machine(&borzoipda_machine);
7382 qemu_register_machine(&terrierpda_machine);
7383 qemu_register_machine(&palmte_machine);
7384 #elif defined(TARGET_SH4)
7385 qemu_register_machine(&shix_machine);
7386 qemu_register_machine(&r2d_machine);
7387 #elif defined(TARGET_ALPHA)
7388 /* XXX: TODO */
7389 #elif defined(TARGET_M68K)
7390 qemu_register_machine(&mcf5208evb_machine);
7391 qemu_register_machine(&an5206_machine);
7392 #else
7393 #error unsupported CPU
7394 #endif
7397 #ifdef HAS_AUDIO
7398 struct soundhw soundhw[] = {
7399 #ifdef HAS_AUDIO_CHOICE
7400 #ifdef TARGET_I386
7402 "pcspk",
7403 "PC speaker",
7406 { .init_isa = pcspk_audio_init }
7408 #endif
7410 "sb16",
7411 "Creative Sound Blaster 16",
7414 { .init_isa = SB16_init }
7417 #ifdef CONFIG_ADLIB
7419 "adlib",
7420 #ifdef HAS_YMF262
7421 "Yamaha YMF262 (OPL3)",
7422 #else
7423 "Yamaha YM3812 (OPL2)",
7424 #endif
7427 { .init_isa = Adlib_init }
7429 #endif
7431 #ifdef CONFIG_GUS
7433 "gus",
7434 "Gravis Ultrasound GF1",
7437 { .init_isa = GUS_init }
7439 #endif
7442 "es1370",
7443 "ENSONIQ AudioPCI ES1370",
7446 { .init_pci = es1370_init }
7448 #endif
7450 { NULL, NULL, 0, 0, { NULL } }
7453 static void select_soundhw (const char *optarg)
7455 struct soundhw *c;
7457 if (*optarg == '?') {
7458 show_valid_cards:
7460 printf ("Valid sound card names (comma separated):\n");
7461 for (c = soundhw; c->name; ++c) {
7462 printf ("%-11s %s\n", c->name, c->descr);
7464 printf ("\n-soundhw all will enable all of the above\n");
7465 exit (*optarg != '?');
7467 else {
7468 size_t l;
7469 const char *p;
7470 char *e;
7471 int bad_card = 0;
7473 if (!strcmp (optarg, "all")) {
7474 for (c = soundhw; c->name; ++c) {
7475 c->enabled = 1;
7477 return;
7480 p = optarg;
7481 while (*p) {
7482 e = strchr (p, ',');
7483 l = !e ? strlen (p) : (size_t) (e - p);
7485 for (c = soundhw; c->name; ++c) {
7486 if (!strncmp (c->name, p, l)) {
7487 c->enabled = 1;
7488 break;
7492 if (!c->name) {
7493 if (l > 80) {
7494 fprintf (stderr,
7495 "Unknown sound card name (too big to show)\n");
7497 else {
7498 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7499 (int) l, p);
7501 bad_card = 1;
7503 p += l + (e != NULL);
7506 if (bad_card)
7507 goto show_valid_cards;
7510 #endif
7512 #ifdef _WIN32
7513 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7515 exit(STATUS_CONTROL_C_EXIT);
7516 return TRUE;
7518 #endif
7520 #define MAX_NET_CLIENTS 32
7522 int main(int argc, char **argv)
7524 #ifdef CONFIG_GDBSTUB
7525 int use_gdbstub;
7526 const char *gdbstub_port;
7527 #endif
7528 int i, cdrom_index, pflash_index;
7529 int snapshot, linux_boot;
7530 const char *initrd_filename;
7531 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7532 const char *pflash_filename[MAX_PFLASH];
7533 const char *sd_filename;
7534 const char *mtd_filename;
7535 const char *kernel_filename, *kernel_cmdline;
7536 DisplayState *ds = &display_state;
7537 int cyls, heads, secs, translation;
7538 char net_clients[MAX_NET_CLIENTS][256];
7539 int nb_net_clients;
7540 int optind;
7541 const char *r, *optarg;
7542 CharDriverState *monitor_hd;
7543 char monitor_device[128];
7544 char serial_devices[MAX_SERIAL_PORTS][128];
7545 int serial_device_index;
7546 char parallel_devices[MAX_PARALLEL_PORTS][128];
7547 int parallel_device_index;
7548 const char *loadvm = NULL;
7549 QEMUMachine *machine;
7550 const char *cpu_model;
7551 char usb_devices[MAX_USB_CMDLINE][128];
7552 int usb_devices_index;
7553 int fds[2];
7554 const char *pid_file = NULL;
7555 VLANState *vlan;
7557 LIST_INIT (&vm_change_state_head);
7558 #ifndef _WIN32
7560 struct sigaction act;
7561 sigfillset(&act.sa_mask);
7562 act.sa_flags = 0;
7563 act.sa_handler = SIG_IGN;
7564 sigaction(SIGPIPE, &act, NULL);
7566 #else
7567 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7568 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7569 QEMU to run on a single CPU */
7571 HANDLE h;
7572 DWORD mask, smask;
7573 int i;
7574 h = GetCurrentProcess();
7575 if (GetProcessAffinityMask(h, &mask, &smask)) {
7576 for(i = 0; i < 32; i++) {
7577 if (mask & (1 << i))
7578 break;
7580 if (i != 32) {
7581 mask = 1 << i;
7582 SetProcessAffinityMask(h, mask);
7586 #endif
7588 register_machines();
7589 machine = first_machine;
7590 cpu_model = NULL;
7591 initrd_filename = NULL;
7592 for(i = 0; i < MAX_FD; i++)
7593 fd_filename[i] = NULL;
7594 for(i = 0; i < MAX_DISKS; i++)
7595 hd_filename[i] = NULL;
7596 for(i = 0; i < MAX_PFLASH; i++)
7597 pflash_filename[i] = NULL;
7598 pflash_index = 0;
7599 sd_filename = NULL;
7600 mtd_filename = NULL;
7601 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7602 vga_ram_size = VGA_RAM_SIZE;
7603 #ifdef CONFIG_GDBSTUB
7604 use_gdbstub = 0;
7605 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7606 #endif
7607 snapshot = 0;
7608 nographic = 0;
7609 kernel_filename = NULL;
7610 kernel_cmdline = "";
7611 #ifdef TARGET_PPC
7612 cdrom_index = 1;
7613 #else
7614 cdrom_index = 2;
7615 #endif
7616 cyls = heads = secs = 0;
7617 translation = BIOS_ATA_TRANSLATION_AUTO;
7618 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7620 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7621 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7622 serial_devices[i][0] = '\0';
7623 serial_device_index = 0;
7625 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7626 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7627 parallel_devices[i][0] = '\0';
7628 parallel_device_index = 0;
7630 usb_devices_index = 0;
7632 nb_net_clients = 0;
7634 nb_nics = 0;
7635 /* default mac address of the first network interface */
7637 optind = 1;
7638 for(;;) {
7639 if (optind >= argc)
7640 break;
7641 r = argv[optind];
7642 if (r[0] != '-') {
7643 hd_filename[0] = argv[optind++];
7644 } else {
7645 const QEMUOption *popt;
7647 optind++;
7648 /* Treat --foo the same as -foo. */
7649 if (r[1] == '-')
7650 r++;
7651 popt = qemu_options;
7652 for(;;) {
7653 if (!popt->name) {
7654 fprintf(stderr, "%s: invalid option -- '%s'\n",
7655 argv[0], r);
7656 exit(1);
7658 if (!strcmp(popt->name, r + 1))
7659 break;
7660 popt++;
7662 if (popt->flags & HAS_ARG) {
7663 if (optind >= argc) {
7664 fprintf(stderr, "%s: option '%s' requires an argument\n",
7665 argv[0], r);
7666 exit(1);
7668 optarg = argv[optind++];
7669 } else {
7670 optarg = NULL;
7673 switch(popt->index) {
7674 case QEMU_OPTION_M:
7675 machine = find_machine(optarg);
7676 if (!machine) {
7677 QEMUMachine *m;
7678 printf("Supported machines are:\n");
7679 for(m = first_machine; m != NULL; m = m->next) {
7680 printf("%-10s %s%s\n",
7681 m->name, m->desc,
7682 m == first_machine ? " (default)" : "");
7684 exit(*optarg != '?');
7686 break;
7687 case QEMU_OPTION_cpu:
7688 /* hw initialization will check this */
7689 if (*optarg == '?') {
7690 #if defined(TARGET_PPC)
7691 ppc_cpu_list(stdout, &fprintf);
7692 #elif defined(TARGET_ARM)
7693 arm_cpu_list();
7694 #elif defined(TARGET_MIPS)
7695 mips_cpu_list(stdout, &fprintf);
7696 #elif defined(TARGET_SPARC)
7697 sparc_cpu_list(stdout, &fprintf);
7698 #endif
7699 exit(0);
7700 } else {
7701 cpu_model = optarg;
7703 break;
7704 case QEMU_OPTION_initrd:
7705 initrd_filename = optarg;
7706 break;
7707 case QEMU_OPTION_hda:
7708 case QEMU_OPTION_hdb:
7709 case QEMU_OPTION_hdc:
7710 case QEMU_OPTION_hdd:
7712 int hd_index;
7713 hd_index = popt->index - QEMU_OPTION_hda;
7714 hd_filename[hd_index] = optarg;
7715 if (hd_index == cdrom_index)
7716 cdrom_index = -1;
7718 break;
7719 case QEMU_OPTION_mtdblock:
7720 mtd_filename = optarg;
7721 break;
7722 case QEMU_OPTION_sd:
7723 sd_filename = optarg;
7724 break;
7725 case QEMU_OPTION_pflash:
7726 if (pflash_index >= MAX_PFLASH) {
7727 fprintf(stderr, "qemu: too many parallel flash images\n");
7728 exit(1);
7730 pflash_filename[pflash_index++] = optarg;
7731 break;
7732 case QEMU_OPTION_snapshot:
7733 snapshot = 1;
7734 break;
7735 case QEMU_OPTION_hdachs:
7737 const char *p;
7738 p = optarg;
7739 cyls = strtol(p, (char **)&p, 0);
7740 if (cyls < 1 || cyls > 16383)
7741 goto chs_fail;
7742 if (*p != ',')
7743 goto chs_fail;
7744 p++;
7745 heads = strtol(p, (char **)&p, 0);
7746 if (heads < 1 || heads > 16)
7747 goto chs_fail;
7748 if (*p != ',')
7749 goto chs_fail;
7750 p++;
7751 secs = strtol(p, (char **)&p, 0);
7752 if (secs < 1 || secs > 63)
7753 goto chs_fail;
7754 if (*p == ',') {
7755 p++;
7756 if (!strcmp(p, "none"))
7757 translation = BIOS_ATA_TRANSLATION_NONE;
7758 else if (!strcmp(p, "lba"))
7759 translation = BIOS_ATA_TRANSLATION_LBA;
7760 else if (!strcmp(p, "auto"))
7761 translation = BIOS_ATA_TRANSLATION_AUTO;
7762 else
7763 goto chs_fail;
7764 } else if (*p != '\0') {
7765 chs_fail:
7766 fprintf(stderr, "qemu: invalid physical CHS format\n");
7767 exit(1);
7770 break;
7771 case QEMU_OPTION_nographic:
7772 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7773 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7774 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7775 nographic = 1;
7776 break;
7777 case QEMU_OPTION_portrait:
7778 graphic_rotate = 1;
7779 break;
7780 case QEMU_OPTION_kernel:
7781 kernel_filename = optarg;
7782 break;
7783 case QEMU_OPTION_append:
7784 kernel_cmdline = optarg;
7785 break;
7786 case QEMU_OPTION_cdrom:
7787 if (cdrom_index >= 0) {
7788 hd_filename[cdrom_index] = optarg;
7790 break;
7791 case QEMU_OPTION_boot:
7792 boot_device = optarg[0];
7793 if (boot_device != 'a' &&
7794 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7795 // Network boot
7796 boot_device != 'n' &&
7797 #endif
7798 boot_device != 'c' && boot_device != 'd') {
7799 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7800 exit(1);
7802 break;
7803 case QEMU_OPTION_fda:
7804 fd_filename[0] = optarg;
7805 break;
7806 case QEMU_OPTION_fdb:
7807 fd_filename[1] = optarg;
7808 break;
7809 #ifdef TARGET_I386
7810 case QEMU_OPTION_no_fd_bootchk:
7811 fd_bootchk = 0;
7812 break;
7813 #endif
7814 case QEMU_OPTION_no_code_copy:
7815 code_copy_enabled = 0;
7816 break;
7817 case QEMU_OPTION_net:
7818 if (nb_net_clients >= MAX_NET_CLIENTS) {
7819 fprintf(stderr, "qemu: too many network clients\n");
7820 exit(1);
7822 pstrcpy(net_clients[nb_net_clients],
7823 sizeof(net_clients[0]),
7824 optarg);
7825 nb_net_clients++;
7826 break;
7827 #ifdef CONFIG_SLIRP
7828 case QEMU_OPTION_tftp:
7829 tftp_prefix = optarg;
7830 break;
7831 case QEMU_OPTION_bootp:
7832 bootp_filename = optarg;
7833 break;
7834 #ifndef _WIN32
7835 case QEMU_OPTION_smb:
7836 net_slirp_smb(optarg);
7837 break;
7838 #endif
7839 case QEMU_OPTION_redir:
7840 net_slirp_redir(optarg);
7841 break;
7842 #endif
7843 #ifdef HAS_AUDIO
7844 case QEMU_OPTION_audio_help:
7845 AUD_help ();
7846 exit (0);
7847 break;
7848 case QEMU_OPTION_soundhw:
7849 select_soundhw (optarg);
7850 break;
7851 #endif
7852 case QEMU_OPTION_h:
7853 help(0);
7854 break;
7855 case QEMU_OPTION_m:
7856 ram_size = atoi(optarg) * 1024 * 1024;
7857 if (ram_size <= 0)
7858 help(1);
7859 if (ram_size > PHYS_RAM_MAX_SIZE) {
7860 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7861 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7862 exit(1);
7864 break;
7865 case QEMU_OPTION_d:
7867 int mask;
7868 CPULogItem *item;
7870 mask = cpu_str_to_log_mask(optarg);
7871 if (!mask) {
7872 printf("Log items (comma separated):\n");
7873 for(item = cpu_log_items; item->mask != 0; item++) {
7874 printf("%-10s %s\n", item->name, item->help);
7876 exit(1);
7878 cpu_set_log(mask);
7880 break;
7881 #ifdef CONFIG_GDBSTUB
7882 case QEMU_OPTION_s:
7883 use_gdbstub = 1;
7884 break;
7885 case QEMU_OPTION_p:
7886 gdbstub_port = optarg;
7887 break;
7888 #endif
7889 case QEMU_OPTION_L:
7890 bios_dir = optarg;
7891 break;
7892 case QEMU_OPTION_S:
7893 autostart = 0;
7894 break;
7895 case QEMU_OPTION_k:
7896 keyboard_layout = optarg;
7897 break;
7898 case QEMU_OPTION_localtime:
7899 rtc_utc = 0;
7900 break;
7901 case QEMU_OPTION_cirrusvga:
7902 cirrus_vga_enabled = 1;
7903 vmsvga_enabled = 0;
7904 break;
7905 case QEMU_OPTION_vmsvga:
7906 cirrus_vga_enabled = 0;
7907 vmsvga_enabled = 1;
7908 break;
7909 case QEMU_OPTION_std_vga:
7910 cirrus_vga_enabled = 0;
7911 vmsvga_enabled = 0;
7912 break;
7913 case QEMU_OPTION_g:
7915 const char *p;
7916 int w, h, depth;
7917 p = optarg;
7918 w = strtol(p, (char **)&p, 10);
7919 if (w <= 0) {
7920 graphic_error:
7921 fprintf(stderr, "qemu: invalid resolution or depth\n");
7922 exit(1);
7924 if (*p != 'x')
7925 goto graphic_error;
7926 p++;
7927 h = strtol(p, (char **)&p, 10);
7928 if (h <= 0)
7929 goto graphic_error;
7930 if (*p == 'x') {
7931 p++;
7932 depth = strtol(p, (char **)&p, 10);
7933 if (depth != 8 && depth != 15 && depth != 16 &&
7934 depth != 24 && depth != 32)
7935 goto graphic_error;
7936 } else if (*p == '\0') {
7937 depth = graphic_depth;
7938 } else {
7939 goto graphic_error;
7942 graphic_width = w;
7943 graphic_height = h;
7944 graphic_depth = depth;
7946 break;
7947 case QEMU_OPTION_echr:
7949 char *r;
7950 term_escape_char = strtol(optarg, &r, 0);
7951 if (r == optarg)
7952 printf("Bad argument to echr\n");
7953 break;
7955 case QEMU_OPTION_monitor:
7956 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7957 break;
7958 case QEMU_OPTION_serial:
7959 if (serial_device_index >= MAX_SERIAL_PORTS) {
7960 fprintf(stderr, "qemu: too many serial ports\n");
7961 exit(1);
7963 pstrcpy(serial_devices[serial_device_index],
7964 sizeof(serial_devices[0]), optarg);
7965 serial_device_index++;
7966 break;
7967 case QEMU_OPTION_parallel:
7968 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7969 fprintf(stderr, "qemu: too many parallel ports\n");
7970 exit(1);
7972 pstrcpy(parallel_devices[parallel_device_index],
7973 sizeof(parallel_devices[0]), optarg);
7974 parallel_device_index++;
7975 break;
7976 case QEMU_OPTION_loadvm:
7977 loadvm = optarg;
7978 break;
7979 case QEMU_OPTION_full_screen:
7980 full_screen = 1;
7981 break;
7982 #ifdef CONFIG_SDL
7983 case QEMU_OPTION_no_frame:
7984 no_frame = 1;
7985 break;
7986 case QEMU_OPTION_alt_grab:
7987 alt_grab = 1;
7988 break;
7989 case QEMU_OPTION_no_quit:
7990 no_quit = 1;
7991 break;
7992 #endif
7993 case QEMU_OPTION_pidfile:
7994 pid_file = optarg;
7995 break;
7996 #ifdef TARGET_I386
7997 case QEMU_OPTION_win2k_hack:
7998 win2k_install_hack = 1;
7999 break;
8000 #endif
8001 #ifdef USE_KQEMU
8002 case QEMU_OPTION_no_kqemu:
8003 kqemu_allowed = 0;
8004 break;
8005 case QEMU_OPTION_kernel_kqemu:
8006 kqemu_allowed = 2;
8007 break;
8008 #endif
8009 case QEMU_OPTION_usb:
8010 usb_enabled = 1;
8011 break;
8012 case QEMU_OPTION_usbdevice:
8013 usb_enabled = 1;
8014 if (usb_devices_index >= MAX_USB_CMDLINE) {
8015 fprintf(stderr, "Too many USB devices\n");
8016 exit(1);
8018 pstrcpy(usb_devices[usb_devices_index],
8019 sizeof(usb_devices[usb_devices_index]),
8020 optarg);
8021 usb_devices_index++;
8022 break;
8023 case QEMU_OPTION_smp:
8024 smp_cpus = atoi(optarg);
8025 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8026 fprintf(stderr, "Invalid number of CPUs\n");
8027 exit(1);
8029 break;
8030 case QEMU_OPTION_vnc:
8031 vnc_display = optarg;
8032 break;
8033 case QEMU_OPTION_no_acpi:
8034 acpi_enabled = 0;
8035 break;
8036 case QEMU_OPTION_no_reboot:
8037 no_reboot = 1;
8038 break;
8039 case QEMU_OPTION_show_cursor:
8040 cursor_hide = 0;
8041 break;
8042 case QEMU_OPTION_daemonize:
8043 daemonize = 1;
8044 break;
8045 case QEMU_OPTION_option_rom:
8046 if (nb_option_roms >= MAX_OPTION_ROMS) {
8047 fprintf(stderr, "Too many option ROMs\n");
8048 exit(1);
8050 option_rom[nb_option_roms] = optarg;
8051 nb_option_roms++;
8052 break;
8053 case QEMU_OPTION_semihosting:
8054 semihosting_enabled = 1;
8055 break;
8056 case QEMU_OPTION_name:
8057 qemu_name = optarg;
8058 break;
8059 #ifdef TARGET_SPARC
8060 case QEMU_OPTION_prom_env:
8061 if (nb_prom_envs >= MAX_PROM_ENVS) {
8062 fprintf(stderr, "Too many prom variables\n");
8063 exit(1);
8065 prom_envs[nb_prom_envs] = optarg;
8066 nb_prom_envs++;
8067 break;
8068 #endif
8069 #ifdef TARGET_ARM
8070 case QEMU_OPTION_old_param:
8071 old_param = 1;
8072 #endif
8073 case QEMU_OPTION_clock:
8074 configure_alarms(optarg);
8075 break;
8080 #ifndef _WIN32
8081 if (daemonize && !nographic && vnc_display == NULL) {
8082 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8083 daemonize = 0;
8086 if (daemonize) {
8087 pid_t pid;
8089 if (pipe(fds) == -1)
8090 exit(1);
8092 pid = fork();
8093 if (pid > 0) {
8094 uint8_t status;
8095 ssize_t len;
8097 close(fds[1]);
8099 again:
8100 len = read(fds[0], &status, 1);
8101 if (len == -1 && (errno == EINTR))
8102 goto again;
8104 if (len != 1)
8105 exit(1);
8106 else if (status == 1) {
8107 fprintf(stderr, "Could not acquire pidfile\n");
8108 exit(1);
8109 } else
8110 exit(0);
8111 } else if (pid < 0)
8112 exit(1);
8114 setsid();
8116 pid = fork();
8117 if (pid > 0)
8118 exit(0);
8119 else if (pid < 0)
8120 exit(1);
8122 umask(027);
8123 chdir("/");
8125 signal(SIGTSTP, SIG_IGN);
8126 signal(SIGTTOU, SIG_IGN);
8127 signal(SIGTTIN, SIG_IGN);
8129 #endif
8131 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8132 if (daemonize) {
8133 uint8_t status = 1;
8134 write(fds[1], &status, 1);
8135 } else
8136 fprintf(stderr, "Could not acquire pid file\n");
8137 exit(1);
8140 #ifdef USE_KQEMU
8141 if (smp_cpus > 1)
8142 kqemu_allowed = 0;
8143 #endif
8144 linux_boot = (kernel_filename != NULL);
8146 if (!linux_boot &&
8147 boot_device != 'n' &&
8148 hd_filename[0] == '\0' &&
8149 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
8150 fd_filename[0] == '\0')
8151 help(1);
8153 /* boot to floppy or the default cd if no hard disk defined yet */
8154 if (hd_filename[0] == '\0' && boot_device == 'c') {
8155 if (fd_filename[0] != '\0')
8156 boot_device = 'a';
8157 else
8158 boot_device = 'd';
8161 setvbuf(stdout, NULL, _IOLBF, 0);
8163 init_timers();
8164 init_timer_alarm();
8165 qemu_aio_init();
8167 #ifdef _WIN32
8168 socket_init();
8169 #endif
8171 /* init network clients */
8172 if (nb_net_clients == 0) {
8173 /* if no clients, we use a default config */
8174 pstrcpy(net_clients[0], sizeof(net_clients[0]),
8175 "nic");
8176 pstrcpy(net_clients[1], sizeof(net_clients[0]),
8177 "user");
8178 nb_net_clients = 2;
8181 for(i = 0;i < nb_net_clients; i++) {
8182 if (net_client_init(net_clients[i]) < 0)
8183 exit(1);
8185 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8186 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8187 continue;
8188 if (vlan->nb_guest_devs == 0) {
8189 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8190 exit(1);
8192 if (vlan->nb_host_devs == 0)
8193 fprintf(stderr,
8194 "Warning: vlan %d is not connected to host network\n",
8195 vlan->id);
8198 #ifdef TARGET_I386
8199 if (boot_device == 'n') {
8200 for (i = 0; i < nb_nics; i++) {
8201 const char *model = nd_table[i].model;
8202 char buf[1024];
8203 if (model == NULL)
8204 model = "ne2k_pci";
8205 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8206 if (get_image_size(buf) > 0) {
8207 option_rom[nb_option_roms] = strdup(buf);
8208 nb_option_roms++;
8209 break;
8212 if (i == nb_nics) {
8213 fprintf(stderr, "No valid PXE rom found for network device\n");
8214 exit(1);
8217 #endif
8219 /* init the memory */
8220 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8222 phys_ram_base = qemu_vmalloc(phys_ram_size);
8223 if (!phys_ram_base) {
8224 fprintf(stderr, "Could not allocate physical memory\n");
8225 exit(1);
8228 /* we always create the cdrom drive, even if no disk is there */
8229 bdrv_init();
8230 if (cdrom_index >= 0) {
8231 bs_table[cdrom_index] = bdrv_new("cdrom");
8232 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
8235 /* open the virtual block devices */
8236 for(i = 0; i < MAX_DISKS; i++) {
8237 if (hd_filename[i]) {
8238 if (!bs_table[i]) {
8239 char buf[64];
8240 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
8241 bs_table[i] = bdrv_new(buf);
8243 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8244 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
8245 hd_filename[i]);
8246 exit(1);
8248 if (i == 0 && cyls != 0) {
8249 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
8250 bdrv_set_translation_hint(bs_table[i], translation);
8255 /* we always create at least one floppy disk */
8256 fd_table[0] = bdrv_new("fda");
8257 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
8259 for(i = 0; i < MAX_FD; i++) {
8260 if (fd_filename[i]) {
8261 if (!fd_table[i]) {
8262 char buf[64];
8263 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
8264 fd_table[i] = bdrv_new(buf);
8265 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
8267 if (fd_filename[i][0] != '\0') {
8268 if (bdrv_open(fd_table[i], fd_filename[i],
8269 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8270 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
8271 fd_filename[i]);
8272 exit(1);
8278 /* Open the virtual parallel flash block devices */
8279 for(i = 0; i < MAX_PFLASH; i++) {
8280 if (pflash_filename[i]) {
8281 if (!pflash_table[i]) {
8282 char buf[64];
8283 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
8284 pflash_table[i] = bdrv_new(buf);
8286 if (bdrv_open(pflash_table[i], pflash_filename[i],
8287 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8288 fprintf(stderr, "qemu: could not open flash image '%s'\n",
8289 pflash_filename[i]);
8290 exit(1);
8295 sd_bdrv = bdrv_new ("sd");
8296 /* FIXME: This isn't really a floppy, but it's a reasonable
8297 approximation. */
8298 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
8299 if (sd_filename) {
8300 if (bdrv_open(sd_bdrv, sd_filename,
8301 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8302 fprintf(stderr, "qemu: could not open SD card image %s\n",
8303 sd_filename);
8304 } else
8305 qemu_key_check(sd_bdrv, sd_filename);
8308 if (mtd_filename) {
8309 mtd_bdrv = bdrv_new ("mtd");
8310 if (bdrv_open(mtd_bdrv, mtd_filename,
8311 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
8312 qemu_key_check(mtd_bdrv, mtd_filename)) {
8313 fprintf(stderr, "qemu: could not open Flash image %s\n",
8314 mtd_filename);
8315 bdrv_delete(mtd_bdrv);
8316 mtd_bdrv = 0;
8320 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8321 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8323 init_ioports();
8325 /* terminal init */
8326 memset(&display_state, 0, sizeof(display_state));
8327 if (nographic) {
8328 /* nearly nothing to do */
8329 dumb_display_init(ds);
8330 } else if (vnc_display != NULL) {
8331 vnc_display_init(ds);
8332 if (vnc_display_open(ds, vnc_display) < 0)
8333 exit(1);
8334 } else {
8335 #if defined(CONFIG_SDL)
8336 sdl_display_init(ds, full_screen, no_frame);
8337 #elif defined(CONFIG_COCOA)
8338 cocoa_display_init(ds, full_screen);
8339 #endif
8342 /* Maintain compatibility with multiple stdio monitors */
8343 if (!strcmp(monitor_device,"stdio")) {
8344 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8345 if (!strcmp(serial_devices[i],"mon:stdio")) {
8346 monitor_device[0] = '\0';
8347 break;
8348 } else if (!strcmp(serial_devices[i],"stdio")) {
8349 monitor_device[0] = '\0';
8350 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8351 break;
8355 if (monitor_device[0] != '\0') {
8356 monitor_hd = qemu_chr_open(monitor_device);
8357 if (!monitor_hd) {
8358 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8359 exit(1);
8361 monitor_init(monitor_hd, !nographic);
8364 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8365 const char *devname = serial_devices[i];
8366 if (devname[0] != '\0' && strcmp(devname, "none")) {
8367 serial_hds[i] = qemu_chr_open(devname);
8368 if (!serial_hds[i]) {
8369 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8370 devname);
8371 exit(1);
8373 if (strstart(devname, "vc", 0))
8374 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8378 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8379 const char *devname = parallel_devices[i];
8380 if (devname[0] != '\0' && strcmp(devname, "none")) {
8381 parallel_hds[i] = qemu_chr_open(devname);
8382 if (!parallel_hds[i]) {
8383 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8384 devname);
8385 exit(1);
8387 if (strstart(devname, "vc", 0))
8388 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8392 machine->init(ram_size, vga_ram_size, boot_device,
8393 ds, fd_filename, snapshot,
8394 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8396 /* init USB devices */
8397 if (usb_enabled) {
8398 for(i = 0; i < usb_devices_index; i++) {
8399 if (usb_device_add(usb_devices[i]) < 0) {
8400 fprintf(stderr, "Warning: could not add USB device %s\n",
8401 usb_devices[i]);
8406 if (display_state.dpy_refresh) {
8407 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8408 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8411 #ifdef CONFIG_GDBSTUB
8412 if (use_gdbstub) {
8413 /* XXX: use standard host:port notation and modify options
8414 accordingly. */
8415 if (gdbserver_start(gdbstub_port) < 0) {
8416 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8417 gdbstub_port);
8418 exit(1);
8421 #endif
8423 if (loadvm)
8424 do_loadvm(loadvm);
8427 /* XXX: simplify init */
8428 read_passwords();
8429 if (autostart) {
8430 vm_start();
8434 if (daemonize) {
8435 uint8_t status = 0;
8436 ssize_t len;
8437 int fd;
8439 again1:
8440 len = write(fds[1], &status, 1);
8441 if (len == -1 && (errno == EINTR))
8442 goto again1;
8444 if (len != 1)
8445 exit(1);
8447 TFR(fd = open("/dev/null", O_RDWR));
8448 if (fd == -1)
8449 exit(1);
8451 dup2(fd, 0);
8452 dup2(fd, 1);
8453 dup2(fd, 2);
8455 close(fd);
8458 main_loop();
8459 quit_timers();
8460 return 0;